Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Context Managers


[Image: hJCWljW.png]
[Image: y4XuedU.png]
[Image: a8DAjI9.png]
[Image: PcUlOcU.png]
[Image: 4hBJ51C.png]

I'm not a fan of the way HF formats code so I'm going to be posting pictures. Click the link at the top for the code itself.

I have a few more tutorials planned, let me know if you guys want anything specific.
Nice! Too many people on here don't use context managers, and then they mess up their try/finally blocks.

It should also be noted that, while Python 2.7 does not have built in support for certain context managers (primarily sockets), you can (and should) use the contextlib module.

PHP Code

<?php 
#!/usr/bin/env python3
import socket
with socket
.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    
sock.connect(("7.7.7.7", 80)) 

This will work in Python3, but will not in Python2. Generally, what you do is this:

PHP Code

<?php 
#!/usr/bin/env python2
import socket

sock 
= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    
sock.connect(("7.7.7.7", 80))
finally:
    
sock.close() 

Equivalently, you can use contextlib's "closing" wrapper:
PHP Code

<?php 
#!/usr/bin/env python2
import socket
from contextlib import closing
with closing
(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
    
sock.connect(("7.7.7.7", 80)) 

etc...

But yes, context managers are just classes that have the_enter_ and_exit_ functions defined. That timer is actually pretty nifty, although I usually just use a decorator.
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials
(Feb 21, 2017 12:18 PM)Goodies Wrote:  -snip-

I didn't know that since I don't work with sockets but I've seen a few other people use them on here. Thanks!
(Feb 21, 2017 12:47 PM)(╯°□°)╯︵ ┻━━┻ Wrote:  I didn't know that since I don't work with sockets but I've seen a few other people use them on here. Thanks!

Yeah! Context managers are about as close as we can get to constructors/destructors.
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Python] by iRazorOct 15, 2021 12:35 PM 3 150 Oct 15, 2021 12:35 PM
Last Post: steel iron
[Shell] by Emre_May 30, 2020 05:19 AM 5 231 May 30, 2020 05:19 AM
Last Post: Emre_
[Shell] by Emre_May 28, 2020 09:36 PM 0 113 May 28, 2020 09:36 PM
Last Post: Emre_