Reputation: 4436
I have searched SO but couldn't find an asnwer. I want to invoke a python script(child script) from another python script(main script). I cannot pass arguments from parent to child? I am expecting "subprocess launched: id1-id2" from the console. But what I am getting is "subprocess launched:test-default". The subprocess is using the default parameters instead of receiving parameters from the parent script.
# parent
import subprocess
subprocess.call(['python', 'child.py', 'id1', 'id2'])
# script name: child.py
def child(id, id2):
print ('subprocess launched: {}-{}'.format(str(id), id2))
if __name__ == '__main__':
main(id='test', id2='default')
Upvotes: 0
Views: 277
Reputation: 477794
The parameters that you pass to a Python process are stored in sys.argv
[Python-doc]. This is a list of parameters, that works a bit similar to $@
in bash
[bash-man] for example.
Note that argv[0]
is not the first parameter, but the name of the Python script you run, as is specified by the documentation:
argv[0]
is the script name (it is operating system dependent whether this is a full pathname or not).
The remaining parameters are the parameters passed to the script.
You can thus rewrite your child.py
to:
# script name: child.py
from sys import argv
def child(id, id2):
print ('subprocess launched: {}-{}'.format(str(id), id2))
if __name__ == '__main__':
child(id=argv[1], id2=argv[2])
Upvotes: 2