如何使用Python访问命令提示符历史记录 [英] How can I access command prompt history with Python

查看:267
本文介绍了如何使用Python访问命令提示符历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows 10上,Python 3.6

假设我打开了一个命令提示符会话(不是Python命令提示符或Python互动式会话),而我一直在建立一个具有许多配置或类似性质的环境。例如,我是否可以通过python模块访问该会话中使用的命令的历史记录?

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.

示例:

在命令提示符下输入: python savecmd.py
并保存该会话的历史记录。

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

推荐答案

您根本不需要Python,为此使用 doskey 工具,即:

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

如果您真的想在Python中执行此操作,则可以使用 subprocess.check_output()捕获命令历史记录,然后将其保存到文件中:

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)

这篇关于如何使用Python访问命令提示符历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