簡體   English   中英

從Python腳本執行時如何檢查bash shell腳本的狀態?

[英]How to check the status of bash shell script while executing from Python script?

我有一個簡單的Python腳本,它將使用Python中的subprocess模塊執行Shell腳本。

下面是我的Python shell腳本,它正在調用testing.sh shell腳本,並且工作正常。

import os
import json
import subprocess

jsonData = '{"pp": [0,3,5,7,9]}'
jj = json.loads(jsonData)

os.putenv( 'jj3', ' '.join( str(v) for v in jj['pp']  ) )

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"
   print stderr
else:
   print stdout
   print "end" # Shell script ran fine.

下面是我的testing.sh shell腳本-

#!/bin/bash

dir1=some_directory
dir2=some_directory

length1=some_number
length2=some_number

if [ "$dir1" = "$dir2" ] && [ "$length1" -gt 0 ] && [ "$length2" -gt 0 ]
then
    for el in $jj3
    do
        scp david@machineB:/data/be_t1_snapshot/20131215/t1_"$el"_5.data /data01/primary/. || scp david@machineC:/data/be_t1_snapshot/20131215/t1_"$el"_5.data /data01/primary/.
    done        
fi

我上面的shell腳本所做的是,它將文件從machineBmachineC復制到machineA 如果文件不在machineB則應該始終在machineC 因此它將嘗試將文件從machineB復制到machineA但是如果文件不在machineB則它將嘗試將文件從machineC復制到machineA

現在,我上面的Python腳本(我正在從machineA運行)試圖執行我上面的shell腳本,並查看我的腳本是否成功執行。 當我存儲shell腳本和stdoutstderr時。

問題陳述:-

通過上述方法,我看到了一個問題。 如前所述,如果machineB中沒有文件,則它將嘗試將文件從machineC復制到machineA 因此,每當我運行調用我的Shell腳本的Python腳本時,發生的是, machineB中不存在某些文件,因此它引發了一些異常,然后嘗試從machineC復制文件,但是當調用返回到Python腳本時,它將if stderr:塊總是進入內部if stderr:因為從machineB復制文件時出現了錯誤(這不是我想要的),並且end print語句沒有被打印出來。

所以問題是,如果machineB中沒有文件,它將嘗試從machineC復制文件,如果文件存在machineC並成功復制到machineA而沒有任何錯誤,那么我想將其稱為success而不是failure 在當前情況下發生了什么,如果文件是不是有machineB並得到了來自成功復制machineC那么它仍然算作是失敗, end打印語句不被打印出來。

我還想查看從Python執行時我的shell腳本是否有問題。 如果是,那么我不想打印end聲明。

我應該如何克服這個問題?

更新:-

下面的shell腳本會發生什么? 因為第一個for循環將失敗,因為david不是linux命令,但是我的scp命令可以正常工作。 所以我仍然會看到狀態碼不等於0嗎?

for i in $( david ); do
    echo item: $i
done

dir1=some_directory
dir2=some_directory

length1=some_number
length2=some_number

if [ "$dir1" = "$dir2" ] && [ "$length1" -gt 0 ] && [ "$length2" -gt 0 ]
then
    for el in $jj3
    do
        scp david@machineB:/data/be_t1_snapshot/20131215/t1_"$el"_5.data /data01/primary/. || scp david@machineC:/data/be_t1_snapshot/20131215/t1_"$el"_5.data /data01/primary/.
    done        
fi

正常工作的進程仍然可以寫入stderr ,因此使用if stderr:來檢查問題if stderr:

相反,您應該檢查進程退出代碼。 如果不等於零,則出現錯誤,例如:

[...]
if proc.returncode != 0:
    print "Shell script gave some error"
[...]

暫無
暫無

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

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