【问题标题】:Extract the error message from the shell script using Python?使用 Python 从 shell 脚本中提取错误消息?
【发布时间】:2013-12-27 06:33:23
【问题描述】:

我有一个简单的 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,如果shell脚本得到了 执行成功,然后我想打印end。但如果为 不管什么原因,我的shell脚本没有成功执行, 那么我不会打印出end
  2. 其次,使用这种方法,我看不到我的 echo 语句从 shell 脚本打印到控制台上?这是否意味着,我的 shell 脚本正在执行,但它没有以某种方式在控制台上打印出来?
  3. 第三,是否有可能从 shell 脚本中提取错误消息,这意味着 shell 脚本失败的原因是什么?

【问题讨论】:

  • 1.因为您在else 子句中打印"end"。 2. 因为您将 shell 脚本的 stderr 和 stdout 通过管道传输到您的脚本,所以它们现在位于您的变量 stderrstdout 中。如果您想在控制台上看到它们,请从您的 Python 脚本中打印它们。 3. 从变量stderr中提取任何错误消息。
  • 也就是说,我的 shell 脚本正在执行,所有输出结果都存储在 stdout 中,而 stderr 中出现错误?
  • 没错。您可能必须将shell=True 作为关键字参数传递,或者使用['/bin/bash', 'testing.sh'] 调用您的脚本。
  • @LukasGraf:感谢您的建议。以及为什么你建议你使用 shell=True 并像这样调用我的脚本['/bin/bash', 'testing.sh']。这样做有什么好处吗?我可以像在上面的问题中那样执行 shell 脚本。
  • 因为我很确定解释#!/bin/bash shebang 是shell 执行脚本的功能。我实际上不知道为什么它在没有 shell=True 或以脚本作为参数调用解释器二进制文件的情况下工作。

标签: python bash shell subprocess


【解决方案1】:

1.是的,您的代码似乎符合您的意图。

2. 正确。因为您使用了stdout=subprocess.PIPEstderr=subprocess.PIPE,所以您不会在控制台上看到 bash 脚本的输出。但是,当您调用 communicate() 时,将在变量 stdoutstderr 的下一行捕获到 stdout 和 stderr 的输出。

3.是的,您已经做到了:只需检查您的 stderr 变量的内容,它将包含您的 shell 脚本打印的所有错误消息。

【讨论】:

    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2019-05-11
    • 2018-06-14
    • 2020-12-06
    • 1970-01-01
    • 2018-06-29
    相关资源
    最近更新 更多