Python: How to get input from console while an infinite loop is running?

后端 未结 3 1462
自闭症患者
自闭症患者 2020-12-03 12:52

I\'m trying to write a simple Python IRC client. So far I can read data, and I can send data back to the client if it automated. I\'m getting the data in a while True<

相关标签:
3条回答
  • 2020-12-03 13:08

    You can use a async library (see answer of schlenk) or use https://docs.python.org/2/library/select.html

    This module provides access to the select() and poll() functions available in most operating systems, epoll() available on Linux 2.5+ and kqueue() available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.

    0 讨论(0)
  • 2020-12-03 13:10

    Another way to do it involves threads.

    import threading
    
    # define a thread which takes input
    class InputThread(threading.Thread):
        def __init__(self):
            super(InputThread, self).__init__()
            self.daemon = True
            self.last_user_input = None
    
        def run(self):
            while True:
                self.last_user_input = input('input something: ')
                # do something based on the user input here
                # alternatively, let main do something with
                # self.last_user_input
    
    # main
    it = InputThread()
    it.start()
    while True:
        # do something  
        # do something with it.last_user_input if you feel like it
    
    0 讨论(0)
  • 2020-12-03 13:23

    What you need is an event loop of some kind.

    In Python you have a few options to do that, pick one you like:

    • Twisted https://twistedmatrix.com/trac/
    • Asyncio https://docs.python.org/3/library/asyncio.html
    • gevent http://www.gevent.org/

    and so on, there are hundreds of frameworks for this, you could also use any of the GUI frameworks like tkinter or PyQt to get a main event loop.

    As comments have said above, you can use threads and a few queues to handle this, or an event based loop, or coroutines or a bunch of other architectures. Depending on your target platforms one or the other might be best. For example on windows the console API is totally different to unix ptys. Especially if you later need stuff like colour output and so on, you might want to ask more specific questions.

    0 讨论(0)
提交回复
热议问题