-1

I'm trying to concatenate python variables into os.system, the command seems to execute but it doesn't take properly the value allocated.

I've tried using both os.system and subprocess, but none of them work. Here is some of my attempts.

interface = os.popen("netstat -i | awk '$1 ~ /^w/ {print $1}'")
os.system("iw dev %s station dump" % (interface))

.

interface = os.popen("netstat -i | awk '$1 ~ /^w/ {print $1}'")
os.system("iw dev" +interface+ "station dump")

.

p1 = subprocess.Popen(["netstat", "-i"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["awk", '$1 ~ /^w/ {print $1}'], stdin=p1.stdout, 
stdout=subprocess.PIPE)

displayInterface = p2.communicate()[0].decode('ascii')
retrieveMac = subprocess.Popen(["iw", "dev", displayInterface, "station", "dump"])
Alvaromr7
  • 25
  • 8
  • try `'string something {} something'.format('loremipsum')` this should return 'string something loremipsum something'. String concatenation is unreliable at least for me. – Alex Bodnya May 08 '19 at 17:59
  • 2
    @AlexBodnya There is no string concatenation in the `subprocess` attempt (which, frankly, is the only one worth debugging). – chepner May 08 '19 at 18:00
  • `os.popen` returns a file handle, not a string. You should use `subprocess` since `os.popen` is deprecated. – Dennis Williamson May 08 '19 at 18:05
  • So how can I use a python variable into os.system() or subprocess? – Alvaromr7 May 08 '19 at 18:24
  • The `subprocess` example looks correct to me, except that the last `Popen` call should probably be `subprocess.check_output` or `subprocess.run` instead. Actually, it will be easier to debug if you run each command one at a time rather than trying to parallelize with a pipeline. What about it is not working? – Daniel Pryden May 08 '19 at 21:20
  • The subprocess command doesn't work well beacause it prints: `iw dev 0 station dump`. Instead I need `iw dev wlan0 station dump`. – Alvaromr7 May 08 '19 at 22:52

1 Answers1

0

In this line:

displayInterface = p2.communicate()[0].decode('ascii')

displayInterface results in a string with a trailing newline. I don't know whether you need the decode(), but you need to strip the newline.

displayInterface = p2.communicate()[0].rstrip()

You can specify the character(s) to strip in an argument to rstrip() if necessary.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439