gpt4 book ai didi

Python 3.3+ : How to suppress exceptions in subprocess. Popen()?

转载 作者:行者123 更新时间:2023-12-01 08:44:05 25 4
gpt4 key购买 nike

我有一个类,其中包含一些函数,这些函数基本上对数据进行输出检查,此类的函数是使用子进程调用的。现在,如果输出检查失败,子进程将进行 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)

subprocess.DEVNULL Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used.

New in version 3.3. docs

关于Python 3.3+ : How to suppress exceptions in subprocess. Popen()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com