我想要做的是在我的一个类方法上使用多处理。我试图遵循Python帮助文件中的示例,但我没有得到预期的结果。这是我的班级文件:
import os
import telnetlib
class PowerSupply():
# ---------------------------------- #
def __init__(self,port_no,my_name):
self.Status = "Off"
self.Port = port_no
self.Name = my_name
self.tn = None
self.HOST = "192"
self.P = Process(target=self.print_time, args=('tname','delay')
self.P.start()
self.P.join()
# ---------------------------------- #
def TurnOn(self):
onCommand = "OUT 1\r"
if self.Status == "ON":
print "I'm already on"
else:
self.tn = telnetlib.Telnet(self.HOST,self.Port)
self.tn.write(onCommand)
self.Status = "ON"
print "I am now on"
# ---------------------------------- #
def TurnOff(self):
offCommand = "OUT 0\r"
self.tn.write(offCommand)
self.tn.close()
print "I am now off"
# ---------------------------------- #
def SetVoltage(self,volts):
voltageCommand = "PV" + " " + str(volts) + "\r"
self.tn.write(voltageCommand)
# ---------------------------------- #
def GetAllData(self):
while(self.Status == "ON"):
self.tn.write("DVC?\r")
all_data = self.tn.read_some()
vdc = all_data.split(',')
vdc = vdc[0]
print vdc
# ---------------------------------- #
def print_time(self, tname, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s"%(tname, time.ctime(time.time()))
以下是我尝试使用该实现的方法:
ps1 = PowerSuppy(8000,'L1')
ps1.print_time('thread1',2)
ps1.print_time('thread2',3)
当我尝试如上所述使用它时,它仍然使用过程方法,并且在thread1完成之前不会调用thread2。我做错了什么,我该如何解决?
答案 0 :(得分:2)
好的,这就是我想程序会做的事情:
PowerSuppy(8000,'L1')
,它启动一个子流程并调用self.print_time('tname','delay')
。由于'delay'
不是数字,因此它会立即在子流程中引发TypeError
并结束(因此self.P.join()
根本没有阻止)。ps1.print_time('thread1',2)
,它在主进程中运行方法,并被阻止直到结束。ps1.print_time('thread2',3)
与前一行在主流程中的行为相同。如何修复它:
__init__
方法中对其进行初始化。print_time
函数的内部方法。target
。以下是代码:
Process.join
答案 1 :(得分:1)
尝试在班级中添加一项功能:
def print_time_subprocess(self, tname, delay):
p = Process(target=self.print_time, args=('tname','delay'))
p.start()
并用它来测试:
ps1 = PowerSupply(8000,'L1')
ps1.print_time_subprocess('thread1',2)
ps1.print_time_subprocess('thread2',3)
并且不要忘记导入Process