python - 从另一个 Python 脚本运行 Python 脚本时处理异常

标签 python exception

我正在从另一个 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/

相关文章:

java - 这是使用 IllegalArgumentException 的正确方法吗?

java - 在 Java 中分割字符串并以随机顺序连接各部分

Java - java.lang.StringIndexOutOfBoundsException : String index out of range: 11

c# - 处理来自外部系统的结果代码查找——如果需要则抛出异常

php - 如何在 Python 中获取相同的 PHP adler32 哈希?

python - MongoEngine 用户认证(django)

python - 如何使用 burp 套件代理 HTTPS 流量?

python - 有没有办法用 PIL 来回退丢失的字形?

python - 如何使用 Pygame 裁剪图像?

java - 将 java 中的文件从本地 xml 文件解析为新文本文件时出现 ArrayOutOfBoundException