2016-05-13 74 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

相關問題