Keyboard Interrupting an asyncio.run() raises CancelledError and keeps running the code












0















I have inspected this SO question on how to gracefully close out the asyncio process. Although, when I perform it on my code:



async def ob_main(product_id: str, freq: int) -> None:
assert freq >= 1, f'The minimum frequency is 1s. Adjust your value: {freq}.'

save_loc = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'ob', product_id)

while True:
close = False
try:
full_save_path = create_save_location(save_loc)
file = open(full_save_path, 'a', encoding='utf-8')
await ob_collector(product_id, file)
await asyncio.sleep(freq)
except KeyboardInterrupt:
close = True
task.cancel()
loop.run_forever()
task.exception()
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
error_msg = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
print(error_msg)
logger.warning(f'[1]-Error encountered collecting ob data: {error_msg}')
finally:
if close:
loop.close()
cwow()
exit(0)


I get the following traceback printed in terminal:



^C['Traceback (most recent call last):n', ' File "/anaconda3/lib/python3.7/asyncio/runners.py", line 43, in runn return loop.run_until_complete(main)n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 555, in run_until_completen self.run_forever()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 523, in run_forevern self._run_once()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 1722, in _run_oncen event_list = self._selector.select(timeout)n', ' File "/anaconda3/lib/python3.7/selectors.py", line 558, in selectn kev_list = self._selector.control(None, max_ev, timeout)n', 'KeyboardInterruptn', 'nDuring handling of the above exception, another exception occurred:nn', 'Traceback (most recent call last):n', ' File "coinbase-collector.py", line 98, in ob_mainn await asyncio.sleep(freq)n', ' File "/anaconda3/lib/python3.7/asyncio/tasks.py", line 564, in sleepn return await futuren', 'concurrent.futures._base.CancelledErrorn']



and the code keeps running.



task and loop are the variables from the global scope, defined in the __main__:




loop = asyncio.get_event_loop()
task = asyncio.run(ob_main(args.p, 10))










share|improve this question























  • What is loop.run_forever() in the exception handler for KeyboardInterrupt supposed to achieve? It looks like a possible source of the problem.

    – user4815162342
    Nov 22 '18 at 17:27













  • I do not even have the loop.run_forever() anywhere, actually

    – i squared - Keep it Real
    Nov 22 '18 at 17:35











  • Can you then post your actual code? The code in the question has loop.run_forever on line 16 or so.

    – user4815162342
    Nov 22 '18 at 18:12


















0















I have inspected this SO question on how to gracefully close out the asyncio process. Although, when I perform it on my code:



async def ob_main(product_id: str, freq: int) -> None:
assert freq >= 1, f'The minimum frequency is 1s. Adjust your value: {freq}.'

save_loc = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'ob', product_id)

while True:
close = False
try:
full_save_path = create_save_location(save_loc)
file = open(full_save_path, 'a', encoding='utf-8')
await ob_collector(product_id, file)
await asyncio.sleep(freq)
except KeyboardInterrupt:
close = True
task.cancel()
loop.run_forever()
task.exception()
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
error_msg = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
print(error_msg)
logger.warning(f'[1]-Error encountered collecting ob data: {error_msg}')
finally:
if close:
loop.close()
cwow()
exit(0)


I get the following traceback printed in terminal:



^C['Traceback (most recent call last):n', ' File "/anaconda3/lib/python3.7/asyncio/runners.py", line 43, in runn return loop.run_until_complete(main)n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 555, in run_until_completen self.run_forever()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 523, in run_forevern self._run_once()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 1722, in _run_oncen event_list = self._selector.select(timeout)n', ' File "/anaconda3/lib/python3.7/selectors.py", line 558, in selectn kev_list = self._selector.control(None, max_ev, timeout)n', 'KeyboardInterruptn', 'nDuring handling of the above exception, another exception occurred:nn', 'Traceback (most recent call last):n', ' File "coinbase-collector.py", line 98, in ob_mainn await asyncio.sleep(freq)n', ' File "/anaconda3/lib/python3.7/asyncio/tasks.py", line 564, in sleepn return await futuren', 'concurrent.futures._base.CancelledErrorn']



