How to select import object name from another function - python

EDIT: I have managed to solved the issue I wa having previously but instead of me creating another new question, this issue I have encountered are pretty much similar I guess?
As I am modifying some of the contents of this script that I am currently doingn, it will boot up this UI whenever user imports in a .chan object
Currently I am trying to edit the camera name such that when users selects the camera, it will inherits the name of the imported camera into its namespace.
Though I am not very sure, I think the reader function in the customNodeTranslator class is the one that reads the imported camera?
This is the error messgae:
# Error: global name 'cameraName' is not defined
# Traceback (most recent call last):
# File "/user_data/scripts/test/maya/plugins/chan.py", line 210, in readFileIn
# self.importTheChan = ChanFileImporter(chanRotationOrder)
# File "/user_data/scripts/test/maya/plugins/chan.py", line 286, in __init__
# self.cameraName = cameraName
# NameError: global name 'cameraName' is not defined #
This is the original code:
class customNodeTranslator(OpenMayaMPx.MPxFileTranslator):
...
...
...
def reader(self, fileObject, optionString, accessMode):
self.initialWindow()
try:
fullName = fileObject.fullName()
print ">>> full Name is %s" %fullName
#self.fileHandle = open(fullName,"r")
camHandle = open(fullName,"r")
camPath = os.path.basename(camHandle.name)
camName = os.path.splitext(camPath)[0]
print ">>> This is the name: %s" % camName
except:
sys.stderr.write( "Failed to read file information\n")
raise
return camName
class chanImport():
""" importing chan camera from nuke """
def __init__(self, rotation):
self.rotation = rotationOrder
# create the camera
self.cameraName = cmds.camera(n=str(camName))
self.cameraShape = self.cameraName[1]
cmds.select(self.cameraShape)
cmds.scale(0.5, 0.5, 0.5)
The following code is the actual code itself before I modified:
class customNodeTranslator(OpenMayaMPx.MPxFileTranslator):
...
...
...
def writer( self, fileObject, optionString, accessMode ):
try:
fullName = fileObject.fullName()
fileHandle = open(fullName,"w")
selectList = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(selectList)
node = OpenMaya.MObject()
depFn = OpenMaya.MFnDependencyNode()
path = OpenMaya.MDagPath()
iterator = OpenMaya.MItSelectionList(selectList)
animationTime = OpenMayaAnim.MAnimControl()
class ChanFileImporter():
def __init__(self, rotationOrder):
self.rotationOrder = rotationOrder
# create the camera
self.cameraName = cmds.camera()
self.cameraShape = self.cameraName[1]
cmds.select(self.cameraShape)
cmds.scale(0.5, 0.5, 0.5)

You aren't passing the camName to the importer class. In fact you're not invoking the importer class at all in the sample above.
If you modify chanImport so it takes the name you want:
class chanImport(object):
""" importing chan camera from nuke """
def __init__(self, camName):
self.desiredCameraName = camName
self.cameraName = None
self.cameraShape = None
def create_camera(self):
self.cameraName, self.cameraShape = cmds.camera(n=str(camName))
cmds.select(self.cameraShape)
cmds.scale(0.5, 0.5, 0.5)
return self.cameraName
You should be able to invoke it inside your reader function:
def reader(self, fileObject, optionString, accessMode):
self.initialWindow()
try:
fullName = fileObject.fullName()
print ">>> full Name is %s" %fullName
camHandle = open(fullName,"r")
camPath = os.path.basename(camHandle.name)
camName = os.path.splitext(camPath)[0]
print ">>> This is the name: %s" % camName
importer = chanImport(camName)
actual_cam_name = importer.create_camera()
print ">>> created " + actual_cam_name
return actual_cam_name
except:
sys.stderr.write( "Failed to read file information\n")
raise

Related

TypeError: __init__() got an unexpected keyword argument 'dir'

