2017-07-27 16 views
0

蟒蛇退出功能,我使用下面的检查在我的剧本之一没有工作

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的是,当该路径/文件不存在,我得到下面的打印:

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(),它仍然继续使用该脚本。谁能告诉我为什么?

由于

+3

你检查'FolderPath'存在,但随后访问'和'在结束FILTS' FolderPath' - 不完整路径存在吗? –

+1

'quit()'不是一个内置的Python函数。你有没有定义它? –

+3

@DanielRoseman是的它是 –

回答

5

the documentationquit()(如由site模块添加其他功能)仅用于交互使用。

因此,解决是双重的:

  • 检查是否os.path.exists(os.path.join(FolderPath, GILTS)),不仅仅是os.path.exists(FolderPath),以保证试图退出解释的代码实际上是达到了。

  • 使用sys.exit(1)(当然你的模块头文件中有import sys后)停止解释器,并退出状态,指示脚本出错。

这就是说,你可能会考虑只使用异常处理:

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) 
+0

感谢您的回答,但我仍然看到整个日志: “UserWarning:退出:使用'exit','quit'或Ctrl-D warn(”退出:使用'exit'退出”,或按Ctrl-d “stacklevel = 1)发生 例外,使用%TB看到完整回溯 SystemExit:1”。 在我的Spyder控制台返回。我正在寻找一种方式,以打印信息为结束,但将接受这个答案,并继续前进。 – naiminp

+0

啊!这就是Spyder(或者更普遍的说是IDE)。直接在交互式解释器上运行代码的用户将看不到SystemExit异常。 –