Python for DevOps: Command Line Arguments and Environment Variables

·

2 min read

Introduction

Command Line Arguments

What Are Command Line Arguments?

Command line arguments allow you to pass values to your Python program directly from the terminal, making your scripts more flexible and dynamic. Instead of hardcoding values inside the program, users can provide inputs when executing the script.

Example: A Dynamic Calculator

Consider a simple calculator program where traditionally you'd hardcode values:

# Old approach (hardcoded values)
def add(x, y):
    return x + y

result = add(5, 10)  # Always the same output

With command line arguments, you can create a more versatile program:

import sys

# New approach (dynamic inputs)
def add(x, y):
    return x + y

# Read arguments from command line
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
result = add(num1, num2)

Now you can run the script like:

python calculator.py 2 3

Key Points about Command Line Arguments

  • Use the sys module to read arguments

  • Arguments are read as strings by default

  • Convert arguments to appropriate data types (int/float)

  • Useful for creating flexible, reusable scripts

Environment Variables

What Are Environment Variables?

Environment variables are a way to store sensitive information like passwords, API keys, or configuration details outside of your code.

Why Use Environment Variables?

  • Protect sensitive information

  • Keep credentials out of source code

  • Easily configurable across different environments

  • Useful in CI/CD pipelines

Using Environment Variables in Python

import os

# Read environment variable
password = os.getenv('MY_PASSWORD')
api_token = os.getenv('API_TOKEN')

Setting Environment Variables

# In terminal
export MY_PASSWORD=secret
export API_TOKEN=xyz123

Best Practices

  • Use for sensitive data

  • Avoid hardcoding credentials

  • Useful in automation scripts and CI/CD workflows

Practical Differences

Command Line ArgumentsEnvironment Variables
Passed during script executionSet in system environment
Good for general inputsBest for sensitive data
Visible in terminalHidden from immediate view
Less secure for sensitive dataMore secure for credentials

Conclusion

Command line arguments and environment variables are powerful tools in Python programming, especially for DevOps engineers. They provide flexibility, security, and ease of configuration for your scripts.

Next Steps

  • Practice creating scripts with command line arguments

  • Experiment with environment variables

  • Explore more advanced use cases in your DevOps workflows