gpt4 book ai didi

python - 模仿 python 2.x 中的 .bash_history

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:05 25 4
gpt4 key购买 nike

我想知道是否有一种方法可以“模仿”linux .bash_history。它会是这样的:

def write_history(cmd):
try:
with open("/root/.python_history","a") as history:
history.write(str(cmd) + "\n")
history.close()
except:
with open("/root/.python_history","w") as history:
history.write(str(cmd) + "\n")
history.close()

while 1:
cmd = raw_input("cmd > ")
write_history(cmd)
if cmd.lower() == "exit":
exit()
elif cmd.lower() == "yay":
print("YAY !")
elif keyup.is.pressed: #it's to do this that I need help
read_the_last_line_of_python_history() #and this too

你能帮我吗?谢谢。

最佳答案

使用 cmd外壳模块和readline对于历史:

import cmd
import sys
import os.path
import readline

histfn = os.path.expanduser('~/.mycmd.history')

class MyCmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
try:
readline.read_history_file(histfn)
except IOError:
pass

def do_yay(self, arg):
print('YAY !')

def do_exit(self, arg):
readline.write_history_file(histfn)
sys.exit(0)

def do_EOF(self, arg):
print()
self.do_exit(arg)


if __name__ == '__main__':
MyCmd().cmdloop()

关于python - 模仿 python 2.x 中的 .bash_history,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50655121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com