I'm trying to get the output of the history command in python, but it returns nothing. When I run it in the terminal it returns my last commands. I'm using Mac OS.
import subprocess
command = 'history'
# Execute the command using a shell
result = subprocess.run(command, shell=True, capture_output=True, text=True)
# Check the result
if result.returncode == 0:
print("Command executed successfully!")
print("Output:")
print(result.stdout)
else:
print("Error executing command:")
print(result.stderr)
Output:
Command executed successfully!
Output:
Here's a simple explanation of what I know about it:
When you run the
historycommand viasubprocessin Python, it typically returns nothing becausehistoryis not an actual command likelsorcat, but rather a shell builtin that's available in your terminal (like bash or zsh). This meanshistoryworks within the context of a shell session to list the commands you've executed in that session, and it relies on the environment of the shell to function.When you execute
subprocess.runwithshell=True, it starts a new shell session for that command, which doesn't have the same command history as your interactive terminal session. Therefore, thehistorycommand doesn't return anything because, from the perspective of that new shell session, no commands have been executed.If you want to access the command history in a script, you might consider reading the history file directly. For bash, this is typically
~/.bash_history, and for zsh, it's~/.zsh_history. You can read this file from Python to get the command history. Here's how you could do it for bash:Adjust the
history_filevariable if you're using a different shell. Thanks