python如何获得控制台输出内容
在Python中,可使用print()
函数将内容输出到控制台。如果想获得控制台输出的内容,可使用subprocess
模块来实现。
以下是一个简单的示例代码:
import subprocess
def get_console_output(command):
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout
output = get_console_output("echo Hello World!")
print(output)
在这个示例中,get_console_output()
函数接受一个命令作为参数,并使用subprocess.run()
方法来履行该命令。capture_output=True
参数表示将输出捕获到result.stdout
中,text=True
则将输出结果以文本情势返回。
在最后一行代码中,将获得到的控制台输出内容打印出来。
请注意,在使用subprocess
模块时需要谨慎处理用户输入,以免潜伏的安全问题。
TOP