How do I pass an argument via command line to set an environ in Python

Viewed 17338

I'm using python 3.7 and os library. I have to run a battery of tests on both STAGE and TEST environments. Currently the code sets the environment to STAGE

ENVIRONMENT = os.getenv('ENV', 'STAGE')

but I want it to be set by passing an argument via command line. Anyone?

3 Answers

In case of a command line of a UNIX shell you can set the env variable as part of your command:

$ ENV=STAGE pytest ./tests/

Setting the environment variable of liking is rather simple, giving the name and the value for a single environmental variable would be something along these lines:

Using the command line

import os
import sys

var_name = sys.argv[1]
var_value = sys.argv[2]

os.environ[var_name] = var_value

Just execute your script from the command line as:

my.script ENV STAGE

This can be verified as follows within python:

var_name in os.environ #python3
os.environ.has_key(var_name) #python2

Interactively

Using a while construct in the script

import os

while True:

    env_var = input("Enter ENV (name:value), type 'done' to exit: ")) #enter var:value

    if env_var.lower() == "done":

        break

    try:

        var, val = env_var.split(":")

    except:

        print ("Wrong input format! name:value required.")

        continue

    os.setenv[var] = val

After "python myfile.py", just type the parameters delimited by spaces, and in the code, you can do the following:

import sys

nameOfScript = sys.argv[0]
commandLineArgs = sys.argv[1:]
commandLineArgsAsStr = str(sys.argv)
numArgs = len(sys.argv)
Related