Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Marc Tompkins
On Tue, Feb 17, 2009 at 7:09 PM, Wayne Watson
wrote:

I have a few notes, but first I just have to say: you're working very hard
to implement an ordered dictionary, and you really, really don't need to.
Python's (unordered) dictionaries work just fine for reading and writing
configurations; you just need to rethink a little.  Or, try ConfigObj, which
reads and writes your config files exactly according to your specification
with very little fuss and minimal wheel-reinvention.  'Nuff said.

Ok, let's see how this works. I've defined this function and the
> config_var_list. stop time is the last entry shown. It is part of the
> constructor for mainloop, Sentinel_GUI. and loads sdict as shown.
> def Set_ConfigDictionary():
>
> *config_var_list* = (['config_file_name',  ['Initial.sen',
> STR]],
> ['mask_file_name',  ['xyz', STR]],
> ...
> ['stop_time',  ['datetime.time(6, 0, 0)', DAT]],
> ...
> )
> # load sdict
> *sdict* = {}
> for j in range(0, len(config_var_list)):
> #print "j: ", j, "str part: ", str(config_var_list[j][0]),
> config_var_list[j][1]
> sdict[str(config_var_list[j][0])] =
> config_var_list[j][1][0]
>   ...
>

These two lines are unnecessary:
*self.sdict = sdict*
*self.config_var_list* = config_var_list
You don't need to create and load "sdict" and "config_var_list" before
assigning them to self - you could start out with
*self.sdict* = {} and *self.config_var_list* = etc.
and work from there.

  ...
> sdict and config_var_list become global to Sentinel_GUI. The first index of
> conf_var_list maintains order for sdict. That is, when I want to output the
> config file, I use to to fetch from sdict what I need, which is a value and
> the "user" type, i.e., STR, DAT, BOO, etc.
>

I don't understand the need for STR, DAT, BOO - if you're type-checking, you
don't need to create your own types to do it, and if they're informational
only, you could just give your variables descriptive names.

Relax and learn to love Python's iterators.  You don't need an index to step
through the members of a list or tuple - Python is happy to give them to you
one at a time and in order!
Instead of:
for j in range(0, len(config_var_list)):
sdict[str(config_var_list[j][0])] = config_var_list[j][1][0]
try this:
for var in config_var_list:
sdict[var[0]] = var[1][0]

Also - config_var_list is a tuple of lists.  (I'm guessing you intended to
make it a list of lists - that's what the name indicates, after all - but
putting it between "( )" makes it a tuple.)  Myself, I'd make it either a
list of dictionaries (preserves ordering), or a dictionary of dictionaries.
Here's what I'm talking about -
*config_var_list* = [{"name":"config_file_name",
"value":"Initial.sen", "type": "STR"},
{"name":"mask_file_name",  "value":"xyz", "type":"STR"},
...
{"name":"stop_time",  "value":"datetime.time(6, 0, 0)",
"type":"DAT"},
...
]
# load sdict
*sdict* = {}
for var in config_var_list:
sdict[var["name"]] = var["value"]

I just find it much, much easier to understand what's going on - with [0]
and [1][0] I had to read the code four or five times to grok it.  I haven't
benchmarked the two approaches - it's possible that access by list indices
is faster - but it's hard to overestimate the importance of clarity.

Now in SaveConfigFile, I go merrily along thusly:
>
>...
> # SAVE CONFIG FILE
> items = self.sdict.keys()
> items.sort()
> for (j, conf_entry) in enumerate(self.config_var_list):
> varName = conf_entry[0]
> varType = self.config_var_list[j][1][1]
> # Note, date-time vars are in hh:mm:ss
> varValue = eval('self.' + varName)
> var_assignment = varName + "=" + str(varValue)<<--- Beep,
> beep
> config_file.write(var_assignment + "\n")
>  ...
>

Don't work so hard!  You're using enumerate() to get both the index and the
item - but you don't need to, and it's easier to use and to read if you
don't.  In other words,
varType = self.config_var_list[j][1][1]
could be shortened to
varType = conf_entry[1][1]
You already did that for varName - just take it the rest of the way.

Next, that eval() - better this way:
varValue = getattr(self, varName)
There _are_ some valid use cases for eval() - but getting and setting
attributes ain't it.

So, taking just this section in isolation (assuming you don't implement any
of my other suggestions) -
for conf_entry in enumerate(self.con

Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Martin Walsh
Marc Tompkins wrote:
> Also - config_var_list is a tuple of lists.  (I'm guessing you intended
> to make it a list of lists - that's what the name indicates, after all -
> but putting it between "( )" makes it a tuple.)  

Sound advice, but a subtle clarification is warranted I think. It's the
comma(s) that make a tuple not the parens (and an absence of square
brackets, I suppose). Consider the following:

In [1]: a = (1)

In [2]: a
Out[2]: 1

In [3]: type(a)
Out[3]: 

In [4]: b = (1,)

In [5]: b
Out[5]: (1,)

In [6]: type(b)
Out[6]: 

In [7]: c = 1, 2, 3

In [8]: c
Out[8]: (1, 2, 3)

In [9]: type(c)
Out[9]: 

...

Wayne, I second Marc's advice that you're making it hard on yourself.
Understandable to a degree, if you are trying to avoid major
modification to inherited code.

But, loading and saving configuration data is a 'solved' problem in that
there are many choices of ready-made tools to help you accomplish the
task. And, I don't see anything in your description that would indicate
a custom solution is necessary -- except perhaps for the learning
experience, almost never a bad idea, IMHO.

Marc has already pointed out ConfigObj, which is excellent, but I
thought I would also suggest ConfigParser -- part of the standard lib,
if a bit less feature-full.

Back to your original question, and I'm probably overstating the obvious
at this point, but the underlying problem is that the operation causing
the exception is expecting a datetime.time object and getting a str. So,
it's less about adding a strftime attribute to the str object, and more
about 'converting' the str into a datetime.time object.

Short of re-writing for ConfigObj (which provides a type conversion and
validation mechanism), or pickle, or similar -- you'll need to work out
how to convert between str and datetime.time. Here are some (untested)
examples:

def time_to_str(t):
return t.strftime('%H:%M:%S')

def str_to_time(s):
h, m, s = [int(u) for u in s.split(':')]
return datetime.time(h, m, s)

HTH,
Marty

PS. You can avoid posting images of tracebacks by enabling 'Quick Edit'
mode in your windows command prompt. More info here:
http://support.microsoft.com/kb/282301

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Wayne Watson
Title: Signature.html




Thanks very much for the comments. Definitely food for thought and
helpful. I'll review them more completely  later today. I'd say chances
of me switching to ConfigObj are high. 

Yes, about config_var_list was supposed to be a list. That was caused
by confusion over syntactically hemming in that long list of items
entries properly with [,}, and ). Too many possible entanglements!
Somehow, it ended up closing it as a tuple. As an aside, in IDLE, those
} and ) sure look alike. Yes, to not putting datetime(...) into the
file. Yes, to changing the oddity of rampant indexes.  They were
beginning to drive me nuts. :-)  Maybe the web documents should warn
about the horrors of eval. VBG. Possibly the same is true of exec?

