我想编写一个简单的 python 程序,其中包含我需要并行运行以加快执行速度的系统命令列表。但也想重试任何可能失败的命令。
例如,如果我有以下命令:
["ls", "w", "echo 'Hello World'", "some-command-that-may-fail"]
所以最后可能失败的命令必须重新运行一次(注意:不是所有的命令都需要重新运行,只是失败的命令)
我尝试在 python 中使用
"subprocess"
库,但无法弄清楚如何添加重试逻辑。exit_codes = [0]*len(commands)
processes = []
print("Executing commands")
for cmd in commands:
process = subprocess.Popen(cmd, shell=True)
processes.append(process)
for process in processes:
if process.poll() is None:
exit_code = process.wait()
exit_codes[processes.index(process)] = exit_code
对于失败逻辑,您可以使用 try 和 except 来捕获命令错误并使用 continue 函数重新运行它。
try:
result = some_function()
except Exception as e:
print(f"Error: {e}") #remove this line if you dont want to print it
time.sleep(10) #modify this if you want to wait longer or shorter or not at all
continue
else:
break