英文:
Python SQLite error only when run from terminal
问题
我使用此脚本在我的树莓派上保存温度和湿度数据,相关部分看起来像这样:
import sqlite3 as db
con = db.connect('hygolog.db')
cur = con.cursor()
# 这部分被注释掉,因为我在第一次运行时使用过它
# cur.execute("CREATE TABLE measure(time STR PRIMARY KEY, humidity REAL, tempertaure REAL)")
# con.commit()
while True:
cur.execute(f"""INSERT INTO measure
VALUES(datetime('now','localtime'),{round(humidity,3)},{round(temperature,3)})""")
con.commit()
当我从代码编辑器中执行文件时,这很好运行(我检查过,数据确实在数据库中找到),但当我从终端执行文件时,我会遇到以下错误:
user@raspberrypi:~ $ python Desktop/hygometer.py
Traceback (most recent call last):
File "/home/user/Desktop/hygometer.py", line 19, in <module>
cur.execute(f"""INSERT INTO measure
sqlite3.OperationalError: no such table: measure
这也是一个奇怪的地方失败,为什么在终端执行时找不到已经存在的表呢?
英文:
So I'm using this script to save temp and humidity data on my raspberry pi, the relevant part looks something like this:
import sqlite3 as db
con = db.connect('hygolog.db')
cur = con.cursor()
#This part is commented because I used it when running the first time
#cur.execute("CREATE TABLE measure(time STR PRIMARY KEY, humidity REAL, tempertaure REAL)")
#con.commit()
while True:
cur.execute(f"""INSERT INTO measure
VALUES(datetime('now','localtime'),{round(humidity,3)},{round(temperature,3)})""")
con.commit()
And this works just fine when executing the file from the code editor (i checked and data is found in the DB after), but when I execute the file from my terminal I get the following error:
user@raspberrypi:~ $ python Desktop/hygometer.py
Traceback (most recent call last):
File "/home/user/Desktop/hygometer.py", line 19, in <module>
cur.execute(f"""INSERT INTO measure
sqlite3.OperationalError: no such table: measure
which is also a weird place to fail, why should it not find the very much existing table when executed through the terminal?
答案1
得分: 2
尝试指定到 hygolog.db 的完整路径,例如 C:/Files/hygolog.db
。当您从终端运行时,您可能是从不同的文件夹运行的,因此它会在那个文件夹中创建一个新的空的 hygolog.db。
英文:
try specifying full path to hygolog.db, for example C:/Files/hygolog.db
. When you run this from terminal, you could be running from a different folder, so it creates a new empty hygolog.db in that folder.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论