子流程.Popen不能在无限循环中工作



subprocess.Popen只在循环结束时调用calculator.py。我需要马上运行计算器的代码。

from subprocess import Popen
import calculator
while True:
a='op'
c='io'
b=input()
if a==b:
#calculator
Popen(['python', 'calculator.py'])
elif c==b:
print('hello')
else:
print("hi")
break

根据文档,调用子流程的推荐方法是对它可以处理的所有用例使用run()函数。对于更高级的用例,可以直接使用底层的Popen接口。这是一个非常简单的用例,因此首选使用run()。这里的问题是Popen不阻塞,这意味着您的程序不会等待它完成执行,我认为这是您想要的。相比之下,run()"等待(命令)完成,然后返回(s)CompletedProcess实例"。

为了清楚起见,这里有一些代码来解释发生了什么:

# instead of Popen, we're going to import run. CompletedProcess is used below
# for illustration purposes, but you don't need it and can remove it from your
# code
from subprocess import CompletedProcess, run
# there's no reason to import calculator, since you don't use it. you should
# remove this line
# import calculator
while True:
a = "op"
c = "io"
b = input()
if a == b:
# after the specified command has completed, run returns an object of
# type CompletedProcess[bytes], which I've indicated below using
# python's type annotation syntax, i.e. variable: Type. this is for
# illustration only. Since you're not using the return value, you can
# simply say:
# run(['python', 'calculator.py'])
_completed_process: CompletedProcess[bytes] = run(["python", "calculator.py"])
elif c == b:
print("hello")
else:
print("hi")
break

subprocess.Popen启动进程,但不等待其完成。您可以使用subprocess.run

最新更新