2011-12-07 15 views
13

Muchas veces usaré el intérprete de Python para inspeccionar variables y pasar comandos antes de escribir en un archivo. Sin embargo, al final tengo alrededor de 30 comandos en el intérprete, y tengo que copiarlos/pegarlos en un archivo para ejecutarlos. ¿Hay alguna forma de exportar/escribir el historial del intérprete de Python en un archivo?¿Exportar el historial del intérprete de Python a un archivo?

Por ejemplo

>>> a = 5 
>>> b = a + 6 
>>> import sys 
>>> export('history', 'interactions.py') 

Y entonces puedo abrir el archivo interactions.py y leer:

a = 5 
b = a + 6 
import sys 
+0

¿Qué pasa con copiar y pegar? Puedes usar find/replace para arreglar el '>>>'. ¿No sería eso lo más simple? –

+0

Copiar/pegar treinta líneas de entrada un par de veces al día se vuelve tedioso ... –

Respuesta

21

IPython es muy útil si te gusta usar sesiones interactivas. Por ejemplo, para su caso de uso, existe el comando guardar, solo ingrese save my_useful_session 10-20 23 para guardar las líneas de entrada 10 a 20 y 23 en my_useful_session.py. (para ayudar con esto, cada línea está precedida por su número)

Mire los videos en la página de documentación para obtener una descripción general rápida de las funciones.

:: O ::

Hay una way para hacerlo. Almacenar el archivo en ~/.pystartup

# Add auto-completion and a stored history file of commands to your Python 
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is 
# bound to the Esc key by default (you can change it - see readline docs). 
# 
# Store the file in ~/.pystartup, and set an environment variable to point 
# to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash. 
# 
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the 
# full path to your home directory. 

import atexit 
import os 
import readline 
import rlcompleter 

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 

También puede agregar este autocompletar para obtener de forma gratuita:

readline.parse_and_bind('tab: complete') 

Tenga en cuenta que esto sólo funcionará en sistemas * nix. Como readline solo está disponible en la plataforma Unix.

+1

+1 para la sugerencia de ipython – silvado

+1

Usa iPython, es el futuro de Python cli. – Will

5

La siguiente no es mi propio trabajo, pero francamente no recuerdo donde llegué por primera vez ... Sin embargo: coloque el siguiente archivo (en un sistema GNU/Linux) en su carpeta de inicio (el nombre del archivo debe ser .pystartup.py):

# Add auto-completion and a stored history file of commands to your Python 
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is 
# bound to the Esc key by default (you can change it - see readline docs). 
# 
# Store the file in ~/.pystartup, and set an environment variable to point 
# to it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash. 
# 
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the 
# full path to your home directory. 

import atexit 
import os 
import readline 
import rlcompleter 

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

endMarkerStr= "# # # histDUMP # # #" 

saveMacro= "import readline; readline.write_history_file('"+historyTmp+"'); \ 
    print '####>>>>>>>>>>'; print ''.join(filter(lambda lineP: \ 
    not lineP.strip().endswith('"+endMarkerStr+"'), \ 
    open('"+historyTmp+"').readlines())[-50:])+'####<<<<<<<<<<'"+endMarkerStr 

readline.parse_and_bind('tab: complete') 
readline.parse_and_bind('\C-w: "'+saveMacro+'"') 

def save_history(historyPath=historyPath, endMarkerStr=endMarkerStr): 
    import readline 
    readline.write_history_file(historyPath) 
    # Now filter out those line containing the saveMacro 
    lines= filter(lambda lineP, endMarkerStr=endMarkerStr: 
         not lineP.strip().endswith(endMarkerStr), open(historyPath).readlines()) 
    open(historyPath, 'w+').write(''.join(lines)) 

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

atexit.register(save_history) 

del os, atexit, readline, rlcompleter, save_history, historyPath 
del historyTmp, endMarkerStr, saveMacro 

A continuación, obtendrá todas las cosas buenas que vienen con el shell bash (flechas arriba y abajo navegando por el historial, ctrl-r para búsqueda inversa, etc. ...).

Su historial de comandos completo se almacenará en un archivo ubicado en: ~/.pyhistory.

Estoy usando esto desde edades y nunca tuve un problema.

HTH!

11

Si está utilizando Linux/Mac y tiene la biblioteca readline, se puede añadir lo siguiente en un archivo y exportarlo en su .bash_profile y usted será tener finalización e historia.

# python startup file 
import readline 
import rlcompleter 
import atexit 
import os 
# tab completion 
readline.parse_and_bind('tab: complete') 
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory') 
try: 
    readline.read_history_file(histfile) 
except IOError: 
    pass 
atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter 

comando Exportar:

export PYTHONSTARTUP=path/to/.pythonstartup 

Esto ahorrará su historia consola de Python en ~/.pythonhistory

1

En Python Shell:

%history 

El comando imprimirá todos los comandos que se han introducido en la cáscara pitón actual.

% history -g 

El comando imprimirá todos los comandos registrados en el shell de python hasta un número significativo de líneas.

%history -g -f history.log 

Escribirá los comandos registrados junto con el número de línea. puede eliminar los números de línea de anchura fija para los comandos de interés utilizando gvim.

Cuestiones relacionadas