python - 如何在不导入所有内容的情况下触发函数?

标签 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()

最佳答案

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

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'是否在全局范围中,但这实际上是没有必要的,因为当您导入第二次调用模块时,它只是检索,不再进行繁重的计算。

关于python - 如何在不导入所有内容的情况下触发函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58540566/

相关文章:

Python 3.3 如何将此递归函数转换为纯 yield 循环版本?

python - 使用 XGBoost 根据输入预测重要性或百分比

python - 将 Unicode 字符串转换为 UTF-8,然后再转换为 JSON

python - 没有名为 'pip._vendor.cachecontrol' 的模块

python - LinkedIn 公司搜索 API

python - 如何将 Wikipedia wikitable 转换为 Python Pandas DataFrame?

python - 如何将光照应用于 pyopengl 上的 .obj 文件

python - 我想在plotly(python)中将数据显示为x轴上的百分比

python - 为什么某些 Python 包名称与其导入名称不同?

python - 从另一个 pip 安装的包针对本地代码运行 py.test 测试