Python脚本在没有shell的情况下运行时跳过某些行

b5buobof  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(144)

我有一些这样的代码:

from stomp import *
from stomp.listener import ConnectionListener
from stomp.utils import parse_frame

class MyListener(ConnectionListener):
  _counter=0
  def on_message(self, frame):
    if self._counter > 10:
      return
    print(self._counter)
    self._counter += 1

print('Starting...')
connection = Connection([('darwin-dist-44ae45.nationalrail.co.uk', '61613')])
connection.set_listener('', MyListener())
connection.connect(REDACTED)
connection.subscribe('/topic/darwin.pushport-v16', 11)
print('Ummm...???')

当我使用Python从命令行运行这个命令时,带有connection的行不会执行:

$ python3 myscript.py                                                                                                                                       
Starting...
Ummm...???

然而,当我打开python shell并逐个运行这些命令时,connection.subscribe('/topic/darwin.pushport-v16', 11)会产生一堆预期的输出:

$ python3
>>> from stomp import *
>>> from stomp.listener import ConnectionListener
>>> from stomp.utils import parse_frame
>>> 
>>> class MyListener(ConnectionListener):
...   _counter=0
...   def on_message(self, frame):
...     if self._counter > 10:
...       return
...     print(self._counter)
...     self._counter += 1
... 
>>> print('Starting...')
Starting...
>>> connection = Connection([('darwin-dist-44ae45.nationalrail.co.uk', '61613')])
>>> connection.set_listener('', MyListener())
>>> connection.connect(REDACTED)
>>> connection.subscribe('/topic/darwin.pushport-v16', 11)
0
1
2

我从来没有遇到过这样奇怪的行为。为什么会发生这种情况,我如何修复它?谢谢

nxowjjhe

nxowjjhe1#

我认为问题是没有什么能阻止你的应用程序退出。因此,它没有时间实际接收任何消息。但是,当你从Python shell运行它时,它有时间接收消息并打印计数器。
试试这样的方法:

import time
from stomp import *
from stomp.listener import ConnectionListener
from stomp.utils import parse_frame

class MyListener(ConnectionListener):
  _counter=0
  def on_message(self, frame):
    if self._counter > 10:
      return
    print(self._counter)
    self._counter += 1

print('Starting...')
connection = Connection([('darwin-dist-44ae45.nationalrail.co.uk', '61613')])
connection.set_listener('', MyListener())
connection.connect(REDACTED)
connection.subscribe('/topic/darwin.pushport-v16', 11)
print('Ummm...???')
time.sleep(30)
connection.disconnect()

需要注意的是,在调用set_listener时在connection上设置的MyListener示例将在消息到达队列时被异步调用。换句话说,客户端不会简单地等待/阻塞直到消息到达。因此,something 需要让消费者在等待消息时保持活动状态。如果消息在此30秒窗口期间到达,则MyListener将接收它并打印消息如果消息没有到达队列,那么MyListener将不会被调用,应用程序将直接终止。

相关问题