可以使用Python内置的os和subprocess模块来实现。
示例代码如下:
import os
# Windows系统需要使用"cls"清屏命令,Linux/Unix或macOS需要使用"clear"
CLEAR_COMMAND = "cls" if os.name == "nt" else "clear"
def input_automatically(prompt=""):
"""自动提供输入的函数"""
while True:
user_input = input(prompt)
os.system(CLEAR_COMMAND) # 清屏
yield user_input
# 测试代码,输入‘q’退出循环
for user_input in input_automatically("Please enter something (press 'q' to quit):\n"):
print(f"You entered: {user_input}")
if user_input == "q":
break
运行以上代码后,程序将自动在终端提供输入,并在输入后自动清屏(Windows系统使用“cls”命令,Linux/Unix或macOS系统使用“clear”命令)。
这里我们使用了一个生成器函数来实现输入自动提供的功能。在主程序中,我们使用for循环遍历生成器输出的值,当输入“q”时,程序退出循环并停止输出。