我有这个代码。基本上我使用subprocess在while循环中多次执行一个程序。它工作正常,但经过几次(准确地说是5次)后,我的python脚本才会终止,并且在完成之前还有很长的路要走。
while x < 50:
# ///////////I am doing things here/////////////////////
cmdline = 'gmx mdrun -ntomp 1 -v -deffnm my_sim'
args = shlex.split(cmdline)
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = proc.communicate()[0].decode()
# ///////////I am doing things here/////////////////////
x += 1
每次我打电话给程序,大约需要一个小时才能完成。同时,子进程应该等待,因为根据输出我必须执行部分代码(这就是我使用.communicate()的原因)。
为什么会这样?
感谢先进的帮助!
子进程在后台异步运行(因为它是一个不同的进程),你需要使用subprocess.wait()等待它完成。由于您有多个子进程,因此您可能希望等待所有子进程,如下所示:
exit_codes = [p.wait() for p in (p1, p2)]
要解决这个问题,我建议您执行以下操作:
while x < 50:
# ///////////I am doing things here/////////////////////
cmdline = 'gmx mdrun -ntomp 1 -v -deffnm my_sim 2>&1 | tee output.txt'
proc = subprocess.check_output(args, shell=True)
with open('output.txt', 'r') as fin:
out_file = fin.read()
# ///////////Do what ever you need with the out_file/////////////
# ///////////I am doing things here/////////////////////
x += 1
我知道不建议使用shell = True,所以如果你不想使用它,那么只需用逗号传递cmdline即可。请注意,使用逗号传递时可能会出错。我想进入细节,但在这种情况下你可以使用shell = True,你的问题就会消失。
使用我刚刚提供的代码片段,当使用子进程很多时间以及具有大量stdout和stderr消息的程序时,你的python脚本不会突然终止。
它花了一些时间来发现这一点,我希望我可以帮助那里的人。