1 year ago

#110691

test-img

jawalking

using atexit.register with a defined __exit__ function

I'm trying to figure out how to best close a connection when I'm done with a custom object, but I'm not to sure how using atexit.register() will work with a defined __exit__() function

import atexit

from pyVim.connect import Disconnect, SmartConnect


class ConnectHostAPI(_ConnectHost):
    def __init__(self, host_ip) -> None:
        self.host_ip = host_ip

    def __enter__(self):
        # Connect to host
        try:
            self.service_instance = SmartConnect(
                host=self.host_ip,
                user=self.host_user,
                pwd=self.host_password,
                disableSslCertValidation=True
            )

            atexit.register(Disconnect, self.service_instance)
        except IOError as io_error:
            print(f"{io_error=}")

        return self

    def __exit__(self, type, value, traceback):
        del self


host_api_connection = ConnectHostAPI(host_ip)
with host_api_connection as con:
    # do something with con
    pass

python

exit

with-statement

pyvmomi

atexit

0 Answers

Your Answer

Accepted video resources