此脚本打开和关闭2个Phidgets继电器(www.phidgets.com)。我想在单独的线程中打开和关闭继电器。下面的脚本运行,但将每个线程打印为主线程,如下所示
Waiting for attach....
172760 attached!
Phidget InterfaceKit 8/8/8 model
MainThread Starting
relay state is True
MainThread Exiting
MainThread Starting
relay state is True
MainThread Exiting
MainThread Starting
relay state is False
MainThread Exiting
MainThread Starting
relay state is False
MainThread Exiting有人能告诉我我哪里做错了吗?提前谢谢。
#!/usr/bin/env python
#Basic imports
from ctypes import *
import sys, random, time, decimal, threading
#Phidget specific imports
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Devices.InterfaceKit import InterfaceKit
class fidget(object):
#Common base class for all phidgets
def __init__(self, device):
self.device = InterfaceKit()
########################################
# open the interfacekit
def openIfkit(self):
try:
self.device.openPhidget()
self.device.waitForAttach(10000)
print("Waiting for attach....")
print ("%d attached!" % (self.device.getSerialNum()))
print ("%s model" % (self.device.getDeviceName()))
except PhidgetException, e:
print ("Phidget Exception %i: %s" % (e.code, e.detail))
exit(1)
# open the interfacekit
def closeIfkit(self):
try:
self.device.closePhidget()
except PhidgetException, e:
print ("Phidget Exception %i: %s" % (e.code, e.detail))
exit(1)
def relayOn(self, output):
# Set digital output port 0 to be on
print threading.currentThread().getName(), 'Starting'
self.device.setOutputState(output, 1)
time.sleep(.1)
print 'relay state is %s' %self.device.getOutputState(output)
print threading.currentThread().getName(), 'Exiting'
def relayOff(self, output):
print threading.currentThread().getName(), 'Starting'
self.device.setOutputState(output, 0)
time.sleep(.1)
print 'relay state is %s' %self.device.getOutputState(output)
print threading.currentThread().getName(), 'Exiting'
#"This would create first object of fidgit class"
x = fidget('ifkit')
x.openIfkit()
#t1 = threading.Thread( target=x.relayOn(0))
#t2 = threading.Thread(target=x.relayOn(1))
#t3 = threading.Thread(target=x.relayOff(0))
#t4 = threading.Thread(target=x.relayOff(1))
t1 = threading.Thread(target=x.relayOn, args=(0,))
t2 = threading.Thread(target=x.relayOff, args=(0,))
t3 = threading.Thread(target=x.relayOn, args=(1,))
t4 = threading.Thread(target=x.relayOff, args=(1,))
t1.start()
t2.start()
t3.start()
t4.start()
x.closeIfkit()发布于 2013-11-16 11:20:19
您需要将一个callable传递给target=,如下所示:
t1 = threading.Thread(target=lambda: x.relayOff(1))此时,您所做的就是在主线程上调用x.relay*并将其返回值(即None,因为在不显式返回的python函数中,返回None)传递给target=。
发布于 2013-11-16 11:23:45
您将在主线程中分别调用relayOn和relayOff两次,而不是在子线程中调用,因为子线程根本不做任何事情。您提供给threading.Thread的target是relayOn或relayOff的返回值,后者(因为这些函数不返回任何内容)是None,所以线程不会运行任何内容。
解决这个问题的一种方法是创建一个可以做你想做的事情的闭包:
t1 = threading.Thread( target=lambda: x.relayOn(0) )等。
https://stackoverflow.com/questions/20014165
复制相似问题