Question

When starting a django application using python manage.py shell, I get an InteractiveConsole shell - I can use tab completion, etc.

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)

When just starting a python interpreter using python, it doesn't offer tab completion.

Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?

Was it helpful?

Solution

I may have found a way to do it.

Create a file .pythonrc

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

then in your .bashrc file, add

export PYTHONSTARTUP=~/.pythonrc

That seems to work.

OTHER TIPS

I think django does something like https://docs.python.org/library/rlcompleter.html

If you want to have a really good interactive interpreter have a look at http://ipython.scipy.org/.

For the record, this is covered in the tutorial: http://docs.python.org/tutorial/interactive.html

I use ptpython. https://github.com/jonathanslenders/ptpython/

ptpython is a wonderful tool autocomplete shell cmd. install ptpython is very easy,use pip tool

pip install ptpython

and for django shell,you should import the django env,like this

import os

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

Trust me,this is the best way to you!!!

It looks like python3 has it out-of box!

In Python3 this feature is enabled by default. My system didn't have the module readline installed. I am on Manjaro. I didn't face this tab completion issue on other linux distributions (elementary, ubuntu, mint).

After pip installing the module, while importing, it was throwing the following error-

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

To solve this, I ran-

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

This resolved the import error. And, it also brought the tab completion in the python repl without any creation/changes of .pythonrc and .bashrc.

I create a more perfect .pythonrc.py, you may found it's useful: https://gist.github.com/guyskk/6f3522e3d17135b470bf3d982c80cc01

fix for windows10 shell:

  • pip install pyreadline
  • pip install ipython[shell]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top