2017-06-21 69 views
0

我必須通過python運行一個bash文件用於Django webapp項目,但我無法檢索bash文件的輸出(這是我真正需要的,因爲它需要顯示在網頁)。這裏是代碼:檢索從python子進程運行的bash文件的輸出

在我的Python文件

import subprocess 


output = subprocess.Popen(['bash', 'countingbash.sh', "hello", "world"]) 
print (output) 

在countingbash.sh:

#!/bin/sh 
file="[email protected]" 
for f in $file 
    do 
    echo "Argument is $f" 

done 

我需要捕捉的輸出,因爲它需要在網頁中顯示後面。如果我運行.py文件,我得到的輸出不是輸出應該通過運行bash文件。輸出看起來是這樣的:

<subprocess.Popen object at 0x102cab290> 

,而應該是:

Argument is hello 
Argument is world 

如果我單獨運行該文件,而無需編寫打印(輸出),編輯器顯示輸出,但我要如何拍攝的呢?

回答

1

此修改應該給你正確的輸出,我已經打開標準輸出管道,並轉換二進制string.I輸出的外殼使用了絕對路徑,以避免任何工作目錄的問題還有:

output = subprocess.Popen(['bash', '/home/demo/test.sh', "hello", "world"], stdout=subprocess.PIPE) 
print (output.communicate()[0].decode('ascii')) 
相關問題