About Python global variable - python

import sys
from threading import Thread
is_online=1
class CommandListenerThread(Thread):
global is_online
def run(self):
while is_online:
next_command=sys.stdin.readlines();
if next_command == 'exit':
is_online=0
else:
print next_command
listener=CommandListenerThread()
listener.start()
When I run this python code,it shows an error: "UnboundLocalError: local variable 'is_online' referenced before assignment"
I tested another code which uses the same way to access the global variable inside a class,and it works fine. So,what is wrong with this specific code?
the code may look weird which using a thread to listen the command line,but it is just
a part of my program which gets an error when I run the whole program.
thank you guys

Move global is_online into run() to solve the error.
To address your other question (in a comment below), why not make it a static class variable ?
class CommandListenerThread(Thread):
is_online = 1
def run(self):
print CommandListenerThread.is_online
In case that you have to use another code with a global is_online, you can take the DI (dependency injection) approach as follows:
import sys
from threading import Thread
is_online = 2
class CommandListenerThread(Thread):
def __init__(self, is_online):
super(CommandListenerThread, self).__init__()
CommandListenerThread.is_online = is_online # now it's a static member
# if you want to make it an instance member use self.is_online
def run(self):
print CommandListenerThread.is_online
listener=CommandListenerThread(is_online) # inject the value to the constructor
listener.start()

Related

Passing arguments from one class to another class using threading python

I'm new to threading and python. I would like to understand how to pass multiple arguments from one class to another class in python using threading.
I'm using a main thread to call a class- Process then inside the run I'm doing some business logic and calling another class- build using thread and passing multiple arguments.
The run of build class is getting executed but Inside the build class, I'm unable to access those arguments and hence not able to proceed further.
Not sure if my approach is right? Any suggestions will be appreciated.
Below is my main class :
from threading import Thread
import logging as log
from process import Process
if __name__ == '__main__':
try:
proc = Process()
proc.start()
except Exception as e:
#log some error
Inside Process:
#all the dependencies are imported
class Process(Thread):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
Thread.__init__(self)
#other intializations
def run(self):
#some other logic
self.notification(pass_some_data)
#inside notification I'm calling another thread
def notification(self,passed_data):
#passed data is converted dict1
#tup1 is being formed from another function.
#build is a class, and if i don't pass None, i get groupname error.
th = build(None,(tup1,),(dict1,))
th.start()
#inside build
class build(Thread):
def _init_(self,tup1,dict1):
super(build,self).__init__(self)
self.tup1 = tup1
self.dict1 = dict1
def run(self):
#some business logic
#I'm unable to get the arguments being passed here.

python checking on thread started in different class

I'm curious how can I get the status of thread that have been started in a separate class in python.
So currently I have:
class VideoCapture:
def record:
Thread(name='uploading', target=self.upload, args=(upload_queue)).start()
In a seperate file main.py I have an instance of VideoCapture.
I want to be able to check the status of the thread "uploading" by typing something like VideoCapture.uploading.isAlive(). However I get the error that VideoCapture has no object uploading. So how can I access it?
Store the thread as something that is part of the class, then after that you have a means of accessing it later on.
class VideoCapture:
def __init__():
self.uploading = None
def record:
self.uploading = Thread(name='uploading', target=self.upload, args=(upload_queue)).start()
Now somewhere else you have:
video_capture = VideoCapture()
video_capture.record()
if video_capture.uploading.isAlive():
# do something
There's method is_alive() in Thread object, so basically you need just use it:
class VideoCapture:
def record(self):
# don't forget to add it on __init__
self.uploading = Thread(name='uploading', target=self.upload, args=(upload_queue)).start()
tmp = VideoCapture()
tmp.record()
tmp.uploading.is_alive() # here it is

Access global instance modified inside main() function of a server from different modules

I have a server that contains a class which performs an expensive computation
during its initialization. I want to initialize this class once, inside the main() method of the server module, before starting the server. Then, I want other modules that import the server module to be able to retrieve the instance of this class.
Example (the sleep emulates the server running)
import time
# I want to store the shared_instance of this global variable
shared_instance = None
class Shared:
def __init__(self):
# Expensive computation that I only want to run once
pass
def main():
global shared_instance
shared_instance = Shared() # Now instance_of_scorer is not None anymore
print(shared_instance)
print("Starting server...")
time.sleep(1000)
if __name__ == '__main__':
main()
When I run this server it prints:
<__main__.Shared object at 0x000001865A3C4320>
Starting server...
Now I have other module that should be able to see the instance:
import server
print(server.shared_instance)
However, shared_instance is not '<main.Shared object at 0x000001865A3C4320>' as expected. It is 'None'. Could you please tell me want I'm doing wrong and how can I solve this issue and achieve this functionality?.
Many thanks

How Pylint determine Instance has variable or not

I have written simple file and run Pylint on this code code. Does anyone have idea How Pylint determine that Class sample does not have second variable.
Purpose: I would like to write simple script which will read sample
file(python code) and check which instance variable is accessed and
set by Instance. Ex if I write in main time.initial_time than my script able to detect that initial_time has been accessed by time Instance. it will be run at the run time. I mean, it will be part of existing flow
Real Purpose
To filter out unused member variable of class which is used thousands places and more than 100 variable
Sample file
"""testing pylint code"""
#!/usr/bin/env py
class Sample(object):
"""create sample class"""
def __init__(self):
"""seting variable"""
self.intial_time = 0
def main():
"""main functionality"""
time = Sample()
print time.second
if __name__ == " __main__":
main()
Pylint Error:
************* Module class_instance
R: 3, 0: Too few public methods (0/2) (too-few-public-methods)
E: 12,10: Instance of 'Sample' has no 'second' member (no-member)

Multithreading python (using _thread), doesn't do anything

First of all, here are my two python files:
sred.py:
import _thread,time
class Thread:
def __init__(self,time:int,say:str):
self.time=time
self.say=say
def create():
id = _thread.get_ident()
for i in range(5):
print("HALLO", id)
return
from sred import Thread
import time,_thread
_thread.start_new_thread(Thread.create,())
The second one:
main.py
from sred import Thread
import time,_thread
_thread.start_new_thread(Thread.create,())
when executing this it doesn't print anything out, why?
UPDATE:
import _thread
class Thread:
#classmethod
def create():
id = _thread.get_ident()
for i in range(5):
print("HALLO", id)
return
main.py:
from sred import Thread
import time,_thread
_thread.start_new_thread(Thread().create,())
Is this now right, or is there still something wrong?
The create method is missing self as a parameter -- it looks like it should also be a #classmethod if you want to call it as it's written now. Note that your __init__ method is never getting called, because you never instantiate any Thread objects. You may want it to read:
_thread.start_new_thread(Thread().create, ())
i.e., instantiate a thread, then pass its create method to be executed in the new thread. I'm not sure what's happening, but I suspect that something is erroring and the stacktrace is being suppressed by something.
Also, you need to delete the space after the for statement -- it's significant, and it should be throwing you a syntax error about an unexpected indent.
EDIT:
This version runs on my machine:
import _thread
class Thread:
def create(self):
id = _thread.get_ident()
for i in range(5):
print("HALLO", id)
return
_thread.start_new_thread(Thread().create, ())

Categories