473,847 Members | 1,709 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unified command line args, environment variables, .conf filesettings.

Just a fun exercise to unify some of the major input methods for a
script into a single dictionary.
Here is the output, given a gr.conf file in the same directory with
the contents stated below:

smitty@localhos t ~/proj/mddl4/test $ ./inputs.py
{'source_db': '/home/sweet/home.db'}
smitty@localhos t ~/proj/mddl4/test $ source_db="test _env" ./inputs.py
{'source_db': 'test_env'}
smitty@localhos t ~/proj/mddl4/test $ ./inputs.py -f "test_cli"
{'source_db': 'test_cli'}
For the file
=========
#!/usr/bin/env python

#Goal: unification of environment variables, command line, and
# configuration file settings.
# The .conf file is the specification.
# Optional environment variables can override.
# Optional command-line inputs trump all.
# Example is a file spec for a source database for an application.
# .conf has a contents like:
#============== =============== ===
# [CONF]
# source_db=/home/sweet/home.db

#TODO:
# 1. Decide (make an option?) to retain the simple dictionary or build
a
# class from the options.
# 2. Allow for multiple .conf locations, trying to be cool like
# xorg.conf

from ConfigParser import SafeConfigParse r
from optparse import OptionParser
import os

CONF = "CONF" #section in .conf file
CONF_FILE = "gr.conf" #name of config file
PLACEBO = "placebo" #mindless default that we don't want
gconf = {} #all your config are belong to here
parser = OptionParser()
parser.add_opti on( "-f" , "--file"
, dest = "source_db"
, help = "source database"
, default = PLACEBO )
(cl_opts, args) = parser.parse_ar gs()

config = SafeConfigParse r()
config.read(CON F_FILE)
file_conf = dict(config.ite ms(CONF))

for k in file_conf:

gconf[k]=file_conf[k]

if os.environ.has_ key(k):
gconf[k] = os.environ[k]

if cl_opts.__dict_ _.has_key(k):
if cl_opts.__dict_ _[k]!=PLACEBO:
gconf[k] = cl_opts.__dict_ _[k]
print gconf
Jun 27 '08 #1
3 2011
smitty1e <sm******@gmail .comwrites:
Just a fun exercise to unify some of the major input methods for a
script into a single dictionary.
Here is the output, given a gr.conf file in the same directory with
the contents stated below:

smitty@localhos t ~/proj/mddl4/test $ ./inputs.py
{'source_db': '/home/sweet/home.db'}
smitty@localhos t ~/proj/mddl4/test $ source_db="test _env" ./inputs.py
{'source_db': 'test_env'}
smitty@localhos t ~/proj/mddl4/test $ ./inputs.py -f "test_cli"
{'source_db': 'test_cli'}
A good start. However, you need to account for two conventions with
configuration of programs via environment variables:

* Environment variables that will be inherited by subprocesses are
conventionally distinguished from variables that will not be
inherited by using an UPPER_CASE name for variables (like process
config variables) that will be inherited, and a lower_case name for
variables (like local state variables) that will not be inherited.

