租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

python如何获取控制台输出内容,python 调用控制台并获取返回结果

发布时间:2023-10-17 03:04:47

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模块时需要谨慎处理用户输入,以免潜伏的安全问题。