[Tutor] Replacing "source" in Bash Scripting

Kent Johnson kent37 at tds.net
Fri Sep 28 16:23:39 CEST 2007


James wrote:
> Hi.
> 
> I'm re-writing a rather complex bash script I've been using for years  
> in Python.  The bash script uses a relatively simple configuration  
> file in order to get pertinent information before it runs.  The  
> configuration file is relatively simple: about 30 variables are  
> defined in this manner in the config file:
> 
> VARNAME=value
> 
> In the bash script I simply "source" this configuration file and the  
> script runs merrily using those variables defined in the  
> configuration file.  i.e.,
> 
> "source configFile"
> 
> I'm trying to implement similar behavior in a Python script,  
> specifically having a configuration file (with a list of variables  
> and their values defined) that my Python program will read once  
> running.  I'm not really sure what the best way to implement this is.

Write configFile as a Python source file, then

import configFile
print configFile.VARNAME

or whatever you want to do with VARNAME

If configFile.VARNAME is too wordy for you you can

import configFile as cf
print cf.VARNAME

or

from configFile import VARNAME
print VARNAME

or (*not* recommended, it obscures your code and risks importing more 
than you want)

from configFile import *
print VARNAME


You can also use .ini file format and the ConfigParser module if you prefer.

Kent


More information about the Tutor mailing list