0

I have a python script that goes like this -

import..
def main ():
  some_condition check
  main() #calling main again
  some condition check
  main() #calling main again
main()

The idea here is to let the script run indefinitely and check for something. This way of calling main() somehow seems incorrect. I am quite new to Python scripting. Can someone guide me if this very inefficient and if yes then how do I achieve this?

Rohit Gupta
  • 23
  • 1
  • 9
  • What is incorrect? What exactly do you want? – Attila Bognár Dec 10 '18 at 09:33
  • 1
    related: https://stackoverflow.com/questions/3754620/a-basic-question-about-while-true – EdChum Dec 10 '18 at 09:33
  • 2
    i don't think you want recrusion here, something like `def main(): do_stuff` then `while True: some_check; main()` et.c – Chris_Rands Dec 10 '18 at 09:34
  • 1
    Agree with @Chris_Rands. Recursion is bad in so many ways (memory, readability of code etc). If only python had tail recursion.. Anyway, use "while True" syntax. – Aaron_ab Dec 10 '18 at 09:37
  • @AttilaBognár nothing was incorrect. I just wanted to know the right way of doing it. As someone pointed out, running it indefinitely would cause stack overflow and instead of calling main from main, I can use while true :) – Rohit Gupta Dec 10 '18 at 09:53
  • @RohitGupta I just wanted to know why it seemed incorrect. – Attila Bognár Dec 10 '18 at 09:55

2 Answers2

4

What you are doing is called recursion. This is certainly not good for long running applications, since it would cause a stack overflow.

Do your checking like this:

quit = False
while not quit:
   do_your_check()
   #maybe sleep
   quit = should_i_stop()
handras
  • 1,548
  • 14
  • 28
  • Thanks! That's what I was looking for - "it would cause a stack overflow". Quitting the script and then restarting would avoid the stack overflow? – Rohit Gupta Dec 10 '18 at 09:47
  • Yes, that would work. Stack overflow happens, because as you call a function the context of the caller function is saved on the stack, so when the called function returns, it can be continued, Since you never return, eventually your computer will run out of memory. At that point the OS will stop the program. – handras Dec 10 '18 at 09:56
1

Just put the things you want to do in a while true loop.

import ...
def main():
  while True:
    some_condition check

Recursion is utilized when it is too complex/hard to write as iterative code. e.g. Tree traversals.

Mattias
  • 416
  • 4
  • 12