AttributeError: 'MainWindow' object has no attribute 'dev' - python-3.x

Hy,
Yeah so, i am writing an python3 programm, that should send the content of an file to an LPC1758.
For testing i will write a simple string above USB. I use libusb1.0 ....
But every time i become the same error, even if i rename "dev" into "device" the error is the same.
--> AttributeError: 'MainWindow' object has no attribute 'dev'<--
class MainWindow(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pb_send.clicked.connect(self.pb_send_clicked)
self.pb_open.clicked.connect(self.pb_open_clicked)
self.pb_exit.clicked.connect(self.pb_exit_clicked)
# SEND button event handler
def pb_send_clicked(self):
send = "Yo Man"
bulk_out_ep = 0x05
bulk_in_ep = 0x82
interface = 0
length = 30
dev = usb.core.find(idVendor= 0xfefe, idProduct= 0x0001)
cfg = usb.control.get_configuration(dev) # get current configuration
print(dev)
if dev is None:
self.USB_label.setText("Device not found !!!")
raise ValueError('Device not found')
else:
self.USB_label.setText("Device found")
found = 1
if(cfg != 1): # check if device is configured
usb.DeviceHandle.setConfiguration(self, 1)
usb.util.claim_interface(dev, interface)
usb.DeviceHandle.bulkWrite(self,bulk_out_ep,send)
print("wrote to estick")
readData = usb.DeviceHandle.bulkRead(self, bulk_in_ep, length)
print("read from estick: "+ readData)
usb.util.release_interface(dev, interface)
This is what Stacktrace shows:
Traceback (most recent call last):
File "/home/user/workspace_Qt/ESS_project/ess_project.py", line 93, in pb_send_clicked
readData = usb.DeviceHandle.bulkRead(self,endpoint=bulk_in_ep,size=length)
File "/usr/lib/python3.3/usb/legacy.py", line 159, in bulkRead
return self.dev.read(endpoint, size, self.__claimed_interface, timeout)
AttributeError: 'MainWindow' object has no attribute 'dev'

dev is a member of the class DeviceHandle which is the type of the first parameter expected by the setConfiguration functions.
And setConfiguration expects 2 parameters instead of 1, because you are calling the method on the class usb.DeviceHandle instead of calling it on an object of type usb.DeviceHandle, you should use:
dev.setConfiguration(1)
(same thing for bulkWrite and bulkRead).
Also the get_configuration method returns a Configuration object instead of a number, so cfg != 1 will always be true (this may work with cfg.index != 1 instead but I'm not sure).

Related

Tweepy StreamingClient custom __init__ / arguments - super() not working

I'm looking to stream tweets to json files. I'm using Twitter API v2.0, with Tweepy 4.12.1 and Python 3.10 on Ubuntu 22.04. I'm working with the tweepy.StreamingClient class, and utilizing the on_data() method.
class TweetStreamer(tweepy.StreamingClient):
def __init__(self,
out_path:str,
kill_time:int=59,
time_unit:str='minutes'):
'''
adding custom params
'''
out_path = check_path_exists(out_path)
self.outfile = out_path
if time_unit not in ['seconds', 'minutes']:
raise ValueError(f'time_unit must be either `minutes` or `seconds`.')
if time_unit=='minutes':
self.kill_time = datetime.timedelta(seconds=60*kill_time)
else:
self.kill_time = datetime.timedelta(seconds=kill_time)
super(TweetStreamer, self).__init__()
def on_data(self, data):
'''
1. clean the returned tweet object
2. write it out
'''
# out_obj = data['data']
with open(self.outfile, 'ab') as o:
o.write(data+b'\n')
As you can see, I'm invoking `super() on the parent class, with the intention of retaining all the stuff that is invoked if I didn't specify a custom init.
However, however I try to change it, I get this error when I try to create an instance of the class, passing a bearer_token as well as the other arguments defined in __init__() :
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [106], line 1
----> 1 streamer = TweetStreamer(bearer_token=bearer_token, out_path='test2.json')
TypeError: TweetStreamer.__init__() got an unexpected keyword argument 'bearer_token'
Any help would be greatly appreciated.
You get this error because you declared that __init__ does not take bearer_token as an argument. You need to pass the keyword arguments your constructor gets to the constructor of the superclass that is expecting them. You can do it using the unpacking operator **:
def __init__(self,
out_path:str,
kill_time:int=59,
time_unit:str='minutes',
**kwargs):
'''
adding custom params
'''
# (...)
super(TweetStreamer, self).__init__(**kwargs)

calling one python object from another

I have two different modules (files) where I store different objects.
The work flow is - call objects from different files and return the values from the database. If I call object from file_1 below, it returns required values from the database. However when I call object from file_1 in file_2, it returns 'None' even though input parameter is supplied.
file_1
class Database(object):
database = None
host = None
port = None
def __init__(self, host=None, port=None):
self.host=None
self.port=None
def client_(self):
return MongoClient()
def find_spefic_director(self, db=None, coll=None, directorId=None):
'''If when a specific director id is supplied it returns director related information'''
project={'_id': 0}
filter={'directorid': directorId}
print(directorId)
if not directorId is None:
result = self.client_()[db][coll].find(projection=project,
filter=filter)
return [i for i in result]
else:
return 'valid Id is required'
if __name__ == "__main__":
Database()
file_2
class Graph(object):
def __init__(self, host=None, port=None):
self.host=None
self.port=None
self.directorId=None
def minMaxDate(self, db=None, coll=None, directorId=None):
dr= Database(self.host, self.port).find_spefic_director(self.directorId)
drt=dr(directorId)
return drt
if __name__ == "__main__":
Graph()
Now I am trying to call Database() in file 2 for further processing in a different file
from file_1 import Database
from file_2 import Graph as gc
gc(directorId=340769.0).minMaxDate(db, coll='directory', directorId=340769.0)
when I run, it returns
None
TypeError Traceback (most recent call last)
<ipython-input-3-2d56a89c0288> in <module>
----> 1 gc().minMaxDate(db, coll='crsp_na_wrds_company_director_names', directorId=340769.0)
~/graph_construct.py in minMaxDate(self, db, coll, directorId)
25
26 dr= Database(self.host, self.port).find_spefic_director(self.directorId)
---> 27 drt=dr(directorId)
28
29
TypeError: 'str' object is not callable
What should be done to return the values stored in the database?

RuntimeError: Queue objects should only be shared between processes through inheritance

I'm having some trouble with ProcessPoolExecutor.
The following code is trying to find the shortest path in a WikiRace game, it gets 2 titles and navigates between one to another.
Here is my code:
class AsyncSearch:
def __init__(self, start, end):
self.start = start
self.end = end
# self.manager = multiprocessing.Manager()
self.q = multiprocessing.Queue()
# self.q = self.manager.Queue()
def _add_starting_node_page_to_queue(self):
start_page = WikiGateway().page(self.start)
return self._check_page(start_page)
def _is_direct_path_to_end(self, page):
return (page.title == self.end) or (page.links.get(self.end) is not None)
def _add_tasks_to_queue(self, pages):
for page in pages:
self.q.put(page)
def _check_page(self, page):
global PATH_WAS_FOUND_FLAG
logger.info('Checking page "{}"'.format(page.title))
if self._is_direct_path_to_end(page):
logger.info('##########\n\tFound a path!!!\n##########')
PATH_WAS_FOUND_FLAG = True
return True
else:
links = page.links
logger.info("Couldn't find a direct path form \"{}\", "
"adding {} pages to the queue.".format(page.title, len(links)))
self._add_tasks_to_queue(links.values())
return "Couldn't find a direct path form " + page.title
def start_search(self):
global PATH_WAS_FOUND_FLAG
threads = []
logger.debug(f'Running with concurrent processes!')
if self._add_starting_node_page_to_queue() is True:
return True
with concurrent.futures.ProcessPoolExecutor(max_workers=AsyncConsts.PROCESSES) as executor:
threads.append(executor.submit(self._check_page, self.q.get()))
I'm getting the following exception:
Traceback (most recent call last):
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\queues.py", line 241, in _feed
obj = _ForkingPickler.dumps(obj)
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\queues.py", line 58, in __getstate__
context.assert_spawning(self)
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\context.py", line 356, in assert_spawning
' through inheritance' % type(obj).__name__
RuntimeError: Queue objects should only be shared between processes through inheritance
It's weird since I'm using multiprocessing.Queue() that should be shared between the processes as mentioned by the exception.
I found this similar question but couldn't found the answer there.
I tried to use self.q = multiprocessing.Manager().Queue() instead of self.q = multiprocessing.Queue(), I'm not sure if this takes me anywhere but the exception I'm getting is different:
Traceback (most recent call last):
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\queues.py", line 241, in _feed
obj = _ForkingPickler.dumps(obj)
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
File "c:\users\tomer smadja\appdata\local\programs\python\python36-32\lib\multiprocessing\process.py", line 282, in __reduce__
'Pickling an AuthenticationString object is '
TypeError: Pickling an AuthenticationString object is disallowed for security reasons
Also, when I'm trying to use multiprocessing.Process() instead of ProcessPoolExecutor, I'm unable to finish the process once I do find a path. I set up a global variable to stop PATH_WAS_FOUND_FLAG to stop the process initiation but still with no success. What I'm missing here?
ProcessPoolExecutor.submit(...) will not pickle multiprocessing.Queue instances as well other shared multiprocessing.* class instances. You can do two things: One is to use SyncManager, or you can initialize the worker with the multiprocessing.Queue instance at ProcessPoolExecutor construction time. Both are shown below.
Following is your original variation with a couple of fixes applied (see note at end)... with this variation, multiprocessing.Queue operations are slightly faster than below SyncManager variation...
global_page_queue = multiprocessing.Queue()
def set_global_queue(q):
global global_page_queue
global_page_queue = q
class AsyncSearch:
def __init__(self, start, end):
self.start = start
self.end = end
#self.q = multiprocessing.Queue()
...
def _add_tasks_to_queue(self, pages):
for page in pages:
#self.q.put(page)
global_page_queue.put(page)
#staticmethod
def _check_page(self, page):
...
def start_search(self):
...
print(f'Running with concurrent processes!')
with concurrent.futures.ProcessPoolExecutor(
max_workers=5,
initializer=set_global_queue,
initargs=(global_page_queue,)) as executor:
f = executor.submit(AsyncSearch._check_page, self, global_page_queue.get())
r = f.result()
print(f"result={r}")
Following is SyncManager variation where queue operations are slightly slower than above multiprocessing.Queue variation...
import multiprocessing
import concurrent.futures
class AsyncSearch:
def __init__(self, start, end):
self.start = start
self.end = end
self.q = multiprocessing.Manager().Queue()
...
#staticmethod
def _check_page(self, page):
...
def start_search(self):
global PATH_WAS_FOUND_FLAG
worker_process_futures = []
print(f'Running with concurrent processes!')
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
worker_process_futures.append(executor.submit(AsyncSearch._check_page, self, self.q.get()))
r = worker_process_futures[0].result()
print(f"result={r}")
Note, for some shared objects, SyncManager can be anywhere from slightly to noticeably slower compared to multiprocessing.* variations. For example, a multiprocessing.Value is in shared memory whereas a SyncManager.Value is in the sync manager processes, requiring overhead to interact with it.
An aside, unrelated to your ask, your original code was passing _check_page with incorrect parameters, where you were passing dequeued item to self, leaving the page parameter None. I resolved this by changing _check_page to a static method and passing self.

How to display image in wxpython?

Please help me with this code. I want to display image in the frame :
import wx
import os
class frame(wx.Frame):
'''frame class that display an image'''
def __init__(self, image, parent=None, id=-1,
pos=wx.DefaultPosition, title='Hello, wxPyhton!'):
'''creat a frame instance and display image.'''
temp = image.ConvertToBitmap()
size = temp.GetWidth(), temp.GetHeight()
wx.Frame(parent, id, pos, title, size)
self.bmp = wx.StaticBitmap(parent=self, bitmap=temp)
class App(wx.App):
'''Application class.'''
def OnInit(self):
image = wx.Image('clem.jpg', wx.BITMAP_TYPE_JPEG)
self.frame = frame(image)
self.frame.Show()
return True
if __name__ == '__main__':
app = App()
app.MainLoop()
But i got this error:
Traceback (most recent call last):
File "C:/PycharmProjects/WXPYHTON/hello.py", line 18, in OnInit
self.frame = frame(image)
File "C:/PycharmProjects/WXPYHTON/hello.py", line 11, in __init__
wx.Frame(parent, id, pos, title, size)
TypeError: Frame(): arguments did not match any overloaded call:
overload 1: too many arguments
overload 2: argument 3 has unexpected type 'Point'
OnInit returned false, exiting...
Process finished with exit code 1
please help this code. i don't know where i'm getting it wrong.
I've changed it but i'm still getting this error
Traceback (most recent call last):
File "C:/PycharmProjects/WXPYHTON/hello.py", line 18, in OnInit
self.frame = frame(image)
File "C:/PycharmProjects/WXPYHTON/hello.py", line 12, in __init__
self.bmp = wx.StaticBitmap(parent=None, bitmap=temp)
TypeError: StaticBitmap(): arguments did not match any overloaded call:
overload 1: 'parent' is not a valid keyword argument
overload 2: 'bitmap' is not a valid keyword argument
OnInit returned false, exiting...
please check my self.bmp, if it is correct. Thanks
You are not initialising the frame properly and you are using keywords as variable names.
Change:
wx.Frame(parent, id, pos, title, size)
To:
wx.Frame.__init__(self,parent,id,pos=pos,title=title,size=size)
and it should work.

How do I pass an attribute to a function in the same class?

I am having trouble with this code. The goal is to "encrypt" a message that the user inputs by reversing the input. The lesson was originally written as a functional block of code, but I wanted to convert it to object-oriented programming and now I get an error. Please let me know if I have any other issues in this code.
This is the code
class Encrypt:
def __init__(self,message,translated):
self.message = message # user input
self.translated = translated # encrypted result
def encryptionProcess(self,message): # encrypting functino
i = len(message) - 1
while i >= 0:
self.translated = self.translated + self.message[i]
i = i - 1
m1 = Encrypt(input(),'') # setting the class attributes
m1.encryptionProcess(message) # calling the function
print(Encrypt.translated) # printing the result
This is the error
Traceback (most recent call last):
File "oopEncrypt.py", line 13, in <module>
m1.encryptionProcess(message)
NameError: name 'message' is not defined
Accessing class instance attributes is done with the self parameter, passed as the first parameter to the class instance method.
Try this:
class Encrypt:
def __init__(self, message):
self.message = message # user input
def encryptionProcess(self): # encrypting functin
translated = "".join(reversed(self.message))
return translated
m1 = Encrypt(input("Enter word to encrypt > "))
translated = m1.encryptionProcess()
print("Encrypted Word:", translated)
self is the instance of the current class.
You may find the python 3 class docs a useful reference: https://docs.python.org/3.6/tutorial/classes.html

Resources