gpt4 book ai didi

python - 如何从with语句返回?

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:20 25 4
gpt4 key购买 nike

我有一个函数,它尝试一些参数列表来连接到 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)

关于python - 如何从with语句返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com