#!/usr/bin/env python

import os, sys

variable =  sys.argv

def enVar(variable):
        This function returns all the environment variable set on the machine or in active project.
        if environment variable name is passed to the enVar function it returns its values.
        nVar = len(sys.argv)-1
        if len(variable) == 1: # if user entered no environment variable name
                for index, each in enumerate(sorted(os.environ.iteritems())):
                        print index, each
        else: # if user entered one or more than one environment variable name
                for x in range(nVar):
                        if os.environ.get(variable[x].upper()): # convertes to upper if user mistakenly enters lowecase
                                print "%s : %s" %  (variable[x].upper(), os.environ.get(variable[x].upper()))
                    else: print 'Make sure the Environment variable "%s" exists or spelled correctly.' % variable[x]


i run the above file as show.py is their a better way to do it ?


Some notes:

  • Indent with 4 spaces (PEP8)
  • Use underscore_names for function and variables.
  • Use meaningful names for functions (specially) and variables.
  • Be concise in docstrings.
  • Don't write for index in range(iterable): but for element in iterable:.
  • Don't write variable = sys.argv in the middle of the code, use it directly as an argument.
  • Use an import for each module.

I'd write (Python 3.0):

import sys
import os

def print_environment_variables(variables):
    """Print environment variables (all if variables list is empty)."""
    if not variables:
        for index, (variable, value) in enumerate(sorted(os.environ.items())):
            print("{0}: {1}".format(variable, value))
        for variable in variables:
          value = os.environ.get(variable)
          if value:
              print("{0}: {1}".format(variable, value))
            print("Variable does not exist: {0}".format(variable))


But if you asked me, I would simplify the function without second thoughts, functions are more useful when they are homogeneous (that's it, they return similar outputs for the different scenarios):

def print_environment_variables(variables):
    """Print environment variables (all if variables list is empty)."""
    variables_to_show = variables or sorted(os.environ.keys())
    for index, variable in enumerate(variables_to_show):
        value = os.environ.get(variable) or "[variable does not exist]"
        print("{0}: {1}={2}".format(index, variable, value))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.