【问题标题】:How do I add a command to current terminal history using python?如何使用 python 将命令添加到当前终端历史记录?
【发布时间】:2017-10-04 23:44:53
【问题描述】:

我已阅读其他答案,命令是history -s COMMAND。 我还看到了以下用于通过 python 访问history 的示例。

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)

但我无法以同样的方式使用history -s COMMAND

我的主要目标是将某个命令附加到用户的当前历史记录中,以便当用户按下up 按钮时,"COMMAND" 会显示出来。

【问题讨论】:

  • 历史是shell实例内部状态的一部分;你不能从外部影响它。
  • @chepner 那么这不可能吗?

标签: python linux bash python-3.x terminal


【解决方案1】:

这会起作用

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)

【讨论】:

  • grep 有效。但它没有出现在终端history
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 2018-05-10
相关资源
最近更新 更多