Execute a file with arguments in Python shell

2019-01-02 22:58发布

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?

标签: python shell
10条回答
放荡不羁爱自由
2楼-- · 2019-01-02 23:44

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__')
查看更多
我命由我不由天
3楼-- · 2019-01-02 23:45

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.

查看更多
放我归山
4楼-- · 2019-01-02 23:47

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.

subprocess.call(['./abc.py', arg1, arg2])
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-02 23:47

You're confusing loading a module into the current interpreter process and calling a Python script externally.

The former can be done by importing 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.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-02 23:50

If you set PYTHONINSPECT in the python file you want to execute

[repl.py]

import os
import sys
from time import time 
os.environ['PYTHONINSPECT'] = 'True'
t=time()
argv=sys.argv[1:len(sys.argv)]

there is no need to use execfile, and you can directly run the file with arguments as usual in the shell:

python repl.py one two 3
>>> t
1513989378.880822
>>> argv
['one', 'two', '3']
查看更多
来,给爷笑一个
7楼-- · 2019-01-02 23:51
import sys
import subprocess

subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])
查看更多
登录 后发表回答