问题描述
TL; DR 我如何使用python在用户终端中“模拟”打字命令?(类似于下面的示例,其中我只键入了第一个命令)
我正在使用asciinema来显示终端会话的演示。但是,我不想编写自己的击键(不幸的是,击键速度不是恒定的,容易出错,...),而是编写脚本,因此目标与https://stackoverflow.com/a/63080929/5913047相同。但是大多数工具(至少是https://stackoverflow.com/a/63080929/5913047回答中的那些工具)没有得到维护,因此我想知道是否可以提出一个python脚本来实现它。
问题,我不知道如何在用户终端中模拟打字,尤其是使用用户终端的语法着色和提示。我非常确定这是有可能的,因为它是在asciiscript中完成的(不幸的是,该工具是错误的,使用的语言我并不了解,也无法维护)。那么是否有可能通过python使用用户的语法着色和提示在用户终端中编写代码?
我想它与subprocess
和管道有关,但是我很难找到所需的信息,而我对此不太熟悉。
解决方法
您可以使用一个简单的功能来遍历每个字符以获得打字机效果。 time.sleep
方法可以通过设置每个字符打印之间的延迟来减慢文本的速度。
import time
def typewriter(text,timeout=0.1):
for c in text:
print(c,end="")
time.sleep(timeout)
print()
typewriter("Hello,world!")
您可以将其与colorama Python模块结合起来进行着色。然后,如您所说,使用subprocess
运行命令并打印出响应。
# Execute the actual command and get the response text
response = subprocess.run(["echo","\"Hello,world!\""],capture_output=True).stdout.decode()
# Print the response in a typewriter style.
typewriter(text)
# Or print it normally
print(text)
# Or print it line by line with a delay
for line in text.split("\n"):
print(line)
time.sleep(0.05)
这是一个更完整的示例。
import time,subprocess
from colorama import *
init()
def typewriter(cmd,timeout=0.1):
text = ""
for arg in cmd:
text += arg + " "
for c in text:
print(c,end="")
time.sleep(timeout)
print()
def prompt():
print(Fore.GREEN+"user@computer:"+Fore.BLUE+"~ $ "+Style.RESET_ALL,end="")
def command(cmd):
prompt()
typewriter(cmd)
response = subprocess.run(cmd,capture_output=True).stdout.decode()
print(response)
command(["echo","Hello,world!"])
请注意,colorama
Python模块在某些设备上可能无法正常工作。如果确实遇到任何问题,我建议您访问colorama
模块中的documentation。我在终端的Linux机器上进行了测试,一切正常。