gpt4 book ai didi

python - 使用 Python 在 Pi 启动时写入 MySQL 数据库

转载 作者:太空宇宙 更新时间:2023-11-04 11:49:42 25 4
gpt4 key购买 nike

我的 Raspberry Pi 托管了一个 MySQL 数据库。当我的 Pi 启动时,它运行一个写入数据库的 python 脚本。该脚本将日期、时间和 IP 地址写入数据库。

执行此操作的 python 脚本在从终端运行时运行完美。但是,当我尝试在启动时运行 python 脚本时,什么也没有发生。创建一个 cronjob 来运行 python 脚本向我展示了一个错误正在产生说:“导入错误:没有名为 mysql.connector 的模块”

我只是不确定如果我手动运行它,为什么脚本在启动时不能正常工作。

我尝试直接从 /etc/rc.local 运行脚本运行方式:

sudo python /home/pi/PyScripts/py2db.py&

我还创建了一个名为 launcher 的 sh 脚本。然后我在 sh 脚本中调用 python 脚本并从 crontab 调用 launcher.sh。启动器脚本背后的想法是,如果我向 Pi 的启动添加更多内容,我可以向该脚本添加 exra 行。

python 脚本在运行 launcher.sh 文件或 py2db.py 文件时正常启动。

我为 contab 创建了一个输出,以查看它尝试运行时会发生什么。

Crontab 代码:

@reboot /home/pi/Scripts/launcher.sh >/home/pi/Logs/cronlog 2>&1

launcher.sh

#!/bin/sh
launcher.sh
python /home/pi/PyScripts/py2db.py

Crontab 日志

Traceback (most recent call last):
File "/home/pi/PyScripts/py2db.py", line 3, in <module>
import mysql.connector
ImportError: No module named mysql.connector

py2db.py

#!/usr/bin/python3

import mysql.connector
import datetime
from ipaddress import IPAddress
import sys

ipaddress = IPAddress()
ip = ipaddress.get_ipaddress()

now = datetime.datetime.now()
time = now.isoformat()
date = now.strftime("%Y-%m-%d")

mydb = mysql.connector.connect(
host="localhost",
user="mark",
passwd="password",
database="mydb"
)

mycursor = mydb.cursor()

sql = "INSERT INTO piLog (date, time, ip) VALUES (%s, %s, %s)"
val = (date, time, ip)
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")
print("[py2db] - Done.")

sys.exit()

我希望 python 脚本在启动时运行并向数据库写入一个条目。该条目将时间、日期和 ip 地址添加到指定的数据库表中。

目前启动时没有任何反应。 python 脚本只会在手动调用时写入数据库。

最佳答案

当您将脚本作为 cronjob 运行时,它似乎无法找到正确的 PYTHONPATH。首先,使用以下脚本找到您的模块路径:

import os
import mysql
mysql_path = os.path.dirname(mysql.__file__)
print(mysql_path)

接下来在导入mysql之前将mysql_path添加到sys.path:

#!/usr/bin/python3

from ipaddress import IPAddress
import datetime
import mysql.connector
import sys
sys.path.append('<mysql_path>')


ipaddress = IPAddress()
ip = ipaddress.get_ipaddress()

now = datetime.datetime.now()
time = now.isoformat()
date = now.strftime("%Y-%m-%d")

mydb = mysql.connector.connect(
host="localhost",
user="mark",
passwd="password",
database="mydb"
)

mycursor = mydb.cursor()

sql = "INSERT INTO piLog (date, time, ip) VALUES (%s, %s, %s)"
val = (date, time, ip)
mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")
print("[py2db] - Done.")

sys.exit()

关于python - 使用 Python 在 Pi 启动时写入 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com