0

I've created a simple reddit bot that reads comments in a specific subreddit.

for comments in reddit.subreddit(.........).comments():     # There is no comment limit so this is an infinite loop.
         # Do stuff

I'd like the for loop to be broken out of, if the user presses a key. But I don't want the loop to stop and wait for any user input. I.e the loop iterates with or without any user input, but IF the user does enter a key, I'd the loop to be broken.
I've tried do these methods but I've not been able to get the desired result:

try:   
   for ........
        # Do stuff
except KeyboardInterrupt:
   pass

try:
    while True:
         for .........
               # Do stuff
except KeyboardInterrupt:
    pass

import msvcrt
for ........
    # Do stuff
    if msvcrt.kbhit():
       break

I would prefer if there was no time.sleep() function required, as it would slow down the programme, but if there is no other way, it's fine.
Thanks.

  • 1
    Make it a function and `yield` results. – NotAName Jan 11 '22 at 05:16
  • What do you mean by break? What do you attempt to accomplish? – Bharel Jan 11 '22 at 05:18
  • @Bharel I mean, as in break out of the for loop that reads the comments. – Thenu Kaluarachchi Jan 11 '22 at 05:19
  • `I've not been able to get the desired result`: What is the desired result? What do you mean by "breaking out without interrupting the loop"? By definition the loop will be interrupted when you break out. – Selcuk Jan 11 '22 at 05:19
  • Based on keyboard output or based on code? Why not just use `break`? – Bharel Jan 11 '22 at 05:19
  • 1
    Yeah sorry, I guess my question was a bit ambiguous. By desired result, I mean that I want the loop to iterate without stopping with or without any keyboard input. But if the user presses a key, the for loop will be broken out of. – Thenu Kaluarachchi Jan 11 '22 at 05:24
  • `msvcrt.kbhit()` doesn't work? – Bharel Jan 11 '22 at 05:57
  • I've [just answered](https://stackoverflow.com/questions/70664041/how-to-break-out-of-a-loop-when-a-keyboard-key-is-pressed/70664042#70664042) a similar question Q&A style. Hope it helps. – Bharel Jan 11 '22 at 09:01
  • @Bharel thanks a lot, but the thing is, I need it to work within a for loop. Does it work with that as well. I won't be at my computer for a while, I'll let you know if it works then. – Thenu Kaluarachchi Jan 12 '22 at 06:04
  • What do you mean, ofc it will – Bharel Jan 12 '22 at 07:07
  • `I'd like the for loop to be broken out of, if the user presses a key.` please elaborate - is this a command line utility script that would receive a sighup (the user starts it and then hits CTRL+C for example), or is this some other UI? What is the actual user interface? – Risadinha Jan 12 '22 at 11:29

0 Answers0