A good bit of the new "hurry up" code was put there to test some ideas
and flush out some unknowns in the code. For some reason, the author
missed the opportunity to put in a config file from the start; however,
I'm sure he had enough to do in the time he had to squeeze out as much
as he did, which is quite good. 

It looks like it's time to rework the code. The good side here is that
I've gotten a better grip on the author's code. That should help as I
continue to add new features. 
...
-- 


   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time)


"Nature, to be commanded, must be obeyed."
   -- Sir Francis Bacon 




Web Page: 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Wayne Watson
Title: Signature.html




Thanks. I'm onboard with the changes Marc and you, as below, suggest,
and will very, very likely grab onto ConfigObj. I'll look into Quick
Edit. I use Snagit to screen capture. One of the most useful tools I've
come across in a long time. 

The real meat to this code is not implementing a config file, although
I believe it warrants one. The real meat is adding analytic
capabilities. The program provides a very good interface between the
hardware and the user, but has no analytic power. 

What's happening here is the program drives a video camera to capture
fireballs (bright meteors). It does almost nothing more, but has a few
administrative functions like deleting false images and making a
composite of the video frames.  The most elementary elementary analytic
calculation it might be able to make for a single observer is a rough
estimate of the distance to some part of the meteor trail. The deepest
calculation it might be able to make is to actually calculate the
trajectory of the trail and determine a possible geographic fall point
for the object.  This requires calculations from two observers.
Nevertheless, neither is available, and they can be implemented. That's
where I'm headed.  The author had his hands full getting this code out,
which is all to his credit.  I'm trying to take it to the next step.
He's a plenty busy guy.

Martin Walsh wrote:

  Marc Tompkins wrote:
  
  
Also - config_var_list is a tuple of lists.  (I'm guessing you intended
to make it a list of lists - that's what the name indicates, after all -
but putting it between "( )" makes it a tuple.)  

  
  
Sound advice, but a subtle clarification is warranted I think. It's the
comma(s) that make a tuple not the parens (and an absence of square
brackets, I suppose). Consider the following:

In [1]: a = (1)

In [2]: a
Out[2]: 1

In [3]: type(a)
Out[3]: 

In [4]: b = (1,)

In [5]: b
Out[5]: (1,)

In [6]: type(b)
Out[6]: 

In [7]: c = 1, 2, 3

In [8]: c
Out[8]: (1, 2, 3)

In [9]: type(c)
Out[9]: 

...

Wayne, I second Marc's advice that you're making it hard on yourself.
Understandable to a degree, if you are trying to avoid major
modification to inherited code.

But, loading and saving configuration data is a 'solved' problem in that
there are many choices of ready-made tools to help you accomplish the
task. And, I don't see anything in your description that would indicate
a custom solution is necessary -- except perhaps for the learning
experience, almost never a bad idea, IMHO.

Marc has already pointed out ConfigObj, which is excellent, but I
thought I would also suggest ConfigParser -- part of the standard lib,
if a bit less feature-full.

Back to your original question, and I'm probably overstating the obvious
at this point, but the underlying problem is that the operation causing
the exception is expecting a datetime.time object and getting a str. So,
it's less about adding a strftime attribute to the str object, and more
about 'converting' the str into a datetime.time object.

Short of re-writing for ConfigObj (which provides a type conversion and
validation mechanism), or pickle, or similar -- you'll need to work out
how to convert between str and datetime.time. Here are some (untested)
examples:

def time_to_str(t):
return t.strftime('%H:%M:%S')

def str_to_time(s):
h, m, s = [int(u) for u in s.split(':')]
return datetime.time(h, m, s)

HTH,
Marty

PS. You can avoid posting images of tracebacks by enabling 'Quick Edit'
mode in your windows command prompt. More info here:
http://support.microsoft.com/kb/282301

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

  


-- 


   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time)


"Nature, to be commanded, must be obeyed."
   -- Sir Francis Bacon 




Web Page: 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Wayne Watson
Title: Signature.html




See Subject. I've run across a 58 page document
, but am
uncertain of its applicability to my present needs (see my thread on
"Changing the Attribute"). Usually, I end up with some 3-4 page
document, so this raises an eyebrow. Am I on the right trail? In the
meantime, I think I'll turn it into a more manageable pdf file before
putting it to paper. 
-- 


   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time)


"Nature, to be commanded, must be obeyed."
   -- Sir Francis Bacon 




Web Page: 




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 7:30 AM, Wayne Watson
wrote:

>  See Subject. I've run across a 58 page document
> ,
> but am uncertain of its applicability to my present needs (see my thread on
> "Changing the Attribute"). Usually, I end up with some 3-4 page document, so
> this raises an eyebrow. Am I on the right trail? In the meantime, I think
> I'll turn it into a more manageable pdf file before putting it to paper.
>

It's a very powerful module - does lots of things you don't need yet, and
maybe never will - and I agree that it could benefit from a
hit-the-ground-running guide...

Here's a quick-and-dirty; you can flesh out the details from the
documentation you downloaded.  (By the way, you'll also want to use the
validate module - another 14 pages or so...)
==
* Download configobj.py and validate.py; put them somewhere in your
Python path (or in the same folder as your project, if you want)
* Add two lines to the top of your program:
from configobj import ConfigObj
from validate import Validator
* To make working with your spec easier,
import StringIO  # allows you to work with strings as if they were
files
# You could just create a spec file, and open it normally, but this
keeps everything in one place.
* Somewhere in your program, create your spec and load it.  There are a
lot of ways you can do this - for me, the simple thing is to put it in a
class.  I create a class called Global - it's a crutch, I know...
class Global(object):
cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current
directory + "\" + filename - but you could put it anywhere and call it
anything
# create your spec as a multi-line string between triple quotes
tmpStr = """
mask_file_name = string(default=None)
gray_scale = boolean(default=True)
post_event_stack = boolean(default=False)
post_event_format = string(default="Tiff 2")
show_real_time = boolean(default=False)
hourly_rate = integer(min=0, default=0)
slowdown= integer(min=0, max=10, default=1) # I don't know what
this value is/does, so this is probably wrong
start_time = string(default="00:00:00") # or you could make the
default None?
stop_time = string(default="00:00:00")
lat = float(min=0.0, max=90.0) # I have no idea what you'd want
as a default latitude, if any...

"""
cfgSpec = StringIO.StringIO(tmpStr) # turns the above string
into a file-like object, which ConfigObj is expecting
cfgFile = ConfigObj(cfgFileName,
configspec=cfgSpec, raise_errors=True,
write_empty_values=True,
create_empty=True, indent_type='',
list_values=True) # creates the actual ConfigObj object
vtor = Validator() # creates a validator to match your config
data against your spec
* Invoke the above code when your program starts - I do it just before
my mainloop, like so:
def main(argv=None):
if argv is None:
argv = sys.argv
test = Global.cfgFile.validate(Global.vtor, copy=True) # tries
to load cfgFile; if it doesn't exist, creates it; fills in defaults for any
missing values
Global.cfgFile.write() # saves the validated file (you don't
need to do this here at the start, but I usually do)
app = MyApp(0)
app.MainLoop()
if __name__ == '__main__':
main()
* Your ConfigObj is ready to use!  Simply access the contents like a
regular dictionary.  To save back to the file, call the write() method.
Global.cfgFile['mask_file_name'] = 'bogus.txt'
Global.cfgFile.write()

