Python try块不会捕获os.system异常
作者:互联网
我有这个python代码:
import os
try:
os.system('wrongcommand')
except:
print("command does not work")
代码打印:
wrongcommand: command not found
而不是命令不起作用.有谁知道为什么它不打印我的错误信息?
解决方法:
如果要在命令不存在时抛出异常,则应使用子进程:
import subprocess
try:
subprocess.call(['wrongcommand'])
except OSError:
print ('wrongcommand does not exist')
想想看,你应该使用subprocess而不是os.system …
标签:except,os-system,python,try-catch 来源: https://codeday.me/bug/20191006/1860134.html