I programmed a gateway to a opcua-server with python-opcua.
The gateway is subscribing some values in the opcua. That is working good and fast.
Now I want to call a script that writes to the opcua.
In principle, it works too. But because I have to import the whole gateway(and all opcua stuff), it is very slow...
My Question: Is is possible to trigger a function in my class-instance without imorting everything?
To start e.g. function setBool(), I have to import 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()
The only way to prevent a code from runing when importing a module is to put it inside a method:
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
I checked that 'pandas' is in global scope before reimport it again but really this is not necessary, because when you import a module for the second time it's just retrieved no heavy calculation again.
Related
I am working on an addon, for anki, which requires me to import a new deck using its python API. I found the function called test_apkg which seems to have parts which do that. I tried implimenting that below, I am getting no errors, however the deck does not get imported. How do I make my testFunction() import a deck for anki?
from aqt import mw
from aqt.utils import showInfo, qconnect
from aqt.qt import *
from anki.importing import *
import os
from anki.collection import Collection as aopen
#from anki.pylib.tests.shared import getEmptyCol
from .shared import getEmptyCol
def testFunction() -> None:
file = "flashcards.apkg"
col = getEmptyCol()
apkg = r"path_to_file/flashcards.apkg"
imp = AnkiPackageImporter(col, apkg)
imp.run()
# create a new menu item, "test"
action = QAction("Import", mw)
# set it to call testFunction when it's clicked
qconnect(action.triggered, testFunction)
# and add it to the tools menu
mw.form.menuTools.addAction(action)
Currently learning ROS with LGSVL Simulator. I want to publish to "/move_base_simple/goal" topic.
In main code just showing important "import" and the end of the code
import rospy
import roslibpy
from rospy import rostime
import lgsvl
import logging
from environs import Env
from geometry_msgs.msg import PoseStamped
import publisher
### LGSVL SETUP ###
...
###################
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()
This is my publisher
import rospy
import rospkg
import std_msgs
from geometry_msgs.msg import PoseStamped
class GoalPublisher():
def __init__(self):
rospy.init_node('webapp', disable_signals=True)
self.goal_publisher = rospy.Publisher("move_base_simple/goal", PoseStamped, queue_size=10)
def publish_2d_nav_goal(self, pose_x, pose_y, pose_z):
goal = PoseStamped()
goal.header.stamp = rospy.Time.now()
goal.header.frame_id = "map"
goal.pose.position.x = pose_x
goal.pose.position.y = pose_y
goal.pose.position.z = pose_z
goal.pose.orientation.x = 0.0
goal.pose.orientation.y = 0.0
goal.pose.orientation.z = -0.663932738254
goal.pose.orientation.w = 0.747792296747
self.goal_publisher.publish(goal)
When i am trying to start my main code, i get this error:rospy.exceptions.ROSInitException: time is not initialized. Have you called init_node()?
Do i need to add "rospy.init_node(...)" in the main code ? Or how can i fix this issue ?
You need to call rospy.init_node() for every ros node you create. You can call it wherever you want in the node, however, it must be called before trying to use anything in the ros api. In this example your publisher is fine but you're calling roslibpy.Ros() before initializing the main code as it's own node.
rospy.init_node('main_node')
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()
I tried to execute the code to create class as client but the problem display talk about the Self._public_key is not defined
...NameError: name 'self' is not defined
# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
# following imports are required by PKI
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
class Client:
def __init__(self):
random = Crypto.Random.new().read
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)
def identity(self):
return
binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
Dinesh = Client()
print (Dinesh.identity)
You are writing binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') at the next line. Try writing it after the return keyword. Hope your error will go away
you should define a Clinet instance and then get it's _public_key:
binascii.hexlify(Client._public_key.exportKey(format='DER')).decode('ascii')
You need to get the identity property with the help of a function, not as a plain attribute. Modify your identity() function as follows:
def identity(self):
idn = binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') # <------
return idn # <------
And then, you can call it like:
Dinesh = Client()
print(Dinesh.identity()) # <------
In a project, I would like to separate the visualization and calculation in two different modules. The goal is to transfer the variables of the calculation-module to a main-script, in order to visualize it with the visualization-script.
Following this post
Using global variables between files?,
I am able to use a config-script in order to transfer a variable between to scripts now. But unfortunately, this is not working when using threading. The Output of the main.py is always "get: 1".
Does anyone have an idea?
main.py:
from threading import Thread
from time import sleep
import viz
import change
add_Thread = Thread(target=change.add)
add_Thread.start()
viz.py:
import config
from time import sleep
while True:
config.init()
print("get:", config.x)
sleep(1)
config.py:
x = 1
def init():
global x
change.py:
import config
def add():
while True:
config.x += 1
config.init()
OK, fount the answer by myself. Problem was in the "main.py". One has to put the "import viz" after starting the thread:
from threading import Thread
from time import sleep
import change
add_Thread = Thread(target=change.add)
add_Thread.start()
import viz
below is my code that I am trying to turn into a windows service. You'll see test.py as the call it makes and all this is a short script that writes into a log file (as a test).
The code is there to make it a windows service and it does that fine, but when I run it nothing writes into the log file. Help greatly appreciated. Below is the code:
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time
class aservice(win32serviceutil.ServiceFramework):
_svc_name_ = "MyServiceShortName"
_svc_display_name_ = "A python test"
_svc_description_ = "Writing to a log"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
self.timeout = 1000 #1 seconds
# This is how long the service will wait to run / refresh itself (see script below)
while 1:
# Wait for service stop signal, if I timeout, loop again
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# Check to see if self.hWaitStop happened
if rc == win32event.WAIT_OBJECT_0:
# Stop signal encountered
servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!") #For Event Log
break
else:
#what to run
try:
file_path = "test.py"
execfile(file_path)
except:
pass
#end of what to run
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(aservice)
Edit: Thought for the sake of it I'd include my test.py file's code, it has unnecessary imports but will get the job done if you run it alone.
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os
logfile = open("log.txt", "a") #open file to log restart timestamp
logfile.write("\nthat's good!!!!")
logfile.close()
Okay so I figured it out and would like to come back and post in case anyone else is dealing with this, all though this was a tad unique.
You have to specify your file path if you are within a windows service, duh... but it wasn't done and I pulled my hair out for no reason.
file_path = "test.py"
should have been
file_path = r"c:\users\...\test.py"
Be careful when using '\' for windows file paths. They must be escaped like '\\' or the string must be declared as raw string ('r'). Using the unix like slash '/' separators works also but may look odd for windows users.