Search code examples
pythonpython-3.xsubprocesssys

How to pass more than two string/variables to my child script when using subprocess?


[1] Can I pass an integer or even a list to my child script(test.py)? How do I do so?

[2] How should I modify my code if I also want to pass the age variable to the child script (test.py) and print the age? Any better way to do so other that stick the string together in the parent script and split it apart in the child script? Can subprocess itself pass more than 1 string or variables?

Parent

#main.py
import subprocess
import sys

name = 'trump'  
age = 80
proc = subprocess.Popen([sys.executable, "test.py", "trump"])

Child

#test.py
import sys
name = sys.argv[1]

print(name)
#print(age)

Solution

  • Read the docs for subprocess and sys.argv; one takes sequence of arguments, the other provides the list of received arguments (minus the path to Python if it was run as python scriptname.py). They must be strings, so you can't pass age as is, but:

    proc = subprocess.Popen([sys.executable, "test.py", name, str(age)])
    

    would work to pass them, and:

    name = sys.argv[1]
    age = int(sys.argv[2])
    

    would suffice to receive them. Personally, I'd recommend avoiding raw sys.argv parsing in favor of argparse, making it:

    # test.py
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('name', help='The name of the person')
    parser.add_argument('age', type=int, help='The age of the person')
    args = parser.parse_args()
    
    print(args.name)
    print(args.age)
    

    or the like, because learning argparse and using it reliably is helpful (importantly, when you forget what the program takes as arguments, you can run programname.py --help and argparse will tell you).