簡體   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