CTRL-C不同步

时间:2018-07-29 00:45:30

标签: python-3.x

当我按下 CTRL + C 时,以下程序不会breakexit。启用 CTRL + C 的正确方法是什么?

import sys

import asyncio
import datetime
import functools

import logging

from tastyworks.streamer import DataStreamer
from tastyworks.tastyworks_api import tasty_session
from tastyworks.models.session import TastyAPISession

LOGGER = logging.getLogger(__name__)


async def main_loop(session: TastyAPISession, streamer: DataStreamer):
    # sub_values = {
    #     "Greeks": [
    #         ".VIX180718C21",
    #         ".YUM180518C95"
    #     ]
    # }
    sub_values = {
        "Quote": ["/ES"]
    }

    # get all active orders
    orders = await session.get_active_orders()
    LOGGER.info('Number of active orders: %s', len(orders))

    # set up some streamers
    await streamer.add_data_sub(sub_values)

    async for item in streamer.listen():
        LOGGER.info('Received item: %s' % item.data)


def main():

    tasty_client = tasty_session.create_new_session('uname', 'pwd')

    streamer = DataStreamer(tasty_client)
    LOGGER.info('Streamer token: %s' % streamer.get_streamer_token())
    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(main_loop(tasty_client, streamer))
    except KeyboardInterrupt:
        print("Received exit, exiting")
    finally:
        # find all futures/tasks still running and wait for them to finish
        pending_tasks = [
            task for task in asyncio.Task.all_tasks() if not task.done()
        ]
        loop.run_until_complete(asyncio.gather(*pending_tasks))
        loop.close()


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

默认情况下,当keyboardInterrupt Exception启动时,它将停止脚本。在脚本中,您将keyboardInterrupt异常替换为代码,该异常不会停止脚本。

要解决该问题,您需要在异常上添加https://qapaper.com/first https://qapaper.com/second https://qapaper.com/third https://qapaper.com/fourth

这是您的代码:

exit()

这是解决方法:

try:
    loop.run_until_complete(main_loop(tasty_client, streamer))
except KeyboardInterrupt:
    print("Received exit, exiting")
finally:
    # find all futures/tasks still running and wait for them to finish
    pending_tasks = [
        task for task in asyncio.Task.all_tasks() if not task.done()
    ]
    loop.run_until_complete(asyncio.gather(*pending_tasks))
    loop.close()