2016-06-12 43 views
1

我試圖製作一個Python程序,該程序將運行在監聽STOMP隊列(基於TCP的簡單文本協議)的AWS上(通過Elastic Beanstalk部署)。我正在使用stomp.py庫,docs here如何保持Python TCP偵聽器應用程序運行?

這裏的程序,我用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函數,它將運行主函數,然後立即結束該過程。

但是,如果你在Python解釋器中寫出它,它將繼續無限地輸出隊列消息。

如何讓程序從PyCharm'Run application'選項無限期運行?或者,當我找出如何部署該程序時,AWS Elastic Beanstalk會如何處理?

我對Python很生疏,對於部署實際的Python應用程序很陌生,所以如果這是一個明顯的問題/答案,請道歉。

回答

1

您可以使用一個無限while循環

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秒。這個過程將會無限地繼續下去,因爲沒有任何條件可以終止循環。

+0

有趣的技術,問題幾個:(1)那個無限循環會不會消耗CPU資源嗎? (2)這真的不像Python最佳實踐方法,是嗎? –

+0

不,不會,因爲你沒有在循環體內做任何cpu密集工作......你只是暫停應用程序 – danidee

+0

好吧,我想這是真的。像Flask和Django這樣的框架如何保持其進程運行?如果他們甚至有長時間運行的過程,我想。 –