为什么使用readline.read_history_file时会出现“IOError: [Errno 2] No such file or directory”的错误?

3

我的Python历史记录文件位于~/.pyhistory,并包含以下内容:

from project.stuff import *
quit()
from project.stuff import *
my_thing = Thing.objects.get(id=21025)
my_thing
my_thing.child_set.all()
my_thing.current_state
my_thing.summary_set
my_thing.summary_set.all()
[ x.type for x in my_thing.child_set.all() ]
[ x.type for x in my_thing.child_set.all().order_by( 'datesubmitted' ) ]
quit()

我正在使用virtualenv和virtualenvwrapper创建虚拟环境。今天我遇到了readline无法读取我的历史文件的问题:

>>> historyPath
'/Users/johndoe/.pyhistory'
>>> readline.read_history_file(historyPath)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory

该文件对我来说可以读写:
[johndoe@here]# ls -l ~/.pyhistory
-rw-------  1 johndoe  somegroup  325 21 Sep  2012 /Users/johndoe/.pyhistory

什么可能导致这个问题?
1个回答

23

您的历史记录文件似乎是旧版本。尝试将其转换为后续版本 readline 预期的格式,最重要的是第一行应该是 '_HiStOrY_V2_' ,并且所有空格应替换为 '\040':

_HiStOrY_V2_
from\040project.stuff\040import\040*
quit()
from\040project.stuff\040import\040*
my_thing\040=\040Thing.objects.get(id=21025)
my_thing
my_thing.child_set.all()
my_thing.current_state
my_thing.summary_set
my_thing.summary_set.all()
[\040x.type\040for\040x\040in\040my_thing.child_set.all()\040]
[\040x.type\040for\040x\040in\040my_thing.child_set.all().order_by(\040'datesubmitted'\040)\040]
quit()

我不确定这是底层readline/libedit库还是Python readline模块的怪癖,但这就是对我有效的方法。


在升级到Mavericks操作系统后,我遇到了这个问题。readline版本可能已经更新或者发生了什么变化。谢谢。 - Jang-hwan Kim
2
我刚遇到了这个问题。错误提示“没有这个文件或目录”真的很烦人,而且还是一个IOError。它应该像readline.FileParseError一样。错误信息应该是“在历史文件中期望版本2头部”。 - onlynone
3
我刚刚发现这是GNU的readline与BSD的libedit之间的问题。我有一个virtualenv,它的readline是针对libedit编译的。正是libedit期望有趣的头文件和\ 040而不是空格。我的系统范围内homebrewed python使用的readline是针对GNU的readline编译的,并且它写入了带有常规空格而没有头文件的历史文件。我通过删除virtualenv并重新创建它来解决了这个问题,以便它指向与系统python相同的readline.so。 - onlynone
2
你刚才用第二人称回答了自己的问题吗? - spicypumpkin
8
是的,我相信E这样认为!也许ManicDee是某种哲学流派(如唯心主义、一元论/逻各斯主义或当下主义)的订阅者,因此认为过去的ManicDee(提问者)是一个无关的实体(毕竟回答问题的ManicDee显然是不同的存在:E有答案,另一个ManicDee没有)。但我也想到过,E可能是一个角色扮演者,在这种情况下扮演“提问者”和“回答者”两个在同一场景中独立的角色。 - ManicDee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接