在Windows 10上的Python 3.6中,假设我打开了一个命令提示符会话(不是Python命令提示符或Python交互式会话)并且我一直在设置环境,进行许多配置等操作。是否有办法使用Python模块访问我在该会话中使用的命令历史记录呢?理想情况下,我希望能够将此历史记录导出到文件中,以便将来重复使用。
示例:
在命令提示符中键入:
python savecmd.py
,它将保存该会话的历史记录。python savecmd.py
,它将保存该会话的历史记录。doskey
来实现,例如:doskey /history
将打印出当前会话的命令历史记录,如果需要保存,可以将其重定向到文件中:
doskey /history > saved_commands.txt
如果你真的想在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)
GetConsoleCommandHistoryLengthW
和GetConsoleCommandHistoryW
,因此不支持这种方法。 - Eryk Sunfor i in list(range(readline.get_current_history_length())): print(readline.get_history_item(i))
。 - not2qubit实际上,您在这里要求三件不同的事情。
要从REPL内部获取历史记录,请使用:
for i in list(range(readline.get_current_history_length())): print(readline.get_history_item(i))
很遗憾,在REPL中没有历史记录,当从外部使用时,就像上面一样,所以您需要找到历史文件并打印它。
要从powershell中查看历史文件:
function see_my_py_history{ cat C:\<path-to>\saved_commands.txt }
Set-Alias -Name seehist -Value see_my_py_history
conda install pyreadline3
。到目前为止,来自pyreadline.BaseReadline.write_history_file
的文件大小为0字节(详细信息在这里)。 - user2153235Conda
是在Python包管理非常不稳定且平台/编译支持不可靠的时候创建的。我强烈建议将来和日常开发中避免使用Conda。现在有更好的包管理工具,如poetry
等,与pip
兼容。 - not2qubit
history = open('/home/.bash_history').readlines()
,然后你就可以从那里获取所有的历史记录。问题是,我不确定你如何将其限制为当前会话。 - cs95