简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM