如何等待Python subprocess.check_output()完成?

问题描述 投票:1回答:2

我在循环中运行此代码 - 在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)确保子进程串行发生的解决方案都可以。

谢谢!

python subprocess wait
2个回答
1
投票

不,check_output仅在子进程运行完毕后返回。你的问题是由别的东西引起的。


1
投票

你描述的情况远非令人满意,因为如果我理解你的描述正确,有时候会产生竞争条件。合乎逻辑的做法是让程序在出现时读取子进程的输出。

如果您想要更好地控制子进程,那么使用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'
>>>
© www.soinside.com 2019 - 2024. All rights reserved.