Python: get output of the shell command 'history'
why don't you read the file directly.
~/.bash_history
for history in open('/home/user/.bash_history'):
print(history, end='')
How do you see the entire command history in interactive Python?
Use readline.get_current_history_length()
to get the length, and readline.get_history_item()
to view each.
How to add a command to the bash history from python
There is no cross-shell, universally portable option: History is an interactive facility without a close POSIX specification as to how it's implemented.
That said, there are some fixes needed to make the general approach attempted above both functional and safe:
subprocess.Popen(['bash', '-ic', 'set -o history; history -s "$1"', '_', command_string])
- The HISTFILE variable is only set in interactive shells. Thus, you need to run bash with
-i
to have it set at all. set -o history
is similarly needed to turn history on.- Passing
command_string
out-of-band instead of substituting it into the argument following-c
avoids massive security bugs (where trying to append a line to history could execute parts of it instead).
How can I access command prompt history with Python
You don't need Python at all, use doskey
facilities for that, i.e.:
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:
import subprocess
cmd_history = subprocess.check_output(["doskey", "/history"])
with open("saved_commands.txt", "wb") as f:
f.write(cmd_history)
How to get the terminal full history
What you want to do, is log the output of stdout, see this answer:
Making Python loggers output all messages to stdout in addition to log file
Invoking history command on terminal via Python script
Use this:
from subprocess import Popen, PIPE, STDOUT
e = Popen("bash -i -c 'history -r;history' ", shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
output = e.communicate()
Related Topics
How to Use the Same Python Virtualenv on Both Windows and Linux
How to Set Explicitly the Terminal Size When Using Pexpect
Using Strides for an Efficient Moving Average Filter
How to Do Parallel Programming in Python
Googletrans Stopped Working with Error 'Nonetype' Object Has No Attribute 'Group'
Execution of Python Code with -M Option or Not
Pandas: Convert Categories to Numbers
Efficient Way to Apply Multiple Filters to Pandas Dataframe or Series
Locale Date Formatting in Python
How to Install Both Python 2.X and Python 3.X in Windows
Importerror: Matplotlib Is Required for Plotting When the Default Backend "Matplotlib" Is Selected
Str' Object Does Not Support Item Assignment
How to Get a List of All the Duplicate Items Using Pandas in Python
How to Get the Input from the Tkinter Text Widget