如何在Python解释器中启用导入语句的Tab补全?

1 投票
1 回答
589 浏览
提问于 2025-04-18 15:05

有没有办法在Python的import语句中启用自动补全功能呢?

举个例子:

$ cd test/
$ ls
mytest.py
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import my<TAB>
>>> import shuti<TAB>

我发现对于mytest或者其他模块(比如shutil)都没有自动补全的功能。在Python 3.4中也是这样。我使用的是Ubuntu 14.04,终端是bash。

不过要注意,在其他Python解释器的环境中,比如补全函数名和标识符名时,自动补全是可以正常工作的。

我的.pystartup配置是这样的:

import atexit
import os
import readline
import rlcompleter

readline.parse_and_bind("tab: complete")

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)

if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath

1 个回答

0

默认的Python交互式命令行(REPL)是做不到这个的。现在唯一(实用)的办法就是使用IPython,这个就像是普通REPL的升级版,功能更强大,速度也更快:http://ipython.org/

撰写回答