使用 python 获得 Shell 输出

Get Shell Output with python

$ jsonlint -cq /home/test/notokay1.json

上面的命令有退出值 1 和下面的输出

/home/notokay1.json:第 6 行,第 1 栏,发现:'EOF' - 预期:'}'、','。

如何在 Python.

中捕获两者

我相信这就是您要找的:

$ jsonlint -cq /home/test/notokay1.json > stdout.txt; echo $? > stderr.txt

然后您可以使用 python's built in file I/O 阅读 stdout.txt 和 stderr.txt

参考:http://www.tldp.org/LDP/abs/html/io-redirection.html

使用subprocess.Popen:

import subprocess

p = subprocess.Popen('jsonlint -cq /home/test/notokay1.json'.split(),
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
out, err = p.communicate()

print "Standard Output:", out
print "Standard Error Output:", err
print "Return Code:", p.returncode

您可以使用subprocess module, more specifically the check_output方法。

假设您有一个名为 test.bash 的文件,其中包含以下内容:

echo "Hi"
exit 1

要捕获退出代码和输出,您可以这样做:

# test.py file
import subprocess

exitCode = 0
output = ""
try:
    output = subprocess.check_output(["bash", "test.bash"]) # get only ouput
except subprocess.CalledProcessError as e:
    # get output and exit code
    exitCode = e.returncode
    output = e.output

print(output, exitCode)

输出:

bash-4.2$ python test.py 
('Hi\n', 1)

您只需要根据您的问题进行调整即可。