我正在从另一个 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()
和
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)
希望这有帮助:)
关于python - 从另一个 Python 脚本运行 Python 脚本时处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56549300/