我有这个 python 代码:
import os
try:
os.system('wrongcommand')
except:
print("command does not work")
代码打印:
wrongcommand: command not found
代替命令不起作用
。有谁知道为什么它不打印我的错误消息?
最佳答案
如果你想在命令不存在时抛出异常,你应该使用subprocess
:
import subprocess
try:
subprocess.run(['wrongcommand'], check = True)
except subprocess.CalledProcessError:
print ('wrongcommand does not exist')
仔细想想,无论如何你应该使用 subprocess
而不是 os.system
...
关于Python try block 不捕获 os.system 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12373563/