convert dictionary entries into variables in a config file - python

import json
# import Adafruit_DHT
CONFIG_FILE = "config.json"
class Config():
def __init__(self):
with open(CONFIG_FILE) as config_file:
self.config_data = json.load(config_file)
locals().update(self.config_data)
print(Sensor_DHT11_PIN)
def get(self, key):
return self.config_data[key]
def Main ():
var = Config()
print(var.get("Sensor_DHT11_PIN"))
if __name__ == '__main__':
Main()
#ERROR MESSAGE:
#$ python loadconfig.py
#4
#Traceback (most recent call last):
# File "loadconfig.py", line 23, in <module>
# Main()
#File "loadconfig.py", line 20, in Main
# print(Sensor_DHT11_PIN)
#NameError: name 'Sensor_DHT11_PIN' is not defined
I want to be able to call a particular key from the dictionary and obtain that value, using the dictionary key as a variable, but when I run the function.
I obtain the value trough the "get" function of the Config class but no as a varible drawn out of the dicitonary:
How can I make this possible?

Related

Unable to construct python class

I have the following functions, that are working within the boundaries on the Python script
The loop_vcenters function will return a dictinary with cluster: host
subs_per_socket function will return the number of sockets for esx
def loop_vcenters(vcenters):
#------------------------- connect to vcenter ----------------------------------------
si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
# disconnect from vcenter one done
atexit.register(Disconnect, si)
#get the object content from vcenter
content = si.RetrieveContent()
#list clusters
cluster_host_dic_list=[]
cluster_name = ""
for cluster_obj in get_obj(content, vim.ComputeResource):
cluster=cluster_obj.name
hosts=[]
for host in cluster_obj.host:
hosts.append(host.name)
#create dictinary ,key=cluster value=esx
cluster_dic={cluster:hosts}
cluster_host_dic_list.append(cluster_dic)
return cluster_host_dic_list
def subs_per_socket(host):
shost = content.searchIndex.FindByDnsName(dnsName=host, vmSearch=False)
socket_count = shost.summary.hardware.numCpuPkgs
sub_per_socket = socket_count/2
return sub_per_socket
I want to put both functions into a class, but I cannot figure out how
class loop_vcenters:
def hosts_dic(self,name):
si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
atexit.register(Disconnect, si)
content = si.RetrieveContent()
cluster_host_dic_list=[]
cluster_name = ""
for cluster_obj in get_obj(content, vim.ComputeResource):
cluster=cluster_obj.name
hosts=[]
for host in cluster_obj.host:
hosts.append(host.name)
cluster_dic={cluster:hosts}
cluster_host_dic_list.append(cluster_dic)
return cluster_host_dic_list
I am unable to get the host dictionary like the loop_vcenters function returned.
d = loop_vcenters('vcenters')
Traceback (most recent call last):
File "", line 1, in
File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
How can I add the subs_per_socket(host) function to the class?
d = loop_vcenters('vcenters')
You are calling the class loop_vcenters with an argument when no init is defined.
File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
If you want to pass the argument to host_dic, you should be calling
d = loop_vcenters.host_dic('vcenters')
which will return cluster_host_dic_list to the variable d.
To add subs_per_socket(host), just define it under the class just as you did the other function.

raise AttributeError(name) AttributeError: LCC_GetChannelHandle

