如果只想返回整数值,可以使用退出值。这与从some_func()返回不同,您必须执行sys.exit(integer_val)。在
如果您想返回一个类似time的字符串,您应该打印该字符串(或写入sys.stdout),然后在调用进程(级别1)中解析子进程的输出,并将其打印到自己的stdout中,以供级别0查看。在
在您的案例中,第二级应该执行以下操作:def test():
# some other code and multiple print statements
val = 'time'
print 'returning value:', val
if __name__ == '__main__':
test()
在第1级,你可以:
^{2}$
用那个主管道_脚本.py有一些内容可以从调用1级脚本中读取。在
我通常使用subprocess.check_output()来传递这些信息。如果被调用的进程具有非零退出状态(即出错时),则会引发异常。我还可以建议,如果子进程写入的信息不仅仅是变量,那么可以通过在行的开头返回一些唯一的内容来使输出行易于解析(这样您仍然可以使用print语句调试各个脚本和从输出中获取正确的值):
二级:def test():
# some other code and multiple print statements
print 'debug: Still going strong'
val = 'time'
print '>>>> returning value:', val
if __name__ == '__main__':
test()
1级:...
out, err = result.communicate()
for line in out.splitlines():
if not line.startswith('>>>>'):
continue
print line
...
0级:...
out, err = result.communicate()
for line in out.splitlines():
if not line.startswith('>>>>'):
continue
try:
value = line.split(':', 1)[1]
except IndexError:
print 'wrong input line', repr(line)
print 'return value: ', value
...
以下文件一起工作。以指定的名称保存它们
强# lvl2
import sys
def test():
# some other code and multiple print statements
print >> sys.stderr, 'argv', sys.argv[1:]
print 'debug: Still going strong'
val = 'time'
print '>>>> returning value:', val
return 0
if __name__ == '__main__':
sys.exit(test())
l1.py级:# lvl1.py
import sys
import subprocess
def some_func():
para = ['a','b']
sub_result = subprocess.Popen(
[sys.executable, "lvl2.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:
print >> sys.stderr, 'level 2 exited with' + return_code
sys.exit(0)
if __name__ == '__main__':
sys.exit(some_func())
lvl0.py:# lvl0
import subprocess
import sys
def func():
para = ['a','b']
result = subprocess.Popen(
[sys.executable, "lvl1.py"] + para,
stdout=subprocess.PIPE)
result.wait()
return_code = result.returncode
out, err = result.communicate()
value = None
if return_code == 0:
for line in out.splitlines():
if not line.startswith('>>>'):
continue
value = line.split(':',1)[1].lstrip()
else:
print 'non-zero exit', return_code
print 'return value:', value
if __name__ == '__main__':
func()
{要运行的输出^然后检查}argv ['a', 'b']
return value: time
现在把它们放在你的修订控制系统下,一次修改几行,每次运行python lvl0.py来检查你可能破坏了什么。提交每个修订,这样您就可以回滚到上一个“已知良好”状态,并慢慢引入其余代码。在