2012-03-04 139 views
3

我有一個shell腳本,詢問用戶太多的問題。Python子進程:與shell腳本交互

我要回答所有以:進入結束的問題上,凡有?y結束問題進入

例如,

 
Enter your name: 
enter 

Enter your email: 
enter 

... 

Are you sure these details are correct? 
yenter 

我已經開始與子:

subprocess.Popen(shell=True, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE) 

如何查詢在腳本的輸出,等待問題出現?

回答

4

嘗試這樣的事情(我沒有測試過):

import pexpect 

child = pexpect.spawn('yourprogram') 
while True: 
    found = child.expect ([r':$', r'\?$', pexpect.EOF]) 
    if found == 0: 
    child.send('\n') 
    elif found == 1: 
    child.send('y\n') 
    else: # EOF 
    return 
+0

+1 Pexpect的,我不知道。這似乎是一個非常有用的方法 - 我會盡量讓它工作。 – 2012-03-04 15:14:51

+2

'pexpect.run('yourprogram',events = {r':$':'\ n',r'\?$':'y \ n'})' – jfs 2012-03-04 15:29:56

+0

這真是太棒了! – 2012-03-05 08:18:19