Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 操作系统(“启动”)错误处理_Python_Python 3.x_Error Handling_Operating System - Fatal编程技术网

Python 操作系统(“启动”)错误处理

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检查目录或文件是否存在,如果存在,请将命

我正在使用os库请求输入文件名,当按下“打开”按钮时,它将打开键入的文件,这是可行的,但如果用户输入一个不存在的文件,它将抛出windows错误,并在shell中显示以下内容

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')