Python OS X 上的 readline 模块缺少 set_pre_input_hook

Python readline module on OS X lacks set_pre_input_hook

我将以下代码添加到我的 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.[=35= 中显示正常]

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

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

上安装相同的模块

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

pip install readline

我收到以下错误:

creating 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: error: no such file or directory: 'readline/libreadline.a'

clang: error: no such file or directory: 'readline/libhistory.a'

error: command 'cc' failed with exit status 1


Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/tmp/pip_build_root/readline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-FYqn9p-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/tmp/pip_build_root/readline Storing debug log for failure in /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.

看来最好的方法是安装 gnureadline

pip install gnureadline

不幸的是,这意味着脚本要跨平台兼容,您需要这样写:

try:
    import gnureadline as readline
except ImportError:
    import readline

不仅如此:

import readline

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