The easiest way to pass arguments to a child process is to use command line parameters.
The first step is to rewrite child.py
so that it accepts command line arguments. There is detailed information about parsing command line arguments in this question: How to read/process command line arguments? For this simple example though, we will simply access the command line arguments through sys.argv
.
import sys
def main(a):
while(True):
print(a)
if __name__ == '__main__':
# the first element in the sys.argv list is the name of our program ("child.py"), so
# the argument the parent process sends to the child process will be the 2nd element
a = sys.argv[1]
main(a)
Now child.py
can be started with an argument like python child.py foobar
and the text "foobar" will be used as the value for the a
variable.
With that out of the way, all that's left is to rewrite parent.py
and make it pass an argument to child.py
. The recommended way to pass arguments with subprocess.Popen
is as a list of strings, so we'll do just that:
import time
import subprocess
def main():
while(True):
a = input("Please enter parameter to pass to subprocess:")
subprocess.Popen(["python", "child.py", a]) # pass a as an argument
print(f"{a} was started")
time.sleep(5)
if __name__ == '__main__':
main()