How to replicate eval command in python for environment path?

In one of my shell script I am using eval command like below to evaluate the environment path -

CONFIGFILE='config.txt'
###Read File Contents to Variables
    while IFS=\| read TEMP_DIR_NAME EXT
    do
        eval DIR_NAME=$TEMP_DIR_NAME
        echo $DIR_NAME
    done < "$CONFIGFILE"

Output:

/path/to/certain/location/folder1
/path/to/certain/location/folder2/another

In config.txt -

$MY_PATH/folder1|.txt
$MY_PATH/folder2/another|.jpg

What is MY_PATH?

export | grep MY_PATH
declare -x MY_PATH="/path/to/certain/location"

So is there any way I can get the path from python code like I could get in shell with eval

Upvotes: 0

Views: 739

Answers (2)

tdelaney
tdelaney

Reputation: 77347

You can do it a couple of ways depending on where you want to set MY_PATH. os.path.expandvars() expands shell-like templates using the current environment. So if MY_PATH is set before calling, you do

td@mintyfresh ~/tmp $ export MY_PATH=/path/to/certain/location
td@mintyfresh ~/tmp $ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> with open('config.txt') as fp:
...     for line in fp:
...         cfg_path = os.path.expandvars(line.split('|')[0])
...         print(cfg_path)
... 
/path/to/certain/location/folder1
/path/to/certain/location/folder2/another

If MY_PATH is defined in the python program, you can use string.Template to expand shell-like variables using a local dict or even keyword arguments.

>>> import string
>>> with open('config.txt') as fp:
...     for line in fp:
...         cfg_path = string.Template(line.split('|')[0]).substitute(
...             MY_PATH="/path/to/certain/location")
...         print(cfg_path)
... 
/path/to/certain/location/folder1
/path/to/certain/location/folder2/another

Upvotes: 1

Matthias Fripp
Matthias Fripp

Reputation: 18625

You could use os.path.expandvars() (from Expanding Environment variable in string using python):

import os
config_file = 'config.txt'
with open(config_file) as f:
    for line in f:
        temp_dir_name, ext = line.split('|')
        dir_name = os.path.expandvars(temp_dir_name)
        print dir_name

Upvotes: 0

Related Questions