使用with语句创建stem.control.Controller对象是否有意义?

时间:2020-01-04 19:03:15

标签: python python-3.x stem

我有一些与Tor守护程序对话的python,在这里它告诉守护程序关闭。

from stem import Signal
from stem.control import Controller

def shutDownTor():
    with Controller.from_port(port=portNum) as controller:
        controller.signal(Signal.SHUTDOWN)

我正在使用with语句,因为我正在学习的代码也是如此。该代码可以正常工作,但是我想知道是否有必要使用with语句。

我知道,当您使用with打开文件时,即使有Exception或中断,也可以确保文件关闭。但是在这种情况下,似乎with所做的一切都是添加不必要的标签。变量controller甚至留在名称空间中。

2 个答案:

答案 0 :(得分:1)

如果您想摆脱 with语句,则必须处理所有opencloseexception靠你自己。

这将导致:

  try:
    controller = Controller.from_port()
  except stem.SocketError as exc:
    print("Unable to connect to tor on port 9051: %s" % exc)
    sys.exit(1)
  finally:
      controller.close()

哪些结果相同,我将引用“不必要的标签”。

如果您知道并准备好应对所有后果,则可以跳过所有内容(处理closeopenexception

答案 1 :(得分:1)

您从Controller导入的stem类是ControlSocket的{​​{3}},它本身就是Tor协议的wrapper。因此,当您在代码中使用with时,便可以打开与给定端口的连接。 file的打开和关闭方式相同,如果要摆脱with,则必须自己打开和关闭连接。