我正在尝试使用子进程调用另一个本地脚本。
本地脚本将其结果打印到屏幕上。
本地
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.PIPE
和subprocess.check_output()
,但没有运气,也许有人可以给我一些更好的方向?
答案 0 :(得分:2)
由@shshank评论解决,这是解决方案:
proc = subprocess.Popen(['python', testRunner.tsPyFile, test], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutValue = proc.communicate()[0]
答案 1 :(得分:1)
我建议使用plumbum。它会让你的生活变得更加轻松。
from plumbum.cmd import python
stdout = python[testRunner.tsPyFile][test]()
答案 2 :(得分:1)
.communicate()
is the way从另一个可能失败的Python脚本中获取合并的stdout / stderr。但这里是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