Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.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 Idle - Fatal编程技术网

Python 如果文件没有';不存在

Python 如果文件没有';不存在,python,python-idle,Python,Python Idle,我在Python 3.2.3中有以下脚本: try: file = open('file.txt', 'r') except IOError: print('There was an error opening the file!') sys.exit() #more code that is relevant only if the file exists 如果文件不存在(或者只是打开文件时出错),如何优雅地退出 我可以使用exit(),但这会打开一个对话框面板,询

我在Python 3.2.3中有以下脚本:

try:
    file = open('file.txt', 'r')
except IOError:
    print('There was an error opening the file!')
    sys.exit()

#more code that is relevant only if the file exists
如果文件不存在(或者只是打开文件时出错),如何优雅地退出

我可以使用
exit()
,但这会打开一个对话框面板,询问是否要终止应用程序

我可以使用
sys.exit()
,但这会引发一个SystemExit异常,它在输出中看起来不太好。我明白了

Traceback (most recent call last):   
File "file", line 19, in <module>
    sys.exit() SystemExit
回溯(最近一次呼叫最后一次):
文件“File”,第19行,在
sys.exit()系统退出
我可以使用
os.exit()
,但这会杀死C级别的Python,而不会执行任何清理

如果。。。但这很难看,而且这不是我执行的唯一检查。所以我想要六个嵌套的如果


我只想打印“有一个错误…”并退出。我在空闲中工作。

这是一种非常优雅的工作方式。SystemExit回溯将不会在IDLE之外打印。您可以选择使用
sys.exit(1)
向shell指示脚本因错误而终止

或者,您可以在“main”函数中执行此操作,并使用
return
终止应用程序:

def main():
    try:
        file = open('file.txt', 'r')
    except IOError:
        print('There was an error opening the file!')
        return

    # More code...

if __name__ == '__main__':
    main()
在这里,应用程序的主执行代码封装在一个名为“main”的函数中,然后仅当脚本由Python解释器直接执行,或者换句话说,如果脚本不是由另一个脚本导入时才执行。(如果直接从命令行执行脚本,
\uuuuuuuu name\uuuuu
变量设置为“\uuuuuu main\uuuuuu”。否则将设置为模块名称。)

这样做的好处是将所有脚本执行逻辑收集到一个函数中,使脚本更干净,并使您能够使用
return
语句干净地退出脚本,就像在大多数编译语言中一样。

使用sys.exit()可以。如果您非常关心输出,那么可以在错误处理部分中添加一个额外的try/except块来捕获SystemExit并阻止它被定向到控制台输出

try:
    file = open('file.txt', 'r')
except IOError:
    try:
        print('There was an error opening the file!')
        sys.exit()
    except SystemExit:
        #some code here that won't impact on anything

这看起来是正确的方法。通常,您不会看到
SystemExit
异常(除非您在其他可能不应该在的地方捕获它)。。。我不确定你在说什么,它在输出中看起来很好。你可以从当前函数中
返回
。引发你自己的异常,该异常在顶级被捕获,或者在需要清理的地方被捕获并重新捕获。(也就是说,你不需要太多显式的清理,因为展开堆栈对你没有好处。)更好的方法是调用
sys.exit()
并在顶层捕获
SystemExit
。(我自己没有看到SystemExit;您在什么环境下运行?@JakubZaverka-只需在空闲之外运行脚本,您就可以看到
sys.exit
不会显示
SystemExit
。IDLE这样做是为了让您知道程序是否异常完成或退出。我最终按照您的建议使用了main函数。然而,在调用main之前,我不理解if的用途。@JakubZaverka:我已经用一些关于“ifmain”方法的信息更新了答案。
IOError
是Python 3中的
OSError
的别名。该解决方案与
不起作用,除了SystemExit:
语句将忽略sys.exit()因此呼叫所需的出口。