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.


import sys
import subprocess

subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])

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])

Tags:

Python

Shell