and the code keeps running.



task and loop are the variables from the global scope, defined in the __main__:




loop = asyncio.get_event_loop()
task = asyncio.run(ob_main(args.p, 10))










share|improve this question























  • What is loop.run_forever() in the exception handler for KeyboardInterrupt supposed to achieve? It looks like a possible source of the problem.

    – user4815162342
    Nov 22 '18 at 17:27













  • I do not even have the loop.run_forever() anywhere, actually

    – i squared - Keep it Real
    Nov 22 '18 at 17:35











  • Can you then post your actual code? The code in the question has loop.run_forever on line 16 or so.

    – user4815162342
    Nov 22 '18 at 18:12
















0












0








0








I have inspected this SO question on how to gracefully close out the asyncio process. Although, when I perform it on my code:



async def ob_main(product_id: str, freq: int) -> None:
assert freq >= 1, f'The minimum frequency is 1s. Adjust your value: {freq}.'

save_loc = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'ob', product_id)

while True:
close = False
try:
full_save_path = create_save_location(save_loc)
file = open(full_save_path, 'a', encoding='utf-8')
await ob_collector(product_id, file)
await asyncio.sleep(freq)
except KeyboardInterrupt:
close = True
task.cancel()
loop.run_forever()
task.exception()
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
error_msg = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
print(error_msg)
logger.warning(f'[1]-Error encountered collecting ob data: {error_msg}')
finally:
if close:
loop.close()
cwow()
exit(0)


I get the following traceback printed in terminal:



^C['Traceback (most recent call last):n', ' File "/anaconda3/lib/python3.7/asyncio/runners.py", line 43, in runn return loop.run_until_complete(main)n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 555, in run_until_completen self.run_forever()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 523, in run_forevern self._run_once()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 1722, in _run_oncen event_list = self._selector.select(timeout)n', ' File "/anaconda3/lib/python3.7/selectors.py", line 558, in selectn kev_list = self._selector.control(None, max_ev, timeout)n', 'KeyboardInterruptn', 'nDuring handling of the above exception, another exception occurred:nn', 'Traceback (most recent call last):n', ' File "coinbase-collector.py", line 98, in ob_mainn await asyncio.sleep(freq)n', ' File "/anaconda3/lib/python3.7/asyncio/tasks.py", line 564, in sleepn return await futuren', 'concurrent.futures._base.CancelledErrorn']



and the code keeps running.



task and loop are the variables from the global scope, defined in the __main__:




loop = asyncio.get_event_loop()
task = asyncio.run(ob_main(args.p, 10))










share|improve this question














I have inspected this SO question on how to gracefully close out the asyncio process. Although, when I perform it on my code:



async def ob_main(product_id: str, freq: int) -> None:
assert freq >= 1, f'The minimum frequency is 1s. Adjust your value: {freq}.'

save_loc = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'ob', product_id)

while True:
close = False
try:
full_save_path = create_save_location(save_loc)
file = open(full_save_path, 'a', encoding='utf-8')
await ob_collector(product_id, file)
await asyncio.sleep(freq)
except KeyboardInterrupt:
close = True
task.cancel()
loop.run_forever()
task.exception()
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
error_msg = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
print(error_msg)
logger.warning(f'[1]-Error encountered collecting ob data: {error_msg}')
finally:
if close:
loop.close()
cwow()
exit(0)


I get the following traceback printed in terminal:



^C['Traceback (most recent call last):n', ' File "/anaconda3/lib/python3.7/asyncio/runners.py", line 43, in runn return loop.run_until_complete(main)n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 555, in run_until_completen self.run_forever()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 523, in run_forevern self._run_once()n', ' File "/anaconda3/lib/python3.7/asyncio/base_events.py", line 1722, in _run_oncen event_list = self._selector.select(timeout)n', ' File "/anaconda3/lib/python3.7/selectors.py", line 558, in selectn kev_list = self._selector.control(None, max_ev, timeout)n', 'KeyboardInterruptn', 'nDuring handling of the above exception, another exception occurred:nn', 'Traceback (most recent call last):n', ' File "coinbase-collector.py", line 98, in ob_mainn await asyncio.sleep(freq)n', ' File "/anaconda3/lib/python3.7/asyncio/tasks.py", line 564, in sleepn return await futuren', 'concurrent.futures._base.CancelledErrorn']



