2014-01-27 72 views
0

我有Python腳本,它在運行時需要用戶輸入並提供一些輸出。 示例代碼:使用Python來運行交互式Python腳本

import random 
l1 = ['Bob', 'Eric', 'Dimitar', 'Kyle'] 
l2 = ['Scott', 'Mat', 'Con'] 
n = raw_input('Enter no. of persons: ') 
for i in range(int(n)): 
    print random.choice(l1) + ' ' + random.choice(l2) 

輸出:

$ ./generate_name.py 
Enter no. of persons: 2 
Kyle Scott 
Eric Mat 

現在我想寫就多次與特定輸入運行的第一個python腳本另一個Python腳本(輸入序列被存儲在一個列表)並將輸出記錄在文件中。 此外,我不能在第一個Python代碼中進行任何更改。

我可以使用subprocess模塊來運行腳本並記錄輸出,但我該如何照顧交互式用戶輸入部分?

+1

如果您使用的是Unix風格的系統,您可能會使用管道...... –

+0

您的意思是:'subprocess.Popen('./ generate_name.py <<< 2',shell = 1)'。是的,這將工作。非常感謝:) –

+3

你應該使用'stdin'作爲'Popen'的參數,而不是使用'shell = True'(或者你不那麼慣用的版本)。 – geoffspear

回答

0

我看到兩個選項:您可以運行它作爲一個單獨的進程確實使用subprocess,如

sp = subprocess.Popen(['./generate_name.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) 
sp.stdin.write("2\n") 
sp.stdin.close() 
answer = sp.stdout.read() 
status = sp.wait() 

或者你把你的腳本和exec它。在這樣做之前,您可以重定向sys.stdinsys.stdout,您可以捕獲並監視所做的所有更改。這樣,你可以在一個進程中運行它。