1

I want to execute this command from a python script:

iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f > scan.txt

I tried like the following

from subprocess import call
call(["iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f > scan.txt"])

but I get an error

SyntaxError: EOL while scanning string literal

How can I do that?

2
  • You can try first: import os and then: os.system("iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f scan.txt")m Commented Apr 18, 2016 at 10:02
  • The lack of an argument to awk -f is an error. Presumably you have a script file you want to run. Commented Apr 18, 2016 at 10:41

3 Answers 3

3

Pass shell=True to subprocess.call:

call("iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f scan.txt", shell=True)

Note that shell=True is not a safe option always.

Sign up to request clarification or add additional context in comments.

1 Comment

shell=True runs the command as if you would have entered it into your OS' terminal. That means as long as it's a fixed string which you verified, it's pretty safe. But never use shell=True if part of the command is not constant but from an insecure source (e.g. user input). Imagine this: text = input(); call("echo " + text, shell=True) and the user inputs I hate you; rm -rf /
1

While setting shell=True and removing the list brackets around the string will solve the immediate problem, running sed and Awk from Python is just crazy.

import subprocess
iw = subprocess.check_output(['is', 'wlan0', 'scan'])  # shell=False
with open('scan.txt', 'r') as w:
  for line in iw.split('\n'):
    line = line.replace('(on wlan', ' (on wlan')
    # ... and whatever your Awk script does
    w.write(line + '\n')

Comments

0

The commands module is simpler to use:

import commands
output = commands.getoutput("iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f scan.txt")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.