user6204136
user6204136

Reputation:

Execute shell command from Python Script

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?

Upvotes: 1

Views: 203

Answers (3)

João Pinto
João Pinto

Reputation: 5619

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

Upvotes: 0

tripleee
tripleee

Reputation: 189297

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

Upvotes: 1

heemayl
heemayl

Reputation: 41987

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.

Upvotes: 3

Related Questions