2017-04-13 1 views
0

Dans l'un de mes script shell je suis en utilisant la commande eval comme ci-dessous pour évaluer le chemin de l'environnement -Comment répliquer la commande eval dans python pour le chemin d'environnement?

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" 

Sortie:

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

Dans config.txt -

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

Qu'est-ce que Mon_Chemin ?

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

est-il possible que je puisse obtenir le chemin à partir du code python comme si je pouvais entrer en coquille avec eval

+0

Voulez-vous définir 'MY_PATH' dans le programme python ou dans l'environnement avant d'exécuter le programme? – tdelaney

Répondre

1

Vous pouvez le faire de deux façons en fonction de l'endroit où vous voulez définir MY_PATH. os.path.expandvars() développe des modèles de type shell en utilisant l'environnement actuel. Donc, si Mon_Chemin est réglé avant d'appeler, vous

[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 

Si Mon_Chemin est défini dans le programme python, vous pouvez utiliser string.Template pour développer des variables comme shell en utilisant un dict local ou même des arguments de mots clés.

>>> 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

Vous pouvez utiliser os.path.expandvars() (de 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