Ativar tab-completion no Shell do Python

  1. Crie o arquivo ~/.pyrc com o seguinte conteúdo:

     julio@julio-acer ~> cat .pyrc
     # ~/.pyrc
     # enable syntax completion
     try:
         import readline
     except ImportError:
         print "Module readline not available."
     else:
         import rlcompleter
         readline.parse_and_bind("tab: complete")
    

Se for usar apenas no Linux, esse try não é realmente necessário, coloquei-o em volta do import readline, pois ele usa a biblioteca GNU readline, que pode ter alguns problemas fora do Linux.

  1. Exporte a variável lida toda vez que um shell do Python é aberto (use caminho completo com o /home/usuario):

    julio@julio-acer ~> export PYTHONSTARTUP="/home/julio/.pyrc"
    
  2. Insira essa mesma linha nos arquivos .bashrc e .zshrc, para a variável sempre ser iniciada. No csh a atribuição de variáveis é diferente. Adicione a seguinte linha ao ~/.cshrc:

    setenv PYTHONSTARTUP ~/.pythonrc"
    
  3. Pronto! Pressione a tecla TAB para exibir a lista de possíveis complementos:

     julio@julio-acer ~> python
     Python 3.2.2 (default, Sep  5 2011, 04:52:19) 
     [GCC 4.6.1 20110819 (prerelease)] on linux2
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import re
     >>> re.
     re.A                  re.__eq__(            re._compile(
     re.ASCII              re.__file__           re._compile_repl(
     re.DEBUG              re.__format__(        re._compile_typed(
     re.DOTALL             re.__ge__(            re._expand(
     re.I                  re.__getattribute__(  re._pattern_type(
     re.IGNORECASE         re.__gt__(            re._pickle(
     re.L                  re.__hash__(          re._subx(
     re.LOCALE             re.__init__(          re.compile(
     re.M                  re.__le__(            re.copyreg
     re.MULTILINE          re.__lt__(            re.error(
     re.S                  re.__name__           re.escape(
     re.Scanner(           re.__ne__(            re.findall(
     re.T                  re.__new__(           re.finditer(
     re.TEMPLATE           re.__package__        re.functools
     re.U                  re.__reduce__(        re.match(
     re.UNICODE            re.__reduce_ex__(     re.purge(
     re.VERBOSE            re.__repr__(          re.search(
     re.X                  re.__setattr__(       re.split(
     re.__all__            re.__sizeof__(        re.sre_compile
     re.__cached__         re.__str__(           re.sre_parse
     re.__class__(         re.__subclasshook__(  re.sub(
     re.__delattr__(       re.__version__        re.subn(
     re.__dict__           re._alphanum_bytes    re.sys
     re.__doc__            re._alphanum_str      re.template(
    

Alternativas

Existem Shells de Python aprimorados, como o iPython. Ele é bastante simples, interativo e contém vários recursos interessantes, inclusive autocompletion.

A wiki oficial sugere alguns outros.

Julio Batista Silva
Julio Batista Silva
Data Engineer

I’m a computer engineer passionate about science, technology, photography, and languages. Currently working as a Data Engineer in Germany.

comments powered by Disqus