我正在循环中运行此代码 - 在 Python 3.6 中:
# previous code: copy certain files to the working folder
shellCmd = "myCmd " + file1 + " " + file2
# myCmd works on file1 and file2
result = subprocess.check_output(myCmd, shell=True)
# delete the files
时不时地,我会遇到由于某些文件的访问被拒绝而导致的失败。我猜测子进程在后台运行并且循环继续,产生其他子进程。有时,这会导致一个子进程尝试复制(或删除) myCmd 在另一子进程中仍忙于处理的文件。
如何停止并等待 subprocess.check_output() 完成?
我看到subprocess.Popen有一个wait()函数,但我需要myCmd进程的结果字符串,所以想使用subprocess.check_output()。
但是任何能够 (a) 获得 myCmd 的字符串输出并 (b) 确保子进程连续发生的解决方案都是可以的。
谢谢!
最佳答案
您描述的情况远不能令人满意,因为如果我正确理解您的描述,多个子进程有时会产生竞争条件。合乎逻辑的做法是让您的程序读取子进程的输出。
如果您想更好地控制子流程,那么使用 subprocess.Popen
对象会更安全,它具有更可用的界面。通过读取一个命令的输出直到到达文件末尾,您就知道您不会创建额外的进程来干扰。使用 stdout=subprocess.PIPE
将命令的标准输出发送到管道,然后您可以将进程的标准输出读取为 Popen
对象的 stdout
属性如下图所示。
>>> process = subprocess.Popen("getmac", stdout=subprocess.PIPE)
>>> for line in process.stdout:
... print(line)
...
b'\r\n'
b'Physical Address Transport Name \r\n'
b'=================== ==========================================================\r\n'
b'94-C6-91-1B-56-A4 \\Device\\Tcpip_{023B9717-B878-43D4-A0BE-28A4295785FA} \r\n'
b'68-EC-C5-52-14-AD Media disconnected \r\n'
b'68-EC-C5-52-14-B1 Media disconnected \r\n'
b'0A-00-27-00-00-0E \\Device\\Tcpip_{89DD54F9-0C99-4F5B-8376-45598FB4C0FD} \r\n'
>>>
关于python - 如何等待Python subprocess.check_output()完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55691357/