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

时间:2017-04-13 04:45:04

标签: python shell sh eval

在我的一个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一样

2 个答案:

答案 0 :(得分:1)

您可以通过几种方式执行此操作,具体取决于您要设置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使用本地dict甚至关键字参数来扩展类似shell的变量。

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

答案 1 :(得分:0)

你可以使用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