Python历史命令没有输出
我想在Python中获取history
命令的输出,但它什么都不返回。当我在终端运行这个命令时,它会显示我之前输入的命令。我是在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)
输出:
Command executed successfully!
Output:
4 个回答
在Mac OSX系统中,我有两个命令行工具,分别是bash和zsh。如果你在终端输入echo $SHELL
,你会看到当前正在使用的命令行工具。通常它会显示类似于/bin/zsh的内容。注意,如果你进入/bin这个文件夹,你也会看到/bin/bash这个文件。所以,为了确保你能获取到当前命令行工具的历史记录,你可以使用下面的代码。我刚刚测试过,确认它能显示当前命令行工具的历史记录:
import os
shell = os.environ["SHELL"]
print(shell)
shell_map = { "/bin/zsh" : ".zsh_history", "/bin/bash" : ".bash_history" }
for history in open(os.path.join(os.environ["HOME"], shell_map[shell])):
print(history, end='')
没错,因为不会有任何历史记录。你在Python程序中做的事情是启动一个新的命令行窗口来运行你传给它的命令。在你的例子中,这个命令行窗口执行的第一个命令就是history。
下面是我对这个问题的简单解释:
当你在Python中通过subprocess
运行history
命令时,通常不会返回任何结果。这是因为history
并不是像ls
或cat
那样的实际命令,而是一个内置命令,只在你的终端(比如bash或zsh)中有效。也就是说,history
是在一个shell会话中工作,用来列出你在这个会话中执行过的命令,它依赖于shell的环境来运行。
当你用subprocess.run
并设置shell=True
时,它会为这个命令启动一个新的shell会话,而这个新的会话没有你在交互式终端中执行过的命令历史。因此,history
命令不会返回任何内容,因为在这个新会话看来,没有执行过任何命令。
如果你想在脚本中访问命令历史,可以考虑直接读取历史文件。对于bash来说,这个文件通常是~/.bash_history
,而对于zsh,则是~/.zsh_history
。你可以从Python中读取这个文件来获取命令历史。下面是如何在bash中做到这一点的示例:
history_file = '~/.bash_history'
# Expand the path to the user's home directory
full_path = os.path.expanduser(history_file)
try:
with open(full_path, 'r') as file:
history = file.readlines()
print("Command executed successfully!")
print("Output:")
for command in history:
print(command.strip())
except Exception as e:
print(f"Error reading history file: {e}")
如果你使用的是其他shell,请调整history_file
变量。
谢谢!