简体   繁体   中英

How do I add a command to current terminal history using python?

I have read other answers and the command is history -s COMMAND . I have also seen an example the following is used for accessing history through python.

shell_command = 'bash -i -c "history -r; history"'      
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, 
stderr=STDOUT)
output = event.communicate()
print(output)

But I am unable to use history -s COMMAND in the same way.

My main goal is to append a certain command to the user's current history so that the when the user presses the up button, the "COMMAND" shows up.

This will work

import subprocess
command = "grep"
shell_command = 'bash -i -c "history -s; %s"' % command
event = subprocess.Popen(shell_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = event.communicate()
print(output)

There is a very easy way to do it.

     import subprocess as sub
     command = input("What do you want to add to history:?")
     sub.call(["echo",command,">>","/root/.bash_history"])
     print("done")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM