1

How can I limit memory usage for a Python script via command line?

For context, I'm implementing a code judge so I need to run every script students submit, I was able to do the same for Java with the following command:

java -Xmx<memoryLimit> Main 

So far no luck with Python, any ideas?

PS: I'm using Python 3.8

Thank you.

Luis Montoya
  • 3,117
  • 1
  • 17
  • 26

2 Answers2

5

You can use ulimit on Linux systems. (Within Python, there's also resource.setrlimit() to limit the current process.)

Something like this (sorry, my Bash is rusty) should be a decent enough wrapper:

#!/bin/bash
ulimit -m 10240  # kilobytes
exec python3 $@

Then run e.g. that-wrapper.sh student-script.py.

(That said, are you sure you can trust your students not to submit something that uploads your secret SSH keys and/or trashes your file system? I'd suggest a stronger sandbox such as running everything in a Docker container.)

AKX
  • 152,115
  • 15
  • 115
  • 172
-1

Not sure why you want/need that. In contrast to Java, Python is very good at handling memory. It has proper garbage collectors and is quite efficient in using memory. So in my 10+ years of python programming, I never had to limit memory in python. However, if you really need it, check out this thread Limit RAM usage to python program. Someone seems to have posted a solution.

You usually limit the memory on OS level, not in python itself. You could also use Docker to achieve all of that.

Özer
  • 2,059
  • 18
  • 22