ikreb
ikreb

Reputation: 2775

How to get wlan device name with python?

I want only the wlan device name at a linux system with python. I could get the device name with shell scripting:

echo /sys/class/net/*/wireless | awk -F'/' '{ print $5 }'

So i want to use this at python with subprocess.

import shlex
import subprocess

def main():
    echo = shlex.split('echo /sys/class/net/*/wireless')
    echo_proc = subprocess.Popen(echo, shell=True, stdout=subprocess.PIPE)
    awk = shlex.split("awk -F'/' '{ print $5 }'")
    awk_proc = subprocess.Popen(awk, stdin=echo_proc.stdout)
    print(awk_proc.stdout)

But I get only None as output. If it is possible, I would prefer a solution with subprocess.run(). So I replaced Popen with run. But then I get the error message AttributeError: 'bytes' object has no attribute 'fileno'.

Upvotes: 1

Views: 619

Answers (1)

tshiono
tshiono

Reputation: 22032

A type glob and a pathname expansion by shell will be a headache.
In my environment, the following snippet works:

import subprocess
subprocess.run('echo /sys/class/net/*/wireless', shell=True)

But the following returns an empty string:

import subprocess
subprocess.run(['echo', '/sys/class/net/*/wireless'], shell=True)

Then please try the following as a starting point:

import subprocess
subprocess.run('echo /sys/class/net/*/wireless | awk -F"/" "{ print \$5 }"', shell=True)

which will bring your desired output.

[Update] If you want to assign a variable to the output above, please try:

import subprocess

proc = subprocess.run('echo /sys/class/net/*/wireless | awk -F"/" "{ print \$5 }"', shell=True, stdout = subprocess.PIPE)
wlan = proc.stdout.decode("utf8").rstrip("\n")
print(wlan)

BTW if you don't stick to the subprocess module, why don't you go with a native way as:

import glob
list = glob.glob('/sys/class/net/*/wireless')
for elm in list:
    print(elm.split('/')[4])

Hope this helps.

Upvotes: 2

Related Questions