我想模拟编码 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/