【发布时间】:2015-06-22 14:39:57
【问题描述】:
我有一个代码工作流程,其中我从一个主脚本(级别 0)通过subprocess 调用另一个脚本。这个subprocess script(级别1)又调用另一个脚本作为subprocess。现在,从这个 2 级子进程脚本中,我想将一个变量的值返回到主脚本(0 级)。我已经尝试过Popen.communicate(),但我无法返回该值。我目前的代码是:
main_script.py
def func():
para = ['a','b']
result = subprocess.Popen([sys.executable,"first_subprocess.py"]+para,stdout=subprocess.PIPE)
result.wait()
return_code = result.returncode
out, err = sub_result.communicate()
if return_code == 1:
return return_code
else:
if out is not None:
print 'return value: ', out
if __name__ == '__main__':
func()
上面的脚本叫做first_subprocess.py,它有:
def some_func():
# some other code and multiple print statements
para = ['a','b']
result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE)
result.wait()
out, err = result.communicate()
return_code = sub_result.returncode
if return_code == 0:
return out
if __name__ == '__main__':
some_func()
second_subprocess.py 返回如下值:
def test():
# some other code and multiple print statements
val = 'time'
print 'returning value'
return val
if __name__ == '__main__':
test()
当我尝试上面的代码时,我将代码中的所有 print 语句作为输出而不是返回值。即使尝试print subprocess 中的变量值而不是返回它也不会达到目的,因为有多个打印语句。
在这种情况下如何返回变量值?
更新版本:
根据@Anthons 的建议,我修改了我的first_subprocess.py 脚本和main_script.py,如下所示:
first_subprocess.py:
def some_func():
try:
key = None
if not (key is None):
para = ['a','b']
result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE)
sub_result.wait()
out, err = sub_result.communicate()
return_code = sub_result.returncode
if return_code == 0:
for line in out.splitlines():
if not line.startswith('>>>'):
continue
print line
else:
sys.exit(0)
except:
return 1
Main_script.py:
if out is not None:
for line in out.splitlines():
if not line.startswith('>>>'):
continue
value = line.split(':',1)[1].lstrip()
print 'return value:',value`
当我在上面执行时,我在print value 命令中得到UnboundLocalError: local variable 'value' referenced before assignment。似乎如果我不执行 1 级脚本中的代码并执行 sys.exit() 那么主脚本中的 out 既不是空的也不是空的,但它有一些未定义的值,因此 value 变量没有得到初始化并抛出错误
【问题讨论】:
-
更新后的 first_subprocess.py 无法运行。也许您的缩进没有正确转移。像这样的一般
try:except隐藏了正在发生的所有错误,这是非常糟糕的风格。key = None在那里做什么? -
@Anthon 那是错误的。我已经更正了缩进。
key = None只是一个演示,显示代码将在不执行底层代码的情况下退出。我保留了try: except以捕捉可能出现的任何错误。上面的代码只是实际代码的一部分。我一直在尝试捕获我上面没有发布的其余代码
标签: python python-2.7 subprocess