2013-11-28 39 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 
相關問題