python退出功能不起作用 [英] python quit function not working
问题描述
我在我的一个脚本中使用以下检查:
I am using the following check in one of my scripts:
if os.path.exists(FolderPath) == False:
print FolderPath, 'Path does not exist, ending script.'
quit()
if os.path.isfile(os.path.join(FolderPath,GILTS)) == False:
print os.path.join(FolderPath,GILTS), ' file does not exist, ending script.'
quit()
df_gilts = pd.read_csv(os.path.join(FolderPath,GILTS))
正好,当路径/文件不存在时,我得到以下打印结果:
Stangely enough, when the path/file doesn't exist, I obtain the following print:
IOError: File G:\On-shoring Project\mCPPI\Reconciliation Tool\Reconciliation Tool Project\3. Python\BootStrap\BBG\2017-07-16\RAW_gilts.csv does not exist
告诉我即使我添加了quit(),脚本仍在继续.谁能告诉我为什么?
Tells me that it's continuing on with the script even though I've added a quit(). Can anyone tell me why?
谢谢
推荐答案
Per the documentation, quit()
(like other functions added by the site
module) is intended only for interactive use.
因此,解决方案是双重的:
Thus, the solution is twofold:
-
检查是否
os.path.exists(os.path.join(FolderPath,GILTS))
,而不只是os.path.exists(FolderPath)
,以确保实际到达尝试退出解释器的代码.
Check whether
os.path.exists(os.path.join(FolderPath, GILTS))
, not justos.path.exists(FolderPath)
, to ensure that the code attempting to exit the interpreter is actually reached.
使用 sys.exit(1)
(当然,在模块头文件中的 import sys
之后),以指示错误的退出状态停止解释器从脚本开始.
Use sys.exit(1)
(after import sys
in your module header, of course) to halt the interpreter with an exit status indicating an error from a script.
也就是说,您可以考虑只使用异常处理:
That said, you might consider just using exception handling:
from __future__ import print_function
path = os.path.join(FolderPath, GILTS)
try:
df_gilts = pd.read_csv(path)
except IOError:
print('I/O error reading CSV at %s' % (path,), file=sys.stderr)
sys.exit(1)
这篇关于python退出功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!