Open In App

Python | os.getgid() and os.setgid() method

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

setgid() and getgid() methods are present in the OS module. OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality. 

All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

Note: os.setgid() and os.getgid() methods are available only on UNIX platforms.

Python os.getgid() method

Python os.getgid() method returns the real group ID of the current process.

Syntax

os.getgid()

Parameter

No parameter is required

Return Type

This method returns an integer value that represents the current process’s real group ID.

Example: Using getgid() method in Python

In this example, the `os.getgid()` function retrieves the group ID of the current process in the operating system. The obtained group ID is then printed to the console. By this example, we can understand how to fetch the group ID of the current user with os.getgid().

Python3




import os
 
gid = os.getgid()
 
print("Group id of the current process:", gid)


Output

Group id of the current process: 1000

Getgid method terminal output

Python os.setgid() method

Python os.setgid() method sets the real group ID of the current process to a specified value. Below is the syntax of os.setgid() function.

Syntax

os.setgid(euid)

Parameter

  • euid: An integer value representing a new group id for the current process.

Return Type 

This method does not return any value.

Example: Using os.setgid() method in Python

In this example, the `os.getgid()` function retrieves and prints the initial group ID of the current process. Subsequently, the group ID is changed using `os.setgid()` to a new value of 23. Finally, the updated group ID is fetched and displayed.

Python3




import os
 
gid = os.getgid()
 
print("Group id of the current process:", gid)
 
gid = 23
os.setgid(gid)
print("Group id changed")
 
gid = os.getgid()
print("Group id of the current process:", gid)


Output

Group id of the current process: 0
Group id changed
Group id of the current process: 23

Setgid method terminal output

We have covered the Python getgid() method and setgid() method. Both these methods belong to the os module and allow users to operate on group process ID.  These methods are very useful in the UNIX operating system as group IDs (GIDs) control access to files, directories, and other resources based on group membership.

Also Read: 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads