Python 3.3+:如何抑制子流程中的异常.Popen()



我有一个类,它有一些函数,基本上对数据进行输出检查,这个类的函数是使用子流程调用的。现在,如果输出检查失败,则子流程会有一个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异常。我实际上记录了所有的错误,所以我不想在命令提示符中显示任何内容,除非我手动打印它。我不太清楚该怎么办。

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

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

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

3.3版新增。文档

相关内容

最新更新