Python Forum
Why am I getting this NameError using threading?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why am I getting this NameError using threading?
#1
I have started working with threading and now I get an error on the function main(). I have made a very simplistic version of my code that reproduces this error. I have now tried a lot to fix this problem, however, I did not even understand it properly. The error can be removed (but so is the use of the code) with the "self, enable=''. I think however the arrangement of the 'a' and 'b' might cause it, but i can't solve it. What could fix this and what causes it?

Error:
Exception in thread main:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: main() takes at least 1 argument (0 given)


import threading
from time import sleep

number = 0
alive = True

class Server(object):

    def main(self, enable=''):
        self.enable = int(enable)
        #here we have some loops that rely on the variables like "enable"

    def background():
        global number
        while alive:
            if number < 20:
                number=number+1
                print 'Number: {0}'.format(number)
                sleep(1)
            else:
                print "20 seconds are over!"
                break

    a = threading.Thread(name='main', target=main)
    b = threading.Thread(name='background', target=background)


    a.start()
    b.start()

while alive: #this is just to terminate early
    try:
        sleep(.1)
    except KeyboardInterrupt:
        alive = False

print 'Terminated!'
Reply
#2
If I understood what your doubt is, try this:

import threading
from time import sleep

srv = 0
number = 0
alive = True

class Server():

    def __init__(self, enable='0'):
        self.enable = int(enable)

    def main(self,enable='0'):
        self.enable = int(enable)
        #here we have some loops that rely on the variables like "enable"

    def background(self):
        global number
        while alive:
            if number < 20:
                number=number+1
                print 'Number: {0}'.format(number)
                sleep(1)
            else:
                print "20 seconds are over!"
                break

srv = Server()
a = threading.Thread(name='main', target=srv.main)
b = threading.Thread(name='background', target=srv.background)
a.start()
b.start()

while alive: #this is just to terminate early
    try:
        sleep(.1)
    except KeyboardInterrupt:
        alive = False

print 'Terminated!'
About the error, it is because your main() needs receive at least one argument (enable) when it is called inside the class.
To pass args using Thread:
my_enable = '1'
a = threading.Thread(name='main', target=srv.main,args=(my_enable,))
Reply
#3
When you are starting a thread you are giving the thread a function that has to run. But since your function needs arguments you have to provide them as well. The self argument will be given when the instance of the class is created, so if you created an instance of the object and using the method you do not have to worry about that. threading.Threads has another argument args. args is expecting a tuple with all the arguments you want to pass to the function (or method in this case). If you want to pass a different value to your function (on thread start) use the args argument. Currently you are running the threads while still creating the object. Get them out of the class and it will work fine ;)

Sry for the double post. See gontajones post.
The error was that the function needed a reference the object and could not get one since the object is still being created. But if you want to pass aditional arguments or different values use gontajones suggestion :)
Reply
#4
Thank you guys for your explanations. That solves my problem. Rep for everybody ;)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Concurrent futures threading running at same speed as non-threading billykid999 13 1,813 May-03-2023, 08:22 AM
Last Post: billykid999
  Tutorials on sockets, threading and multi-threading? muzikman 2 2,120 Oct-01-2021, 08:32 PM
Last Post: muzikman
  NameError: NameError: global name 'BPLInstruction' is not defined colt 7 4,384 Oct-27-2019, 07:49 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020