How can I access command prompt history with Python [duplicate]

一笑奈何 提交于 2019-12-24 06:58:10

问题


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)


来源:https://stackoverflow.com/questions/44894992/how-can-i-access-command-prompt-history-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!