[英]How can I access command prompt history with Python
On Windows 10, Python 3.6在 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.假设我打开了一个命令提示符会话(不是 Python 命令提示符或 Python 交互式会话) ,并且我一直在设置一个具有很多配置或类似性质的环境。 Is there any way for me to access the history of commands I used in that session with a python module for example?
例如,我有什么方法可以通过 python 模块访问我在该会话中使用的命令的历史记录?
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.输入命令提示符:
python savecmd.py
并保存该会话的历史记录。
You don't need Python at all, use doskey
facilities for that, ie:您根本不需要 Python,为此使用
doskey
工具,即:
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:如果您真的想在 Python 中执行此操作,可以使用
subprocess.check_output()
捕获命令历史记录,然后将其保存到文件中:
import subprocess
cmd_history = subprocess.check_output(["doskey", "/history"])
with open("saved_commands.txt", "wb") as f:
f.write(cmd_history)
You're actually asking for 3 different things there.你实际上在那里要求 3 种不同的东西。
To get the history from inside your REPL, use:要从 REPL 中获取历史记录,请使用:
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.不幸的是,REPL 中没有历史记录,当从外部使用时,如上所述,因此您需要找到历史记录文件并打印它。
To see the history file from powershell:要从 powershell 查看历史文件:
function see_my_py_history{ cat C:\<path-to>\saved_commands.txt }
Set-Alias -Name seehist -Value see_my_py_history
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.