Skip to main content

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.environ for configuration injection.
  • Guard secrets; never commit them.

Processes & system info

TaskSnippet
Current working directoryos.getcwd()
Change directoryos.chdir(path)
Run commandsos.system('ls') (prefer subprocess.run)
CPU countos.cpu_count()
Signals / exit codesos.kill(pid, signal.SIGTERM)

Permissions

  • Inspect file metadata with os.stat.
  • Set modes using os.chmod and os.umask.
  • Use os.path.expanduser, os.path.abspath when still on legacy code that hasn’t migrated to pathlib.

Next up in your learning path