有没有办法将 linux 命令的输出存储到 python 网络编程中的变量中?

Is there a way to store the output of a linux command into a variable in python network programming?

我正在尝试构建一个系统,其中将存储可用 wifi 网络列表以用于某些特定目的。现在的问题是,在变量 'res' 中使用 os.system() 执行系统命令只会存储命令的 return 值,这对我来说目前是无用的。

据我所知,没有任何方法可以提供我想要的结果。

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

变量 res 必须存储所有需要的结果而不是 return 值。即使它存储结果,它也会完成工作。

您可以使用 subprocess 模块中的 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))