I have some python that talks to a tor daemon, here it tells the daemon to shut down.
from stem import Signal
from stem.control import Controller
def shutDownTor():
with Controller.from_port(port=portNum) as controller:
controller.signal(Signal.SHUTDOWN)
I'm using a with
statement because the code I'm stealing from learning from does so too. The code works fine, but I'm wondering if there is any point to using the with
statement.
I know that when you use with
to open files it makes sure the file closes even if there's an Exception
or interrupt. But in this case it seems like all with
is doing is adding an un-necessary tab. The variable controller
is even left inside the namespace.
If you would like to get rid of the with
statement you will have to handle all of the open
, close
and exception
on your own.
This will results with:
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()
Which results with the same and I will quote "un-necessary tab".
You can skip all of it (handle the close
, open
and exception
) if you are aware of and ready for all the consequences of it.
The Controller
class you import from stem
is a wrapper for ControlSocket
which is itself a wrapper around a socket connection to Tor protocol. So when you use with
in your code, you do so to open a connection with the given port. The same way the file
is open and closed, you will have to open and close the connection yourself if you want to get rid of with
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.