从Python脚本执行shell命令

时间:2016-04-18 10:00:33

标签: python bash shell

我想从python脚本执行此命令:

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

我尝试了以下

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

但是我收到了错误

SyntaxError: EOL while scanning string literal

我该怎么做?

3 个答案:

答案 0 :(得分:3)

shell=True传递给subprocess.call

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

请注意,shell=True始终不是一个安全的选择。

答案 1 :(得分:1)

设置shell=True并删除字符串周围的列表括号将解决当前问题,从Python运行sed和Awk只是疯了。

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

答案 2 :(得分:0)

commands模块更易于使用:

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