Operating System Tasks with `os`
Standard Library
os Module Essentials
Reach for the `os` module when you need capabilities beyond pathlib: environment variables, process management, permissions, and more.
Environment
import os
api_key = os.getenv('API_KEY', 'development-key')
os.environ['MODE'] = 'production'
- Use
os.environfor configuration injection. - Guard secrets; never commit them.
Processes & system info
| Task | Snippet |
|---|---|
| Current working directory | os.getcwd() |
| Change directory | os.chdir(path) |
| Run commands | os.system('ls') (prefer subprocess.run) |
| CPU count | os.cpu_count() |
| Signals / exit codes | os.kill(pid, signal.SIGTERM) |
Permissions
- Inspect file metadata with
os.stat. - Set modes using
os.chmodandos.umask. - Use
os.path.expanduser,os.path.abspathwhen still on legacy code that hasn’t migrated to pathlib.