簡體   English   中英

使用Python從Shell腳本中提取錯誤消息?

[英]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

  1. 首先,那么這是解決此類問題的正確方法嗎? 基本上,我想先打印start ,如果成功執行了外殼腳本,那么我想打印end 但是如果由於某種原因我的shell腳本沒有成功執行,那么我就不會打印出end
  2. 其次,通過這種方法,我無法看到我的echo語句從shell腳本在控制台上打印出來了嗎? 這是否意味着我的shell腳本正在執行,但未以某種方式在控制台上打印出來?
  3. 第三,是否有可能從shell腳本中提取錯誤消息,這意味着shell腳本失敗的原因是什么?

1.是的,看來您的代碼符合您的意圖。

2.正確。 因為您使用了stdout=subprocess.PIPEstderr=subprocess.PIPE ,所以您的bash腳本不會在控制台上看到任何輸出。 但是,當您調用communicate()時,stdout和stderr的輸出將捕獲到變量stdoutstderr的下一行。

3.是的,您已經做到了:只需檢查stderr變量的內容,它將保存您的Shell腳本打印的所有錯誤消息。

暫無
暫無

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

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