[英]Run class in different Thread in Python
I want to show the status on a Raspberry PI using a LED. 我想使用LED在Raspberry PI上显示状态。 To do this I have a program in Python that will run class methods in background using threads. 为此,我有一个Python程序,它将在后台使用线程运行类方法。
This is the code I have written: 这是我编写的代码:
#!/usr/bin/python
import time
import os
import threading
status = 0
class LEDStatus(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
global status
self.current_value = None
self.running = True
def run(self):
global status
os.system("echo gpio | sudo tee /sys/class/leds/led0/trigger")
while True:
for i in xrange(0, status):
os.system("echo 1 | sudo tee /sys/class/leds/led0/brightness")
time.sleep(0.25)
os.system("echo 0 | sudo tee /sys/class/leds/led0/brightness")
time.sleep(0.25)
time.sleep(2)
os.system("echo mmc0 | sudo tee /sys/class/leds/led0/trigger")
if __name__ == '__main__':
leds = LEDStatus()
try:
leds.status = 3
leds.start()
while True:
print "X"
time.sleep(2)
except (KeyboardInterrupt, SystemExit): #Al pulsar ctrl+c
print "\nFinish"
leds.running = False
leds.join()
After the program comes to this line os.system("echo gpio | sudo tee /sys/class/leds/led0/trigger")
, it doesn't execute anything in the run
method. 程序进入此行os.system("echo gpio | sudo tee /sys/class/leds/led0/trigger")
,它在run
方法中不执行任何操作。
What am I doing wrong? 我究竟做错了什么? How can I change the value of the status variable from the main method? 如何通过main方法更改status变量的值?
Running sudo
in os.system()
call may block. 在os.system()
调用中运行sudo
可能会阻塞。 It will sit there waiting for user input (the password). 它将坐在那里等待用户输入(密码)。 This depends on how sudoers
file has been set up. 这取决于sudoers
文件的设置方式。
Your code also mixes global variables and class attributes. 您的代码还混合了全局变量和类属性。 The status
global variable is never updated, since you assign self.status = 3
instead of status = 3
. status
全局变量永远不会更新,因为您分配了self.status = 3
而不是status = 3
。
Using global variables like this is a bit frowned upon, since you might as well really use a class attribute here. 像这样使用全局变量有点不习惯,因为您最好在这里真正使用class属性。 Change your __init__
to take initial status as an argument. 更改__init__
以将初始状态作为参数。
def __init__(self, status):
threading.Thread.__init__(self)
self.status = status
self.current_value = None
self.running = True
and in your run
method use self.status
: 并在您的run
方法中使用self.status
:
for i in xrange(0, self.status):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.