树莓派64位系统已装requests却提示模块缺失的问题求助
PiHole监控脚本依赖问题与解决办法
问题背景
PiHole偶尔宕机导致全网无法解析域名,编写监控脚本时出现No module named Requests报错。已通过sudo pip install requests安装模块,pip show requests显示版本为2.25.1,但当前运行环境为Python2.7.18,且requests实际安装路径为/home/usr/.local/lib/python3.9/site-packages(属于Python3.9环境)。本机装有OMV,不敢随意测试PiHole操作,计划通过cron+tmux设置脚本开机启动。
核心原因
Python2与Python3的包管理是独立的,pip默认对应Python2,但requests被安装到了Python3的站点包目录中,导致Python2.7无法找到该模块。
解决方案
1. 匹配Python版本安装依赖
- 若坚持用Python2.7运行脚本,安装对应版本的requests:
sudo pip2 install requests==2.25.1 - 若改用Python3运行脚本,无需重新安装,直接用
python3命令执行即可(已有的requests属于Python3.9环境)。
2. 修正脚本错误
原脚本存在两处问题,需修正后使用:
- 网址拼写错误:
htts://google.com改为https://google.com - Python2.7不支持
subprocess.run(),若用Python2运行需替换为subprocess.call()
适配Python3的修正脚本
import requests import subprocess import time def check_reachability(url): try: response = requests.get(url, timeout=10) # 增加超时限制,避免无响应卡顿 return response.status_code == 200 except: return False def reboot_pihole(): subprocess.run(["pihole", "restartdns"]) while True: reachable = check_reachability("https://google.com") if not reachable: reboot_pihole() time.sleep(60) # 每60秒执行一次检查
适配Python2.7的修正脚本
import requests import subprocess import time def check_reachability(url): try: response = requests.get(url, timeout=10) return response.status_code == 200 except: return False def reboot_pihole(): subprocess.call(["pihole", "restartdns"]) # Python2.7兼容写法 while True: reachable = check_reachability("https://google.com") if not reachable: reboot_pihole() time.sleep(60)
3. 设置开机启动(cron+tmux)
- 安装tmux(若未安装):
sudo apt update && sudo apt install tmux -y - 编辑用户crontab:
crontab -e - 添加开机启动命令,替换
/path/to/your/script.py为脚本实际路径:
此命令会在开机时创建一个名为# 用Python3运行脚本的情况 @reboot tmux new-session -d -s pihole_monitor 'python3 /path/to/your/script.py' # 用Python2运行脚本的情况 # @reboot tmux new-session -d -s pihole_monitor 'python /path/to/your/script.py'pihole_monitor的后台tmux会话,自动运行监控脚本。
内容的提问来源于stack exchange,提问作者grunchyelliptical
相关产品推荐
相关产品推荐

