在python 2.x中模仿.bash_history

时间:2018-06-02 08:48:12

标签: python linux

我想知道是否有办法模仿" 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
你可以帮我吗? 感谢。

1 个答案:

答案 0 :(得分:0)

cmd模块用于shell,将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()