0

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
2
  • 2
    Can you modify the "callee-script"? Commented Aug 28, 2012 at 14:40
  • 1
    Replace the script with a proper wrapper, that has the same functionality, but calls methods or classes from your original script. Commented Aug 28, 2012 at 14:59

1 Answer 1

2

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

1 Comment

Note this is on python 2.7, for python 3 use the module imp and imp.reload

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.