从python调用shell脚本

时间:2017-03-25 17:08:47

标签: python shell

我有一个调用shell scrips的python脚本,后者又调用一个名为iv4_console的.exe文件。我需要打印iv4_console的stdout以进行调试。我用过这个: 的Python:

import sys
import subprocess

var="rW015005000000"
proc = subprocess.Popen(["c.sh", var], shell=True, stdout=subprocess.PIPE)

output = ''
for line in iter(proc.stdout.readline, ""):
        print line
        output += line

外壳:

start_dir=$PWD
release=$1
echo Release inside shell: $release
echo Directory: $start_dir
cd $start_dir
cd ../../iv_system4/ports/visualC12/Debug
echo Debug dir: $PWD
./iv4_console.exe ../embedded/LUA/analysis/verbose-udp-toxml.lua ../../../../../logs/$release/VASP_DUN722_20160307_Krk_Krk_113048_092_1_$release.dvl &>../../../../FCW/ObjectDetectionTest/VASP_DUN722_20160307_Krk_Krk_113048_092_1_$release.xml
./iv4_console.exe ../embedded/LUA/analysis/verbose-udp-toxml.lua ../../../../../logs/$release/VASP_FL140_20170104_C60_Checkout_afterIC_162557_001_$release.dvl &>../../../../FCW/ObjectDetectionTest/VASP_FL140_20170104_C60_Checkout_afterIC_162557_001_$release.xml

exit

但这没有用,它什么都没打印。你觉得怎么样?

2 个答案:

答案 0 :(得分:0)

请参阅我的评论,最好的方法(i.m.o)只是使用python。

但是,在回答您的问题时,请尝试:

import sys
import subprocess

var="rW015005000000"
proc = subprocess.Popen(["/bin/bash", "/full/path/to/c.sh"], stdout=subprocess.PIPE) 
# Best to always avoid shell=True because of security vulnerabilities. 
proc.wait() # To make sure the shell script does not continue running indefinitely in the background 
output, errors = proc.communicate()

print(output.decode()) 
# Since subprocess.communicate() returns a bytes-string, you can use .decode() to print the actual output as a string. 

答案 1 :(得分:-1)

您可以使用

import subprocess
subprocess.call(['./c.sh'])

在python文件中调用shell脚本

import subprocess
import shlex

subprocess.call(shlex.split('./c.sh var'))