AntiqueZamba
AntiqueZamba

Reputation: 185

Best way to call a python script from within a python script multiple times

I need to execute a python script from within another python-script multiple times with different arguments. I know this sounds horrible but there are reasons for it. Problem is however that the callee-script does not check if it is imported or executed (if __name__ == '__main__': ...).

  1. I know I could use subprocess.popen("python.exe callee.py -arg") but that seems to be much slower then it should be, and I guess thats because Python.exe is beeing started and terminated multiple times.
  2. I can't import the script as a module regularily because of its design as described in the beginning - upon import it will be executed without args because its missing a main() method.
  3. I can't change the callee script either
  4. As I understand it I can't use execfile() either because it doesnt take arguments

Upvotes: 0

Views: 260

Answers (1)

gbin
gbin

Reputation: 3000

Found the solution for you. You can reload a module in python and you can patch the sys.argv.

Imagine echo.py is the callee script you want to call a multiple times :

#!/usr/bin/env python
# file: echo.py

import sys
print sys.argv

You can do as your caller script :

#!/usr/bin/env python
# file: test.py 
import sys
sys.argv[1] = 'test1'
import echo
sys.argv[1] = 'test2'
reload(echo)

And call it for example with : python test.py place_holder

it will printout :

['test.py', 'test1']
['test.py', 'test2']

Upvotes: 2

Related Questions