2016-05-13 33 views
0

我必须Python脚本:Tester1.py和Tester2.py。 在Tester1内我想不时启动Tester2.py。我也想通过Tester2.py一些参数。目前我的代码看起来是这样的:Python:子进程与终端不同。我必须改变什么?

Tester1:

subprocess.call(['python3 Tester2.py testString']) 

Tester2:

def start(): 
    message = sys.argv[1] 
    print(message) 

start() 

现在我的问题:如果我和我的终端Tester2像 'python3 Tester2.py的TestString' 运行我的控制台打印出testString。但是,如果我运行Tester1并且Tester1尝试启动Tester2,则会出现IndexError:“列表索引超出范围”。

我该如何改变我的代码才能让所有的东西都能正常工作?

编辑: niemmi告诉我,我有我的代码更改为:

subprocess.call(['python3', 'Tester2.py', 'testString']) 

,但现在我得到一个没有这样的文件或目录错误尽管这两个脚本是在同一目录下。有人知道为什么吗?

+0

仅供参考,如果你正在使用Python 3.5或更高,文档建议使用子进程的run()函数:https://docs.python.org/3/library/subprocess.html – tschale

回答

3

您需要提供的参数既可以作为表上单独的元素或字符串:

subprocess.call(['python3', 'Tester2.py', 'testString']) 
# or 
subprocess.call('python3 Tester2.py testString') 

Python documentation有以下描述:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

+0

我仍然有同样的错误:( – TomHere

+0

哦,我的错。作品 – TomHere

+0

现在我得到一个没有这样的文件或目录错误a尽管两个脚本都在同一个目录中? – TomHere

相关问题