I am very new in python cffi. I have to access my temprature module by using its Index or with its channel name. I am trying with both as you can see in my QmixTC class. I am getting attribute error. In other class, there is no errors. Can someone help me understand where is the problem. I am putting my code as well as error trace. Thanks.
main code with name qmix.py (importing it in to sample code):
class QmixTC (object):
"""
"""
def __init__(self, index=0, handle=None,name=''):
self.dll_dir = DLL_DIR
self.dll_file = os.path.join(self.dll_dir,
'labbCAN_Controller_API.dll')
self._ffi = FFI()
self._ffi.cdef(CONTROLLER_HEADER)
self._dll = self._ffi.dlopen(self.dll_file)
self._handle = self._ffi.new('dev_hdl *', 0)
if handle is None:
self.index = index
self._handle = self._ffi.new('dev_hdl *', 0)
self._call('LCC_GetChannelHandle', self.index, self._handle)
else:
self.index = None
self._handle = handle
self._ch_name="QmixTC_1_DO0_INA"
self._channel = self._ch_name + str(index)
self._call('LCC_LookupChanByName',
bytes(self._channel,'utf8'),
self._handle)
self.name = name
def _call(self, func_name, *args):
func = getattr(self._dll, func_name)
r = func(*args)
r = CHK(r, func_name, *args)
return r
def Setpoint_write (self, setpoint):
"""
Write setpoint value to controller device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[in] fSetPointValue The setpoint value to write
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_WriteSetPoint', self._handle[0], setpoint)
def enable_controllLoop (self, enable):
"""
Enables / disables a control loop.
If the control loop is enabled, then the output value is calculated periodically.
Parameters
ChanHdl Valid handle of a controller channel
Enable 1 = enable, 0 = disable
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_EnableControlLoop', self._handle[0], enable)
def read_temp_value (self, actualvalue):
"""
Read actual value from device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[out] pfActualValue Returns the actual controller value
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_ReadActualValue', self._handle[0], actualvalue)
if __name__ == '__main__':
import os.path as op
dll_dir = op.normpath('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = op.normpath('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_Pump\\Configurations\\QmixTC_pump')
bus = QmixBus(config_dir=config_dir)
bus.open()
bus.start()
controller_0 = QmixTC(index=0)
controller_0.enable_controllLoop(1)
sample program:
from __future__ import division, print_function
from win32api import GetSystemMetrics
import numpy as np
import os
import qmix
import pandas as pd
#%% CHANNEL INITIALIZATION
if __name__ == '__main__':
dll_dir = ('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = ('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_test1\\Configurations\\QmixTC_test1')
qmix_bus = qmix.QmixBus(config_dir=config_dir,dll_dir=dll_dir)
qmix_bus.open()
qmix_bus.start()
controller_0 = qmix.QmixTC(index=0)
controller_0.Setpoint_write(50)
error:
Traceback (most recent call last):
File "<ipython-input-5-40d4a3db9493>", line 17, in <module>
controller_0 = qmix.QmixTC(index=0)
File "qmix.py", line 921, in __init__
self._call('LCC_GetChannelHandle', self.index, self._handle)
File "qmix.py", line 937, in _call
func = getattr(self._dll, func_name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 875, in __getattr__
make_accessor(name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 870, in make_accessor
raise AttributeError(name)
AttributeError: LCC_GetChannelHandle

how to return a collection from mongodb using pymongo

I'm trying to create a Collection Class in Python to access the various collections in my db. Here's what I've got:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
# self.data_base = getattr(self.client, db)
# self.collObject = getattr(self.data_base, self.collection_name)
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
def getCollectionKeys(self, collection):
"""Get a set of keys from a collection"""
keys_list = []
collection_list = collection.find()
for document in collection_list:
for field in document.keys():
keys_list.append(field)
keys_set = set(keys_list)
return keys_set
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
agents_collection = agents.getCollection
print agents_collection
print agents.getCollectionKeys(agents_collection)
I get the following output:
Begin Main
agents is <__main__.Collection instance at 0x10ff33e60>
<bound method Collection.getCollection of <__main__.Collection instance at 0x10ff33e60>>
Traceback (most recent call last):
File "collection.py", line 52, in <module>
print agents.getCollectionKeys(agents_collection)
File "collection.py", line 35, in getCollectionKeys
collection_list = collection.find()
AttributeError: 'function' object has no attribute 'find'
The function getCollectionKeys works fine outside of a class. What am I doing wrong?
This line:
agents_collection = agents.getCollection
Should be:
agents_collection = agents.getCollection()
Also, you don't need to use getattr the way you are. Your getCollection method can be:
def getCollection(self):
return self.client[self.db][self.collection_name]

Python unittesting initiate values

Sorry if this question is stupid. I created an unittest class which needs to take given inputs and outputs from outside. Thus, I guess these values should be initiated. However, I met some errors in the following code:
CODE:
import unittest
from StringIO import StringIO
##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
return a+b
class MyTestCase(unittest.TestCase):
def __init__(self,a,b,out):
self.a=a
self.b=b
self.out=out
def testMsed(self):
for i in range(self.tot_iter):
print i
fun = func1(self.a[i],self.b[i])
value = self.out[i]
testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
self.assertEqual(round(fun,3),round(value,3),testFailureMessage)
if __name__ == '__main__':
f = MyTestCase(a,b,out)
from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun
However, I got the following error
Traceback (most recent call last):
File "C:testing.py", line 33, in <module>
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class
Can anyone give me some suggestions? Thanks!
The root of the problem is this line,
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
unittest.makeSuite expects a class, not an instance of a class. So just MyTestCase, not MyTestCase(a, b, out). This means that you can't pass parameters to your test case in the manner you are attempting to. You should probably move the code from init to a setUp function. Either access a, b, and out as globals inside setUp or take a look at this link for information regarding passing parameters to a unit test.
By the way, here is the source file within python where the problem originated. Might be informative to read.

Why does pickle not see the class 'painter' when loading?

I am working with a o.o.p and trying to use pickle to load a list of lines I save in a .txt file. I can save the data with pickle, but I am not sure why it can't see 'painter' after I have initialized it.
class LoadButton(MTButton):
def __init__(self, **kwargs):
super(LoadButton, self).__init__(**kwargs)
self.buttonLoad = kwargs.get('painter')
def on_release(self, touch):
if touch.device != 'wm_pen':
newLoad = self.buttonLoad
loadFile = open('savefiles/savetest.txt', 'rb')
newpainter = painter
scatter.remove_widget(painter) # if removed error: EOF, no data read
# error: local var 'painter' referenced before assignment
oldlines = pickle.load(loadFile)
painter = newpainter
scatter.add_widget(painter)
pprint.pprint(oldlines)
loadFile.close()
return True
Any help would be awesome. Thanks.
It is because painter = newpainter creates a local variable painter, even if after the part when you call the global painter.
Do something like this:
painter_ = newpainter
scatter.add_widget(painter_)
EDIT: But why don't you use only painter?
scatter.remove_widget(painter)
oldlines = pickle.load(loadFile)
scatter.add_widget(painter)
EDIT 2:
Example:
>>> bar = 'Bar'
>>> def foo():
... bar # This is the local bar. It has not been assigned a value yet.
... bar = 'Local Bar' # Here I assign a value to the bar.
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'bar' referenced before assignment
>>>

Categories

Resources