[英]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"
所以有什么辦法可以像我可以使用eval
進入shell一樣從python代碼獲取路徑
您可以根據要在何處設置MY_PATH的方式執行幾種操作。 os.path.expandvars()
使用當前環境擴展類似於外殼的模板。 因此,如果在調用之前設置了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
您可以使用os.path.expandvars()( 使用python通過字符串中的Expanding Environment變量 ):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.