python无法从命令行写入sqlite3 db

时间:2014-01-20 02:45:35

标签: python command-line sqlite

我有一个python脚本,它读取ds18b20传感器的临时文件并将其写入位于同一目录中的sqlite3数据库。写入数据库的代码部分如下所示:

def write_DB(devID, devNAME, temp):
    conn = sqlite3.connect('templog.db')
    curs = conn.cursor()

    curs.execute("INSERT INTO temps values((?),(?), datetime('now'), (?))", (devID, devNAME, temp))

    conn.commit()

从idle3运行时它运行正常,但是从命令行或cron运行时,这是输出:

 ~/python/HydroMon $ /usr/bin/python /home/pi/python/HydroMon/ds18b20_scanner.py
Traceback (most recent call last):
 File "/home/pi/python/HydroMon/ds18b20_scanner.py", line 102, in <module>
  scan_dev()
 File "/home/pi/python/HydroMon/ds18b20_scanner.py", line 69, in scan_dev
  write_DB(file, dev, temp)
 File "/home/pi/python/HydroMon/ds18b20_scanner.py", line 49, in write_DB
  curs.execute("INSERT INTO temps values((?),(?), datetime('now'), (?))", (devID, devNAME, temp))
sqlite3.OperationalError: unable to open database file

知道为什么这不会从命令行运行?所有权限都是正确的。

编辑:我将此添加到write_db()

global basedir
db_file = basedir + '/templog.db'
conn = sqlite3.connect(db_file)

这不再产生和错误。这是打开和读取conf文件的basedir赋值函数,现在会导致错误。我试过python和python3。

#Configuratio Directory
fullpath = sys.argv[0]
basedir = os.path.dirname(fullpath)
confdir = basedir + "/conf"

#Variable to check if scan was good
reading = 0
def get_dev_name(devID):
    global confdir
    devName = 'NONE'
    #open conf file
    conf = confdir + '/devname.conf'
    print(conf)
    cfile = open(conf,mode='r')

从idle3运行时,结果是:     /home/pi/python/HydroMon/conf/devname.conf

从命令行运行时:

~/python/HydroMon $ sudo python3 ds18b20_scanner.py 
/conf/devname.conf
Traceback (most recent call last):
 File "ds18b20_scanner.py", line 105, in <module>
  scan_dev()
 File "ds18b20_scanner.py", line 70, in scan_dev
  dev = get_dev_name(file)
 File "ds18b20_scanner.py", line 27, in get_dev_name
  cfile = open(conf,mode='r')
IOError: [Errno 2] No such file or directory: '/conf/devname.conf'

1 个答案:

答案 0 :(得分:0)

从命令行运行时,请尝试打印sys.argv[0]。您可能会惊讶地发现它是ds18b20_scanner.py,这使得dirname成为一个空字符串。

如果您尝试写入与脚本相同的位置,也许您想要使用__file__而不是sys.argv[0]