Learn Python Coding
39.1K subscribers
624 photos
29 videos
24 files
387 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Limiting program resources using the resource module 🛡️

import resource
import sys

# 1. Limiting the size of RAM (soft and hard limits in bytes)
# Limit the memory to ~50 MB
memory_limit = 50 * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (memory_limit, memory_limit))

# 2. Checking the protection's working
try:
print("Trying to allocate a huge array of memory...")
huge_list = [i for i in range(10_000_000)]
except MemoryError:
print("The limit worked! The program didn't crash, but caught the error.")

# 3. Finding out how many resources the script has already consumed
usage = resource.getrusage(resource.RUSAGE_SELF)
print(f"Peak memory consumption (in KB): {usage.ru_maxrss}")

Protecting the server from "greedy" code 🔧

When you run someone else's code, process user files, or write parsers, there's always a risk of a memory leak or an infinite loop. If such a script runs on the server, it can fill up all the RAM and bring down neighboring important processes (for example, the database). The built-in resource module (works on Unix/Linux/macOS) allows you to strictly limit the program's appetites.

Safe environment: You can limit not only RAM (RLIMIT_AS), but also CPU time (RLIMIT_CPU). If the code goes into an infinite loop, the system will gracefully terminate it after a specified number of seconds.

File system control: Using RLIMIT_FSIZE, you can prevent the script from creating files larger than a certain size. This will save the server's disks from being accidentally overwritten by gigantic logs.

Precise audit: The getrusage function provides detailed statistics on the current process: how much time the CPU spent on calculations, how many I/O operations there were, and what the maximum amount of memory used was during the entire operation.

#Python #ResourceManagement #ServerSafety #Coding #DevOps #Linux

Join Best TG Channels https://t.iss.one/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A

🚀 Level up your AI & Data Science skills with HelloEncyclo — a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
13 courses live + 40+ coming soon
🎯 One access, lifetime updates
🔑 Use code: PRESALE-BOOK-WAVE-2GFG
👉 https://helloencyclo.com/?ref=HUSSEINSHEIKHO
3