Reputation: 3
subprocess.Popen
calls the calculator.py
only when the loop ends. I need the code to run the calculator at once.
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
Upvotes: 0
Views: 856
Reputation: 3075
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, meaning that your program isn't waiting for it to finish executing, which I think is what you want. run()
, by contrast, "Wait(s) for (the) command to complete, then return(s) a CompletedProcess
instance."
For clarity's sake, here's some code to explain what's going on:
# 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
Upvotes: 2
Reputation: 3296
subprocess.Popen
starts the process, but does not wait for its completion. You might use subprocess.run
instead.
Upvotes: 0