2016-02-09 47 views
0

我需要在命令啓動後發送命令到shell「MYSHELL>」。使用Python將命令發送到子殼

prcs = subprocess.Popen("MYSHELL; cmnd1; cmnd2;",shell=True, 
subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

outputPrcs, err = prcs.communicate() 
print outputPrcs 

只有進入shell的問題被執行,其他命令(cmnd1; cmnd2;)不會被髮送。

結果: MYSHELL>

+0

可能是因爲'MYSHELL'仍在執行。你的命令的意思是「啓動MYSHELL,等待它完成,然後執行cmnd1和cmnd2」 – Dunno

+0

你想實現什麼?你想發送「cmnd1」和「cmnd2」到你的shell作爲輸入,還是你想執行其他程序? – Dunno

+0

我想發送cmnd1 cmnd2到MYSHELL作爲輸入在那個shell –

回答

1

docs

communicate(self, input=None) 
    Interact with process: Send data to stdin. Read data from 
    stdout and stderr, until end-of-file is reached. Wait for 
    process to terminate. The optional input argument should be a 
    string to be sent to the child process, or None, if no data 
    should be sent to the child. 

通知,Wait for process to terminate.我想你需要的是pexpect。它不在標準庫中,但它會做你想做的。

例子:

import pexpect 

process = pexpect.spawn("python") 
process.expect_exact(">>> ") 
process.sendline('print("It works")') 
process.expect("\n.*\n") 
response = process.after.strip() 
print(response) 

輸出:

It works 
0

如果你想輸入發送到你的shell,那麼你應該把它作爲一個參數在communicate,像這樣:

prcs = subprocess.Popen("MYSHELL",shell=True, 
subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

outputPrcs, err = prcs.communicate("cmnd1; cmnd2;") 
print outputPrcs 

test:

>>> from subprocess import * 
>>> p = Popen("python", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) 
>>> o,e = p.communicate("print 'it works'") 
>>> print o 
it works 

>>> 
+0

我試過上面的代碼,它的工作原理。而不是python.I使用了bash和echo。 但是,仍然不能與MYSHELL合作> –