command-line args
Peter Hansen
peter at engcorp.com
Sat Apr 24 13:20:21 EDT 2004
(Michael, I'm keeping this on the mailing list, if you don't
mind. I prefer not answering offline questions, unless the
customer is a paying one. ;-)
Michael [mailto:mogmios at mlug.missouri.edu] wrote:
> Peter Hansen wrote:
> > Michael wrote:
> > >What do you do about multiple processes (of the same program)
> > >running at once? Save to /tmp/<pid>/globals.py or something like
> > >that?
> >
> >Why would you save anything? If you're just parsing command-line
> >arguments, the settings are not persistent, are they? Just kept in
> >memory for the duration of the current program. If you have multiple
> >processes, each gets its own command line arguments and thus its own
> >in-memory values from globals.py.
> >
> In what way can you create a module and import it from other
> modules without saving it as a file?
> [snip]
> No interest in persisitance. What I'm doing right now creates
> the globals_<pid>.py file when command-line options are
> parsed and deletes
> globals_<pid>.py* when the program stops.
What I mean is this.
You create globals.py ahead of time, the usual way with a text
editor. It can contain defaults if you wish, or be empty. E.g.:
(globals.py)
logging = False
userName = None
timeout = 5.0
Then you simply import this where you are doing the command-line
argument parsing:
import globals, getopt
opts, args = getopt.getopt(sys.argv[1:], 'at:fse:') # or whatever
for opt, val in opts:
if opt = '-t':
globals.timeout = float(val)
# etc etc
Then, elsewhere where you need to use the values, just do another
import.
(some code that needs to know the timeout)
import globals, time
time.sleep(globals.timeout)
# or whatever
There is no reason to create the .py file on the fly...
(This works because after the first import of a module inside an
application, subsequent imports do *not* re-read the .py file,
but simply get a reference to the already-imported module object
from the sys.modules dictionary.)
-Peter
More information about the Python-list
mailing list