Python 3.6.6 Popen,在子进程中使用sys.exit,如何抑制回溯/异常

时间:2018-11-19 12:45:11

标签: python subprocess

我有一个带有一些功能的类,这些功能基本上对数据进行输出检查,该类的功能使用子过程调用。 现在,如果输出检查失败,则子进程将调用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异常。 我实际上记录了所有错误,因此除非我手动打印它,否则我不希望在命令提示符下显示任何内容。 我不太确定该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以使用library(ggplot2) gg <- ggplot(X, aes(x = XX, y = XY)) + geom_point(col = "steelblue", size = 3) + geom_smooth(method = "lm", col = "firebrick", se = FALSE) + labs(title = "XX vs XY", subtitle = "X", y = "XX", x = "XY") + scale_x_continuous(breaks = seq(76, 82, 1)) + scale_y_continuous(breaks = seq(15, 19, 1)) library(ggrepel) gg + geom_text_repel(aes(label = Female), size = 3, data = X) gg + geom_label_repel(aes(label = Female), size = 2, data = X) 标志指定stderr写入os.devnull

subprocess.DEVNULL

  

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

     

3.3版中的新功能。 docs