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

时间:2019-06-11 17:55:00

标签: python exception

我正在从另一个python脚本运行一个python脚本,我想知道如何从父python脚本中捕获异常。

我的父python脚本调用n次了另一个python脚本。最终,被调用的脚本将退出并出现“ 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()

1 个答案:

答案 0 :(得分:1)

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(),输出将发送到终端,但是使用子进程,您可以收集输出,以便可以搜索错误消息或其他内容。或者,您可以只放弃输出。

同样的程序也可以使用子过程来完成;

# 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)

希望这会有所帮助:)

相关问题