Python | os.confstr() method
Last Updated :
11 Oct, 2021
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.
os.confstr() method in Python is used to get string-valued system configuration values. It normally accepts a string parameter name which specifies which configuration value is to retrieve.
All possible values for name parameter is given as the keys of confstr_names dictionary. We can also pass an integer value for name parameter for those configuration variables which is not included in the dictionary.
If the configuration variables specified by the name parameter is not defined by the system, then os.confstr() method will return None and if the name does not specify any existing configuration variables then ValueError exception is raised. Also, if configuration value is not supported by the host operating system, OSError exception is raised.
Note: os.confstr() method is available only on UNIX platforms.
Syntax: os.confstr(name)
Parameter:
name: A string or an integer value representing a system configuration variable.
Return Type: This method returns a string value which represents the configuration value corresponding to the specified configuration variable.
Code: Use of os.confstr() method
Python3
import os
name = "CS_GNU_LIBC_VERSION"
value = os.confstr(name)
print ( "% s :" % name, value)
name = "CS_PATH"
value = os.confstr(name)
print ( "% s :" % name, value)
conf_var = "CS_GNU_LIBC_VERSION"
name = os.confstr_names[conf_var]
print ( "\nInteger value corresponding to % s:" % conf_var, name)
value = os.confstr(name)
print ( "Configuration value corresponding to % s :" % name, value)
|
Output:
CS_GNU_LIBC_VERSION : glibc 2.26
CS_PATH : /bin:/usr/bin
Integer value corresponding to CS_GNU_LIBC_VERSION: 2
Configuration value corresponding to 2 : glibc 2.26
Code #2: Possible errors while using os.confstr() method
Python3
import os
name = "cs_PATH"
value = os.confstr(name)
print ( "% s:" % name, value)
|
Output:
Traceback (most recent call last):
File "confstr.py", line 15, in
value = os.confstr(name)
ValueError: unrecognized configuration name
Code #3: Handling possible errors while using os.confstr() method
Python3
import os
name = "cs_PATH"
try :
value = os.confstr(name)
print ( "% s:" % name, value)
except ValueError :
print ( "'% s' is not a configuration variable" % name)
except OSError :
print ( "'% s' is not supported by Operating system" % name)
|
Output:
'cs_PATH' is not a configuration variable
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...