Read or update environment variables
A script needs configuration supplied by its execution environment.
Python · Module
Python’s os module provides portable interfaces to operating-system functionality, including environment variables, process parameters, files, directories, and file descriptors. Use os.path for pathname manipulation and specialized modules for higher-level file operations.
The os module exposes portable interfaces to operating-system facilities. Use it for process environment access, current-directory operations, file-descriptor work, and other system interactions; use os.path for pathname manipulation and higher-level modules such as shutil or tempfile for specialized tasks.
import os
os.system(command)
os.stat(path, *, dir_fd=None, follow_symlinks=True)| Name | Type | Description |
|---|---|---|
command | str | Command string to execute in a subshell. |
path | path-like object or file descriptor | Path or file descriptor whose status is requested by os.stat(). |
dir_fd | int or None | Optional directory file descriptor for relative path resolution in functions that support it. |
follow_symlinks | bool | Whether symbolic links are followed by functions that provide this option. |
Return values depend on the selected os function; os.system() returns the command’s status, while os.stat() returns file-status information.
import os
print(os.getcwd())
os.environ["CARD_EXAMPLE"] = "ready"
print(os.environ["CARD_EXAMPLE"])
Shows the current working directory and reads a value from the process environment.
A script needs configuration supplied by its execution environment.
A backend task must inspect or change its working-directory context.
A tool needs operating-system file metadata or lower-level descriptors.
A script must invoke a host command through the shell.
The os module provides a portable interface to operating-system-dependent functionality. It covers areas such as environment variables, process parameters, files and directories, and file descriptors.
Follow-up: Which module should handle pathname manipulation? Use os.path; higher-level file and directory operations are handled by shutil.
The process environment is exposed through os.environ, which maps environment-variable names to values. The documentation describes both keys and values as strings.
Follow-up: Why might bytes matter? Some systems require names or values to be encoded or decoded before passing them to the operating system.
os.system(command) executes a command string in a subshell. It is therefore an interface to the host shell rather than a direct Python implementation of the command.
Follow-up: What should be considered before using it? Shell behavior and operating-system differences apply, so a more specialized subprocess interface may be preferable when precise process control is needed.
os.pathopen()fileinputtempfileshutilos.environos.stat()os.system()