2017-06-21 46 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')) 
相关问题