maskFile = Global.cfgFile['mask_file_name']
* Or use the values directly without copying to intermediate variables:
with open(Global.cfgFile['mask_file_name'], 'w+b') as maskFile:
maskFile.write('some bogus text')
==
I'm attaching that as a text file too - I suspect that my indentation won't
survive the trip...

My Global class is an ugly hack.  I'm sure you'll come up with something
more aesthetically pleasing...
ConfigObj has lots of very cool features - sections, repeated sections,
custom input validators - that's what the 50+ pages of documentation are
about.  When you need that stuff, it's available.
-- 
www.fsrtechnologies.com

* Download configobj.py and validate.py; put them somewhere in your Python 
path (or in the same folder as your project, if you want)
* Add two lines to the top of your program: 
from configobj import ConfigObj
from validate import Validator
* To make working with your spec easier, 
import StringIO  # allows you t

Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Wayne Watson
Title: Signature.html




OK, I got the ObjectConfig and Validate downloads, and copied your
Global class successfully. Don't I need to get the two files into
Python as a module? How does that work?

Marc Tompkins wrote:

  On Wed, Feb 18, 2009 at 7:30 AM, Wayne
Watson 
wrote:
  
See Subject. I've run across
a 58 page document
,
but am
uncertain of its applicability to my present needs (see my thread on
"Changing the Attribute"). Usually, I end up with some 3-4 page
document, so this raises an eyebrow. Am I on the right trail? In the
meantime, I think I'll turn it into a more manageable pdf file before
putting it to paper. 
  
  
It's a very powerful module - does lots of things you don't need yet,
and maybe never will - and I agree that it could benefit from a
hit-the-ground-running guide...
  
Here's a quick-and-dirty; you can flesh out the details from the
documentation you downloaded.  (By the way, you'll also want to use the
validate module - another 14 pages or so...)
==
    * Download configobj.py and validate.py; put them somewhere in your
Python path (or in the same folder as your project, if you want)
    * Add two lines to the top of your program: 
    from configobj import ConfigObj
    from validate import Validator
    * To make working with your spec easier, 
    import StringIO  # allows you to work with strings as if they
were files
    # You could just create a spec file, and open it normally, but
this keeps everything in one place.
    * Somewhere in your program, create your spec and load it.  There
are a lot of ways you can do this - for me, the simple thing is to put
it in a class.  I create a class called Global - it's a crutch, I
know...
    class Global(object):  
    cfgFileName = os.getcwd() + os.sep + 'Initial.sen' #
current directory + "\" + filename - but you could put it anywhere and
call it anything
    # create your spec as a multi-line string between triple
quotes
    tmpStr = """
    mask_file_name = string(default=None)
    gray_scale = boolean(default=True)
    post_event_stack = boolean(default=False)
    post_event_format = string(default="Tiff 2")
    show_real_time = boolean(default=False)
    hourly_rate = integer(min=0, default=0)
    slowdown= integer(min=0, max=10, default=1) # I don't know
what this value is/does, so this is probably wrong
    start_time = string(default="00:00:00") # or you could make
the default None?
    stop_time = string(default="00:00:00")
    lat = float(min=0.0, max=90.0) # I have no idea what you'd
want as a default latitude, if any...
  
    """
    cfgSpec = StringIO.StringIO(tmpStr) # turns the above
string into a file-like object, which ConfigObj is expecting
    cfgFile = ConfigObj(cfgFileName, 
    configspec=cfgSpec, raise_errors=True,
write_empty_values=True, 
    create_empty=True, indent_type='    ',
list_values=True) # creates the actual ConfigObj object
    vtor = Validator() # creates a validator to match your
config data against your spec
    * Invoke the above code when your program starts - I do it just
before my mainloop, like so:
    def main(argv=None):
    if argv is None:
    argv = sys.argv
    test = Global.cfgFile.validate(Global.vtor, copy=True) #
tries to load cfgFile; if it doesn't exist, creates it; fills in
defaults for any missing values
    Global.cfgFile.write() # saves the validated file (you
don't need to do this here at the start, but I usually do)
    app = MyApp(0)    
    app.MainLoop()
    if __name__ == '__main__':
    main()
    * Your ConfigObj is ready to use!  Simply access the contents like
a regular dictionary.  To save back to the file, call the write()
method.
    Global.cfgFile['mask_file_name'] = 'bogus.txt'
    Global.cfgFile.write()
    
    maskFile = Global.cfgFile['mask_file_name']
    * Or use the values directly without copying to intermediate
variables:
    with open(Global.cfgFile['mask_file_name'], 'w+b') as maskFile:
    maskFile.write('some bogus text')
==
I'm attaching that as a text file too - I suspect that my indentation
won't survive the trip...
  
My Global class is an ugly hack.  I'm sure you'll come up with
something more aesthetically pleasing...
  
  
ConfigObj has lots of very cool features - sections, repeated sections,
custom input validators - that's what the 50+ pages of documentation
are about.  When you need that stuff, it's available.
-- 
  www.fsrtechnologies.com
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



-- 


   Wayne Wa

Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 1:01 PM, Wayne Watson
wrote:

>  OK, I got the ObjectConfig and Validate downloads, and copied your Global
> class successfully. Don't I need to get the two files into Python as a
> module? How does that work?
>

Simplest: put them in the same folder as your own program.  More standard:
put them in one of the folders in your Python path - same general idea as
the DOS search path, it's a list of directories where Python will look for
modules you ask it to import.

