【问题标题】:Python 3.3+: How to suppress exceptions in subprocess.Popen()?Python 3.3+:如何抑制 subprocess.Popen() 中的异常?
【发布时间】:2018-11-19 12:45:10
【问题描述】:

我有一个类,其中包含一些基本上对数据进行输出检查的函数,这个类的函数是使用子进程调用的。 现在,如果输出检查失败,子进程会有一个 sys.exit 调用,其中包含不同的代码,具体取决于它失败的检查。

在主代码中我有这个:

try:
    exitCode = 0
    #import module for current test
    teststr = os.path.splitext(test)[0]
    os.chdir(fs.scriptFolder)
    test = __import__(teststr)
    #delete old output folder and create a new one
    if  os.path.isdir(fs.outputFolder):
        rmtree(fs.outputFolder)
    os.mkdir(fs.outputFolder)
    # run the test passed into the function as a new subprocess
    os.chdir(fs.pythonFolder)
    myEnv=os.environ.copy()
    myEnv["x"] = "ON"
    testSubprocess = Popen(['python', test.testInfo.network + '.py', teststr], env=myEnv)
    testSubprocess.wait()
    result = addFields(test)
    # poke the data into the postgresql database if the network ran successfully 
    if testSubprocess.returncode == 0:
        uploadToPerfDatabase(result)     
    elif testSubprocess.returncode == 1:
        raise Exception("Incorrect total number of rows on output, expected: " + str(test.testInfo.outputValidationProps['TotalRowCount']))
        exitCode = 1
    elif testSubprocess.returncode == 2:
        raise Exception("Incorrect number of columns on output, expected: " + str(test.testInfo.outputValidationProps['ColumnCount']))
        exitCode = 1
except Exception as e:
    log.out(teststr + " failed", True)
    log.out(str(e))
    log.out(traceback.format_exc())
    exitCode = 1 
return exitCode

现在,此输出显示子进程中 sys.exit 调用的所有回溯和 python 异常。 我实际上记录了所有错误,所以我不希望在命令提示符中显示任何内容,除非我手动打印它。 我不太确定该怎么做。

【问题讨论】:

    标签: python python-3.x exception subprocess popen


    【解决方案1】:

    您可以使用subprocess.DEVNULL 标志指定stderr 写入os.devnull

    p = Popen(['python', '-c', 'print(1/0)'], stderr=subprocess.DEVNULL)

    subprocess.DEVNULL 可用作 Popen 的 stdin、stdout 或 stderr 参数的特殊值,表示将使用特殊文件 os.devnull。

    3.3 版中的新功能。 docs

    【讨论】:

    • 谢谢,我必须浏览一下文档中的那个标志,这对大多数输出​​来说都是一种魅力。我得到了我所期望的:Caused by: Python exception: 2 File "C:\x\performance_branch\python\outputValidation.py", Line 31, in onEnd sys.exit(2)
    • @Methodicle 这就是你得到的全部?没有提及究竟是什么异常以及导致by: Python exception...的原因是什么?
    • 在我的日志记录中没有,我得到了由事实输出不正确引起的完整详细信息,因此运行终止,但在提示中它只是显示现在可能会尝试抑制它都包含在 .log 文件中。
    • @Methodicle 哦,对不起,我忽略了“我所期望的”,并认为你有一个持续存在的问题 :)
    • 别担心!非常感谢对 python 相当新的帮助和快速响应,所以他们的一些内容让我明白了:D
    猜你喜欢
    • 2011-04-19
    • 2019-12-03
    • 1970-01-01
    • 2012-04-22
    • 2011-10-28
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多