我有一个函数,它尝试一些参数列表来连接到 ftp 并连接到它可以连接到的第一个服务器。
def connect(params):
for user, passw, host in params:
try:
import pdb;pdb.set_trace()
with FTPHost(host, user, passw) as h:
return h
except FTPError as e:
logger.debug("Can't connect to ftp error is {}".format(e))
else:
raise Exception(
"Can't connect to ftp server with none of the {}".format(params)
)
在代码中我正在尝试类似的事情
host = connect(*args)
host.walk()
但返回后连接立即关闭。我想这可能就是它应该如何工作,尽管我希望它不会。但现在我真的不知道如何正确封装应用程序逻辑中的连接尝试。
我的意思是我当然可以将其更改为连续传递样式(这是正确的名称,对吧?)
def connect(params, some_application_function):
for user, passw, host in params:
try:
import pdb;pdb.set_trace()
with FTPHost(host, user, passw) as host:
some_application_function(host)
except FTPError as e:
logger.debug("Can't connect to ftp error is {}".format(e))
else:
raise Exception(
"Can't connect to ftp server with none of the {}".format(params)
)
但这似乎不太可读。还有其他选择吗?
也许可以将 with 语句移到 connect 函数之外?
def connect(params):
for user, passw, host in params:
try:
import pdb;pdb.set_trace()
return FTPHost(host, user, passw)
except FTPError as e:
logger.debug("Can't connect to ftp error is {}".format(e))
else:
raise Exception(
"Can't connect to ftp server with none of the {}".format(params)
)
def main():
with connect(params) as h:
do_something(h)
我是一名优秀的程序员,十分优秀!