How to set memory limit for thread or process in python?

后端 未结 2 476
情深已故
情深已故 2021-01-01 04:16

I\'m writing program in Python which would be able to run untrusted python code in some kind of sandbox. So, I need a way to limit the amount of memory that untrusted code c

2条回答
  •  攒了一身酷
    2021-01-01 04:42

    Under Unix, you could use resource.setrlimit(resource.RLIMIT_AS, ...) to restrict "the maximum area (in bytes) of address space which may be taken by the process."

    import sys
    import resource
    soft, hard = 10**7, 10**7
    # soft, hard = 10**8, 10**8   # uncommenting this allows program to finish
    resource.setrlimit(resource.RLIMIT_AS,(soft, hard))
    memory_hog = {}
    try:
        for x in range(10000):
            print(x)
            memory_hog[str(x)]='The sky is so blue'
    except MemoryError as err:
        sys.exit('memory exceeded')
        # memory exceeded
    

提交回复
热议问题