* The process environment is a flat namespace, so config environment
variables need to be named to reduce the risk of namespace collision
with variables used by other programs. This is often done by
prefixing the name with the name of the program or system that will
consume it. e.g. The search path for Python imports is configured
via an attribute named 'path', but in the environment by a variable
named 'PYTHONPATH' (yes, I know that's not exactly equivalent, but
it's a good example).

Neither of these distinctions need to be made in a program-specific
configuration file, so these conventions don't apply there and would
be inappropriate. So you then need to deal with a configuration
setting being named one way in the environment, and another way in the
configuration file and elsewhere in the program.

This is probably best done by a mapping specifically for the
environment variable names:

config_env_name s = {
'source_db': 'GR_SOURCE_DB',
}

and then referencing that dictionary when inspecting the environment:

for key in config.keys():
# ...
environ_name = config_env_name s[key]
environ_value = os.environ.get( environ_name)
if environ_value is not None:
config[key] = environ_value
#...

--
\ "Pinky, are you pondering what I'm pondering?" "I think so, |
`\ Brain, but how will we get a pair of Abe Vigoda's pants?" -- |
_o__) _Pinky and The Brain_ |
Ben Finney
Jun 27 '08 #2
On May 2, 11:29 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
wrote:
smitty1e <smitt...@gmail .comwrites:
Just a fun exercise to unify some of the major input methods for a
script into a single dictionary.
Here is the output, given a gr.conf file in the same directory with
the contents stated below:
smitty@localhos t ~/proj/mddl4/test $ ./inputs.py
{'source_db': '/home/sweet/home.db'}
smitty@localhos t ~/proj/mddl4/test $ source_db="test _env" ./inputs.py
{'source_db': 'test_env'}
smitty@localhos t ~/proj/mddl4/test $ ./inputs.py -f "test_cli"
{'source_db': 'test_cli'}

A good start. However, you need to account for two conventions with
configuration of programs via environment variables:
[snip]
This is probably best done by a mapping specifically for the
environment variable names:

config_env_name s = {
'source_db': 'GR_SOURCE_DB',
}

and then referencing that dictionary when inspecting the environment:

for key in config.keys():
# ...
environ_name = config_env_name s[key]
environ_value = os.environ.get( environ_name)
if environ_value is not None:
config[key] = environ_value
#...
Hmmm...
I kinda think your excellent points are more in the realm of policy
than mechanism.
What I was going for was to assert that there a designated section (of
many possible ones)
in a .conf file that represents the set of possible program inputs,
and then
offering an example of letting environment and command line arguments
override that
..conf section.
Your points for reducing collision are well taken. Possibly having a
removable prefix
(which could be a "magic" .conf entry) would allow for a de-conflictor
prefix like
MY_PROGRAM_REAL LY_ROCKSsource_ db without having to propagate such an
eyesore throughout
the program code.
In any case, it stands as a fun little worked example.
R,
C
Jun 27 '08 #3
On May 3, 12:16 pm, smitty1e <smitt...@gmail .comwrote:
Just a fun exercise to unify some of the major input methods for a
script into a single dictionary.
Here is the output, given a gr.conf file in the same directory with
the contents stated below:

How about extending this to include other sources of control inputs.
I think a reasonable heirarchy is:

Interactive Input
Command Line Argument
Command Line Input File
Environment Variables
Local Defaults File
System Wide Defaults File
Installation Defaults File
'Factory' Defaults File
In-Code Initialization Defaults
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2663
by: joe | last post by:
Hello, I have the following commands: testb -s <size> testb -s <size> -o <input file> testb -s <size> -o <codes> How do i split the commands so that all three are valid. And how do i check for missing arguments?
12
5394
by: Rhino | last post by:
I am having an odd problem: the sqlj command on my system doesn't work. I am running DB2 (LUW) V8 (FP8) on WinXP. I haven't done an sqlj program since Version 6 of DB2 (LUW) so I checked the manuals for the proper techniques to prepare an sqlj program. When I went to try the sqlj command, I got this: Exception in thread "main" java.lang.NoClassDefFoundError: sqlj/tools/Sqlj
6
2939
by: Edd Dawson | last post by:
Hi. I have a strange problem involving the passing of command line arguments to a C program I'm writing. I tried posting this in comp.programming yesterday but someone kindly suggested that I'd have better luck here. So here goes! My program ignores any command line arguments, or at least it's supposed to. However, when I pass any command line arguments to the program, the behaviour of one of the functions changes mysteriously. I have...
2
3983
by: paul | last post by:
I have a file type that is going to be associated with my visual basic application and i want the user to be able to double click on a file of said type and have it launch the program and load the file. I know there are certain keys in the registry that i have to create and/or edit. I have located them, namely HKEY_CLASSES_ROOT\.stdf and HKEY_CLASSES_ROOT\stdf_auto_file\shell\open\command The default value for that last key is the path...
6
1484
by: CMG | last post by:
Hi, I have been looking for this quite some time now. I want to be able to pass along a string of data into my compiled programs, like prog.exe "myvar1" "myvar2" etc. or prog.exe /f whatever /g whatever. Anny ideas? Is this at all possible? If not, i think i should really quit VB :( This is like the 20th thing i wanna be able to do but can't do in vb.net :-/
5
1856
by: waltbrad | last post by:
Hi folks. I'm learning Python from the Mark Lutz Book, Programming Python 3rd edition. He seems to be able to invoke the Python interpreter from any command line prompt. C:\temp>python C:\PP3rdEd\examples>python
6
2757
by: tvaughan77 | last post by:
Hi, I have some code that I want to use to run a command line utility and I want to be able to run it from an aspx page running under IIS. The command line utility is a local utility running on the same box as my IIS server, and the code works in Visual Studio, just not under IIS. Any suggestions? The logs are totally silent on the issue. On line 36 (below), the log says: "I read this from our process:" . . . .just blank after that. ...
10
2523
by: teddyber | last post by:
Hello, first i'm a newbie to python (but i searched the Internet i swear). i'm looking for some way to split up a string into a list of pairs 'key=value'. This code should be able to handle this particular example string : qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des, 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess
7
9380
by: Jwe | last post by:
Hi, I've written a program which has both a command line interface and Windows form interface, however it isn't quite working correctly. When run from command line with no arguments it should display the Windows form. The form is being displayed but the command only returns when the form is closed. I want the command line to return immediately, leaving the form displayed.
0
9886
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10983
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10647
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10706
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10338
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9482
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
4528
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3164
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.