为什么Python的readline.read_history_file在脚本中不起作用,但可以交互地起作用?


1

我在Stack Overflow上进行了询问,但这似乎是Mac OS X特有的问题,因为在其他OS(例如ubuntu)上不会发生该错误。

https://stackoverflow.com/q/42637680/447830在下方重复:

所以。我拥有名为〜/ .osc_history的文件,如下所示:

$ w
17:53  up  3:15, 5 users, load averages: 1.30 1.17 1.10
USER     TTY      FROM              LOGIN@  IDLE WHAT
kyma     console  -                14:39    3:14 -
kyma     s001     -                17:20       - w

$ ls -l ~/.osc_history 
-rw-r--r--  1 kyma  staff  13 Mar  6 17:41 /Users/kyma/.osc_history

$ ls -lO ~/.osc_history 
-rw-r--r--  1 kyma  staff  - 13 Mar  6 17:41 /Users/kyma/.osc_history

文件中的标题正确:

$ cat ~/.osc_history 
_HiStOrY_V2_

在交互式提示符下,以下代码运行良好:

$ python
Python 2.7.10 (default, Jul 30 2016, 19:40:32) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> import readline
>>> histfile = os.path.join(os.path.expanduser("~"), ".osc_history")
>>> histfile
'/Users/kyma/.osc_history'
>>> readline.read_history_file(histfile)
>>> ^D

但是,当我尝试运行以下代码时,我将其称为“ yeuch.py​​” ...

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import readline                 # Command line history
import os.path

histfile = os.path.join(os.path.expanduser("~"), ".osc_history")
if not os.path.isfile(histfile):     # If there's no history file...
    empty = open(histfile, "a")      # ... create an ALMOST empty one...
    empty.write("_HiStOrY_V2_\n")    # ... with the special header line
    empty.close()
readline.read_history_file(histfile) # Read history from previous sessions
readline.set_history_length(1000)    # Default length was -1 (infinite)

...我懂了:

$ python yeuch.py
Traceback (most recent call last):
  File "yeuch.py", line 14, in <module>
    readline.read_history_file(histfile) # Read history from previous sessions
IOError: [Errno 1] Operation not permitted

到底发生了什么事?(我希望我不要多次忽略一些愚蠢的错别字,并且我也不是一个足以自己发现错误的阅读线代码专家。)


感谢您链接到其他站点。这看起来是一个有趣的问题。我希望从尝试回答和/或正确答案中学习。
bmike

Answers:


1

不确定您是否已解决此问题。我自己就碰到它了 我可以解决这个问题,使python历史记录文件可见。

例如:> cp .pyhistory-> pyhistory


1
他没有.pyhistory文件的问题如何解决?您得到了什么确切的代码和错误
马克
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.