保存subprocess命令的错误信息 [英] Save error message of subprocess command

查看:503
本文介绍了保存subprocess命令的错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用子进程运行bash命令时,我可能遇到命令无效的情况。在这种情况下,bash会返回错误消息。我们如何抓住这个讯息?我想将此消息保存到日志文件。
以下是一个示例,我尝试在不存在的目录中列出文件。

  try:
subprocess.check_call([ls,/ home / non])
df = subprocess.Popen([ls,/ home / non],stdout = subprocess.PIPE)
输出,err = df.communicate()
#进程输出
除了异常作为错误:
打印错误
sys.exit(1)

Bash会打印ls:不能访问/ home / non:没有这样的文件或目录。如何获取此错误消息?除了行外的错误明显不同,它表示Command['ls','/ home / non']'返回非零退出状态2。

解决方案

您可以将stderr重定向到文件对象:



<$ p $从子进程PIPE,CalledProcessError,check_call,Popen

中打开(log.txt,w)作为f:
try:
check_call([ls,/ home / non],stderr = f)
df = Popen([ls,/ home / non],stdout = PIPE)
输出,err = df.communicate()
除了CalledProcessError作为e:
print(e)
exit(1)

输出到log.txt:

  ls:无法访问/ home /非:没有这样的文件或目录

如果你想要消息在除了:

  try:
check_call([ls,/ home / non])
df = Popen([ ls,/ home / non],stdout = PIPE)
输出,err = df.communicate()
除了CalledProcessError作为e:
print(e.message)

对于python 2.6, e.message 不行您可以使用与python 2.6相似的版本的python 2.7的 check_output

来自子进程的PIPE,CalledProcessError,Popen 

def check_output(* args,** kwargs):
process = Popen(stdout = PIPE,* args,** kwargs)
out,err = process.communicate()
ret = process.poll()
如果ret:
cmd = kwargs.get(args)
如果cmd为None:
cmd = args [0]
error = CalledProcessError(ret,cmd)
error.out = out
error.message = err
提高错误
退出

尝试:
out = check_output([ls,/ home],stderr = PIPE)
df = Popen([ ls,/ home / non],stdout = PIPE)
输出,err = df.communicate()
除了CalledProcessError作为e:
print(e.message)
else:
print(out)


When running bash command using subprocess, I might run into situation where the command is not valid. In this case, bash would return an error messsage. How can we catch this message? I would like to save this message to a log file. The following is an example, where I try to list files in a non-existed directory.

try:
    subprocess.check_call(["ls", "/home/non"]) 
    df = subprocess.Popen(["ls", "/home/non"], stdout=subprocess.PIPE)        
    output, err = df.communicate()
    # process outputs
except Exception as error:        
    print error
    sys.exit(1)

Bash would prints "ls: cannot access /home/non: No such file or directory". How can I get this error message? The error caught by the except line is clearly different, it says "Command '['ls', '/home/non']' returned non-zero exit status 2".

解决方案

You can redirect stderr to a file object:

from subprocess import PIPE, CalledProcessError, check_call, Popen

with open("log.txt", "w") as f:
    try:
        check_call(["ls", "/home/non"], stderr=f)
        df = Popen(["ls", "/home/non"], stdout=PIPE)
        output, err = df.communicate()
    except CalledProcessError as e:
        print(e)
        exit(1)

Output to log.txt:

ls: cannot access /home/non: No such file or directory

If you want the message in the except:

try:
    check_call(["ls", "/home/non"])
    df = Popen(["ls", "/home/non"], stdout=PIPE)
    output, err = df.communicate()
except CalledProcessError as e:
    print(e.message)

For python 2.6 the e.message won't work. You can use a similar version of python 2.7's check_output that will work with python 2.6:

from subprocess import PIPE, CalledProcessError, Popen

def check_output(*args, **kwargs):
    process = Popen(stdout=PIPE, *args, **kwargs)
    out, err = process.communicate()
    ret = process.poll()
    if ret:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = args[0]
        error = CalledProcessError(ret, cmd)
        error.out = out
        error.message = err
        raise error
    return out

try:
    out = check_output(["ls", "/home"], stderr=PIPE)
    df = Popen(["ls", "/home/non"], stdout=PIPE)
    output, err = df.communicate()
except CalledProcessError as e:
    print(e.message)
else:
    print(out)

这篇关于保存subprocess命令的错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