I would like to run a command in Python Shell to execute a file with an argument.
For example: execfile("abc.py")
but how to add 2 arguments?
I would like to run a command in Python Shell to execute a file with an argument.
For example: execfile("abc.py")
but how to add 2 arguments?
For more interesting scenarios, you could also look at the
runpy
module. Since python 2.7, it has therun_path
function. E.g:try this:
Note that when
abc.py
finishes, control will be returned to the calling program. Note too thatabc.py
can callquit()
if indeed finished.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.You're confusing loading a module into the current interpreter process and calling a Python script externally.
The former can be done by
import
ing the file you're interested in. execfile is similar to importing but it simply evaluates the file rather than creates a module out of it. Similar to "sourcing" in a shell script.The latter can be done using the subprocess module. You spawn off another instance of the interpreter and pass whatever parameters you want to that. This is similar to shelling out in a shell script using backticks.
If you set
PYTHONINSPECT
in the python file you want to execute[repl.py]
there is no need to use
execfile
, and you can directly run the file with arguments as usual in the shell: