Raj Kumar Singh
Raj Kumar Singh

Reputation: 23

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

I am trying to build a system where a list of the available wifi networks would be stored for some specific purpose. Now the problem is that executing a system command with os.system() in a variable 'res' only stores the return value of the command which is useless to me at this point.

I know of no approach that provide me the desired result.

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

The variable res must store all the desired result into it rather than the return value. Even if it stores result, it will do the work.

Upvotes: 1

Views: 98

Answers (1)

babaliaris
babaliaris

Reputation: 703

You can do this using the Popen method from the subprocess module

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))

Upvotes: 1

Related Questions