【问题标题】:python quit function not workingpython退出功能不起作用
【发布时间】:2017-07-27 14:53:40
【问题描述】:

我在我的一个脚本中使用以下检查:

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

奇怪的是,当路径/文件不存在时,我得到以下打印:

  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(),它仍在继续执行脚本。谁能告诉我为什么?

谢谢

【问题讨论】:

  • 您正在检查FolderPath 是否存在,但最后使用FILTS 访问FolderPath - 完整路径是否存在?
  • quit() 不是 Python 内置函数。你有没有在某个地方定义它?
  • @DanielRoseman 是的
  • quit() 由站点模块添加。它不应该用于脚本。请参阅文档:docs.python.org/3/library/constants.html?highlight=quit#quit。我会使用sys.exit()
  • 这个假设似乎是错误的。

标签: python exit


【解决方案1】:

根据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)

【讨论】:

  • 感谢您的回答,但我仍然看到整个日志:“用户警告:要退出:使用 'exit'、'quit' 或 Ctrl-D。警告(“退出:使用'exit', 'quit', or Ctrl-D.", stacklevel=1) 发生异常,使用 %tb 查看完整的回溯。 SystemExit: 1" 在我的 spyder 控制台中返回。我一直在寻找一种方法,让它以预期的打印消息结束,但会接受这个答案并继续前进。
  • 啊!这特别是一个 Spyder(或更一般地说,一个 IDE)的东西。直接在交互式解释器上运行代码的用户不会看到 SystemExit 异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多