我正在从另一个 python 脚本运行 python 脚本,我想知道如何从父 python 脚本捕获异常。
我的父 python 脚本调用另一个 python 脚本 n 次。最终,被调用的脚本将以“ValueError”异常退出。我想知道是否有办法让我的父 python 脚本注意到这一点然后停止执行。
这是基本代码:
import os
os.system('python other_script.py')
Run Code Online (Sandbox Code Playgroud)
我试过这样的事情无济于事:
import os
try:
os.system('python other_script.py')
except ValueError:
print("Caught ValueError!")
exit()
Run Code Online (Sandbox Code Playgroud)
和
import os
try:
os.system('python other_script.py')
except:
print("Caught Generic Exception!")
exit()
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
但是,我建议您使用 os.system() 的 subprocess 模块。它比 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)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)
归档时间: |
|
查看次数: |
1996 次 |
最近记录: |