2016-01-31 35 views
0

我试图扩展python shell(我不能使用IPython,可悲)。我想能够完成关键字和解释一些自定义输入(这将不是有效的Python)。但是我无法使readline/rlcompleter和InteractiveConsole一起工作。为了演示这个问题:有没有什么办法可以在Python中结合readline/rlcompleter和InteractiveConsole?

$ python -c "import code; code.InteractiveConsole().interact()" 
Python 2.7.10 (default, Jun 1 2015, 18:05:38) 
[GCC 4.9.2] on cygwin 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 
>>> import readline 
>>> import rlcompleter 
>>> readline.parse_and_bind("tab: complete") 
>>> import string 
>>> stri 

这里点击标签什么都不做。

$ python 
Python 2.7.10 (default, Jun 1 2015, 18:05:38) 
[GCC 4.9.2] on cygwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import readline 
>>> import rlcompleter 
>>> readline.parse_and_bind("tab: complete") 
>>> import string 
>>> stri 

点击标签现在完成“字符串”。

任何人都可以解释这是为什么,如果有解决方法?

回答

0

好的 - 有些在python源文件中进行挖掘可以发现答案。问题是在InteractiveConsole中,名称空间被设置为__main__以外的其他名称。但rlcompleter从builtins__main__完成。上面的Import string导入到当前名称空间中,该名称空间不是__main__,并且不由rlcompleter搜索。

所以,一个解决方案是构建自己的rlcompleter.Completer和当地人)通(到构造函数:

$ python -c "import code; code.InteractiveConsole().interact()" 
Python 2.7.10 (default, Jun 1 2015, 18:05:38) [GCC 4.9.2] on cygwin 
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole) 
>>> import readline 
>>> from rlcompleter import Completer 
>>> readline.parse_and_bind("tab: complete") 
>>> readline.set_completer(Completer(locals()).complete) 
>>> import string 
>>> str 
str( string 
相关问题