How can I access command prompt history with Pytho

2019-07-30 00:49发布

问题:

This question already has an answer here:

  • how do you see the entire command history in interactive python? 9 answers

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.

回答1:

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)