15.2.1 Get Current Process and Limit Memory Usage

This example illustrates how you can use the psutil library to retrieve the current Python process and apply a memory limit to it.

By setting the process's virtual memory (RLIMIT_AS) to 1 GB, you can test how your application behaves when available memory is limited. The memory limit applies only to the current process and remains in effect only for the duration of its execution.

%python

import psutil
import os

# Get current process
proc = psutil.Process(os.getpid())
proc

# Set a lower memory limit (e.g., 1 GB)
ONE_GB = 1024 * 1024 * 1024
proc.rlimit(psutil.RLIMIT_AS, (ONE_GB, ONE_GB)

Listing the Example

>>> import psutil
... import os
... 
... # Get current process
... proc = psutil.Process(os.getpid())
... 
>>> proc
psutil.Process(pid=392175, name='python3', status='running')
>>> ONE_GB = 1024 * 1024 * 1024
... proc.rlimit(psutil.RLIMIT_AS, (ONE_GB, ONE_GB))
... 
>>> print(proc.rlimit(psutil.RLIMIT_AS))
(1073741824, 1073741824)