我是python的新手。我正在编写一个类来为我正在为我的Raspberry Pi构建的应用程序创建多个线程(因此是GPIO引脚)。我基本上通过从数据库中提取一些数据,创建运行线程的类的实例,将两个变量传递给它(deviceGPIO和持续时间),并暂停一段时间。
基本上问题是我的线程实例在运行的第二次重复,尽管从数据库中提取了唯一值并传递给了类。我对使用kwargs和args感到有些困惑,所以在这个空间里会有任何帮助。
类/线程代码:
class MyThreadWithArgs(threading.Thread):
def __init__(self, deviceGPIO="default value", duration="default value", group=None, target=None, name=None,
args=(), verbose=None, **kwargs):
threading.Thread.__init__(self, group=group, target=target, name=name,
verbose=verbose)
self.deviceGPIO = deviceGPIO
self.duration = duration
return
def run(self):
logging.debug('Current GPIO pin: %s', deviceGPIO)
#pause for some time...
time.sleep(duration)
logging.debug('ending')
return
调用实例:
在DB查询的结果中调用以下内容(例如,每个类都是根据返回的每个DB行创建的)
for row in rows:
duration = int(row["programDuration"])
deviceGPIO = int(row["deviceGPIO"])
t = MyThreadWithArgs(args=(), kwargs={deviceGPIO, duration})
t.start()
结果:
以下是结果(python日志输出)
(Thread-1 ) Current GPIO pin: 12
(Thread-2 ) Current GPIO pin: 16
(Thread-3 ) Current GPIO pin: 16
(Thread-1 ) ending
(Thread-2 ) ending
(Thread-3 ) ending
我已经尝试清除传递给类的变量,但没有成功,因为前两个实例显示重复的结果(尽管将唯一的DB记录传递给类)。
我在这里错过了一些简单的东西吗?
更新
我使用提供的反馈更新了脚本,尽管我仍然继续显示重复值,尽管我做了更改。最后,我使用了以下代码,但我使用deviceGPIO
作为变量,而不是使用self.deviceGPIO
变量。我不确定为什么会这样 - 我很想知道我哪里出错了,为什么使用self.deviceGPIO
与原始变量相比具有相同的价值。
class MyThreadWithArgs(threading.Thread):
def __init__(self, deviceGPIO="default value", duration="default value", **kwargs):
threading.Thread.__init__(self, **kwargs)
self.deviceGPIO = deviceGPIO
self.duration = duration
def run(self):
logging.debug('Current GPIO pin: %s', self.deviceGPIO)
#pause for some time...
time.sleep(duration)
logging.debug('ending')
答案 0 :(得分:0)
您没有正确传递变量。
t = MyThreadWithArgs(args=(), kwargs={deviceGPIO, duration})
创建两个新的关键字参数;有效地将kwargs
方法的__init__
参数设置为:
{'args': (), 'kwargs': {<deviceGPIO value>, <duration value>}}
kwargs
值是集,而不是字典。
在__init__
方法中,您使用deviceGPIO
和duration
的默认值,因为您从未为这两个值提供特定参数。
使用:
t = MyThreadWithArgs(deviceGPIO=deviceGPIO, duration=duration)
创建线程子类实例,明确地将deviceGPIO
和duration
值传递给关键字参数。
如果您不打算指定剩余的Thread.__init__
个参数,可以完全保留这些参数,因为Thread
类本身已经有以下默认值:
class MyThreadWithArgs(threading.Thread):
def __init__(self, deviceGPIO="default value", duration="default value"):
threading.Thread.__init__(self)
self.deviceGPIO = deviceGPIO
self.duration = duration
请注意,此处不需要return
。您可以随时添加参数,或者只使用:
class MyThreadWithArgs(threading.Thread):
def __init__(self, deviceGPIO="default value", duration="default value", **kwargs):
threading.Thread.__init__(self, **kwargs)
self.deviceGPIO = deviceGPIO
self.duration = duration
将任何额外的关键字参数传递给Thread._init__()
方法,允许您根据需要创建新的MyThreadWithArgs()
实例,添加关键字参数,例如group
或name