0

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

1
  • Do you want to set MY_PATH in the python program, or in the environment before running the program? Commented Apr 13, 2017 at 4:59

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.