2013-11-28 41 views
1

我想使用子进程调用另一个本地脚本。调用另一个python脚本的main()并获取STDOUT结果

本地脚本将其结果打印到屏幕上。

地方:

def main(): 
    """ 
     main function 
     controls the method call, the method is decided by TS runner 
    """ 

    sParams = ScriptParamHandler() 
    paramsList = ['TestName'] # ordered list of parameters 
    paramsDict = sParams.AnalyzeParametersForScript(paramsList) 

    mainReturn = None 

    with ProductXXXXX() as testSequence: 

     testSequence.testFixture.InitDevices() 

     func = getattr(testSequence, paramsDict['TestName']) 

     returnVal = func() 

     print paramsDict['TestName'], "\n", returnVal, "\n" 

if __name__ == "__main__": 
    main() 

来电脚本:

with BasicRunner(testSet, testSetLocation, paramsDict['ProfileName']) as testRunner: 

    if testRunner.CheckFolderAndFile(): 

     testRunner.GetProfile() 

     for test in testRunner.testList: 

      testRunner.logger.Info("Test {} started...".format(test)) 

      testResult = subprocess.call(testRunner.tsPyFile + " " + test, shell=True) 

      testRunner.logger.Info("Test {} result {}".format(test, testResult)) 

    else: 

     pass 

我想主叫脚本testResult是当地脚本stout

我试过stdout=subprocess.PIPEsubprocess.check_output()但没有运气,也许有人能给我一些更好的方向?

+2

你尝试testResult.communicate(),而不是subprocess.check_output()? (使用stdout = subprocess.PIPE of course) – shshank

+0

当脚本在同一个python进程中运行时,您也可以重定向stdout。虽然[如果子脚本生成非Python输出(比如来自外部子进程,C扩展库等的输出)] [更复杂](https://gist.github.com/zed/991e006c822740aa6896#file-parent-py)。 – jfs

回答

2

通过@shshank评论解决,这是解决方案:

proc = subprocess.Popen(['python', testRunner.tsPyFile, test], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
stdoutValue = proc.communicate()[0] 
+1

正如我在[我的回答](http://stackoverflow.com/a/20278271/4279)中提到的,如果已知儿童脚本,“.communicate()”比“check_output()可能会失败。你应该接受你自己的答案。 – jfs

1

我推荐使用plumbum。它会让你的生活变得如此简单。

from plumbum.cmd import python 
stdout = python[testRunner.tsPyFile][test]() 
+0

+1不错的选择,不知道。 –

1

.communicate() is the way要获取其它Python脚本可能会失败合并标准输出/标准错误。但这里的check_output()变种,只是为了显示它是如何做到:

import sys 
from subprocess import check_output, STDOUT, CalledProcessError 

try: 
    stdout_value = check_output(
     [sys.executable or 'python', testRunner.tsPyFile, test], stderr=STDOUT) 
except CalledProcessError as e: 
    stdout_value = e.output 
相关问题