重用打开的连接到另一个脚本

时间:2019-03-09 15:52:21

标签: python

我正在尝试构建包含多个python文件的项目。第一个文件称为“ startup.py”,仅负责打开与多个路由器和交换机的连接(每个设备一次仅允许一个连接)并将它们保存到列表中。该脚本应该一直运行,以便其他文件可以使用它

#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)

现在,我想在另一个python文件中重新使用这些打开的连接,而不必再次建立连接。如果我仅将其导入到另一个文件中,它将再次重新执行启动脚本。

有人可以帮助我确定我在这里缺少哪些部分吗?

1 个答案:

答案 0 :(得分:1)

您应该将startup.py文件视为所有逻辑所在的入口点。您应该将其他文件导入并在该文件内部使用。

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)

在您的其他文件中,它将很简单:

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