1

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'.

ikreb
  • 2,133
  • 1
  • 16
  • 35
  • 1
    Have you tried just using subprocess.run? – Mad Physicist Nov 06 '19 at 23:59
  • Yes, but then I get the error message ``AttributeError: 'bytes' object has no attribute 'fileno'``. I replaced only Popen with run. – ikreb Nov 07 '19 at 00:05
  • 2
    Show how you did it. Sounds like you passed in the wrong thing. – Mad Physicist Nov 07 '19 at 00:06
  • It looks like my current code except ``Popen`` is replaced with ``run``. – ikreb Nov 07 '19 at 07:19
  • I mean edit your question with actual code. If something isn't working, describing what you think is important isn't really a good technique. If you knew what was important, you wouldn't be asking on SO. Please be specific and detailed. – Mad Physicist Nov 07 '19 at 07:26

1 Answers1

2

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.

tshiono
  • 21,248
  • 2
  • 14
  • 22
  • Thanks four your answer. But how do I get the result form subprocess.run? ``stdout`` is None. I get the ``CompletedProcess``. – ikreb Nov 07 '19 at 22:27
  • 1
    If my script properly prints the desired output on the terminal and you want to capture it to a variable, please try the updated answer. Hope it will work. – tshiono Nov 07 '19 at 23:31