>From the docs: (http://docs.python.org/tutorial/modules.html)
The Module Search
Path¶

When a module named spam is imported, the interpreter searches for a file
named spam.py in the current directory, and then in the list of directories
specified by the environment variable
*PYTHONPATH*.
This has the same syntax as the shell variable *PATH*, that is, a list of
directory names. When
*PYTHONPATH*is
not set, or when the file is not found there, the search continues in
an
installation-dependent default path; on Unix, this is usually
.:/usr/local/lib/python.

Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory containing the
input script (or the current directory),
*PYTHONPATH*and
the installation- dependent default. This allows Python programs that
know what they're doing to modify or replace the module search path. Note
that because the directory containing the script being run is on the search
path, it is important that the script not have the same name as a standard
module, or Python will attempt to load the script as a module when that
module is imported. This will generally be an error. See section *Standard
Modules* for
more information.



>
> Marc Tompkins wrote:
>
> On Wed, Feb 18, 2009 at 7:30 AM, Wayne Watson <
> sierra_mtnv...@sbcglobal.net> wrote:
>
>> See Subject. I've run across a 58 page document
>> ,
>> but am uncertain of its applicability to my present needs (see my thread on
>> "Changing the Attribute"). Usually, I end up with some 3-4 page document, so
>> this raises an eyebrow. Am I on the right trail? In the meantime, I think
>> I'll turn it into a more manageable pdf file before putting it to paper.
>>
>
> It's a very powerful module - does lots of things you don't need yet, and
> maybe never will - and I agree that it could benefit from a
> hit-the-ground-running guide...
>
> Here's a quick-and-dirty; you can flesh out the details from the
> documentation you downloaded.  (By the way, you'll also want to use the
> validate module - another 14 pages or so...)
> ==
> * Download configobj.py and validate.py; put them somewhere in your
> Python path (or in the same folder as your project, if you want)
> * Add two lines to the top of your program:
> from configobj import ConfigObj
> from validate import Validator
> * To make working with your spec easier,
> import StringIO  # allows you to work with strings as if they were
> files
> # You could just create a spec file, and open it normally, but this
> keeps everything in one place.
> * Somewhere in your program, create your spec and load it.  There are a
> lot of ways you can do this - for me, the simple thing is to put it in a
> class.  I create a class called Global - it's a crutch, I know...
> class Global(object):
> cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current
> directory + "\" + filename - but you could put it anywhere and call it
> anything
> # create your spec as a multi-line string between triple quotes
> tmpStr = """
> mask_file_name = string(default=None)
> gray_scale = boolean(default=True)
> post_event_stack = boolean(default=False)
> post_event_format = string(default="Tiff 2")
> show_real_time = boolean(default=False)
> hourly_rate = integer(min=0, default=0)
> slowdown= integer(min=0, max=10, default=1) # I don't know what
> this value is/does, so this is probably wrong
> start_time = string(default="00:00:00") # or you could make the
> default None?
> stop_time = string(default="00:00:00")
> lat = float(min=0.0, max=90.0) # I have no idea what you'd want
> as a default latitude, if any...
>
> """
> cfgSpec = StringIO.StringIO(tmpStr) # turns the above string
> into a file-like object, which ConfigObj is expecting
> cfgFile = ConfigObj(cfgFileNa

[Tutor] "Ctrl-C (unix)" in python

2009-02-18 Thread pa yo
I am  running my Twitter>>Wiki bots in infinite loops but can't find
an easy way to turn them off gracefully once I have started them. At
the moment I have to go into the terminal window where they are
running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2)

I was thinking that I could get the bot script to read a text file at
the start of the main loop and have a separate script writing the
"exit" order to the same text file but before I get too involved
with this I wanted to know if there  was an  built-in function to
switch scripts on and off.

Any help or assistance much appreciated.

Payo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Wayne Watson
Title: Signature.html




Thanks. I recall installing several libraries though, where somehow
they were packaged to automatically install when opened. 

In the 
description, I do not see much of an explanations of examples of items
like, integer(min=0, default=0). It looks like they may be called
configspecs. I see this in section 5.3.2.2.
key1 = integer(0, 30, default=15)
key2 = integer(default=15)
key3 = boolean(default=True)
key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today')

but not much else. Validators? Are there others like integer, booleand
and option?  Items like start_time would then be called keywords?

Marc Tompkins wrote:

  On Wed, Feb 18, 2009 at 1:01 PM, Wayne
Watson 
wrote:
  
OK, I got the ObjectConfig
and Validate downloads, and copied your
Global class successfully. Don't I need to get the two files into
Python as a module? How does that work?

  
  
Simplest: put them in the same folder as your own program.  More
standard: put them in one of the folders in your Python path - same
general idea as the DOS search path, it's a list of directories where
Python will look for modules you ask it to import.
  
>From the docs: (http://docs.python.org/tutorial/modules.html)
  The Module Search Path¶
  When a module named spam is
imported, the interpreter searches for a file
named spam.py
in the current directory, and then in the list of
directories specified by the environment variable PYTHONPATH. This
has the same syntax as the shell variable PATH, that is, a
list of
directory names. When PYTHONPATH is not set, or when the file is
not
found there, the search continues in an installation-dependent default
path; on
Unix, this is usually .:/usr/local/lib/python.
  Actually, modules are searched in the list of directories given by
the variable sys.path
which is initialized from the directory containing the input script
(or the current directory), PYTHONPATH and the installation- dependent
default. This allows Python programs that know what they're doing to
modify or
replace the module search path. Note that because the directory
containing the
script being run is on the search path, it is important that the script
not have
the same name as a standard module, or Python will attempt to load the
script as
a module when that module is imported. This will generally be an error.
See
section Standard
Modules for more information.
  
 
  

Marc Tompkins wrote:

  
  
  On Wed, Feb 18, 2009 at 7:30 AM, Wayne
Watson 
wrote:
  
See Subject. I've run
across
a 58 page document ,
but am
uncertain of its applicability to my present needs (see my thread on
"Changing the Attribute"). Usually, I end up with some 3-4 page
document, so this raises an eyebrow. Am I on the right trail? In the
meantime, I think I'll turn it into a more manageable pdf file before
putting it to paper. 
  
  
It's a very powerful module - does lots of things you don't need yet,
and maybe never will - and I agree that it could benefit from a
hit-the-ground-running guide...
  
Here's a quick-and-dirty; you can flesh out the details from the
documentation you downloaded.  (By the way, you'll also want to use the
validate module - another 14 pages or so...)
==
    * Download configobj.py and validate.py; put them somewhere in your
Python path (or in the same folder as your project, if you want)
    * Add two lines to the top of your program: 
    from configobj import ConfigObj
    from validate import Validator
    * To make working with your spec easier, 
    import StringIO  # allows you to work with strings as if they
were files
    # You could just create a spec file, and open it normally, but
this keeps everything in one place.
    * Somewhere in your program, create your spec and load it.  There
are a lot of ways you can do this - for me, the simple thing is to put
it in a class.  I create a class called Global - it's a crutch, I
know...
    class Global(object):  
    cfgFileName = os.getcwd() + os.sep + 'Initial.sen' #
current directory + "\" + filename - but you could put it anywhere and
call it anything
    # create your spec as a multi-line string between triple
quotes
    tmpStr = """
    mask_file_name = string(default=None)
    gray_scale = boolean(default=True)
    post_event_stack = boolean(default=False)
    post_event_format = string(default="Tiff 2")
    show_real_time = boolean(default=False)
    hourly_rate = integer(min=0, default=0)
    slowdown= integer(min=0, max=10, default=1) # I don't know
what this value is/does, so this is probably wrong
    start_time = string(default="00:00:00") # or you could make
the default None?
    stop_time = string(default="00:00:00")
    lat = float(min=0.0, max=90.0) # I have no idea what

[Tutor] confused with dates and which way to start

2009-02-18 Thread johnf
Hi,

I need to develope a routine that will provide the some dates between a 
starting date and an ending date.  The dates will be used to schedule 
instructors for specific class dates from the list of available dates.   
Class is normally on Monday, Wedesday, and Friday (or any days of the week 
including Sat and Sun).  If the length of the class is 6 months (01/01/09 - 
06/30/09).  I need to generate all the dates that would match the Monday, 
Wedesday, and Friday (or whatever days are used for the class) for the entire 
period.  

I have done this is FoxPro in the past.  Now I'm in python 2.5.  

Now the problem is there appears many ways to deal with dates in python.  
time(), calendar(), datetime(), dateutil().  Which is the easy way guys???  
And is there something already written I should be using  Also there is 
something called 'mx'.

Thanks in advance. 

-- 
John Fabiani
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 2:57 PM, Wayne Watson
wrote:

>  Thanks. I recall installing several libraries though, where somehow they
> were packaged to automatically install when opened.
>
> In the 
> description,
>  I do not see much of an explanations of examples of items like,
> integer(min=0, default=0). It looks like they may be called configspecs. I
> see this in section 5.3.2.2.
>
> key1 = integer(0, 30, default=15)
> key2 = integer(default=15)
> key3 = boolean(default=True)
> key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today')
>
> but not much else. Validators? Are there others like integer, booleand and
> option?  Items like start_time would then be called keywords?
>
The configspec (configuration specification) is that thing I put inside of
triple quotes.  It's basically a template of what your config file will look
like once it has actual data in it.

In 5.3.2, the sentence "The validate method uses the
validatemodule to do
the validation" links to the validate.py documentation - but
you won't see that if you're reading it on paper...

Remember I said there's a bunch of stuff there you might not need just now?
A good deal of it has to do with extending ConfigObj for your own twisted,
nefarious purposes (bwahahahahaha!) - you can write your own validators for
just about any kind of values you can imagine.  However, just to get
started, the built-ins are probably good (from the validate.py doc,
http://www.voidspace.org.uk/python/validate.html#the-standard-functions):




The standard functions come built-in to every Validator instance. They work
with the following basic data types :

   - integer
   - float
   - boolean
   - string
   - ip_addr

plus lists of these datatypes.

Adding additional checks is done through coding simple functions.

The full set of standard checks are :
  'integer':

matches integer values (including negative). Takes optional 'min' and 'max'
arguments :

integer()
integer(3, 9)# any value from 3 to 9
integer(min=0) # any positive value
integer(max=9)

 'float':

matches float values Has the same parameters as the integer check.
 'boolean':matches boolean values: True or False.

Acceptable string values for True are :

true, on, yes, 1

 Acceptable string values for False are :

false, off, no, 0

Any other value raises an error.
 'string':

matches any string. Takes optional keyword args 'min' and 'max' to specify
min and max length of string.
 'ip_addr':

matches an Internet Protocol address, v.4, represented by a dotted-quad
string, i.e. '1.2.3.4'.
 'list':

matches any list. Takes optional keyword args 'min', and 'max' to specify
min and max sizes of the list. The list checks always return a list.
 'tuple':

matches any list. This check returns a tuple rather than a list.
 'int_list':

Matches a list of integers. Takes the same arguments as list.
 'float_list':

Matches a list of floats. Takes the same arguments as list.
 'bool_list':

Matches a list of boolean values. Takes the same arguments as list.
 'string_list':

Matches a list of strings. Takes the same arguments as list.
 'ip_addr_list':

Matches a list of IP addresses. Takes the same arguments as list.
 'mixed_list':

Matches a list with different types in specific positions. List size must
match the number of arguments.

Each position can be one of :

int, str, boolean, float, ip_addr

So to specify a list with two strings followed by two integers, you write
the check as :

mixed_list(str, str, int, int)

 'pass':

matches everything: it never fails and the value is unchanged. It is also
the default if no check is specified.
 'option':

matches any from a list of options. You specify this test with :

option('option 1', 'option 2', 'option 3')

  ===


-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confused with dates and which way to start

2009-02-18 Thread Kent Johnson
On Wed, Feb 18, 2009 at 6:10 PM, johnf  wrote:
> Hi,
>
> I need to develope a routine that will provide the some dates between a
> starting date and an ending date.  The dates will be used to schedule
> instructors for specific class dates from the list of available dates.
> Class is normally on Monday, Wedesday, and Friday (or any days of the week
> including Sat and Sun).  If the length of the class is 6 months (01/01/09 -
> 06/30/09).  I need to generate all the dates that would match the Monday,
> Wedesday, and Friday (or whatever days are used for the class) for the entire
> period.
>
> I have done this is FoxPro in the past.  Now I'm in python 2.5.
>
> Now the problem is there appears many ways to deal with dates in python.
> time(), calendar(), datetime(), dateutil().  Which is the easy way guys???

This is pretty easy using datetime.date and timedelta. For example,
this shows all the M, W, F between (more or less) your given dates:

In [1]: from datetime import date, timedelta
In [3]: end = date(2009, 6, 30)
In [4]: start = date(2009, 1, 4) # a Sunday
In [7]: offsets = [timedelta(days=offset) for offset in (1, 3, 5) ] #
Mon, Wed, Fri
In [8]: current = start

In [9]: while current < end:
   ...: for offset in offsets:
   ...: print current + offset
   ...: current += timedelta(days=7)

2009-01-05
2009-01-07
2009-01-09
2009-01-12
2009-01-14
2009-01-16
...etc

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Ctrl-C (unix)" in python

2009-02-18 Thread W W
On Wed, Feb 18, 2009 at 4:44 PM, pa yo  wrote:

> I am  running my Twitter>>Wiki bots in infinite loops but can't find
> an easy way to turn them off gracefully once I have started them. At
> the moment I have to go into the terminal window where they are
> running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2)
>
> I was thinking that I could get the bot script to read a text file at
> the start of the main loop and have a separate script writing the
> "exit" order to the same text file but before I get too involved
> with this I wanted to know if there  was an  built-in function to
> switch scripts on and off.
>

Unless you want to play with sockets, that's probably the easiest way to do
it that I know of.

-Wayne
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Proxies/Interceptors for file-like objects

2009-02-18 Thread Oxymoron
Hello,

I'm trying to intercept one or more methods in file-like objects (in
this particular case just sys.stdin really), essentially I need a
decorator/proxy implemented.

What's the idiomatic way to do this? Since file objects do not have a
base class(?), would I need to implement all methods to delegate down
to my wrapped object, or can I use a special method to define default
behaviour?

I came across http://pypi.python.org/pypi/filelike/0.3.2 on googling.
It seems a little overkill for what I want to do however, but it does
define a base class.

Thanks.

-- Kamal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Ctrl-C (unix)" in python

2009-02-18 Thread John Fouhy
2009/2/19 pa yo :
> I am  running my Twitter>>Wiki bots in infinite loops but can't find
> an easy way to turn them off gracefully once I have started them. At
> the moment I have to go into the terminal window where they are
> running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2)
>
> I was thinking that I could get the bot script to read a text file at
> the start of the main loop and have a separate script writing the
> "exit" order to the same text file but before I get too involved
> with this I wanted to know if there  was an  built-in function to
> switch scripts on and off.

You could go multithreaded.  Something like this:

In your main thread, replace

while True:

with

while not self.done:

and then have another thread that does something like:

while True:
response = raw_input('Type "quit" to quit:')
if response.lower() == 'quit':
self.done = True
break

Or even more simply:

raw_input("Hit return to quit.")
self.done = True

It would also be easy to replace this with, say, Tkinter code to put a
"Quit" button in a window on your desktop.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confused with dates and which way to start

2009-02-18 Thread johnf
On Wednesday 18 February 2009 03:10:41 pm johnf wrote:
> Hi,
>
> I need to develope a routine that will provide the some dates between a
> starting date and an ending date.  The dates will be used to schedule
> instructors for specific class dates from the list of available dates.
> Class is normally on Monday, Wedesday, and Friday (or any days of the week
> including Sat and Sun).  If the length of the class is 6 months (01/01/09 -
> 06/30/09).  I need to generate all the dates that would match the Monday,
> Wedesday, and Friday (or whatever days are used for the class) for the
> entire period.
>
> I have done this is FoxPro in the past.  Now I'm in python 2.5.
>
> Now the problem is there appears many ways to deal with dates in python.
> time(), calendar(), datetime(), dateutil().  Which is the easy way guys???
> And is there something already written I should be using  Also there is
> something called 'mx'.
>
> Thanks in advance.

Kent Johnson provided the following:

This is pretty easy using datetime.date and timedelta. For example,
this shows all the M, W, F between (more or less) your given dates:

In [1]: from datetime import date, timedelta
In [3]: end = date(2009, 6, 30)
In [4]: start = date(2009, 1, 4) # a Sunday
In [7]: offsets = [timedelta(days=offset) for offset in (1, 3, 5) ] #
Mon, Wed, Fri
In [8]: current = start

In [9]: while current < end:
   ...:     for offset in offsets:
   ...:         print current + offset
   ...:     current += timedelta(days=7)

2009-01-05
2009-01-07
2009-01-09
2009-01-12
2009-01-14
2009-01-16
...etc

Kent


thanks Kent.  This appears to work.  I was not aware of datetime.timedelta().  
I really think there should be a place to find this type of information.  
I'll study the module.  Again, thanks.
-- 
John Fabiani
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Alan Gauld


"Wayne Watson"  wrote

 I'll look into Quick Edit. I use Snagit to screen capture. 


Quick edit allows you to use the mouse to select text on the 
console screen then use the Enter key to copy it to the clipboard.


So to paste an error message into an email simple select 
it with the mouse, hit enter then go to your mail message 
and paste it in as normal text. Avoids any screen captures 
or attachments etc.


You can do the same thing more slowly without QuickEdit 
using the menu accessed via the icon on the left of the window 
title bar. Navigate to the edit submenu...


Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing the Attribute of a Variable

2009-02-18 Thread Alan Gauld


"Wayne Watson"  wrote

 Maybe the web documents should warn about the horrors of eval. 
VBG. Possibly the same is true of exec?


Yes the same is true of exec and also potentially execfile.
All need to be used with extreme care where there is any 
risk of the executed code being tampered with outside 
the program.


Thats why we have been saying that setattr/getattr etc 
are better ways of doing things.


HTH,


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/l

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Ctrl-C (unix)" in python

2009-02-18 Thread Jervis Whitley
On Thu, Feb 19, 2009 at 9:44 AM, pa yo  wrote:
> I am  running my Twitter>>Wiki bots in infinite loops but can't find
> an easy way to turn them off gracefully once I have started them. At
> the moment I have to go into the terminal window where they are
> running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2)
>
> I was thinking that I could get the bot script to read a text file at
> the start of the main loop and have a separate script writing the
> "exit" order to the same text file but before I get too involved
> with this I wanted to know if there  was an  built-in function to
> switch scripts on and off.
>
> Any help or assistance much appreciated.
>
> Payo
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
how about kill -9   :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Proxies/Interceptors for file-like objects

2009-02-18 Thread Emile van Sebille

Oxymoron wrote:
I'm trying to intercept one or more methods in file-like objects 


Shadowing perhaps?

>>> class open(open):
... def mything(self):
... print "it's my thing"
...
>>> a = open(r'c:\testfile','wb')
>>> a.mything()
it's my thing
>>> a.write("this is a test")
>>> a.flush()
>>> a.close()
>>> open(r'c:\testfile','r').read()
'this is a test'
>>>


Emile

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Proxies/Interceptors for file-like objects

2009-02-18 Thread Oxymoron
On Thu, Feb 19, 2009 at 11:51 AM, Emile van Sebille  wrote:
> Oxymoron wrote:
>>
>> I'm trying to intercept one or more methods in file-like objects
>
> Shadowing perhaps?

Neat stuff - but not applicable for me I think:

1. I receive the handle. I need this function in a CGI script for
example, so sys.stdin is already open.
2. I actually need to forward requests to the underlying handle
before/after intercepting, does shadowing in your example allow me to
do that?

-- Kamal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confused with dates and which way to start

2009-02-18 Thread Kent Johnson
On Wed, Feb 18, 2009 at 6:55 PM, johnf  wrote:

> thanks Kent.  This appears to work.  I was not aware of datetime.timedelta().
> I really think there should be a place to find this type of information.

That's what the library reference is for:
http://docs.python.org/library/datetime.html
http://docs.python.org/library/index.html

and comp.lang.python and the tutor list :-)

It's really worth your time to at least browse the library reference.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Proxies/Interceptors for file-like objects

2009-02-18 Thread Kent Johnson
On Wed, Feb 18, 2009 at 7:51 PM, Emile van Sebille  wrote:

 class open(open):
> ... def mything(self):
> ... print "it's my thing"

Hmm. I guess this is Python 3? In 2.6, open is a function and trying
to subclass it gives an error:

In [10]: open
Out[10]: 

In [11]: class myopen(open): pass

   :

TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances

In any event, it's pretty easy to define a generic delegate in Python
using the __getattr__() hook to delegate attribute access. Here is an
example (that assumes all attributes are methods and doesn't actually
do anything other than delegate):
http://code.activestate.com/recipes/252151/

Here is an example using old-style classes that logs attribute access,
both fields and methods:

class LoggingWrapper:
def __init__(self, instance):
self.__dict__['_instance'] = instance  # Actual instance

def __getattr__(self, attrName):
''' Log member access '''

# Get the attribute from the delegate
attrValue = getattr(self._instance, attrName)

# Don't log access to private attributes
if attrName.startswith('_'):
return attrValue

if callable(attrValue):
# Create a delegate function that will log the actual parameters
def delegate(*args, **kwds):
params = []
if args:
params.extend(map(repr, args))
if kwds:
params.extend( ['%s=%s' % (key, repr(value)) for
key, value in kwds.items()] )

paramStr = ', '.join(params)

__log.debug('%s(%s)' % (attrName, paramStr))

return attrValue(*args, **kwds)

return delegate

else:
__log.debug(attrName)
return attrValue

def __setattr__(self, attr, value):
__log.debug('%s = %s' % (attr, repr(value)))
return setattr(self._instance, attr, value)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu

2009-02-18 Thread Eric Dorsey
I did an aptitute install of  ibreadline5-dev and then did ./configure and
make again, and still don't have any functionality to be able to hit
up-arrow and get a command repeated while inside the interpreter. Any ideas?


On Tue, Feb 17, 2009 at 7:24 PM, Lie Ryan  wrote:

> On Mon, 16 Feb 2009 22:34:23 -0700, Eric Dorsey wrote:
>
> > Greetings Tutor:
> > I've managed to install Python 2.6 on my Ubuntu VM from source, however,
> > it looks as though I missed something important along the way. My 2.6
> > interpreter does not have readline support (example: I cant hit up arrow
> > to repeat the last command) Is there a way to add this functionality
> > now?
>
> WORKSFORME
> I have Ubuntu and python2.6 and the up arrow history works fine.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Wayne Watson
Title: Signature.html




I took your "starter" code, and formatted it to be what I hope is an
acceptable program, Gobal_Config.py. See attached.  I'm using Python
2.5.2. I put the two modules in the same folder with it, and executed
it in IDLE. I got this:
  ...
  File
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
line 1637, in _parse
    ParseError, infile, cur_index)
  File
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
line 1748, in _handle_error
    raise error
ParseError: Invalid line at line "1".

As far as I can tell, line 1 of config.obj looks OK. It's a comment.
Something is amiss.

Does PYTHONPATH apply in Win XP? I haven't played at the level of paths
for a long time in any OS. We can worry about an install "package"
later for the modules. It might be best for the users of this program. 

When I was using Python 2.4, I could find an entry on Start for it, and
get an item on it under Python 2.4 called something like Library Paths.
I don't see that at all on Python 2.5. Bad memory, I just checked on my
laptop, which has 2.4; however, I recall being able to probe Python
library paths. This may be irrelevant.

The ConfigObj 4 Introduction and Ref doc doesn't seem to associate it
with any version of Python. Its version is 4.5.3. Puzzled ...

Marc Tompkins wrote:

  On Wed, Feb 18, 2009 at 1:01 PM, Wayne
Watson 
wrote:
  
OK, I got the ObjectConfig
and Validate downloads, and copied your
Global class successfully. Don't I need to get the two files into
Python as a module? How does that work?

  
  
Simplest: put them in the same folder as your own program.  More
standard: put them in one of the folders in your Python path - same
general idea as the DOS search path, it's a list of directories where
Python will look for modules you ask it to import.
  
>From the docs: (http://docs.python.org/tutorial/modules.html)
  The Module Search Path¶
  When a module named spam is
imported, the interpreter searches for a file
named spam.py
in the current directory, and then in the list of
directories specified by the environment variable PYTHONPATH. This
has the same syntax as the shell variable PATH, that is, a
list of
directory names. When PYTHONPATH is not set, or when the file is
not
found there, the search continues in an installation-dependent default
path; on
Unix, this is usually .:/usr/local/lib/python.
  Actually, modules are searched in the list of directories given by
the variable
  sys.path
which is initialized from the directory containing the input script
(or the current directory), PYTHONPATH and the installation- dependent
default. This allows Python programs that know what they're doing to
modify or
replace the module search path. Note that because the directory
containing the
script being run is on the search path, it is important that the script
not have
the same name as a standard module, or Python will attempt to load the
script as
a module when that module is imported. This will generally be an error.
See
section Standard
Modules for more information.
  
  
  


  
  
  www.fsrtechnologies.com
  
  
  
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



-- 
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time)


"Nature, to be commanded, must be obeyed."
   -- Sir Francis Bacon 




Web Page: 



  
  
  
  
  
-- 
  www.fsrtechnologies.com
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  


-- 


   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time)


"Nature, to be commanded, must be obeyed."
   -- Sir Francis Bacon 




Web Page: 



import os, os.path
from configobj import ConfigObj
from validate import Validator
import StringIO

class Global(object): 
cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current directory + 
"\" + filename --
#   but you could put it anywhere and call it anything
# create your spec as a multi-line string between triple quotes
tmpStr = """
mask_file_name = string(default=None)
gray_scale = boolean(default=True)
post_event_stack = boolean(default=False)
post_event_format = string(default="Tiff 2")
show_real_time = boolean(default=False)
hourly_rate = integer(min=0, default=0)
slowdown= integer(min=0, max=10, default=1) # I don't know what
#   this v

Re: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu

2009-02-18 Thread زياد بن عبدالعزيز البا تلي
On Wed, 18 Feb 2009 20:19:56 -0700
Eric Dorsey  wrote:
> I did an aptitute install of  ibreadline5-dev and then
> did ./configure and make again, and still don't have any
> functionality to be able to hit up-arrow and get a command repeated
> while inside the interpreter. Any ideas?
> 
> 
I don't know what's wrong, Python should pickup "libreadline" and use
it automatically if it was installed.

Try passing "--with-readline" to the "configure" script.

If that doesn't help, then I'm sorry, I'm out of ideas.

Hope that help.
Ziyad.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu

2009-02-18 Thread Genevi�ve DIAGORN
Bonjour,
Je suis absente jusqu'au 22/02/09 inclus.
Cordialement.

Geneviève 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] confused with dates and which way to start

2009-02-18 Thread Che M



> From: jfabi...@yolo.com
> To: tutor@python.org
> Date: Wed, 18 Feb 2009 15:55:05 -0800
> Subject: Re: [Tutor] confused with dates and which way to start
> 
> On Wednesday 18 February 2009 03:10:41 pm johnf wrote:
> > Hi,
> >
> > I need to develope a routine that will provide the some dates between a
> > starting date and an ending date.  The dates will be used to schedule
> > instructors for specific class dates from the list of available dates.
> > Class is normally on Monday, Wedesday, and Friday (or any days of the week
> > including Sat and Sun).  If the length of the class is 6 months (01/01/09 -
> > 06/30/09).  I need to generate all the dates that would match the Monday,
> > Wedesday, and Friday (or whatever days are used for the class) for the
> > entire period.
> >
> > I have done this is FoxPro in the past.  Now I'm in python 2.5.
> >
> > Now the problem is there appears many ways to deal with dates in python.
> > time(), calendar(), datetime(), dateutil().  Which is the easy way guys???
> > And is there something already written I should be using  Also there is
> > something called 'mx'.
> >
> > Thanks in advance.
> 
> Kent Johnson provided the following:
> 
> This is pretty easy using datetime.date and timedelta. For example,
> this shows all the M, W, F between (more or less) your given dates:
> 
> In [1]: from datetime import date, timedelta
> In [3]: end = date(2009, 6, 30)
> In [4]: start = date(2009, 1, 4) # a Sunday
> In [7]: offsets = [timedelta(days=offset) for offset in (1, 3, 5) ] #
> Mon, Wed, Fri
> In [8]: current = start
> 
> In [9]: while current < end:
>...: for offset in offsets:
>...: print current + offset
>...: current += timedelta(days=7)
> 
> 2009-01-05
> 2009-01-07
> 2009-01-09
> 2009-01-12
> 2009-01-14
> 2009-01-16
> ...etc
> 
> Kent
> 
> 
> thanks Kent.  This appears to work.  I was not aware of datetime.timedelta(). 
>  
> I really think there should be a place to find this type of information.  
> I'll study the module.  Again, thanks.

Well, if you Google "dates Python", three page-downs down the first hit and it 
shows about datetime.timedelta().  It's also mentioned in the second hit.  Of 
course, it does require scanning and reading, since you start unsure of what to 
be on the lookout for.  

I'd also recommend you look at dateutil, because it is expressly for doing what 
you need, in case you need to do more and more complex date work.  The page 
includes a ton of example code:
http://labix.org/python-dateutil

_
Stay up to date on your PC, the Web, and your mobile phone with Windows Live.
http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for ConfigObj Documentation

2009-02-18 Thread Marc Tompkins
On Wed, Feb 18, 2009 at 7:42 PM, Wayne Watson
wrote:

>  I took your "starter" code, and formatted it to be what I hope is an
> acceptable program, Gobal_Config.py. See attached.  I'm using Python 2.5.2.
> I put the two modules in the same folder with it, and executed it in IDLE. I
> got this:
>   ...
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
> line 1637, in _parse
> ParseError, infile, cur_index)
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py",
> line 1748, in _handle_error
> raise error
> ParseError: Invalid line at line "1".
>
> As far as I can tell, line 1 of config.obj looks OK. It's a comment.
> Something is amiss.
>

