2017-04-13 26 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