Невозможно удалить файл .db из моего скрипта, но это можно сделать из любого другого места - PullRequest
0 голосов
/ 06 июня 2019

Если я запускаю приведенный ниже скрипт, он выдает ошибку, показанную. Однако, если я переключаю терминал и запускаю ту же команду для удаления файла (os.remove("test.db")), файл удаляется.

import gc
import os
import time

from sqlite3 import connect
from contextlib import contextmanager


file = "test.db"


@contextmanager
def temptable(cur: object):
    cur.execute("create table points(x, int, y int)")
    try:
        yield
    finally:
        cur.execute("drop table points")


with connect(file) as conn:
    cur = conn.cursor()
    with temptable(cur=cur):
        cur.execute("insert into points (x, y) values(1, 1)")
        cur.execute("insert into points (x, y) values(1, 2)")
        cur.execute("insert into points (x, y) values(2, 1)")
        for row in cur.execute("select x, y from points"):
            print(row)
        for row in cur.execute("select sum(x * y) from points"):
            print(row)

os.remove(file)

Файл "c: \ Users \ You_A \ Desktop \ 2019Coding \ context_generator_decorator.py", строка 32, в os.remove (файл) PermissionError: [WinError 32] Процесс не может получить доступ к файлу, поскольку он используется другим процессом: 'test.db'

Опять же, запуск os.remove("test.db") в любом терминале успешно удаляет файл.

1 Ответ

1 голос
/ 06 июня 2019

Это может быть вызвано тем, что соединение с базой данных не закрыто. Попробуйте использовать contextlib.closing(). Модифицированный код будет выглядеть так:

import gc
import os
import time

from sqlite3 import connect
from contextlib import contextmanager, closing


file = "test.db"


@contextmanager
def temptable(cur: object):
    cur.execute("create table points(x, int, y int)")
    try:
        yield
    finally:
        cur.execute("drop table points")


with closing(connect(file)) as conn:
    # cur = closing(conn.cursor()) --> if auto-closing of cursor is desired
    cur = conn.cursor() # if auto closing of cursor is not desired
    with temptable(cur=cur):
        cur.execute("insert into points (x, y) values(1, 1)")
        cur.execute("insert into points (x, y) values(1, 2)")
        cur.execute("insert into points (x, y) values(2, 1)")
        for row in cur.execute("select x, y from points"):
            print(row)
        for row in cur.execute("select sum(x * y) from points"):
            print(row)

os.remove(file)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...