I hate to say it, but IDLE is really holding you back.  It's convenient
because it installs automagically with Python, but it does funky, confusing
things - as in this case, where it's somehow stepped on the real error and
assigned blame in the wrong place; you've already experienced its internal
conflicts with Tkinter...  I use wxPython for my GUI goodness, and swear by
SPE (Stani's Python Editor).  I don't want to re-ignite the IDE wars, but I
definitely think you need to do yourself a favor and move away from IDLE.

Anyway, I didn't mean for that to be a standalone program, but to be picked
apart into chunks and dropped into an existing program (or, actually, just
to be used as an example - maybe of what _not_ to do, but an example...)
First error:
if argv is None:
   argv = sys.argv  <<== you haven't imported "sys"

Second error:
app = MyApp(0)  <<== you haven't defined a class called "MyApp", so you
can't do this...

So I cut it down to just this bit:
test = Global.cfgFile.validate(Global.vtor, copy=True)
Global.cfgFile.write()

(unindented all the way to the left, so that it executes as the main body of
the program) and it works just fine... except:
Third error (well, issue not error):
Take all my comments out!  They weren't meant to be included in final code.
ConfigObj allows inline comments in your config file, and in the configspec
- so my comments show up in there too.  Here's what Initial.sen ends up
looking like:

mask_file_name = None
gray_scale = True
post_event_stack = False
post_event_format = Tiff 2
show_real_time = False
hourly_rate = 0
slowdown = 1# I don't know what
#   this value is/does, so this is probably wrong
start_time = 00:00:00# or you could make the default None?
stop_time = 00:00:00
#   as a default latitude, if any...

I've cut everything down; I'm attaching it as Global_Config1.py (just to
avoid confusion with the earlier version).  If you do actually want to use
it as the basis of anything, you'll want to place the call to .validate()
somewhere near the beginning of the action - remember, the call to .write()
just afterward is completely optional; I had it in there for testing and
have kept it in there for the same reason.



> Does PYTHONPATH apply in Win XP? I haven't played at the level of paths for
> a long time in any OS. We can worry about an install "package" later for the
> modules. It might be best for the users of this program.
>

Ya know, I have no idea anymore.  I thought I knew - but I just did a SET
from a command prompt, and I don't have a PYTHONPATH variable.  I seem to
reacall something from a year or two ago... (looking now)  Oh yes - there's
a directory under your Python directory (Python25 in my case) called "Lib",
and a folder under that called "site-packages"; any text files with the
extension ".pth" will be scaned for the names of folders to add to the
search path.  As much as I love Python, I wish they'd get all this
together...

-- 
www.fsrtechnologies.com
import os, os.path
from configobj import ConfigObj
from validate import Validator
import StringIO

class Global(object): 
cfgFileName = os.getcwd() + os.sep + 'Initial.sen'
tmpStr = """
mask_file_name = string(default=None)
gray_scale = boolean(default=True)
post_event_stack = boolean(default=False)
post_event_format = string(default="Tiff 2")
show_real_time = boolean(default=False)
hourly_rate = integer(min=0, default=0)
slowdown= integer(min=0, max=10, default=1) 
start_time = string(default="00:00:00")
stop_time = string(default="00:00:00")
lat = float(min=0.0, max=90.0)
"""
cfgSpec = StringIO.StringIO(tmpStr) 
cfgFile = ConfigObj(cfgFileName,
configspec=cfgSpec, raise_errors=True, write_empty_values=True,
create_empty=True, indent_type='', list_values=True) 
vtor = Validator() 

test = Global.cfgFile.validate(Global.vtor, copy=True)
Global.cfgFile.write()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor