Execute a file with arguments in Python shell
try this:
import sys
sys.argv = ['arg1', 'arg2']
execfile('abc.py')
Note that when abc.py
finishes, control will be returned to the calling program. Note too that abc.py
can call quit()
if indeed finished.
Actually, wouldn't we want to do this?
import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')
execfile
runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
If you want to run a program from within Python, use subprocess.call
. E.g.
import subprocess
subprocess.call(['./abc.py', arg1, arg2])
import sys
import subprocess
subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])
For more interesting scenarios, you could also look at the runpy
module. Since python 2.7, it has the run_path
function. E.g:
import runpy
import sys
# argv[0] will be replaced by runpy
# You could also skip this if you get sys.argv populated
# via other means
sys.argv = ['', 'arg1' 'arg2']
runpy.run_path('./abc.py', run_name='__main__')