When i run the code below, i got an exception
# System
import time
import logging
import sys
import os
import threading
# cv2 and helper:
import cv2
class inic_thread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
if self.counter == 1: capture_continuos()
elif self.counter == 2: face_search()
def capture_continuos():
#os.system('python capture_continuos.py')
while(1):
print 'a'
def face_search():
# atributes
pool = []
path_pool = './pool/'
while(1):
pool_get = os.listdir(path_pool)
if len(pool_get) > 0:
#print(str(len(pool_get))+' images in the pool')
for image in pool_get:
print(image)
os.system('python face_search.py -i '+str(image))
else:
print('Empty Pool')
try:
capture_continuos = inic_thread(1, "capture_continuos_1", 1)
face_search_2 = inic_thread(2, "face_search_2", 2)
capture_continuos.start()
face_search_2.start()
except:
print("Error: unable to start thread")
But it don't make sense to me, because one of the threads run normal, (face_search) but the other one give this exception.
Starting capture_continuos_1
Exception in thread capture_continuos_1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "main.py", line 44, in run
if self.counter == 1: capture_continuos()
TypeError: 'inic_thread' object is not callable
What i'm doing wrong?
I run in a Raspberry Pi 3 model B with Ubuntu MATE 14.04; Python 2.7.12
At the bottom of your script you redefine variable capture_continuos assigning thread object to it.
Also as was mentioned to terminate thread it's better to call os._exit() instead of sys.exit().
Related
I am trying to run a simple threading function within my simple class.
I am trying to call the Thread function within a method of a class. This Thread function within this method points to another method within the class. The way I tested it out is through the python terminal. Here is my class in increment_thread.py:
from threading import Thread
import time
class Increment:
def __init__(self):
self.count = 0
def add_one(self):
while True:
self.count = self.count + 1
time.sleep(5)
def start(self):
background_thread = Thread(target=add_one)
background_thread.start()
print("Started counting up")
return
def get_count(self):
return print(self.count)
In order to test this, I run python in my terminal, which prompt the python terminal.
Then, I run the following lines:
from increment_thread import Increment
inc = Increment()
inc.get_count() # Yields 0
inc.start()
I expect the thread to start and indicate "Started counting up", but instead I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/python-sandbox/increment_thread.py", line 14, in start
background_thread = Thread(target=add_one)
NameError: name 'add_one' is not defined
Is what I am trying to do possible?
In the Thread constructor should it not be target=self.add_one rather than target=add_one
To pass parameters:
from threading import Thread
import time
class Increment:
count = None
def __init__(self):
self.count = 0
def add_one(self, start_at=0):
self.count = start_at
while True:
self.count = self.count + 1
time.sleep(5)
def start_inc(self, start_at=count):
# Pass args parameter as a tuple
background_thread = Thread(target=self.add_one, args=(start_at,))
background_thread.start()
print("Started counting up")
return
def get_count(self):
return print(self.count)
if __name__ == "__main__":
inc = Increment()
inc.get_count() # Yields 0
inc.start_inc(start_at=5)
while True:
inc.get_count()
time.sleep(2)
Just like class fields, class methods need to be referred to using self.method syntax. So
def start(self):
background_thread = Thread(target=self.add_one)
background_thread.start()
print("Started counting up")
return
python async_io.py
Giving this following
error traceback (most recent call last): File "aysnc_io.py", line 64, in Task(get('/foo')) NameError: name 'get' is not defined
I am using python2.7 of coroutines to get concurrent processing and i am getting error get not defined however it is defined inside the Task class.
from selectors2 import DefaultSelector,EVENT_WRITE,EVENT_READ
import socket
import time
selector=DefaultSelector()
global n_tasks
n_tasks=0
class Future:
def __init__(self):
self.callbacks=[]
def resolve(self):
for c in self.callbacks:
c()
class Task:
def __init__(self,gen):
self.gen=gen
self.step()
def step(self):
try:
f=next(self.gen)
except StopIteration:
return
f.callbacks.append(self.step)
def get(path):
n_tasks +=1
s=socket.socket()
s.setblocking(False)
try:
s.connect(('localhost',80))
except BlockingIOError:
pass
request ='GET %s HTTP/1.0 \r\n\r\n' % path
f=Future()
selector.register(s.fileno(),EVENT_WRITE,data=f)
#need to pause s until it is writable
yield f
selector.unregister(s.fileno())
#s is writable
s.send(request.encode())
chunks=[]
while TRUE:
f=Future()
selector.register(s.fileno(),EVENT_READ,data=f)
yield f
selector.unregister(s.fileno())
chunk=s.recv(1000)
if chunk:
chunk.append(chunk)
else:
body=(b''.join(chunks)).decode()
print(body.split('\n')[0])
n_tasks-=1
return
start=time.time()
Task(get('/www.google.com'))
while n_tasks:
events=selector.select()
for event,mask in events:
fut=event.data
fut.resolve()
print('executed %.lf seconds' % (time.time()-start()))
As I understand, you should move get definition outside of class
class Task:
def __init__(self,gen):
...
def step(self):
...
def get(path):
...
New to Python multi-thread and write such simple program, here is my code and error message, any ideas what is wrong? Thanks.
Using Python 2.7.
import time
import thread
def uploader(threadName):
while True:
time.sleep(5)
print threadName
if __name__ == "__main__":
numOfThreads = 5
try:
i = 0
while i < numOfThreads:
thread.start_new_thread(uploader, ('thread'+str(i)))
i += 1
print 'press any key to exit test'
n=raw_input()
except:
print "Error: unable to start thread"
Unhandled exception in thread started by <pydev_monkey._NewThreadStartupWithTrace instance at 0x10e12c830>
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydev_monkey.py", line 521, in __call__
return self.original_func(*self.args, **self.kwargs)
TypeError: uploader() takes exactly 1 argument (7 given)
thanks in advance,
Lin
The args of thread.start_new_thread need to be a tuple. Instead of this:
('thread' + str(i)) # results in a string
Try this for the args:
('thread' + str(i),) # a tuple with a single element
Incidentally, you should check out the threading module, which is a higher-level interface than thread.
In the following, threadName is now a global variable defined towards the top of the program code, then the variable is initialized before the new thread is started with the target being the upload function.
Try this:
import time
import thread
threadName = ''
def uploader():
while True:
time.sleep(5)
print threadName
if __name__ == "__main__":
numOfThreads = 5
try:
i = 0
while i < numOfThreads:
threadName = 'thread' + str(i)
newThread = threading.Thread(target=uploader)
newThread.start()
i += 1
print 'press any key to exit test'
n=raw_input()
except:
print "Error: unable to start thread"
I got a problem with my python program for my Raspberry Pi. I want to create a thread from a def in a class. It displays the following error when I try to run the code:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 505, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: check_keys() takes no arguments (1 given)
Here is my code:
import thread
import RPi.GPIO as GPIO
import threading
ROW = []
COL = []
chars = []
GPIO.setmode(GPIO.BOARD)
MATRIX = [ ['1','2','3'],
['4','5','6'],
['7','8','9'],
['*','0','#'] ]
class keypad():
def __init__(self, gpio_col, gpio_row):
COL = gpio_col
ROW = gpio_row
for j in range(3):
GPIO.setup(COL[j], GPIO.OUT)
GPIO.output(COL[j], 1)
for i in range(4):
GPIO.setup(ROW[i], GPIO.IN, pull_up_down = GPIO.PUD_UP)
def check_keys():
try:
while(True):
for j in range(3):
GPIO.output(COL[j],0)
for i in range(4):
if GPIO.input(ROW[i]) == 0:
chars.append(MATRIX[i][j])
print(MATRIX[i][j])
while(GPIO.input(ROW[i]) == 0):
pass
GPIO.output(COL[j],1)
except KeyboardInterrupt:
GPIO.cleanup()
def get_chars():
return chars
and:
import socket
import time
import pylcdlib
import keypadlib
from threading import Thread
#init keypad
ROW = [23,21,19,18]
COL = [13, 15, 16]
keypad = keypadlib.keypad(COL, ROW)
thread = Thread(target = keypad.check_keys)
Anyone got a solution?
Thanks in advance
You're doing it wrong. First of all:
def check_keys(self):
because it is a method of a class (the first parameter is always an instance). Secondly:
def __init__(self, gpio_col, gpio_row):
COL = gpio_col
ROW = gpio_row
# some code
You either want to store those variables on the instance, in which case you should use self.COL = gpio_col (and then in check_keys refer to self.COL) or you want to change them globaly in which case you should use
def __init__(self, gpio_col, gpio_row):
global COL
COL = gpio_col
I advise storing them on the instance though.
Final note: you do realize that catching KeyboardInterrupt in a thread won't work because only the main thread can catch signals?
#!/usr/bin/env python
#coding=utf-8
import sys,os,threading
import Queue
keyword = sys.argv[1]
path = sys.argv[2]
class keywordMatch(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
line = self.queue.get()
if keyword in line:
print line
queue.task_done()
def main():
concurrent = 100 # Number of threads
queue = Queue.Queue()
for i in range(concurrent):
t = keywordMatch(True)
t.setDaemon(True)
t.start()
allfiles = os.listdir(path)
for files in allfiles:
pathfile = os.path.join(path,files)
fp = open(pathfile)
lines = fp.readlines()
for line in lines:
queue.put(line.strip())
queue.join()
if __name__ == '__main__':
main()
This program is for searching the keyword in a directory,
but there occurs an error:
Exception in thread Thread-100:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "du.py", line 17, in run
line = self.queue.get()
AttributeError: 'bool' object has no attribute 'get'
How can I get rid of the error?
You're instantiating the thread with t = keywordMatch(True), and then in __init__ you're taking this argument and saving it as self.queue - so naturally self.queue is going to be a bool. If you want there to be a Queue instance there, you should pass it in.
In main() you wrote:
t = keywordMatch(True)
The keywordMatch class's __init__ does this:
def __init__(self,queue):
self.queue = queue
So now self.queue is True! Later, trying to do self.queue.get fails because it isn't a queue at all.