5
如何實現以下功能:Python的執行命令行中,發送輸入和讀取輸出
- 的Python執行一個外殼命令時,用戶鍵入的
input
之後等待用戶到input
東西 - ,一些
output
- 的Python程序響應捕獲
output
如何實現以下功能:Python的執行命令行中,發送輸入和讀取輸出
input
之後等待用戶到input
東西output
output
你可能想subprocess.Popen
。要與流程溝通,您需要使用communicate
方法。
例如
process=subprocess.Popen(['command','--option','foo'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
inputdata="This is the string I will send to the process"
stdoutdata,stderrdata=process.communicate(input=inputdata)
請看[subprocess module](http://docs.python.org/library/subprocess.html)。 – RanRag
在更普遍的情況下[pexpect](http://www.noah.org/python/pexpect/)可能會有用。 – jfs