python: how to send packets in multi thread and then the thread kill itself

后端 未结 7 1613
忘掉有多难
忘掉有多难 2020-12-03 12:40

I have a question. I\'d like to send a continuous streams of byte to some host for certain amount of time (let\'s say 1 minute) using python.

Here is my code so far

7条回答
  •  没有蜡笔的小新
    2020-12-03 13:26

    I don't know how to do this with the "thread" module, but I can do it with the "threading" module. I think this code accomplishes what you want.

    For documentation on the threading module: http://docs.python.org/library/threading.html

    #!/usr/bin/python
    
    import time
    from threading import Thread
    import threading
    import sys
    
    test_time = 10
    killed = False
    
    class SillyThread( threading.Thread ):
        def run(self):
            global killed
            starttime = time.time()
            counter = 0
            while (time.time() - starttime) < test_time:
                if killed:
                    break
                counter = counter + 1
                time.sleep(0.1)
            print "I did %d loops" % counter
    
    class ManageThread( threading.Thread ):
        def run(self):
            global killed
            while True:
                var = raw_input("Enter something: ")
                if var == "quit":
                    killed = True
                    break
            print "Got var [%s]" % var
    
    silly = SillyThread()
    silly.start()
    ManageThread().start()
    Thread.join(silly)
    print "bye bye"
    sys.exit(0)
    

    Note that I use time.time() instead of time.clock(). time.clock() gives elapsed processor time on Unix (see http://docs.python.org/library/time.html). I think time.clock() should work everywhere. I set my test_time to 10 seconds because I don't have the patience for a minute.

    Here's what happens if I let it run the full 10 seconds:

    leif@peacock:~/tmp$ ./test.py
    Enter something: I did 100 loops
    bye bye
    

    Here's what happens if I type 'quit':

    leif@peacock:~/tmp$ ./test.py
    Enter something: quit
    Got var [quit]
    I did 10 loops
    bye bye
    

    Hope this helps.

提交回复
热议问题