Home > Software design >  setting the Python recursion limit from the command line
setting the Python recursion limit from the command line

Time:12-15

I'd like to set the recursion limit from the python command line (as part of a pipeline for grading scripts that are written by students). Let's ignore the fact that students shouldn't be using very deep recursion.

Basically, I want something like

python studentcode.py --firstrunmycode "sys.setrecursionlimit(5000)"

...so that the interpreter's recursion limit is increased to 5000 before running the student's python script.

One solution is to first prepend the code to set the recursion limit at the start of the student's file, but there must be a more elegant way to proceed.

CodePudding user response:

Try this:

python -c "import sys;sys.setrecursionlimit(5000);exec(open('studentcode.py.py').read())"

CodePudding user response:

I don't know how to do it from cmd, but you could just add the setrecursionlimit code at the beginning of each file. If there are too many files to do manually, try some python code.

import os
#Assuming all python files are in a directory called "files"
dirfiles = os.listdir("./files")

for item in dirfiles:
    if item.endswith(".txt"):
        with open("./files/"   item, "r") as f:
            code = f.read()
            
        with open("./files/"   item, "w") as f:
            f.write("""import sys
sys.setrecursionlimit(<some recursion limit>)

"""   code)

This will add a line setting the recursion limit above every python file in the directory files.

EDIT: Or you could use exec() and make your own interpreter extension.

import os
import sys
import argparse

pa = argparse.ArgumentParser()
pa.add_argument(
    "File",
    type=str
)
pa.add_argument(
    "recurse",
    type=int
)

args = pa.parse_args()

with open(args.File, "r") as f:
    os.chdir(os.path.dirname(args.File))
    exec(
        """import sys
sys.setrecursionlimit("""   str(args.recurse)   """)

"""   f.read()
    )

This creates a python interpreter extension, so assuming the code above is in a file called run.py then you just use python run.py <path to python file to run> <recursionlimit>, so for example python run.py files/foo.py 2000

  • Related