[英]Execute shell command from Python Script
I want to execute this command from a python script: 我想从python脚本执行以下命令:
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
: 将shell=True
传递给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. 请注意, shell=True
并非总是安全的选项。
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. 虽然设置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')
The commands
module is simpler to use: commands
模块更易于使用:
import commands
output = commands.getoutput("iw wlan0 scan | sed -e 's#(on wlan# (on wlan#g' | awk -f scan.txt")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.