gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:26 25 4
gpt4 key购买 nike

我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com