Limiting program resources using the resource module π‘οΈ
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://xn--r1a.website/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
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://xn--r1a.website/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
Telegram
AI PYTHON π
Youβve been invited to add the folder βAI PYTHON πβ, which includes 15 chats.
β€4
Smart counting of elements using collections.Counter π
Forget about manual loops and dictionaries π«π
When you need to count the frequency of words in a text, the distribution of log types, or popular products in a store, developers usually create an empty dictionary and write a loop with a check if key not in dict: dict[key] = 1. The Counter class takes all this dirty work on itself and makes it as efficient as possible.
β Automatic initialization: You no longer need to check if a key exists in the dictionary. If the element is not there, Counter will not throw a KeyError, but simply return 0. π‘οΈ
β Finding leaders without sorting: The most_common(k) method returns a list of the k most frequently occurring elements. Under the hood, Python uses optimized heap algorithms, which work much faster than a full dictionary sort via sorted(). π
β Mathematical operations: You can add, subtract, intersect, and merge Counter objects. This turns them into a powerful tool for aggregating metrics and analytics from different data sources in a few lines of code. ββ
#Python #DataScience #Coding #Programming #Automation #DevOps
β¨ Join Best TG Channels https://xn--r1a.website/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
from collections import Counter
# Initial list with duplicate elements
logs = ["error", "info", "error", "warning", "error", "info"]
# 1. Instantly count the number of occurrences
count_dict = Counter(logs)
print(count_dict) # Counter({'error': 3, 'info': 2, 'warning': 1})
# 2. Get the most frequent elements (Top-2)
print(count_dict.most_common(2)) # [('error', 3), ('info', 2)]
# 3. Set math for counters
clicks_day1 = Counter(item=4, banner=2)
clicks_day2 = Counter(item=1, banner=5)
# Combine the results of two days in a single operation
print(clicks_day1 + clicks_day2) # Counter({'banner': 7, 'item': 5})
Forget about manual loops and dictionaries π«π
When you need to count the frequency of words in a text, the distribution of log types, or popular products in a store, developers usually create an empty dictionary and write a loop with a check if key not in dict: dict[key] = 1. The Counter class takes all this dirty work on itself and makes it as efficient as possible.
β Automatic initialization: You no longer need to check if a key exists in the dictionary. If the element is not there, Counter will not throw a KeyError, but simply return 0. π‘οΈ
β Finding leaders without sorting: The most_common(k) method returns a list of the k most frequently occurring elements. Under the hood, Python uses optimized heap algorithms, which work much faster than a full dictionary sort via sorted(). π
β Mathematical operations: You can add, subtract, intersect, and merge Counter objects. This turns them into a powerful tool for aggregating metrics and analytics from different data sources in a few lines of code. ββ
#Python #DataScience #Coding #Programming #Automation #DevOps
β¨ Join Best TG Channels https://xn--r1a.website/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
Telegram
AI PYTHON π
Youβve been invited to add the folder βAI PYTHON πβ, which includes 15 chats.
β€6π₯1
3 quick ways to merge dictionaries in Python π
1οΈβ£ The operator | (Python 3.9+) β the most modern and elegant way. Creates a new dictionary.
2οΈβ£ The in-place update operator |= (Python 3.9+) β if you need to modify the first dictionary in place.
#Python #Coding #DevOps #Programming #Tech #DataScience
β¨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk
βοΈ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
1οΈβ£ The operator | (Python 3.9+) β the most modern and elegant way. Creates a new dictionary.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 99, 'c': 4}
combined = dict1 | dict2
# Result: {'a': 1, 'b': 99, 'c': 4} (values of the second dictionary replace the first)2οΈβ£ The in-place update operator |= (Python 3.9+) β if you need to modify the first dictionary in place.
dict1 |= dict2
#Python #Coding #DevOps #Programming #Tech #DataScience
β¨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk
βοΈ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Telegram
AI PYTHON π
Youβve been invited to add the folder βAI PYTHON πβ, which includes 15 chats.
β€4
π₯ Free IT & Dev Study Kits β 2026 Prep, No Signup
If youβre prepping for cloud, dev, or AI roles this year, these free kits cover the gaps most people skip β cert basics, hands-on labs, and mock exams. No signup traps, no hidden fees.
π Cert E-Book β covers Cisco & AWS fundamentals, good for first-time cert takers
β https://bit.ly/4yrk1Ti
πͺ Online Free Course β structured path, works as a refresher before exams
β https://bit.ly/4hUprRP
βοΈ Free AI Materials β LLM basics to fine-tuning practice notebooks
β https://bit.ly/4yt1iXy
π Cloud Study Guide β cheat-sheet style, handy for interview prep
β https://bit.ly/4el4Eod
π§ Free Mock Exam β test yourself before booking the real thing
β https://bit.ly/4sbWlkl
π Save this or forward it to your dev/study group β good resources are worth sharing. πͺ
π Community: https://chat.whatsapp.com/CS7VOvQCLZG5BJPazBGm1v
π² Personalized help: https://wa.link/xd2fu6
#Python #Cloud #AWS #Cisco #AI #MachineLearning #DevOps #ITCertification #FreeResources #TechCareers
If youβre prepping for cloud, dev, or AI roles this year, these free kits cover the gaps most people skip β cert basics, hands-on labs, and mock exams. No signup traps, no hidden fees.
π Cert E-Book β covers Cisco & AWS fundamentals, good for first-time cert takers
β https://bit.ly/4yrk1Ti
πͺ Online Free Course β structured path, works as a refresher before exams
β https://bit.ly/4hUprRP
βοΈ Free AI Materials β LLM basics to fine-tuning practice notebooks
β https://bit.ly/4yt1iXy
π Cloud Study Guide β cheat-sheet style, handy for interview prep
β https://bit.ly/4el4Eod
π§ Free Mock Exam β test yourself before booking the real thing
β https://bit.ly/4sbWlkl
π Save this or forward it to your dev/study group β good resources are worth sharing. πͺ
π Community: https://chat.whatsapp.com/CS7VOvQCLZG5BJPazBGm1v
π² Personalized help: https://wa.link/xd2fu6
#Python #Cloud #AWS #Cisco #AI #MachineLearning #DevOps #ITCertification #FreeResources #TechCareers
β€4