2016-10-05 127 views
-1

我有一個shell腳本,詢問用戶輸入。考慮下面的例子在python中執行交互式shell腳本

Test.sh

#!/bin/bash 
echo -n "Enter name > " 
read text 
echo "You entered: $text" 
echo -n "Enter age > " 
read text 
echo "You entered: $text" 
echo -n "Enter location > " 
read text 
echo "You entered: $text" 

腳本執行:

sh test.sh 
Enter name> abc 
You entered: abc 
Enter age > 35 
You entered: 35 
Enter location > prop 
You entered: prop 

現在,我稱此腳本Python程序。我正在使用子流程模塊來做這件事。據我所知,子過程模塊創建一個新的過程。問題是當我執行python腳本時,我無法將參數傳遞給底層shell腳本,scipt處於hault階段。可能某些時候我哪裏做錯了

python腳本(CHECK.PY):

import subprocess, shlex 


cmd = "sh test.sh" 
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
stdout,stderr = proc.communicate() 

print stdout 

Python的執行:check.py

python check.py 
+0

我們可以通過OS模塊完成同樣的事情,但我嘗試使用子模塊 –

回答

2

你的代碼工作,但因爲你提及stdout=subprocess.PIPE內容將會在stdout,stderr = proc.communicate()中定義的變量stdout。從您的Popen()呼叫中刪除stdout=subprocess.PIPE參數,您將看到輸出。

或者,你應該使用subprocess.check_call()爲:

subprocess.check_call(shlex.split(cmd)) 
+0

感謝實現答案。我們如何捕獲該腳本的輸出?我正在使用Python 2.6.6 –

+0

如果您將捕獲輸出,您將無法在控制檯上看到腳本打印的內容。那是你要的嗎?爲此,你可以使用'subprocess.check_output()' –

+0

Check_output工作正常..我測試..但我需要使用python 2.6.6 –

1

其實,子不工作 - 但你沒有看到提示,因爲出來的子進程的標準正在由proc.communicate()抓獲。您可以通過輸入3個提示的值來確認,最終應該看到提示並回顯您的輸入。

只要刪除stdout=subprocess.PIPE(與stderr相同)並且子進程的stdout(stderr)將轉到終端。

或者有其他功能,將啓動一個子進程,並呼籲communicate()你,如subprocess.call()subprocess.check_call()