[英]Extract the error message from the shell script using Python?
我有一個簡單的Python腳本,它將使用Python中的subprocess
進程mdoule執行shell腳本。
下面是我的Python shell腳本,它正在調用testing.sh
shell腳本,並且工作正常。
import os
import json
import subprocess
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
jj = json.loads(jsonData)
print jj['pp']
print jj['sp']
os.putenv( 'jj1', 'Hello World 1')
os.putenv( 'jj2', 'Hello World 2')
os.putenv( 'jj3', ' '.join( str(v) for v in jj['pp'] ) )
os.putenv( 'jj4', ' '.join( str(v) for v in jj['sp'] ) )
print "start"
proc = subprocess.Popen('testing.sh', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if stderr:
print "Shell script gave some error"
else:
print "end" # Shell script ran fine.
下面是我的testing.sh
shell腳本-
#!/bin/bash
for el1 in $jj3
do
echo "$el1"
done
for el2 in $jj4
do
echo "$el2"
done
for i in $( david ); do
echo item: $i
done
現在我的問題是-
如果您看到我的Python腳本,則我先打印出start
,然后執行我的Shell腳本,如果執行我的Shell腳本時出現任何錯誤,則不會打印出end
。 在上面的示例中,由於出現錯誤,因此不會打印出end
。
start
,如果成功執行了外殼腳本,那么我想打印end
。 但是如果由於某種原因我的shell腳本沒有成功執行,那么我就不會打印出end
。 1.是的,看來您的代碼符合您的意圖。
2.正確。 因為您使用了stdout=subprocess.PIPE
和stderr=subprocess.PIPE
,所以您的bash腳本不會在控制台上看到任何輸出。 但是,當您調用communicate()
時,stdout和stderr的輸出將捕獲到變量stdout
和stderr
的下一行。
3.是的,您已經做到了:只需檢查stderr
變量的內容,它將保存您的Shell腳本打印的所有錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.