Python SQLite error only when run from terminal

huangapple go评论74阅读模式
英文:

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(&#39;hygolog.db&#39;)
cur = con.cursor()

#This part is commented because I used it when running the first time
#cur.execute(&quot;CREATE TABLE measure(time STR PRIMARY KEY, humidity REAL, tempertaure REAL)&quot;)
#con.commit()

while True:
    cur.execute(f&quot;&quot;&quot;INSERT INTO measure
VALUES(datetime(&#39;now&#39;,&#39;localtime&#39;),{round(humidity,3)},{round(temperature,3)})&quot;&quot;&quot;)
    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 &quot;/home/user/Desktop/hygometer.py&quot;, line 19, in &lt;module&gt;
    cur.execute(f&quot;&quot;&quot;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.

huangapple
  • 本文由 发表于 2023年2月18日 21:09:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定