繁体   English   中英

如何使用Python中的子进程模块检查Shell脚本的状态?

[英]How to check the status of a shell script using subprocess module in 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"
subprocess.call(['./testing.sh'])
print "end"

下面是我的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脚本,然后再打印end ..因此,无论出于何种原因,假设我正在执行的shell脚本有任何问题,那么我就不想打印出end

因此,在以上示例中,shell脚本将无法正常运行,因为david不是linux命令,因此它将引发错误。 因此,我应该如何查看整个bash shell脚本的状态,然后决定是否需要end打印?

我刚刚添加了一个for循环示例,它可以是任何shell脚本。

有可能吗?

只需使用call()返回的值即可:

import subprocess

rc = subprocess.call("true")
assert rc == 0 # zero exit status means success
rc = subprocess.call("false")
assert rc != 0 # non-zero means failure

如果命令失败,则可以使用check_call()自动引发异常,而不是手动检查返回的代码:

rc = subprocess.check_call("true") # <-- no exception
assert rc == 0

try:
    subprocess.check_call("false") # raises an exception
except subprocess.CalledProcessError as e:
    assert e.returncode == 1
else:
    assert 0, "never happens"

好吧,根据文档 ,.call将把退出代码返回给您。 但是,您可能需要检查您是否确实收到错误返回码。 (我认为for循环或多或少已经完成,仍然会返回0代码。)

您可以检查bash脚本的stderr而不是返回代码。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM