是否有一种方法可以将Linux命令的输出存储到Python网络编程中的变量中



我正在尝试构建一个系统,其中可用的WiFi网络列表将出于某些特定目的而存储。现在的问题是,在变量" res"中使用os.system((执行系统命令仅存储命令的返回值,而这对我来说毫无用处。

我知道没有给我带来理想结果的方法。

import os
res = os.system('nmcli dev wifi')

变量res必须将所有所需结果存储在其中而不是返回值中。即使其存储会产生,它也将完成工作。

您可以使用子过程模块中的Popen方法

进行此操作
from subprocess import Popen, PIPE

#First argument is the program name.
arguments = ['ls', '-l', '-a']
#Run the program ls as subprocess.
process = Popen(arguments, stdout=PIPE, stderr=PIPE)
#Get the output or any errors. Be aware, they are going to be
#in bytes!!!
stdout, stderr = process.communicate()
#Print the output of the ls command.
print(bytes.decode(stdout))

最新更新