0

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')
5
  • You call main(..) instead of child(..). Commented Aug 4, 2019 at 20:10
  • Furthermore you can, but these parameters are in sys.args. Commented Aug 4, 2019 at 20:11
  • sorry didn't get what you are saying. I want a subprocess instead of call main directly. That way my parent scrip can keep going instead of waiting for the child to complete.@WillemVanOnsem Commented Aug 4, 2019 at 20:13
  • every script get arguments from command line in sys.args but your child.py doesn't use sys.argv Commented Aug 4, 2019 at 20:15
  • @Lisa, ...if that's all you're trying to do, there are cheaper/more efficient ways to fork() a copy of your current interpreter with startup-time initialization already done; when you use subprocess to start a whole new interpreter, it pays what would otherwise be one-time startup costs a second time. See the multiprocessing module for an example. And of course, there's also threading (though whether that's appropriate depends on implementation details). Commented Aug 4, 2019 at 20:59

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

1 Comment

;) i think you mean: from sys import argv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.