【问题标题】:How to keep a Python TCP listener application running?如何保持 Python TCP 侦听器应用程序运行?
【发布时间】:2016-06-12 13:55:45
【问题描述】:

我正在尝试制作一个 Python 程序,该程序将在 AWS(通过 Elastic Beanstalk 部署)上运行,该程序侦听 STOMP 队列(基于 TCP 的简单文本协议)。我正在使用stomp.py 库,docs here

这是程序,我正在使用 PyCharm 的“运行应用程序”功能运行它:

# PyPI imports
import stomp

# TODO: TESTING ONLY, REMOVE WHEN DONE!
import time


def main():
    '''Starts the STOMP listener.'''

    print('Running main function')

    # See the following example for the template this file was based on:
    # http://jasonrbriggs.github.io/stomp.py/quickstart.html
    conn = stomp.Connection([('example.com', 61613)],
                            auto_decode=False)
    conn.set_listener('print', stomp.PrintingListener())
    conn.start()
    conn.connect(username = 'username', passcode = 'password', wait=False)

    conn.subscribe(destination='/destination',
                   id=1,
                   ack='auto')

    time.sleep(30)


if __name__ == '__main__':
    main()

它工作得很好,打印出队列消息,但只有 30 秒,然后它停止运行并输出: Process finished with exit code 0

如果你注释掉 sleep 函数,它会运行 main 函数,然后立即结束进程。

但如果你在 Python 解释器中写出来,它会继续无限期地打印出队列消息。

如何通过 PyCharm 的“运行应用程序”选项让程序无限期地运行?或者当我弄清楚如何部署程序时,AWS Elastic Beanstalk 会处理这个问题吗?

我对 Python 很生疏,而且对部署实际的 Python 应用程序很陌生,所以如果这是一个明显的问题/答案,我深表歉意。

【问题讨论】:

    标签: python pycharm amazon-elastic-beanstalk stomp


    【解决方案1】:

    你可以使用无限循环

    def main():
        '''Starts the STOMP listener.'''
    
        print('Running main function')
    
        # See the following example for the template this file was based on:
        # http://jasonrbriggs.github.io/stomp.py/quickstart.html
        conn = stomp.Connection([('example.com', 61613)],
                                auto_decode=False)
        conn.set_listener('print', stomp.PrintingListener())
        conn.start()
        conn.connect(username = 'username', passcode = 'password', wait=False)
    
        conn.subscribe(destination='/destination',
                       id=1,
                       ack='auto')
    
        while True:
            time.sleep(30)
    

    while 循环将运行,您的程序将休眠 30 秒,while 循环将再次运行,然后程序将再次休眠 30 秒。由于没有条件终止循环,此过程将无限继续

    【讨论】:

    • 有趣的技术,几个问题:(1) 无限循环不会占用 CPU 资源吗? (2) 这真的不像是 Python 最佳实践方法,是吗?
    • 不,它不会因为你没有在循环体中做任何 CPU 密集型工作......你只是暂停应用程序
    • 好吧,我想这是真的。 Flask 和 Django 等框架如何保持其进程运行?如果他们甚至有长时间运行的进程,我猜。
    • Django 是一个 Web 框架,而不是一个服务器。因此,有关 Web 服务器进程的所有内容都由您决定使用的任何 Web 服务器处理,而不是由 django 处理。 django 有线程,但这些线程不会无限运行,如果不是所有 django 网络应用程序都会很烦人,总会有超时:)
    • python 的 manage.py runserver 在后台使用 WSGI,不幸的是我对 WSGI 服务器的工作原理没有深入了解
    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多