Basim Aly
Basim Aly

Reputation: 134

Reuse opened connection to another script

I'm trying to build project consists of multiple python files. The first file is called "startup.py" and just responsible of opening connections to multiple routers and switches (each device allow only one connection at a time) and save them to the list. This script should be running all the time so other files can use it

#startup.py
def validate_connections_to_leaves():
    leaves = yaml_utils.load_yaml_file_from_directory("inventory", topology)["fabric_leaves"]
    leaves_connections = []
    for leaf in leaves:
        leaf_ip = leaf["ansible_host"]
        leaf_user = leaf["ansible_user"]
        leaf_pass = leaf["ansible_pass"]

        leaf_cnx = junos_utils.open_fabric_connection(host=leaf_ip, user=leaf_user, password=leaf_pass)
        if leaf_cnx:
            leaves_connections.append(leaf_cnx)

        else:
            log.script_logger(severity="ERROR", message="Unable to connect to Leaf", data=leaf_ip, debug=debug,
                              indent=0)

    return leaves_connections


if __name__ == '__main__':
    leaves = validate_connections_to_leaves()
    pprint(leaves)

    #Keep script running
    while True:
        time.sleep(10)

now I want to re-use these opened connections in another python file(s) without having to establish connections again. if I just import it to another file it will re-execute the startup script one more time.

can anyone help me to identify which part I'm missing here?

Upvotes: 0

Views: 50

Answers (1)

Thom
Thom

Reputation: 1623

You should consider your startup.py file as your entry point where all the logic is. You other files should be imported and used inside this file.

import otherfile1
import otherfile2
# import other file here

def validate_connections_to_leaves:
    # ...

if __name__ == '__main__':
    leaves = validate_connections_to_leaves()

    otherfile1.do_something_with_the_connection(leaves)

    #Keep script running
    while True:
        time.sleep(10)

And in your other file it will be simply:

def do_something_with_the_connection(leaves):
    # do something with the connections

Upvotes: 1

Related Questions