2017-04-13 25 views
0

在我的shell脚本的一个我使用eval命令象下面这样来评价环境路径 -如何在python环境路径中复制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" 

输出: - 什么是my_path的

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

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

config.txt

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

那么,有没有办法,我可以从Python代码的路径一样,我可以在外壳与获得eval

+0

想要在运行程序之前在python程序或环境中设置MY_PATH吗? – tdelaney

回答

1

根据您想要设置MY_PATH的位置,您可以通过几种方法来实现。 os.path.expandvars()使用当前环境扩展壳状模板。所以,如果my_path的被调用之前设置,你做

[email protected] ~/tmp $ export MY_PATH=/path/to/certain/location 
[email protected] ~/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 

如果my_path的是在Python程序中定义,你可以使用string.Template扩大使用本地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 
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