簡體   English   中英

從python調用Shell腳本

[英]Calling a shell script from python

我有一個Python腳本,它調用外殼腳本,然后又調用一個名為iv4_console的.exe。 我需要打印iv4_console的標准輸出以進行調試。 我用了這個: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

但這不起作用,它什么也不打印。 你怎么看?

看到我的評論,最好的方法(imo)是僅使用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. 

您可以使用

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

調用python文件中的shell腳本

要么

import subprocess
import shlex

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM