用python模拟编码会话

2024-10-17 08:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想模拟一个编码会话(对于视频录制会话:我不是触摸打字员:-)

例如,我有这样一个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

也就是说,我只得到stdout和按键不显示。你知道吗

我想看到的是:

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

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

我试图使用Expect,但它没有按预期工作(也没有显示stdin)。你知道吗

请帮忙!你知道吗


Tags: pytestimportechosendhelloworldtime
2条回答

可以将程序tee用作:

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

将此添加到脚本中如何:

subprocess.call("./{}".format(filename), shell=True)

结果将是

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

Hello, world

相关问题 更多 >