Python 快捷执行工具:简易命令行执行器
以下是一个使用 Python 编写简单的命令行执行工具的示例,它可以执行用户输入的命令并返回结果:
import subprocess
def execute_command(command):
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout.strip()
except Exception as e:
return str(e)
while True:
user_input = input('请输入命令(输入 q 退出): ')
if user_input == 'q':
break
output = execute_command(user_input)
print(output)
这个示例使用 subprocess 模块来执行命令并捕获输出。execute_command 函数接收一个命令作为参数,然后使用 subprocess.run() 来执行命令。capture_output=True 参数用于捕获命令的输出,text=True 参数用于将输出作为字符串返回。
在主循环中,用户可以输入命令并执行。当用户输入 'q' 时,程序退出。
请注意,这只是一个简单的示例,并没有对输入进行任何验证或处理错误。在实际使用中,您可能需要添加一些逻辑来处理错误、验证输入等。
原文地址: https://www.cveoy.top/t/topic/qmFF 著作权归作者所有。请勿转载和采集!