繁体   English   中英

如何将制表符补全添加到 Python shell?

[英]How do I add tab completion to the Python shell?

使用python manage.py shell启动 django 应用程序时,我得到一个 InteractiveConsole shell - 我可以使用选项卡完成等。

Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

当刚使用python启动 python 解释器时,它不提供制表符补全。

有人可以告诉我 django 正在做什么来给我一个交互式控制台,或者我需要做什么才能在没有 django 应用程序的情况下启动交互式控制台?

我可能已经找到了一种方法来做到这一点。

创建一个文件 .pythonrc

# ~/.pythonrc
# enable syntax completion
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

然后在您的 .bashrc 文件中,添加

export PYTHONSTARTUP=~/.pythonrc

这似乎有效。

我认为 django 会做类似https://docs.python.org/library/rlcompleter.html 的事情

如果您想拥有一个非常好的交互式解释器,请查看IPython

作为记录,这在教程中进行了介绍: http : //docs.python.org/tutorial/interactive.html

我使用ptpython - 它是一个很棒的工具自动完成 shell cmd。

安装ptpython非常简单,使用pip工具

pip install ptpython

对于 django shell,你应该像这样导入 django env

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testweb.settings")

相信我,这对你来说是最好的方法!!!

修复 Windows 10 外壳:

  • pip install pyreadline
  • pip install ipython [shell]

看起来python3已经开箱即用了!

在 Python3 中,此功能默认启用。 我的系统没有安装模块readline 我在 Manjaro。 我在其他 Linux 发行版(基本版、ubuntu、mint)上没有遇到过这个选项卡完成问题。

pip安装模块后,在导入时,它抛出以下错误-

ImportError: libncursesw.so.5: cannot open shared object file: No such file or directory

为了解决这个问题,我跑了-

cd /usr/lib ln -s libncursesw.so libncursesw.so.5

这解决了导入错误。 而且,它还在 python repl 中引入了选项卡完成,而无需创建/更改.pythonrc.bashrc

我创建了一个更完美的.pythonrc.py ,你可能会发现它很有用: https.pythonrc.py

是的。 它内置于 3.6。

fernanr@gnuruwi ~ $ python3.6
Python 3.6.3 (default, Apr 10 2019, 14:37:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.
Display all 318 possibilities? (y or n)
os.CLD_CONTINUED             os.O_RDONLY                  os.ST_NOEXEC                 os.environ                   os.getpid(                   os.readlink(                 os.spawnvpe(
os.CLD_DUMPED                os.O_RDWR                    os.ST_NOSUID                 os.environb                  os.getppid(                  os.readv(                    os.st

对于旧版本(2.x),上面的脚本就像魅力一样:)

fernanr@crsatx4 ~ $ cat .bashrc | grep -i python
#Tab completion for python shell
export PYTHONSTARTUP=~/.pythonrc
fernanr@crsatx4 ~ $ . ~/.bashrc
fernanr@crsatx4 ~ $ echo $?
0
fernanr@crsatx4 ~ $ python2
Python 2.7.5 (default, Jun 11 2019, 14:33:56)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.
Display all 249 possibilities? (y or n)
os.EX_CANTCREAT             os.O_WRONLY                 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM