python中until的用法_Python中“Try until no exception”的习惯用法

我希望我的代码能够自动尝试多种方法来创建数据库连接。一旦一个程序运行起来,代码就需要继续运行(也就是说,它不应该再尝试其他方法)。如果它们都失败得很好,那么脚本就可能爆炸。在

所以,在-我认为是,但很可能不是-一个天才的中风我尝试了这个:import psycopg2

from getpass import getpass

# ouch, global variable, ooh well, it's just a simple script eh

CURSOR = None

def get_cursor():

"""Create database connection and return standard cursor."""

global CURSOR

if not CURSOR:

# try to connect and get a cursor

try:

# first try the bog standard way: db postgres, user postgres and local socket

conn = psycopg2.connect(database='postgres', user='postgres')

except psycopg2.OperationalError:

# maybe user pgsql?

conn = psycopg2.connect(database='postgres', user='pgsql')

except psycopg2.OperationalError:

# maybe it was postgres, but on localhost? prolly need password then

conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass())

except psycopg2.OperationalError:

# or maybe it was pgsql and on localhost

conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass())

# allright, nothing blew up, so we have a connection

# now make a cursor

CURSOR = conn.cursor()

# return existing or new cursor

return CURSOR

但第二个和随后的except语句似乎不再捕捉到操作错误。可能是因为Python在try…except语句中只捕获一次异常?在

是这样吗?如果没有:还有什么我做错的吗?如果是这样的话:那你怎么做这样的事?有标准的成语吗?在

(我知道有一些方法可以解决这个问题,比如让用户在命令行中指定连接参数,但这不是我的问题好:)

编辑:

我接受了retracile的出色回答,并接受了gnibbler关于使用for..else结构的评论。最后的代码变成了(抱歉,我没有真正遵循pep8中每行最多字符数的限制):

编辑2:从Cursor类的注释中可以看到:我真的不知道如何调用这种类。它不是一个真正的单一实例(我可以有多个不同的Cursor实例),但是当调用get_Cursor时,我每次都会得到相同的Cursor对象。所以它就像是一个单件工厂?:)

^{pr2}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值