python - 在 python 中模拟编码 session

标签 python python-3.x

我想模拟编码 session (用于视频录制 session :我不是触摸打字员:-)

例如,我有一个像这样的 shell 脚本 (test.sh)

hello="Hello"
world="world"
echo $hello", "$world

我有一个像这样的Python脚本(Simulate_KeyPresses.py):

import sys
import time
import subprocess

def send_letter(letter):
  # V1 : simple print
  sys.stdout.write(letter)
  sys.stdout.flush()

  # V2: Test with expect (apt-get install expect)
  # cmd = """echo 'send "{}"' | expect""".format(c)
  # subprocess.run(cmd, shell=True)


def simulate_keypresses(content):
  lines = content.split("\n")
  for line in lines:
    for c in line:
      send_letter(c)
      time.sleep(0.03)
    send_letter("\n")
    time.sleep(0.5)


if __name__ == "__main__":
  filename = sys.argv[1]
  with open(filename, "r") as f:
    content = f.read()
  simulate_keypresses(content)

我可以这样调用:

python Simulate_KeyPresses.py test.sh

而且效果非常好。 但是,当我通过管道将其传输到 bash 时,如下所示:

python Simulate_KeyPresses.py test.sh | /bin/bash

我明白了

Hello, world

即我只得到标准输出,并且不显示按键。

我想看到什么:

hello="Hello"
world="world"
echo $hello", "$world
Hello, world

我找到了一个相关的答案( Simulate interactive python session ),但它只处理 python 编码 session 。

我尝试使用 Expect ,但它没有按预期工作(也不显示标准输入)。

帮助将不胜感激!

最佳答案

您可以将程序 tee 用作:

python Simulate_KeyPresses.py test.sh | tee /dev/tty | /bin/bash

关于python - 在 python 中模拟编码 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53668488/

相关文章:

python-3.x - 使用 Altair 工具提示和 mark_text 显示图形和名称

python - 在 Python 中为任意 n 嵌套 n 循环

python - 为什么表达式 0 < 0 == 0 在 Python 中返回 False?

python - 从 python 读取 BerkleyDB 文件 : `\x01\x0b\x88\x0c\x01` ?

条件的 Python 子列表

python - 使用 basemap 时,两个子图之间的线没有在正确的点结束

python - 带有 matplotlib 的 Colorbar 图……但是是灰色的?

python - 如何计算分组 df 的差异?

python - 如何进行 future 的调用并等待 Python 完成?

python - 如何为每个索引值添加差异行?