Skip to content

Instantly share code, notes, and snippets.

@Stampede
Created April 4, 2023 12:51
Show Gist options
  • Save Stampede/25f9187e0db996767d424fec46f141b6 to your computer and use it in GitHub Desktop.
Save Stampede/25f9187e0db996767d424fec46f141b6 to your computer and use it in GitHub Desktop.
From the interactive Python shell, this will print the last N lines that you entered (default is 50). Useful when you've been working out a problem in the shell and now want to copy & paste the code into your program.
import readline
def history(tail_length=50):
total = readline.get_current_history_length()
for i in range(total - tail_length, total):
print(readline.get_history_item(i + 1))
"""
Meant to be used from the Python interactive shell. The function will print the
last several lines of command history. Default is 50 lines.
I find it most useful when I am writing a program and testing the code in the interactive shell.
After I get the code working, I use this to show my recent history and then I copy / paste it into
the IDE. Delete the mistakes from the IDE and you're all set!
USAGE EXAMPLES:
Print the last 100 lines of shell history to your screen:
>>>> history(100)
Print the last 50 lines:
>>>> history()
OR:
>>>> history(50)
Modified from a code snippet that I found here:
https://medium.com/@oalejel/printing-command-history-within-the-python-interactive-terminal-repl-simplified-5fd202c64880
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment