如何在不导入所有内容的情况下触发功能?

时间:2019-10-24 11:38:53

标签: python

我用python-opcua编程了一个通往opcua服务器的网关。 网关在opcua中订阅了一些值。效果很好而且很快。 现在,我想调用一个写入opcua的脚本。 原则上,它也可以工作。但是因为我必须导入整个网关(以及所有opcua东西),所以它非常慢...

我的问题:是否可以在我的类实例中触发一个函数而又不影响所有内容?

例如要开始函数setBool(),我必须导入Gateway ...

#!/usr/bin/env python3.5 -u
# -*- coding: utf-8 -*-

import time
import sys
import logging
from logging.handlers import RotatingFileHandler
from threading import Thread

from opcua import Client
from opcua import ua

from subscribeOpcua import SubscribeOpcua
from cmdHandling import CmdHandling 
from keepConnected import KeepConnected

class Gateway(object):

    def __init__(self):

        OPCUA_IP   = '1.25.222.222'
        OPCUA_PORT = '4840' 
        OPCUA_URL = "opc.tcp://{}:{}".format(OPCUA_IP, str(OPCUA_PORT))
        addr = "OPCUA-URL:{}.".format(OPCUA_URL)

        # Setting up opcua-handler
        self.client = Client(OPCUA_URL)

        self.opcuaHandlers = [SubscribeOpcua()]

        # Connect to opcua
        self.connecter = KeepConnected(self.client,self.opcuaHandlers)
        self.connecter.start()

    def setBool(self, client):
        """Set e boolean variable on opcua-server.
        """
        path = ["0:Objects","2:DeviceSet"...]
        root = client.get_root_node()
        cmd2opcua = root.get_child(path)
        cmd2opcua.set_value(True)

if __name__ == "__main__":
    """Open connecter when gateway is opened directly.
    """
    connect = Gateway()

1 个答案:

答案 0 :(得分:0)

防止代码在导入模块时运行的唯一方法是将其放入方法中:

def import_first_part():
    global re
    global defaultdict
    print('import this first part')
    # import happen locally 
    # because when you do `import re` actually
    # re = __import__('re')
    import re
    from collections import defaultdict


def import_second_part():
    print('import pandas')
    # really unnecessary check here because if we import
    # pandas for the second time it will just retrieve the object of module
    # the code of module is executed only in the first import in life of application. 
    if 'pandas' in globals():
        return
    global pandas
    import pandas



def use_regex():
    import_first_part()
    # do something here



if __name__ == '__main__':
    use_regex()
    re.search('x', 'xb')  # works fine

我再次检查了'pandas'之前global scope是否在reimport中,但这确实不是必须的,因为当您第二次导入模块时,它只是已检索< / strong>无需再进行大量计算。