Python 操作系统(“启动”)错误处理
我正在使用os库请求输入文件名,当按下“打开”按钮时,它将打开键入的文件,这是可行的,但如果用户输入一个不存在的文件,它将抛出windows错误,并在shell中显示以下内容Python 操作系统(“启动”)错误处理,python,python-3.x,error-handling,operating-system,Python,Python 3.x,Error Handling,Operating System,我正在使用os库请求输入文件名,当按下“打开”按钮时,它将打开键入的文件,这是可行的,但如果用户输入一个不存在的文件,它将抛出windows错误,并在shell中显示以下内容 The system cannot find the file ______. 有没有办法在没有Windows错误的情况下处理此问题?比如使用try-and-except语句 谢谢除了暂停您平台上的错误之外,我还将寻求一种独立于平台的解决方案。您可以使用os.path.exists检查目录或文件是否存在,如果存在,请将命
The system cannot find the file ______.
有没有办法在没有Windows错误的情况下处理此问题?比如使用try-and-except语句
谢谢除了暂停您平台上的错误之外,我还将寻求一种独立于平台的解决方案。您可以使用
os.path.exists
检查目录或文件是否存在,如果存在,请将命令传递到os.system
以打开文件:
if os.path.exists(path):
os.system(...)
else:
# file does not exist
...
我不建议使用
os.system
,这样会使应用程序的安全性变得脆弱。如果不使用system
,您可能需要使用子流程
模块
您可以调用os.path.isfile
检查该文件是否存在,也可以引发异常,如下所示:
if os.path.isfile('your_file'):
# If required, you can read your file's output through this way
output = subprocess.Popen(['./your_file'], stdout = subprocess.PIPE)
或者
查看子流程
模块的文档。检查操作系统
的返回值;如果有错误,它应该是非零的。谢谢你,你提供的第一个解决方案工作得很好。
try:
output = subprocess.Popen(['./your_file'], stdout = subprocess.PIPE)
except FileNotFoundError as e:
print('Oops, file not found')