Python中的“尝试”,除了明确导入的模块,还可能出现的错误

2024-04-18 10:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

当一个模块类不在我的脚本中,但被其中一个模块使用时(我确实显式地导入了),我如何捕获他的错误?

例如:

from sqlite3 import dbapi2 as sqlite

class sqldb:

def __init__(self):
  self.sqlite.connect('records.db')
  self.c = self.conn.cursor()    

def query(self,query,values)
 try:
  self.c.execute(query, values)
  self.conn.commit()
 except sqlite3.OperationalError:
  print "SQLite DB locked"

将导致(当数据库被锁定时):

NameError: global name 'sqlite3' is not defined

但当我没有捕捉到错误时,它会给我一个异常:“sqlite3.operationaleror”

那我该怎么说呢?还是只导入整个sqlite3模块?如果是,这不增加我的程序的资源占用吗?


Tags: 模块fromimportself脚本sqlitedefas
2条回答

将以下行放在程序的顶部:

import sqlite3

告诉Python将名称sqlite3与模块关联。

或者,可以显式导入捕获的错误:

from sqlite3 import OperationalError

...

try:
    self.c.execute(query, values)
    self.conn.commit()
except OperationalError:
    print "SQLite DB locked"

Or should I just import the whole sqlite3 module?

是的。

If yes, doesn't this increase the resources footprint of my program?

不——模块还是导入的。您的import语句所做的一切就是向模块的全局命名空间添加对sqlite3的引用。

相关问题 更多 >