简体   繁体   English

为什么我的python else语句不会触发?

[英]Why won't my python else statement trigger?

Here is the code, these are dummy classes that will eventually be replaced by something more useful. 这是代码,这些是虚拟类,最终将由更有用的东西替换。 What I want the while loop to do is pull data from the queue to see if a poison pill was dropped. 我想要的while循环要做的是从队列中提取数据,看是否丢弃了毒药。 If not I want whatever is in the else statement to trigger. 如果不是,我想触发else语句中的任何内容。 However for some reason it will wait till it gets a poison pill and only execute the kill condition if statement 但是由于某种原因,它会等到它得到毒药后,才执行if条件的kill条件

class test_imports:#Test classes remove 

      def import_1(self, control_queue, thread_number):
          print ("Import_1 number %d started") % thread_number
          run = True
          count = 1
          while run == True:
                alive = control_queue.get()                
                count = count + 1
                if alive == 't1kill':#<==will trigger
                   print ("Killing thread type 1 number %d") % thread_number
                   run = False                   
                else:#<== won't trigger
                     print ("Thread type 1 number %d run count %d") % (thread_number, count) 

If needed the rest of the code is: 如果需要,其余代码为:

import multiprocessing 
import time 

class test_imports:#Test classes remove 

      def import_1(self, control_queue, thread_number):
          print ("Import_1 number %d started") % thread_number
          run = True
          count = 1
          while run == True:
                alive = control_queue.get()                
                count = count + 1
                if alive == 't1kill':
                   print ("Killing thread type 1 number %d") % thread_number
                   run = False                   
                else:
                    print ("Thread type 1 number %d run count %d") % (thread_number, count)     



      def import_2(self, control_queue, thread_number):
          print ("Import_2 number %d started") % thread_number
          run = True
          count = 1
          while run == True:
                alive = control_queue.get()                   
                count = count + 1
                if alive == 't2kill':
                   print ("Killing thread type 2 number %d") % thread_number
                   run = False
                else:
                     print ("Thread type 2 number %d run count %d") % (thread_number, count)


class worker_manager:
     def __init__(self):
        self.children = {}

     def generate(self, control_queue, threadName, runNum):
        i = test_imports()
        if threadName == 'one':
            print ("Starting import_1 number %d") % runNum
            p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
            self.children[threadName] = p
            p.start()        
        elif threadName == 'two': 
            print ("Starting import_2 number %d") % runNum
            p = multiprocessing.Process(target=i.import_2, args=(control_queue, runNum))
            self.children[threadName] = p
            p.start()
        elif threadName == 'three':    
            p = multiprocessing.Process(target=i.import_1, args=(control_queue, runNum))
            print ("Starting import_1 number %d") % runNum
            p2 = multiprocessing.Process(target=i.import_2, args=(control_queue, runNum))
            print ("Starting import_2 number %d") % runNum
            self.children[threadName] = p
            self.children[threadName] = p2
            p.start()
            p2.start()

        else:
            print ("Not a valid choice choose one two or three")     

     def terminate(self, threadName):
         self.children[threadName].join


if __name__ == '__main__':
    # Establish communication queues
    control = multiprocessing.Queue()
    manager = worker_manager()

    runNum = int(raw_input("Enter a number: ")) 
    threadNum = int(raw_input("Enter number of threads: "))
    threadName = raw_input("Enter number: ")
    thread_Count = 0

    print ("Starting threads") 

    for i in range(threadNum):
        manager.generate(control, threadName, i)
        thread_Count = thread_Count + 1              

    time.sleep(runNum)#let threads do their thing

    print ("Terminating threads")     

    for i in range(thread_Count):
        control.put("t1kill")
        control.put("t2kill")

    manager.terminate(threadName) 

Please note import_2 is identical to import_1 except prints something different. 请注意import_2是相同的import_1除了打印不同的东西。 The point is to prove the ability to handle different thread types. 关键是要证明处理不同线程类型的能力。

In your driver code, you control.put("t1kill") first. 在您的驱动程序代码中,首先control.put("t1kill")

And your handler for t1kill sets run = False , so you won't come back through the while run == True loop ever again. 而且您的t1kill处理程序将run = False设置run = False ,因此您将不会再通过while run == True循环回来。

So, there's no opportunity for your else to be triggered. 因此,没有机会触发您的else

If you want to test it, just add that put s some dummy value: 如果要测试它,只需添加put的一些虚拟值即可:

for i in range(thread_Count):
    control.put("dummy")
    control.put("t1kill")
    control.put("t2kill")

However, in your real code, you're probably going to want that manager.generate method to put some useful values on the queue. 但是,在您的实际代码中,您可能会希望该manager.generate方法将一些有用的值放在队列中。


As a side note, you're making your code more complicated than it needs to be. 附带说明,您使代码变得比所需的复杂。

First, it's almost always a bad idea to write while run == True: instead of just while run: . 首先, while run == True:时而不是仅while run:编写几乎总是一个坏主意。 As PEP 8's Programming Recommendations section says: 正如PEP 8的《 编程建议》部分所述:

Don't compare boolean values to True or False using ==. 不要使用==将布尔值与True或False进行比较。

But really, you can just return as soon as you're done, and scrap the run flag entirely: 但实际上,您可以在完成后立即return ,并完全废弃run标志:

while True:
    alive = control_queue.get()                
    count = count + 1
    if alive == 't1kill':
        print ("Killing thread type 1 number %d") % thread_number
        return                   
    else:
        print ("Thread type 1 number %d run count %d") % (thread_number, count)

(There are some people who will tell you that break , early return , etc. are "bad structured programming". But Python isn't C.) (有些人会告诉您breakreturn等是“不良的结构化编程”。但是Python不是C。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM