【发布时间】:2021-12-03 22:13:44
【问题描述】:
我无法对这个做出正面或反面。尝试在 python 脚本中使用子进程通过iw 抓取我的 wifi 信号。终端命令工作正常:
root@123da06:/app# iw dev wlan0 link | grep signal | awk '{print $2}'
-62
但是尝试在 python 中运行时失败:
root@123da06:/app# python3 sub.py
Traceback (most recent call last):
File "sub.py", line 2, in <module>
output_bytes = subprocess.check_output("iw dev wlan0 link | grep signal | awk '{print $2}'")
File "/usr/local/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/local/lib/python3.8/subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/local/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/local/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: "iw dev wlan0 link | grep signal | awk '{print $2}'"
脚本再简单不过了:
import subprocess
output_bytes = subprocess.check_output("iw dev wlan0 link | grep signal | awk '{print $2}'")
output = output_bytes.decode("utf-8")
print(f'Signal: {output}')
我做错了什么?
【问题讨论】:
-
您可以尝试使用
shell=True选项运行,例如:subprocess.check_output("iw dev wlan0 link | grep signal | awk '{print $2}'", shell=True) -
即使在 shell 中,也最好将其写为双命令管道:
iw dev wlan 0 link | awk '/signal/ {print $2}'。使用 Python,我也会跳过awk并在 Python 本身中处理iw的输出。for line in subprocess.check_output(["iw", "dev", "wlan0", "link"]): ....
标签: python shell command-line subprocess