Python3 (os.system) 中的错误处理
Error Handling in Python3 (os.system)
在 Python 中,我从主 python 文件中调用子文件。
在所有子 python 文件中,我都包含了 try 和 except 块。
在主文件中,我需要按照下面提到的顺序执行子文件。
如果在 os.system("python SubFile1.py")
语句中发现任何错误,有没有办法停止执行 os.system("python SubFile2.py")
语句?
而且我还需要在主 python 文件中获取错误详细信息。
这是主文件的代码片段:
import os
import sys
print("start here")
try:
print('inside try')
os.system("python SubFile1.py")
os.system("python SubFile2.py")
os.system("python SubFile4.py")
except:
print("Unexpected error:")
print(sys.exc_info()[0])
print(sys.exc_info()[1])
print(sys.exc_info()[2])
finally:
print('finally ended')
提前致谢
你应该考虑使用[subprocess][1]
如果你想捕获异常并结束另一个进程,不建议使用os.system
,因为os.system()
表示通过退出代码失败方法。有关更多详细信息,您应该考虑阅读此答案:Python try block does not catch os.system exceptions
对于您的解决方法,您可以尝试这段有效的代码,但我使用的是子流程。
import os
import sys
import subprocess
print("start here")
files = ["first.py", "second.py"]
count=0
for file in files:
try:
cmd = subprocess.Popen(["python", file],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output, error = cmd.communicate()
if(error):
print(error)
sys.exit()
except OSError as e:
print("inside exception", e)
sys.exit()
count+=1
在 Python 中,我从主 python 文件中调用子文件。
在所有子 python 文件中,我都包含了 try 和 except 块。
在主文件中,我需要按照下面提到的顺序执行子文件。
如果在 os.system("python SubFile1.py")
语句中发现任何错误,有没有办法停止执行 os.system("python SubFile2.py")
语句?
而且我还需要在主 python 文件中获取错误详细信息。
这是主文件的代码片段:
import os
import sys
print("start here")
try:
print('inside try')
os.system("python SubFile1.py")
os.system("python SubFile2.py")
os.system("python SubFile4.py")
except:
print("Unexpected error:")
print(sys.exc_info()[0])
print(sys.exc_info()[1])
print(sys.exc_info()[2])
finally:
print('finally ended')
提前致谢
你应该考虑使用[subprocess][1]
如果你想捕获异常并结束另一个进程,不建议使用os.system
,因为os.system()
表示通过退出代码失败方法。有关更多详细信息,您应该考虑阅读此答案:Python try block does not catch os.system exceptions
对于您的解决方法,您可以尝试这段有效的代码,但我使用的是子流程。
import os
import sys
import subprocess
print("start here")
files = ["first.py", "second.py"]
count=0
for file in files:
try:
cmd = subprocess.Popen(["python", file],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output, error = cmd.communicate()
if(error):
print(error)
sys.exit()
except OSError as e:
print("inside exception", e)
sys.exit()
count+=1