本文介绍了Python try 块不捕获 os.system 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个python代码:
I have this python code:
import os
try:
os.system('wrongcommand')
except:
print("command does not work")
代码打印:
wrongcommand: command not found
代替命令不起作用
.有谁知道为什么它不打印我的错误消息?
Instead of command does not work
. Does anyone know why it's not printing my error message?
推荐答案
如果你想在命令不存在时抛出异常,你应该使用subprocess
:
If you want to have an exception thrown when the command doesn't exist, you should use subprocess
:
import subprocess
try:
subprocess.run(['wrongcommand'], check = True)
except subprocess.CalledProcessError:
print ('wrongcommand does not exist')
想想看,无论如何你应该使用 subprocess
而不是 os.system
...
Come to think of it, you should probably use subprocess
instead of os.system
anyway ...
这篇关于Python try 块不捕获 os.system 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!