【发布时间】:2019-12-26 01:15:11
【问题描述】:
我有一个 Python 程序,它创建一个 SQLite .db 文件,然后执行一个 .sql 脚本来初始化该 db 中的表 TRANSACTIONS。作为我设计的一部分,如果在创建 TRANSACTIONS 表时出现任何问题,我想删除 .db 本身,以免留下不完整的数据库。
我的问题是,当我尝试使用os.remove(db_path) 删除 .db 文件时,我收到一个 Win32 错误,表明 .db 文件正在被另一个进程使用。我无法弄清楚这个过程是什么。
我的模块,initialize_db.py:
import sqlite3 as sql
import os
class initialize_db:
# Parameters are Path objects of where to create the DB,
# and where to find the DB initialization script
def __init__(self, db_path, init_script_path):
self.db_path = db_path
self.init_script_path = init_script_path
try:
self.cursor = self.create_db()
self.initialize_transactions()
# If an exception is raised, delete the entire database
except ValueError:
print('Error encountered, DB not created')
self.cursor.close()
os.remove(db_path) # This is causing the issue
raise
def create_db(self):
'''Creates .db database at self.db_path'''
conn = sql.connect(self.db_path)
print('creating database')
return conn.cursor()
def initialize_transactions(self):
'''Initializes the TRANSACTIONS table within the database'''
with open(self.init_script_path, 'r') as init_script:
sql_script = init_script.read()
raise ValueError # Raise this before executing sql script as a test
self.cursor.execute(sql_script)
print('initialization script executed')
我故意在initialize_transactions() 中引发一个ValueError,以测试我的.db 是否从__init__() 中正确删除。如果我执行此操作,我会得到以下信息:
from initialize_db import initialize_db
initialize_db(my_db_path, my_db_script_path)
Traceback(最近一次调用最后一次):
...
文件 "C:\some_database_path\initialize_db.py", 第 26 行,在 init
中os.remove(db_path)
PermissionError: [WinError 32] 进程无法访问文件 因为它正在被另一个进程使用: 'C:\some_database_path\database.db'
所以基本上,我的程序正在创建我的数据库,但在引发异常时没有正确删除它。对我的程序到达那里时可能正在使用db_path 的进程有任何想法吗?我尝试调查是否应该关闭 Path 对象以及光标,但似乎都不起作用。
【问题讨论】:
-
您是否尝试使用“以管理员身份运行”打开命令提示符,然后运行您的脚本?
-
我不是从命令提示符运行我的程序,而是从 Spyder 中运行。但是,这是在我的个人资料具有管理权限的个人计算机上。如果我误解了您的问题,请告诉我。
-
不,你没有误解我的意思。我误解了错误。特权没有问题。尝试改用“os.removedirs”并告诉我