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

时间:2019-05-19 20:16:38

标签: linux network-programming python-3.7

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

我不知道有什么方法可以提供理想的结果。

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

变量res必须将所有想要的结果存储到其中,而不是返回值。即使存储结果,它也可以完成工作。

1 个答案:

答案 0 :(得分:0)

您可以使用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))