【问题标题】:How to do error handling with subprocess pipes如何使用子进程管道进行错误处理
【发布时间】:2019-06-10 21:30:59
【问题描述】:

似乎我无法访问 process.stdout 两次。但我不知道如何解决它。我正在尝试捕获我的命令导致的任何 git 错误,并捕获任何有用的输出。

如果输出错误或不存在,我想知道它,因此我最终不会尝试修改不存在或无意义的变量。

但是,通过探测输出是否有错误,我似乎失去了捕获有意义输出的能力。

有没有更好的方法来满足这两种情况?

到目前为止,我刚刚尝试了这两种排列方式。但是当我首先检查有效性时,我似乎无法访问输出以对其进行任何操作。但是,如果我尝试在没有验证的情况下使用它,我就会失去错误处理。

def gitinfo(sha1, placeholder, repoDir = '/mnt/d/stash.projects/rea'):
    placeholders = {'hash':'%H', 'comment':'%s', 'time':'%cd', 'newline':'%n'}

    if placeholder not in placeholders:
        print('Error: function gitinfo is not programmed for paceholder: ' + placeholder)
        print('Please see source, or try \'hash\', \'comment\', \'time\', or \'newline\'.')
        return 'Good day.'

    format_option = '--format="' + str(placeholders[placeholder.lower()]) + '"'
    date_format = '%Y-%m-%d %H:%M:%S'
    date_option = '--date=format:\'' + date_format + '\''
    cmd = ['git', 'show', format_option, date_option, '-s', sha1]

    with subprocess.Popen(cmd, cwd=repoDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) as proc:

        if not proc.stdout.read():
            warn(proc.stderr.read())
            return 'Error retrieving ' + placeholder + ' in function gitinfo.'


        for line in proc.stdout:
            result = line.rstrip('\n')


    if placeholder.lower() == 'time':
        result = result.replace("'", "")

    return result

【问题讨论】:

    标签: python-3.x error-handling subprocess


    【解决方案1】:

    stdoutstderr 不是字符串,它们是流。将它们想象成水箱的一种方式是:该过程是将水倒入顶部,底部有一个水龙头可以使用。 stdout.read() 说“打开水龙头,让它运行,直到水箱里没有水为止”——如果你没有在水龙头下放一个桶(在这个类比中分配给一个变量),水就没有了,而且再次从空水箱中打开水龙头不会把它带回来。

    如果您需要多次访问流中的相同输出,则必须将其存储在一个变量中,然后每次都引用该变量。在您的情况下,您可以执行以下操作:

    output = proc.stdout.read()
    if not output:
        # your error handling here
    for line in output.split("\n"):
        # do stuff with line here
    

    【讨论】:

    • 忘记回复了,谢谢您的回答。我想我知道它就像一条溪流……但我没有把这些点联系起来。这是完美的。
    猜你喜欢
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2019-03-13
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多