【问题标题】:How to replicate eval command in python for environment path?如何在 python 中复制 eval 命令以获取环境路径?
【发布时间】:2017-04-13 04:45:03
【问题描述】:

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

【问题讨论】:

  • 是在python程序中设置MY_PATH,还是在运行程序前的环境中设置?

标签: python shell sh eval


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2015-01-27
      • 2011-05-03
      • 2019-03-14
      • 1970-01-01
      • 2019-06-26
      • 2011-01-10
      相关资源
      最近更新 更多