首页 > 解决方案 > SIGINT 在谷歌 pubsub_v1/python 中被忽略

问题描述

from google.cloud import pubsub_v1

def run():
  # created full_* vars here...

  future = subscriber.subscribe(full_subscription, print_and_ack_message)

  try:
    future.result()
  except KeyboardInterrupt: # this doesn't work for some reason...
    logging.info("Subscription terminated...")
    future.cancel()
  except BaseException as exc:
    logging.info("Other %s", type(exc))

if __name__ == '__main__':
  run()

上面的代码不能在 macOS、zsh、iTerm 和 pyenv-virtualenv 上用 python 2.7.15 中断,出于某种原因?

CTRL+C 使用此代码从终端失败;什么都没有发生,只有^C在输出中可见,它既不终止也不打印任何东西。怎么了?

我正在关注文档

标签: pythongoogle-cloud-pubsub

解决方案


您不需要在result此处使用该方法:

订阅者是非阻塞的,所以我们必须阻止主线程退出以允许它在后台处理消息。

def run():
    future = subscriber.subscribe(full_subscription, print_and_ack_message)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        future.cancel()

推荐阅读