I try to start a timer to do some file arvchival job. the code is like this:
from threading import Timer
message_archive_dir = "achivedir"
message_archive_format = "zip"
archive_timer = Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
archive_timer.start()
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = dir
self.message_archive_format = fmt
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
I got below error:
Traceback (most recent call last):
File "sa_listener.py", line 43, in <module>
archive_timer = Timer(archive_interval, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
TypeError: __init__() got an unexpected keyword argument 'dir'
I'm not sure why _init_ does not accept **kwargs.
This specific init error is because you are passing multiple variables to the timer class.
In this line:
Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
You are passing the archive function, the dir variable, and the fmt variable to TIMER and not to the messageachiver class. Timer has no named variables for dir and fmt.
So the line should be Timer(86400, messageachiver.archive)
This only partially fixes your problem though. Because you are never actually initializing the class with the variables you need them to have. So before you call timer, you need to initialize the class messageachiver by adding mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
Also you need to put your class definition before you try to initialize it.
The final code:
from threading import Timer
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = kwargs['dir']
self.message_archive_format = kwargs['fmt']
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
message_archive_dir = "achivedir"
message_archive_format = "zip"
mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
# That's a huge wait time, try something like 10 for a smaller wait during testing.
archive_timer = Timer(86400, mymessageachiver.archive)
archive_timer.start()

how to read data by using pywinusb in python

I can't read hid data by using pywinusb in python.
I referred to this page(https://www.reddit.com/r/learnpython/comments/3z346p/reading_a_usb_data_stream_on_windows/)
and I have question.
def sample_handler(data):
print("Raw data: {0}".format(data))
sample_handler function needs to data.
but
device.set_raw_data_handler(sample_handler)
this code do not give data to sample_handler. is it not error?
and below is my code.
my code don't catch read_handler function.
how can i fix it. could you help me?
from pywinusb import hid
import time
class PIC18f:
def __init__(self, VID = 0x04D8, PID=0x003f):
filter = hid.HidDeviceFilter(vender_id = VID, product_id = PID)
self.devices = filter.get_devices()
self.device = self.devices[0]
self.device.open()
def write(self, args):
out_report = self.device.find_output_reports()
out_report[0].set_raw_data(args)
out_report[0].send()
time.sleep(1)
def read_handler(self, data):
print("Raw data: {0}".format(data))
print("done")
def I2C_Init(self):
buf = [0x00]
buf = buf + [0 for i in range(65-len(buf))]
buf[1] = 0xF1
buf[2] = 0x1D
self.write(buf)
self.device.set_raw_data_handler(read_handler)
test = PIC18f()
test.I2C_Init()
this is error.
Traceback (most recent call last):
File "d:/1. Siliconmitus/python/test2.py", line 35, in
test.I2C_Init()
File "d:/1. Siliconmitus/python/test2.py", line 32, in I2C_Init
self.device.set_raw_data_handler(read_handler)
NameError: name 'read_handler' is not defined
read_handler is not defined because the "read_handler" should be defined inside I2C_Init.
The following is an example:
from pywinusb import hid
filter = hid.HidDeviceFilter(vendor_id = 0x0001, product_id = 0x0002)
devices = filter.get_devices()
device = devices[0]
def readData(data):
print(data)
return None
device.set_raw_data_handler(readData)
device.open()

instantiate object inside of class

Im trying to understand why I cannot access the methods on an object that is instantiated inside of a class. For example i'm attempting to build a script that utilizes the python-pptx library and I want to wrap the entire slide creation within a class to abstract it and make it a bit more reusable based on my configuration.
class Builder():
def __init__(self, template='template.pptx', output_file='out.pptx'):
self.cust_name = ''
self.author = ''
self.job_title = ''
self.present_date = ''
self.assessment_type = ''
self.template = template
self.agenda = ['Overview','Resources']
self.outfile = output_file
self.prs = Presentation('template.pptx') <--- This is what im referring to.
def addAgendaSlide(self):
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA]) <-- When trying to access this
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[10].text = 'A test Agenda slide'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
for para in self.agenda:
p = agenda_slide.placeholders[15].text_frame.add_paragraph()
p.text = para
Traceback (most recent call last):
File "test.py", line 19, in <module>
test.addAgendaSlide()
File "/dev/pythonpptx/DocMaker/Slides.py", line 89, in addAgendaSlide
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
AttributeError: 'Presentation' object has no attribute 'add_slide'
If I use the same bits of code outside the class it works fine. I do have other methods in the class that are fine, it seems to be my implementation of the Presentation() bit that is messing me up.
The following works fine:
prs = Presentation('template.pptx')
agenda_slide = prs.slides.add_slide(prs.slide_layouts[AGENDA])
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
prs.save('out.pptx')
I think your problem is you are forgetting to add slides as follows:
agenda_slide = self.prs.slides.add_slide(self.prs.slide_layouts[AGENDA])
instead of
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])

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

Categories

Resources