python 命令行互动,如何使用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.

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值