我对
subprocess
模块有疑问,returncode
和poll()
是相关的。
Python版本为3.9.6
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet.
Popen.poll()
Check if child process has terminated. Set and return returncode attribute. Otherwise, returns None.
所以,根据文档,它们的工作方式相似,但实际上它们会导致不同的结果,我不知道为什么会这样
但是,下面的代码是无限循环,如果我在循环中添加
print(proc.poll())
,它会正常工作。
import shlex
import subprocess
proc = subprocess.Popen(shlex.split('python3 --version'),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
while proc.returncode is None:
# print(proc.poll())
print(proc.stdout.readline())
以下代码工作正常。
import shlex
import subprocess
proc = subprocess.Popen(shlex.split('python3 --version'),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
while proc.poll() is None:
# print(proc.poll())
print(proc.stdout.readline())