Jonathan Porter
Jonathan Porter

Reputation: 1566

How can I access command prompt history with Python

On Windows 10, Python 3.6

Let's say I have a command prompt session open (not Python command prompt or Python interactive session) and I've been setting up an environment with a lot of configurations or something of that nature. Is there any way for me to access the history of commands I used in that session with a python module for example?

Ideally, I would like to be able to export this history to a file so I can reuse it in the future.

Example:

Type in command prompt: python savecmd.py and it saves the history from that session.

Upvotes: 3

Views: 6050

Answers (2)

not2qubit
not2qubit

Reputation: 16910

You're actually asking for 3 different things there.

  1. Getting Python REPL command hisotry
  2. Getting info from "prompt", which I assume is the Powershell or CMD.exe.
  3. Save the history list to a file.

To get the history from inside your REPL, use:

for i in list(range(readline.get_current_history_length())): print(readline.get_history_item(i))

Unfortunately, there is no history in REPL, when using from outside, as above, so you need to find the history file and print it.

To see the history file from powershell:

function see_my_py_history{ cat C:\<path-to>\saved_commands.txt }

Set-Alias -Name seehist -Value see_my_py_history

Upvotes: 0

zwer
zwer

Reputation: 25789

You don't need Python at all, use doskey facilities for that, i.e.:

doskey /history

will print out the current session's command history, you can then redirect that to a file if you want to save it:

doskey /history > saved_commands.txt

If you really want to do it from within Python, you can use subprocess.check_output() to capture the command history and then save it to a file:

import subprocess

cmd_history = subprocess.check_output(["doskey", "/history"])
with open("saved_commands.txt", "wb") as f:
    f.write(cmd_history)

Upvotes: 3

Related Questions