subprocess.Popen 在无限循环中不起作用

subprocess.Popen does not work in an infinite loop

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

subprocess.Popen starts the process, but does not wait for its completion. You might use subprocess.run 代替。

Per the docs, "The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly." This is a very simple use case, so using run() is preferred. The problem here is that Popen isn't blocking,这意味着您的程序不会等待它完成执行,我认为这正是您想要的。 run(),相比之下,“等待(s)命令完成,然后 return(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