python3.3+:如何在子流程.Popen()?

2024-09-27 04:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,它的一些函数基本上对数据进行输出检查,这个类的函数是用子进程调用的。 现在,如果输出检查失败,子进程将有一个系统出口根据失败的检查使用不同的代码调用。在

在主代码中我有这样的:

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

现在,该文件的输出显示了系统出口在子流程中调用。 我实际上记录所有的错误,所以我不想任何东西显示在命令提示符,除非我手动打印它。 我不太清楚该怎么办。在


Tags: thetestoutputifosexceptionfsmyenv
1条回答
网友
1楼 · 发布于 2024-09-27 04:28:52

可以使用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

相关问题 更多 >

    热门问题