【问题标题】:Python readline module on OS X lacks set_pre_input_hookOS X 上的 Python readline 模块缺少 set_pre_input_hook
【发布时间】:2015-04-28 06:15:29
【问题描述】:

我将以下代码添加到我的 python 启动脚本中。在我通过 pip 安装 pyreadline 后,它在 Windows 7 上运行良好,但它不适用于 OS X Yosemite(具体为 10.10.2)。

import readline

def atPrompt():
    import readline
    global freshPrompt
    if freshPrompt:
        freshPrompt = False

    last = readline.get_history_item(readline.get_current_history_length())

    spaces = last[:len(last) - len(last.lstrip())]
    if last.isspace():
        spaces = spaces[:-4]
    elif last and last.strip()[-1] == ':':
        spaces += '    '
    readline.insert_text(spaces)

readline.set_pre_input_hook(atPrompt)

# (I also make it so that when PS1 is called, global freshPrompt is set to True.)

当我在交互式 Python 中键入时,此代码会自动为我缩进。如果我输入的前一行以: 结尾,它会自动缩进四个额外的空格。如果前一行以空格开头,但不仅仅包含空格,则它将新行与前一行对齐。如果前一行只是空格,它会为我减少新行。

虽然这段代码在 Windows 上非常适合我(使用 pyreadline 来自 pip),但它在 OS X 上没有任何作用。它没有告诉我缺少任何模块。我在 OS X 的其他地方使用readlineget_history_item()get_current_history_length() 就好了。

如果我在atPrompt 的开头插入print 语句,它在 OS X 中永远不会出现,但在 Windows 中会正常显示。

这让我认为set_pre_input_hook() 在 OS X 中什么都不做。

我知道 OS X 中的 readline 模块与其他 *nix 发行版中的模块不同(出于许可原因)。我听说可以在 OS X 上安装相同的模块。

但是当我尝试通过 pip 安装 readline 时,使用

pip install readline

我收到以下错误:

创建 build/lib.macosx-10.10-intel-2.7

cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F。 build/temp.macosx-10.10-intel-2.7/Modules/2.x/readline.o readline/libreadline.a readline/libhistory.a -lncurses -o build/lib.macosx-10.10-intel-2.7/readline.so

clang:错误:没有这样的文件或目录:'readline/libreadline.a'

clang:错误:没有这样的文件或目录:'readline/libhistory.a'

错误:命令“cc”失败,退出状态为 1


正在清理... 命令 /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/readline/setup.py';exec(compile(getattr(tokenize, 'open', open)(@ 987654337@).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-FYqn9p-record/install-record. txt --single-version-externally-managed --compile 失败,错误代码 1 在 /private/tmp/pip_build_root/readline 在 /Users/Taylor/Library/Logs/pip.log 中存储失败的调试日志

(我在__file__ 周围添加了反引号,以防止它显示为文件。)

如何让set_pre_input_hook() 在 OS X 上工作?我是否认为我应该替换 readline 模块?如果是这样,我该如何安装它,因为只是尝试通过pip 安装它会导致上述错误消息。

作为额外的细节,Windows 机器正在运行 Python 2.7.8。 OS X 机器正在运行 Python 2.7.6。

【问题讨论】:

标签: python macos readline


【解决方案1】:

似乎最好的方法是安装gnureadline

pip install gnureadline

不幸的是,这意味着脚本要跨平台兼容,您需要编写以下代码:

try:
    import gnureadline as readline
except ImportError:
    import readline

不仅仅是这样:

import readline

如果有人知道更好、更简洁的导入解决方案,请分享。

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多