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"
Related
im new to learning python and was trying code port scan script using Queue and Threading python 2.7 it keep giving me this error. multiple error to be precise
here is the last line of the erorr. meanwhile all the error have the "TypeError: thre() takes no arguments (1 given)".
The error here:
File "C:\Python27\lib\threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: thre() takes no arguments (1 given)
The code here:
import socket
import sys
import time
import Queue
import colorama
import threading
from Queue import Queue
from threading import Thread
from colorama import Fore, Back, Style
colorama.init(autoreset=True)
print_lock = threading.Lock()
q = Queue()
num_threads = '10'
def sshcan(host):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
rez = s.connect_ex((host, port))
if rez == 0:
print (Fore.GREEN + Style.DIM + 'PORT {}: Open on', +host)
s.close()
time.sleep(0.1)
except sockect.error:
print (Fore.RED + Style.DIM + 'Couldn\'t connect to server')
sys.exit()
except KeyboardInterrupt:
print ('Stoping...')
sys.exit()
pass
def thre():
while True:
host = q.get()
sshcan(host)
q.task_done()
def main():
try:
host = open(raw_input('\033[91m[\033[92m+\033[91m]\033[92m File Path: \033[97m'),'r').read().splitlines()
port = raw_input('\033[91m[\033[92m+\033[91m]\033[92m Port: \033[97m')
for i in range(int(num_threads)):
thread = threading.Thread(target=thre,args=(i,))
thread.daemon = True
thread.start()
for host in range(5):
q.put(host)
pass
if __name__ == "__main__":
main()
q.join()
> def thre():
> ...Thread(target=thre, args=(i,))
The diagnostic is pretty clear.
You defined the function to take no args.
And then you essentially called thre(i),
offering a single arg. Definition differs from
the call.
Make them match.
I'm writing a Python module to read jstest output and make Xbox gamepad working in Python on Linux. I need to start in background infinite while loop in __init__ on another thread that looks like this:
import os
from threading import Thread
import time
import select
import subprocess
class Joystick:
"""Initializes base class and launches jstest and xboxdrv"""
def __init__(self, refreshRate=2000, deadzone=4000):
self.proc = subprocess.Popen(['xboxdrv', '-D', '-v', '--detach-kernel-driver', '--dpad-as-button'], stdout=subprocess.PIPE, bufsize=0)
self.pipe = self.proc.stdout
self.refresh = refreshRate
self.refreshDelay = 1.0 / refreshRate
self.refreshTime = 0 # indicates the next refresh
self.deadzone = deadzone
self.start()
self.xbox = subprocess.Popen(['jstest', '--normal', '/dev/input/js0'], stdout=subprocess.PIPE, bufsize=-1, universal_newlines=True)
self.response = self.xbox.stdout.readline()
a = Thread(target=self.reload2())
a.start()
print("working")
def reload2(self):
while True:
self.response = self.xbox.stdout.readline()
print("read")
time.sleep(0.5)
def start(self):
global leftVibrateAmount, rightVibrateAmount
leftVibrateAmount = 0
rightVibrateAmount = 0
readTime = time.time() + 1 # here we wait a while
found = False
while readTime > time.time() and not found:
readable, writeable, exception = select.select([self.pipe], [], [], 0)
if readable:
response = self.pipe.readline()
# tries to detect if controller is connected
if response == b'[ERROR] XboxdrvDaemon::run(): fatal exception: DBusSubsystem::request_name(): failed to become primary owner of dbus name\n':
raise IOError("Another instance of xboxdrv is running.")
elif response == b'[INFO] XboxdrvDaemon::connect(): connecting slot to thread\n':
found = True
self.reading = response
elif response == b'':
raise IOError('Are you running as sudo?')
if not found:
self.pipe.close()
# halt if controller not found
raise IOError("Xbox controller/receiver isn't connected")
The loop is defined to start running in __init__ function like so:
a = threading.Thread(target=self.reload2) # code hangs here
a.start()
But each time I create variable "a", whole program hangs in while loop, which should be running in another thread.
Thanks for help.
You may be having issues with your __init__. I put it in a simple class as an example, and it runs as expected.
import time
from threading import Thread
class InfiniteLooper():
def __init__(self):
a = Thread(target=self.reload2) # reload, not reload(), otherwise you're executing reload2 and assigning the result to Target, but it's an infinite loop, so...
print('Added thread')
a.start()
print('Thread started')
def reload2(self):
while True:
self.response = input('Enter something')
print('read')
time.sleep(0.5)
loop = InfiniteLooper()
Output:
Added thread
Thread started
Enter something
1
read
Enter something
1
read
As you can see, the "Enter something" appears after I've added the thread and started it. It also loops fine
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().
I want to trigger upfunction and stop when it writes 3 in the filename. Basically I want to stop a thread once the condition is met as shown below.
def getstatus():
fh = open(filename,'r')
return fh.read()
def upfunction(arg):
for i in range(arg):
print ("backup running")
print(getstatus())
target = open(filename, 'w')
target.write(str(i))
sleep(1)
if __name__ == "__main__":
thread = Thread(target = upfunction, args = (10, ))
thread.start()
print(getstatus())
while getstatus() != "3":
print("NOT 3 ")
sleep(0.5)
continue
thread.stop()
print("thread finished...exiting")
It shows
AttributeError: 'Thread' object has no attribute 'stop'
Please see me as newbie to python.
Any help will be highly appreciated
'Thread' object has no attribute 'stop' is helpful answer from python interpretator to you
You should place thread termination condition to upfunction.
def upfunction(arg):
i = 0
while getstatus() != "3":
print ("backup running")
print(getstatus())
target = open(filename, 'w')
target.write(str(i))
i += 1
sleep(1)
if __name__ == "__main__":
thread = Thread(target = upfunction, args = (10, ))
thread.start()
print(getstatus())
print("thread finished...exiting")
you can just use threading deamon method to kill this new thread.
thread.start()
thread.deamon()
when the main threads ends this custom threads also dies .so there is no need of that.
Here are some explanation about the right way to do that: Is there any way to kill a Thread in Python?.
And as Lex said [0], you can add a condition (in upfunction arguments) to stop your target function.
Okay, I've been doing some tests, so I need to check the result every time I run a method. Because the test doesn't work properly.
I've made an example that works fine(not a test, but same behavior). In my test the result doesn't change, while in the example it changes.
EXAMPLE
def thread():
global result
import time
time.sleep(0.5)
result = 5/2
Gtk.main_quit()
import threading
from gi.repository import Gtk
result = None
t = threading.Thread(target=thread, args=())
t.start()
Gtk.main()
print result
OUTPUT: 2
TEST
def testSi_Button_clicked(self):
def thread(button=self.builder.get_object('Si_Button')):
import time
global result
time.sleep(0.5)
result = self.esci.Si_Button_clicked(button)
print 'result ' + str(result)
#Gtk.main_quit()
import threading
self.current_window = 'Home_Window' #DO NOT TRY WITH 'Azioni_Window'
result = None
t = threading.Thread(target=thread, args=())
t.start()
Gtk.main()
print 'assert'
print 'result ' + str(result)
self.assertIsNotNone(result)
OUTPUT:
Home_Window
return true
result True
assert
result None
F
======================================================================
FAIL: testSi_Button_clicked (testC_Esci.tstEsci)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testC_Esci.py", line 78, in testSi_Button_clicked
self.assertIsNotNone(result)
AssertionError: unexpectedly None
In thread, global result refers to a module-level variable named result in the module where testSi_Button_clicked (or rather, the class that defines testSi_Button_clicked) is defined. It does not refer to the local variable of the same name that you define in testSi_Button_clicked.
To fix, make result a mutable object (such as a dict), drop the global result statement, and let thread be a closure over result. (In Python 3, you can use the nonlocal keyword to avoid this kind of wrapper trickery.)
def testSi_Button_clicked(self):
def thread(button=self.builder.get_object('Si_Button')):
import time
time.sleep(0.5)
result['result'] = self.esci.Si_Button_clicked(button)
print 'result ' + str(result['result'])
#Gtk.main_quit()
import threading
self.current_window = 'Home_Window' #DO NOT TRY WITH 'Azioni_Window'
result = {'result': None}
t = threading.Thread(target=thread, args=())
t.start()
Gtk.main()
print 'assert'
print 'result ' + str(result['result'])
self.assertIsNotNone(result['result'])