如何在 python 中为环境路径复制 eval 命令?

How to replicate eval command in python for environment path?

在我的一个 shell 脚本中,我正在使用如下所示的 eval 命令来评估环境路径 -

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"

输出:

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

config.txt-

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

什么是 MY_PATH?

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

那么有什么方法可以从 python 代码中获取路径,就像我可以使用 eval

进入 shell 一样

您可以使用 os.path.expandvars()(来自 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

根据您要设置的位置,您可以通过多种方式完成此操作 MY_PATH。 os.path.expandvars() 使用当前环境扩展类似 shell 的模板。因此,如果 MY_PATH 在调用之前设置,您可以

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

如果在python程序中定义了MY_PATH,你可以使用string.Template扩展shell类变量,使用局部dict甚至关键字参数。

>>> 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