【发布时间】:2016-09-03 14:56:26
【问题描述】:
def run_cmd(self, cmd):
print cmd
status = os.system(cmd)
print 'Command ran with Status: %s' % status
if status:
s = 'Command Failed: Status: %s for %s' % (status, cmd)
print s
sys.exit(status)
else:
s = 'Command Success: %s' % cmd
return status
我正在使用此函数从另一个脚本运行 python 脚本。
例如:
command_to_exec = 'python script_b.py'
run_cmd(command_to_exec)
现在,如果 script_b.py 失败,则 script_a.py 会以状态退出。
没关系。
案例 2:
command_to_exec = 'python script_a.py --options'
rum_cmd(command_to_exec)
这个案例是 script_a.py 从自身运行'python script_a.py'。 在这种情况下,如果新生成的 script_a.py 失败,外部 script_a.py 仍然是成功的,因为它无法捕捉到内部 script_a.py 的失败(因为 sys.exit(status))
现在,我该如何处理这种情况? (如果内部 script_a 失败,外部 script_a 应该退出)
【问题讨论】:
-
你为什么要这样调用整个脚本?为什么不导入“内部”脚本或您需要的部分并运行它们?比如为什么不在“内部”脚本中调用函数?
-
您可以测试
sys.argv[0]以防止自己跑,这可能会导致可怕的分叉炸弹(不断产卵过程)。
标签: python python-2.7 command os.system