and the code keeps running.



task and loop are the variables from the global scope, defined in the __main__:




loop = asyncio.get_event_loop()
task = asyncio.run(ob_main(args.p, 10))







python-3.x python-asyncio






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 15:59









i squared - Keep it Reali squared - Keep it Real

700520




700520













  • What is loop.run_forever() in the exception handler for KeyboardInterrupt supposed to achieve? It looks like a possible source of the problem.

    – user4815162342
    Nov 22 '18 at 17:27













  • I do not even have the loop.run_forever() anywhere, actually

    – i squared - Keep it Real
    Nov 22 '18 at 17:35











  • Can you then post your actual code? The code in the question has loop.run_forever on line 16 or so.

    – user4815162342
    Nov 22 '18 at 18:12





















  • What is loop.run_forever() in the exception handler for KeyboardInterrupt supposed to achieve? It looks like a possible source of the problem.

    – user4815162342
    Nov 22 '18 at 17:27













  • I do not even have the loop.run_forever() anywhere, actually

    – i squared - Keep it Real
    Nov 22 '18 at 17:35











  • Can you then post your actual code? The code in the question has loop.run_forever on line 16 or so.

    – user4815162342
    Nov 22 '18 at 18:12



















What is loop.run_forever() in the exception handler for KeyboardInterrupt supposed to achieve? It looks like a possible source of the problem.

– user4815162342
Nov 22 '18 at 17:27







What is loop.run_forever() in the exception handler for KeyboardInterrupt supposed to achieve? It looks like a possible source of the problem.

– user4815162342
Nov 22 '18 at 17:27















I do not even have the loop.run_forever() anywhere, actually

– i squared - Keep it Real
Nov 22 '18 at 17:35





I do not even have the loop.run_forever() anywhere, actually

– i squared - Keep it Real
Nov 22 '18 at 17:35













Can you then post your actual code? The code in the question has loop.run_forever on line 16 or so.

– user4815162342
Nov 22 '18 at 18:12







Can you then post your actual code? The code in the question has loop.run_forever on line 16 or so.

– user4815162342
Nov 22 '18 at 18:12














1 Answer
1






active

oldest

votes


















0














Applying this question's method solves the issue. So in the above case:



try:
loop.run_until_complete(ob_main(args.p, 10))
except KeyboardInterrupt:
cwow()
exit(0)


However, I do not uderstand why that works.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434605%2fkeyboard-interrupting-an-asyncio-run-raises-cancellederror-and-keeps-running-t%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Applying this question's method solves the issue. So in the above case:



    try:
    loop.run_until_complete(ob_main(args.p, 10))
    except KeyboardInterrupt:
    cwow()
    exit(0)


    However, I do not uderstand why that works.






    share|improve this answer




























      0














      Applying this question's method solves the issue. So in the above case:



      try:
      loop.run_until_complete(ob_main(args.p, 10))
      except KeyboardInterrupt:
      cwow()
      exit(0)


      However, I do not uderstand why that works.






      share|improve this answer


























        0












        0








        0







        Applying this question's method solves the issue. So in the above case:



        try:
        loop.run_until_complete(ob_main(args.p, 10))
        except KeyboardInterrupt:
        cwow()
        exit(0)


        However, I do not uderstand why that works.






        share|improve this answer













        Applying this question's method solves the issue. So in the above case:



        try:
        loop.run_until_complete(ob_main(args.p, 10))
        except KeyboardInterrupt:
        cwow()
        exit(0)


        However, I do not uderstand why that works.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 16:37









        i squared - Keep it Reali squared - Keep it Real

        700520




        700520






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53434605%2fkeyboard-interrupting-an-asyncio-run-raises-cancellederror-and-keeps-running-t%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin