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

2024-04-29 11:08:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输出:

^{pr2}$

config.txt-

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

我的路径是什么?

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

那么有没有什么方法可以像在shell中使用eval从python代码中获取路径


Tags: topathname命令路径txt脚本config
2条回答

你可以用几种方法来做,这取决于你想在哪里设置我的路径。os.path.expandvars()使用当前环境展开类似shell的模板。所以如果我的路径在打电话之前就设置好了,你就可以了

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

如果mypath是在python程序中定义的,那么可以使用string.Template来扩展shell类型的变量,使用一个局部的dict甚至关键字参数。在

^{pr2}$

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

相关问题 更多 >