2

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.

2

2 Answers 2

6

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.)

Sign up to request clarification or add additional context in comments.

Comments

-3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.