1)使用psutils检查进程是否使用了数据库文件:import os
import psutil
import sqlite3
con = sqlite3.connect('temp.db')
def is_open(path):
for proc in psutil.process_iter():
try:
files = proc.get_open_files()
if files:
for _file in files:
if _file.path == path:
return True
except psutil.NoSuchProcess as err:
print(err)
return False
con = sqlite3.connect('temp.db')
path = os.path.abspath('temp.db')
print(is_open(path))
con.close()
print(is_open(path))
输出:True
False
2)为了读取,操作系统无论如何都应该缓存文件以便您可以读取,如果您尝试写入,将引发以下错误:sqlite3.OperationalError: attempt to write a readonly database
正如您所说,在运行sqlite3.connect之前检查db是否存在:if os.path.exists(db):You can't force the sqlite3.connect function to not create the db file.