Python SQLite error only when run from terminal

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

Python SQLite error only when run from terminal

问题

我使用此脚本在我的树莓派上保存温度和湿度数据,相关部分看起来像这样:

  1. import sqlite3 as db
  2. con = db.connect('hygolog.db')
  3. cur = con.cursor()
  4. # 这部分被注释掉,因为我在第一次运行时使用过它
  5. # cur.execute("CREATE TABLE measure(time STR PRIMARY KEY, humidity REAL, tempertaure REAL)")
  6. # con.commit()
  7. while True:
  8. cur.execute(f"""INSERT INTO measure
  9. VALUES(datetime('now','localtime'),{round(humidity,3)},{round(temperature,3)})""")
  10. con.commit()

当我从代码编辑器中执行文件时,这很好运行(我检查过,数据确实在数据库中找到),但当我从终端执行文件时,我会遇到以下错误:

  1. user@raspberrypi:~ $ python Desktop/hygometer.py
  2. Traceback (most recent call last):
  3. File "/home/user/Desktop/hygometer.py", line 19, in <module>
  4. cur.execute(f"""INSERT INTO measure
  5. 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:

  1. import sqlite3 as db
  2. con = db.connect(&#39;hygolog.db&#39;)
  3. cur = con.cursor()
  4. #This part is commented because I used it when running the first time
  5. #cur.execute(&quot;CREATE TABLE measure(time STR PRIMARY KEY, humidity REAL, tempertaure REAL)&quot;)
  6. #con.commit()
  7. while True:
  8. cur.execute(f&quot;&quot;&quot;INSERT INTO measure
  9. VALUES(datetime(&#39;now&#39;,&#39;localtime&#39;),{round(humidity,3)},{round(temperature,3)})&quot;&quot;&quot;)
  10. 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:

  1. user@raspberrypi:~ $ python Desktop/hygometer.py
  2. Traceback (most recent call last):
  3. File &quot;/home/user/Desktop/hygometer.py&quot;, line 19, in &lt;module&gt;
  4. cur.execute(f&quot;&quot;&quot;INSERT INTO measure
  5. 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:

确定