how to set/get shell env variable in python script

greetings,

i have a sh script that calls a python script. the sh script sets an env variable BIN:

export BIN=bin64

i need to get that BIN variable's value and use it within this python script. anyone know how to do this? thanx in advance.

Use getenv in your python script

15.1. os ? Miscellaneous operating system interfaces � Python v2.7.2 documentation

mpiRoot is passed as a command line option:

MPI_ROOTDIR=mpiRoot
os.getenv(BIN)
mpdCmd="%s/BIN/mpd" % MPI_ROOTDIR
mpdtraceCmd="%s/BIN/mpdtrace" % MPI_ROOTDIR
mpdtraceCmd2="%s/BIN/mpdtrace -l" % MPI_ROOTDIR

although i replaced the os.getenv with below and succeeded but looking for a more efficient way.

MPI_ROOTDIR=mpiRoot
if MPI_ROOTDIR == "/usr/apps/intel/impi/3.2.2.006":
    Bin="bin64"
else:
    Bin="bin"
mpdCmd="%s/%s/mpd" % (MPI_ROOTDIR, Bin)
mpdtraceCmd="%s/%s/mpdtrace" % (MPI_ROOTDIR, Bin)
mpdtraceCmd2="%s/%s/mpdtrace -l" % (MPI_ROOTDIR, Bin)

It works for me! Check below:

# export BIN="123456789"
# python
Python 2.3.4 (#1, Jul 16 2009, 07:03:37)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print os.getenv('BIN')
123456789

If you are using: "os.getenv(BIN)" and BIN, in this context in not a variable, it will not work! It must be between quotes (single or double).

I hope it helps.

that works for me as well HOWEVER:

# export BIN=bin64
# python
Python 2.4.3 (#1, Jun 11 2009, 14:09:37)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print os.getenv('BIN')
bin64
>>>

how do i get that "BIN" to be recognized on the code i posted in my second post? therein lies my issue. thanx.

In the same way as you are doing as a command line argument:

def getEnvVarValue(envVar):
    tmpVal = os.getenv(envVar)
    if not tmpVal:
        print("Environment variable: [%s] not set." % (envVar))
        sys.exit(1)
        
    retValue = tmpVal.strip("'") 
    return retValue


Bin=getEnvVarValue('BIN')
mpdCmd="%s/%s/mpd" % (MPI_ROOTDIR, Bin)
mpdtraceCmd="%s/%s/mpdtrace" % (MPI_ROOTDIR, Bin)
mpdtraceCmd2="%s/%s/mpdtrace -l" % (MPI_ROOTDIR, Bin)

I hope it helps!