Python recursion limit

前端 未结 3 1070
太阳男子
太阳男子 2021-01-23 17:54

So I understand the reason for the recursion limit of 1000. I want to run a script continuously, but am I right understanding that eventually the recursion limit will be reache

相关标签:
3条回答
  • 2021-01-23 18:36

    CPython has no optimizations for recursion, so you really want to avoid deeply-recursive code in favor of regular loops:

    def main():
        while True:
            all_files = getFiles(LOC_DIR)
            files = []
            for f in all_files:
                if checkExt(f):
                    files.append(f)
            if len(files) == 1:
                printLog('<<< Found %s matching file >>>' % len(files))
            elif len(files) > 1:
                printLog('<<< Found %s matching files >>>' % len(files))
            for f in files:
                if checkSize(f):
                    rsyncFile(f)
            printLog('No files found.  Checking again in %s seconds' % RUN_INT)
            time.sleep(RUN_INT)
            printLog('Checking for files')
    
    if __name__ == "__main__":    
        main()
    
    0 讨论(0)
  • 2021-01-23 18:37

    The recursion limit is only set with recursive functions from my understanding, so If you really want to run something repeatedly, you can simply run.

    while True:
       #repeated stuff goes here
    

    Recursion is an amazing tool, but handle with care, it often can end up burning you. You were right in the fact that python can only go 1000 calls deep recursively, so if you recursive method doesn't finish by then the exception gets thrown.

    Goodluck.

    0 讨论(0)
  • 2021-01-23 18:50

    You're going about this in the wrong way.

    Replace the main loop with a loop.

    # main logic
    def main():
        while True:
            all_files = getFiles(LOC_DIR)
            files = []
            for f in all_files:
                if checkExt(f):
                    files.append(f)
            if len(files) == 1:
                printLog('<<< Found %s matching file >>>' % len(files))
            elif len(files) > 1:
                printLog('<<< Found %s matching files >>>' % len(files))
            for f in files:
                if checkSize(f):
                    rsyncFile(f)
            printLog('No files found.  Checking again in %s seconds' % RUN_INT)
            time.sleep(RUN_INT)
            printLog('Checking for files')
    
    0 讨论(0)
提交回复
热议问题