我正在从另一个 python 脚本运行一个 python 脚本,我想知道如何从父 python 脚本中捕获异常。
我的父 python 脚本调用另一个 python 脚本 n 次。最终,被调用的脚本将退出并出现“ValueError”异常。我想知道是否有办法让我的父 python 脚本注意到这一点然后停止执行。
这是基本代码:
import os
os.system('python other_script.py')
我尝试过诸如此类的事情但无济于事:
import os
try:
os.system('python other_script.py')
except ValueError:
print("Caught ValueError!")
exit()
and
import os
try:
os.system('python other_script.py')
except:
print("Caught Generic Exception!")
exit()
os.system() 始终返回整数结果代码。和,
当返回0时,说明命令运行成功;
当它返回非零值时,表明发生错误。
为了检查您是否可以简单地添加一个条件,
import os
result = os.system('python other_script.py')
if 0 == result:
print(" Command executed successfully")
else:
print(" Command didn't executed successfully")
但是,我建议您使用 os.system() 的子进程模块。它比 os.system() 有点复杂,但比 os.system() 更灵活。
使用 os.system() ,输出会发送到终端,但使用 subprocess,您可以收集输出,以便在其中搜索错误消息或其他内容。或者您可以直接丢弃输出。
同样的程序也可以使用子进程来完成;
# Importing subprocess
import subprocess
# Your command
cmd = "python other_script.py"
# Starting process
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE.PIPE)
# Getting the output and errors of the program
stdout, stderr = process.communicate()
# Printing the errors
print(stderr)
希望这可以帮助 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)