Re: naming objects from string

2006-09-21 Thread Gabriel Genellina

At Thursday 21/9/2006 00:59, manstey wrote:


If I have a string, how can I give that string name to a python object,
such as a tuple.

e.g.

a = 'hello'
b=(1234)

and then a function
name(b) = a

which would mean:
hello=(1234)

is this possible?


You may use another object as a namespace:

class X: pass
x = X()

a = 'hello'
b = (1,2,3,4)
setattr(x, a, b)

print x.hello # prints (1,2,3,4)
getattr(x, a) # returns the same

but perhaps if you explain better what you want, we can figure out 
how to do that...




Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is it possible to change a picture resolution with Python?

2006-09-21 Thread Lad

Tim Roberts wrote:
> "Lad" <[EMAIL PROTECTED]> wrote:
>
> >from
> >> image:
> >> http://www.pythonware.com/library/pil/handbook/image.htm
> >>
> >> This is some example code:
> >>
> >> from PIL import Image
> >> im = Image.open("1.jpg")
> >> nx, ny = im.size
> >> im2 = im.resize((int(nx*1.5), int(ny*1.5)), Image.BICUBIC)
> >> im2.save("2.png")
> >>
> >> Bye,
> > bearophile,
> >Thank you for your reply.
> >But the above code increases size only , but not DPI resolutions(
> >vertical nad horizontal).I need  a higher  vertical and horisontal
> >resolutions.
>
> I'm not convinced that you know what you are asking for.
>
> Let's say you have an image that is 300x300 pixels, that is tagged as being
> 100 dpi.  Such an image is expected to be printed at a 3" x 3" size.
>
> Now, if you want to increase the dpi to 300 dpi, what does that mean?  Does
> it mean you want that same picture to be printed at a 1" x 1" size?  If so,
> then all you need to change is the picture header.  It will still be
> 300x300 pixels, and the file will be the same number of bytes.
>
> Or, do you mean that you want the picture to continue to print as 3" x 3",
> but to have three times as many pixels in each direction?  That means you
> have to increase the number of pixels to 900x900.  That's exactly what the
> code above is doing.  The image file will be 9 times larger.

Tim ,
Thank you for the explanation,
And I must also thank you all you others, who helped me.
Particularly,  bearophile and Max.

Now I use the following code , that provided bearophile,

from PIL import Image
im = Image.open("output3.jpg")
nx, ny = im.size
im2 = im.resize((int(nx*2.5), int(ny*2.5)), Image.BICUBIC)
im2.save("2000.png",dpi=(520,520))


and very important thing was dpi=(520,520) that provided Max,
L.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: view page source or save after load

2006-09-21 Thread Gabriel Genellina

At Thursday 21/9/2006 02:26, alex23 wrote:


page = urllib.urlopen('http://some.address')


add .read() at the end


open('saved_page.txt','w').write(page).close()


write() does not return the file object, so this won't work; you have 
to bind the file to a temporary variable to be able to close it.




Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: view page source or save after load

2006-09-21 Thread alex23

Gabriel Genellina wrote:


Thanks for the corrections, Gabriel. I really need to learn to
cut&paste working code :)

Cheers.

-alex23

-- 
http://mail.python.org/mailman/listinfo/python-list


Is it possible to save a running program and reload next time ?

2006-09-21 Thread [EMAIL PROTECTED]
Hi,

I have a program which will continue to run for several days. When it is 
running, I can't do anything except waiting because it takes over most 
of the CUP time.

Is it possible that the program can save all running data to a file when 
I want it to stop, and can reload the data and continue to run from 
where it stops when the computer is free ?

Regards,

xiaojf

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get process id...

2006-09-21 Thread billie

[EMAIL PROTECTED] ha scritto:

> SpreadTooThin wrote:
> > How does one get the process id?
> > Is there a method for windows and unix (mac os x etc...)
>
> under linux, do:
>   import os
>   os.getpid()

Under Windows:
import ctypes
ctypes.windll.kernel32.GetCurrentProcessId()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new string method in 2.5 (partition)

2006-09-21 Thread Fredrik Lundh
Irmen de Jong wrote:

> Because the result of partition is a non mutable tuple type containing
> three substrings of the original string, is it perhaps also the case
> that partition works without allocating extra memory for 3 new string
> objects and copying the substrings into them?

nope.  the core string type doesn't support sharing, and given the 
typical use cases for partition, I doubt it would be more efficient
than actually creating the new strings.

(note that partition reuses the original string and the separator,
where possible)

(and yes, you're not the first one who thought of this.  check the 
python-dev archives from May this year for more background).



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get process id...

2006-09-21 Thread Tim Golden
billie wrote:
> [EMAIL PROTECTED] ha scritto:
>
> > SpreadTooThin wrote:
> > > How does one get the process id?
> > > Is there a method for windows and unix (mac os x etc...)
> >
> > under linux, do:
> >   import os
> >   os.getpid()
>
> Under Windows:
> import ctypes
> ctypes.windll.kernel32.GetCurrentProcessId()

Anything wrong with os.getpid () under Windows, too?


Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getpid ()
3504
>>>


TJG

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do we need to delete "ImageDraw.Draw" after using it?

2006-09-21 Thread Fredrik Lundh
Steve Holden wrote:

>> Is there any general rule that we must delete the object after using
>> it?
>>
> Just consider it good hygiene.

in this specific case, it may not be obvious for the casual reader that 
the global "draw" variable will contain an indirect reference to the 
original image object, so even if you throw away (or replace) the "im" 
variable with something else, the original image will still be present
in memory.

if you put the same code inside a function, you can safely leave the 
garbage handling to Python.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get process id...

2006-09-21 Thread Fredrik Lundh
billie wrote:

>> under linux, do:
 >
>>   import os
>>   os.getpid()
> 
> Under Windows:
 >
> import ctypes
> ctypes.windll.kernel32.GetCurrentProcessId()

getpid() works just fine on Windows too:

 >>> import ctypes
 >>> ctypes.windll.kernel32.GetCurrentProcessId()
1916
 >>> import os
 >>> os.getpid()
1916



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: naming objects from string

2006-09-21 Thread Fredrik Lundh
manstey wrote:

> so they might provide a list of names, like 'bob','john','pete', with 3
> structures per name, such as 'apple','orange','red' and I need 9 tuples
> in my code to store their data:
> 
> bob_apple=()
> bob_orange=()
> ..
> pete_red=()
> 
> I then populate the 9 tuples with data they provide in a separate file,
> and the filled tuples are then validated against the metadata to make
> sure they are isomorphic.

if you want a dictionary, use a dictionary.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for elucidation: enhanced generators

2006-09-21 Thread Michele Simionato
Ben Sizer wrote:
> But do you have an example of such a use case?

Here is a 69 lines implementation of the idea of applying extended
generators to manage Web forms (obviously this is only a proof of
concept and it contains many mistakes, but you have something to get
started).
Notice that I am not claiming that this is a good idea.

  Michele Simionato

---

import datetime
import cherrypy as cp

# each user (but really should be each session) has her input loop
# one should disable the back button and implement an undo mechanism
def inputloop(user):
start_time = datetime.datetime.today()
cart = []
while True: # fill the shopping cart
item = yield locals()
if item == 'start':
continue
elif item == 'end':
break
elif item:
cart.append(item)
finish_time = datetime.datetime.today()
yield locals()

class User(object):
def __init__(self, name):
self.name = name
self.inputloop = inputloop(self)
self.inputloop.send(None) # start the user loop

users = dict(michele=User('michele'))

class Root(object):
@cp.expose
def login_welcome(self):
yield 'hello!'
yield ''
yield "what's your name? "
yield ''
yield ''

@cp.expose
def login_action(self, name):
yield (''
   'You may start shopping') % name

@cp.expose
def shopping_loop(self, name, item):
if not name in users:
yield '%r is not a valid name; please retry' % name
return
user = users[name]
status  = user.inputloop.send(item)
if item == 'start':
yield 'Today is %s' % status['start_time']
yield 'Please buy something!'
if item == 'end':
yield 'Thanks for shopping, %s' % user.name
yield 'You bought items %s' % status['cart']
yield 'Today is %s' % status['finish_time']
return
yield ''
yield 'The content of your cart is %s' % status['cart']
yield 'Please enter the item you want to buy: '
yield ''
yield '' % name
yield '(enter end to finish)'
yield ''

index = login_welcome

if __name__ == '__main__':
cp.root = Root()
cp.server.start()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using py2exe to wrap a service?

2006-09-21 Thread MaR
Thanks guys! :o)

It seems that no module is missing since the Service starts and the
error message seem to indicate an error in the COM call to the AD.
I would expect some other exception..

I do have a separate thread for the asyncore.loop() as I otherwise
would risk a lockup.

I do not call pythoncom.CoInitialize ()  as I tend to expect a module
wrapping COM stuff to do that. Since I am not really into Windows, I
have to ask you, do I make a wrong assumption here?

Some further info that may be of interest:
python 2.4.3
active_directory 0.4
py2exe 0.6.5
pywin32 208
The Service code is taken from MyService.py supplied with py2exe as a
sample.

Rgrds//M

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Iain King

[EMAIL PROTECTED] wrote:
> Hi,
>
> I have a program which will continue to run for several days. When it is
> running, I can't do anything except waiting because it takes over most
> of the CUP time.
>
> Is it possible that the program can save all running data to a file when
> I want it to stop, and can reload the data and continue to run from
> where it stops when the computer is free ?
>
> Regards,
>
> xiaojf

Can't you just use time.sleep to put your program to, uh, sleep?  For
example, time.sleep(10) will effectively pause your program for ten
seconds, making it use very few CPU cycles.  I don't know what
interface you have, but assuming you can pick up a button or a key
press, you can ask for a length of time, or just put your code into a
holding pattern:

def pause():
  paused = True
  while paused:
time.sleep(1)
if wake_up_key_pressed:
  paused = False

or with a gui:

paused = False

def pause():
  global paused
  paused = True
  while paused:
time.sleep(1)

def onWakeUpButton():  #bind this to button
  global paused
  paused = False


Iain

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> Is it possible that the program can save all running data to a file when
> I want it to stop, and can reload the data and continue to run from
> where it stops when the computer is free ?

This isn't what you asked for (I have no idea how to do that), but
given your description, perhaps a different solution would work.

If you're using a *nix type OS (or possibly Cygwin, never tried) with a
bash-style shell, then you probably already have job control built in.
For example, in bash you can type Z to stop the current process,
and you can see all jobs and their states and job numbers with the
'job' command, and you can resume a stopped job with '%[job_number]'.
So for example, if only one job is in he queue, just stop it and then
when you're ready do %1.

Another *nix option would be to use the nice command to set the
schedular priority of the process so that when something with a higher
priority needs the CPU then it gets it first rather than your nice'd
process (something like 'nice -n 15 python your_program.py' should do
well -- very low priority). I'm pretty sure windows has some kind of
priority option for tasks as well, in fact, IIRC you open the task
manager and right click on a task and can set the priority lower.

Regards,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Evaluation of Truth Curiosity

2006-09-21 Thread James Stroud
Hello All,

I'm curious, in

py> 0 | (1 == 1)
1
py> False | (1 == 1)
True

What is the logic of the former expression not evaluating to True (or 
why the latter not 1?)? Is there some logic that necessitates the first 
operand's dictating the result of the evaluation? Or is this an artefact 
of the CPython implementation?

James
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and CORBA

2006-09-21 Thread rodmc
Can anyone recommend an easy to install COBRA implementation which
works with Python? I am using Windows XP.

Thanks in advance.

Best,

rod

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Using py2exe to wrap a service?

2006-09-21 Thread Tim Golden
[MaR]

| I do not call pythoncom.CoInitialize ()  as I tend to expect a module
| wrapping COM stuff to do that. 

Hmmm. A slightly philosophical point. As the author of
the said module, I think I'd have said that the other
way round: I do not call CoInit... because I expect a
user of the module *who needs to involve threading*
to do that. However, I'm quite happy to call it willy-nilly
as long as there's no overhead. But I'm afraid my
knowledge of the interaction of COM with threading
is slim and mostly anecdotal.

| Some further info that may be of interest:
| python 2.4.3
| active_directory 0.4
| py2exe 0.6.5
| pywin32 208
| The Service code is taken from MyService.py supplied with py2exe as a
| sample.

All that looks good enough.

Is it possible for you to include the CoInit... call
anyway, simply as a test to see if it is the problem.
It might not be, in which case the point is moot.
(At least in this case)

If you don't get much help on this list, might
be worth moving the discussion over to the python-win32
list. I'm sure many people (like myself) watch both, but
there may be some who don't follow this list, but
do watch the -- lower traffic -- win32 list.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Jeremy Sanders
[EMAIL PROTECTED] wrote:

> I have a program which will continue to run for several days. When it is
> running, I can't do anything except waiting because it takes over most
> of the CUP time.
> 
> Is it possible that the program can save all running data to a file when
> I want it to stop, and can reload the data and continue to run from
> where it stops when the computer is free ?

For Linux (and other Unix like OSs), there are several "checkpointing"
libraries available which allow programs to be saved to disk, and restarted
later.

If the other suggestions people have given to you (STOPping and CONTinuing
processes), or sleep statements, or saving state, don't work investigate
these.

e.g. http://www.cs.wisc.edu/~zandy/ckpt/

These programs have limitations on what can be restored (e.g. threads,
shared memory, network connections...). I don't know which ones work with
python.

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: naming objects from string

2006-09-21 Thread Jeremy Sanders
manstey wrote:

> so they might provide a list of names, like 'bob','john','pete', with 3
> structures per name, such as 'apple','orange','red' and I need 9 tuples
> in my code to store their data:
> 
> bob_apple=()
> bob_orange=()
> ..
> pete_red=()

I really think you should be using dictionaries here. You don't want to be
messing around creating random variables in the local or global namespace.

For instance

myvals = {}
myvals['bob'] = {}
myvals['pete'] = {}
...
myvals['bob']['apple'] = (1,2,3,4)
myvals['bob']['orange'] = (2,3,4)
myvals['pete']['red'] = (4,5,6,7)

and so on

>>> myvals
{'pete': {'red': (4, 5, 6, 7)}, 'bob': {'orange': (2, 3, 4), 'apple': (1, 2,
3,4)}}

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Roland.Csaszar
On 2006-09-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Is it possible that the program can save all running data to a file when 
> I want it to stop, and can reload the data and continue to run from 
> where it stops when the computer is free ?

Well, on Irix you could use cpr

but i don't know if your OS supports a similar feature

-- 
Roland Csaszar ---  \\\   ///  -- +43 316 495 2129
Software Development --  \\\ ///  --- http://www.knapp.com 
KNAPP Logistics Automation -  \\V//  - mailto:[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


how to use timer in python

2006-09-21 Thread yxh
how to use timer in python.
the functionnality is like the MFC SetTimer()


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Evaluation of Truth Curiosity

2006-09-21 Thread MonkeeSage
James Stroud wrote:
> What is the logic of the former expression not evaluating to True (or
> why the latter not 1?)? Is there some logic that necessitates the first
> operand's dictating the result of the evaluation? Or is this an artefact
> of the CPython implementation?

If I understand correctly, OR'ing an int and a bool (your first
example) returns an int by coercing the bool to an int; and OR'ing two
bools (your second example) returns a bool.

Regards,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use timer in python

2006-09-21 Thread Gabriel Genellina

At Thursday 21/9/2006 06:03, yxh wrote:


how to use timer in python.
the functionnality is like the MFC SetTimer()


Use the Timer class.


Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Evaluation of Truth Curiosity

2006-09-21 Thread Fredrik Lundh
James Stroud wrote:

> I'm curious, in
> 
> py> 0 | (1 == 1)
> 1
> py> False | (1 == 1)
> True
> 
> What is the logic of the former expression not evaluating to True (or 
> why the latter not 1?)? Is there some logic that necessitates the first 
> operand's dictating the result of the evaluation? Or is this an artefact 
> of the CPython implementation?

looks like you're confusing binary or ("|") with logical or ("or").

binary or on booleans are only defined for boolean | boolean; for any 
other combination, the usual coercion rules apply.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Evaluation of Truth Curiosity

2006-09-21 Thread Christophe
James Stroud a écrit :
> Hello All,
> 
> I'm curious, in
> 
> py> 0 | (1 == 1)
> 1
> py> False | (1 == 1)
> True
> 
> What is the logic of the former expression not evaluating to True (or 
> why the latter not 1?)? Is there some logic that necessitates the first 
> operand's dictating the result of the evaluation? Or is this an artefact 
> of the CPython implementation?
> 
> James

| is the binary or operator, not the truth value operator. Also, True == 
1 and False == 0. Always use the "or" and "and" keywords for truth 
operations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-21 Thread Simon Brunning
On 21 Sep 2006 01:48:55 -0700, rodmc <[EMAIL PROTECTED]> wrote:
> Can anyone recommend an easy to install COBRA implementation which
> works with Python? I am using Windows XP.

 is the 2nd hit if you go to
. ;-)

-- 
Cheers,
Simon B,
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Threading

2006-09-21 Thread Calvin Spealman
On 20 Sep 2006 00:27:07 -0700, daniel <[EMAIL PROTECTED]> wrote:
> Hello,
> Can anyone explain the main points in working with threads in Python.
> Why use threading and not Thread.I have read an article that i have to
> subclass the Thread class and override some function.

I repeat this all the time, but the best advice I can give you about
using threads is to not use threads at all. I would point you to good
references like Threads Considered Harmful
(http://www.kuro5hin.org/story/2002/11/18/22112/860) and The Problem
with Threads (http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.html
- With Link to PDF). It might seem an inappropriate response to your
question to simply tell you that you should not do what you are asking
how to do, but its just the case that most often anyone without
exposure to threads has little or no understanding on just how bad
they are for many of the tasks they will be used for. Threads are
difficult to control, impossible to predict, and simply one of the
most over used, least understood causes of buggy, unmaintainable
software in the whole spectrum of development techniques.

As alternatives, look into what tasks can spawn into other processes,
asyncronous programming (a'la Twisted -
http://www.twistedmatrix.com/), and co-routine and similar facilities,
such as the tasklets of Stackless and two-way generators now included
with Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using py2exe to wrap a service?

2006-09-21 Thread MaR
Tim Golden wrote:
> [MaR]
>
> | I do not call pythoncom.CoInitialize ()  as I tend to expect a module
> | wrapping COM stuff to do that.
>
> Hmmm. A slightly philosophical point.
[snip]

:o) I agree!

I have added the CoInit.. call to the __init__() of the threaded class
(I understood the documentation as that was a proper place.)
The exception message changed!
Unfortunately I get little wiser.. (yes I confess.. I am spoonfed with
unix ;o)

The instance's SvcRun() method failed
  File "win32serviceutil.pyc", line 785, in SvcRun
  File "MailProxySvc.pyc", line 132, in SvcDoRun
  File "MailProxySvc.pyc", line 100, in setup
  File "D:\projects\MailProxy\AddressDB.py", line 54, in
loadPersonsFromAD
  File "active_directory.pyc", line 367, in search
  File "active_directory.pyc", line 217, in query
  File "win32com\client\gencache.pyc", line 540, in EnsureDispatch
  File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass
exceptions.KeyError: '{B08400BD-F9D1-4D02-B856-71D5DBA123E9}'

//M

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Threading

2006-09-21 Thread Fredrik Lundh
Dennis Lee Bieber wrote:

> ... slightly
> simpler to use without subclassing (at the simplest level, you just pass
> the function that is to be run, and a list of the arguments/parameters
> it needs, to the threading creation class).

that's exactly how thread.start_new_thread(func, args) works, of course, 
so I'm not sure that's much of an argument.



-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Using py2exe to wrap a service?

2006-09-21 Thread Tim Golden
[MaR]
| Tim Golden wrote:
| > [MaR]
| >
| > | I do not call pythoncom.CoInitialize ()  as I tend to 
| expect a module
| > | wrapping COM stuff to do that.
| >
| > Hmmm. A slightly philosophical point.
| [snip]
| 
| :o) I agree!
| 
| I have added the CoInit.. call to the __init__() of the threaded class
| (I understood the documentation as that was a proper place.)
| The exception message changed!
| Unfortunately I get little wiser.. (yes I confess.. I am spoonfed with
| unix ;o)
| 
| The instance's SvcRun() method failed
|   File "win32serviceutil.pyc", line 785, in SvcRun
|   File "MailProxySvc.pyc", line 132, in SvcDoRun
|   File "MailProxySvc.pyc", line 100, in setup
|   File "D:\projects\MailProxy\AddressDB.py", line 54, in
| loadPersonsFromAD
|   File "active_directory.pyc", line 367, in search
|   File "active_directory.pyc", line 217, in query
|   File "win32com\client\gencache.pyc", line 540, in EnsureDispatch
|   File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass
| exceptions.KeyError: '{B08400BD-F9D1-4D02-B856-71D5DBA123E9}'

OK. Now we're into the ClassID thing. I'm hoping that someone with
py2exe knowhow will chip in here. That line is trying to generate
a Python module to correspond to the ADODB.Command typelib:

command = EnsureDispatch ("ADODB.Command")

The py2exe wiki suggests that a slight nudge to the code
might fix the problem:

http://www.py2exe.org/index.cgi/IncludingTypelibs

At this point there are several options open to us:

(in no particular order)
1) You could nudge the code at line 217 to make use of
that suggestion.
2) I could do that and send you the result.
3) I could alter the module so it doesn't use gencache
at all. I don't seem to be using any constants so the
Dispatch might as well be dynamic.
4) None of the above.

I'm happy to do (3) and send it to you privately if you're
willing to try. Of course, it might not be the cause
of the problem in any case!

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Duncan Booth
Jeremy Sanders <[EMAIL PROTECTED]> wrote:

> For Linux (and other Unix like OSs), there are several "checkpointing"
> libraries available which allow programs to be saved to disk, and
> restarted later.
> 
Another option which will work on just about anything would be to run the 
program in a vmware virtual machine. Then you can suspend or resume the 
virtual machine whenever you wish.
-- 
http://mail.python.org/mailman/listinfo/python-list


Can I inherit member variables?

2006-09-21 Thread lm401
I'm trying to work with the following idea:

class animal:
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour


class bird(animal):
  def __init__(self, wingspan):
self.wingspan = wingspan
print self.weight, self.colour, self.wingspan

class fish(animal):
  def __init__(self, length):
self.length = length
print self.weight, self.colour, self.length


So basically I have a base class (animal) that has certain attributes.
When animal is inherited by a specific instance, further attributes are
added, but I need to have access to the original attributes (weight,
colour). When I run my code from within the derived class, self.weight
and self.colour are not  inherited (although methods are inherited as I
would have expected).

It seems from reading the newsgroups that a solution might be to
declare weight and colour as global variables in the class animal:

class animal:
  pass

myanimal = animal()
myanimal.weight = 4
myanimal.colour = 'blue'

But this is not exactly what I want to do.

I'm not very experienced with OOP techniques, so perhaps what I'm
trying to do is not sensible. Does Python differ with regard to
inheritance of member variables from C++ and Java?

Thanks for any help,



 Lorcan.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-21 Thread Eric Brunel
On Thu, 21 Sep 2006 10:48:55 +0200, rodmc <[EMAIL PROTECTED]>  
wrote:

> Can anyone recommend an easy to install COBRA implementation which
> works with Python? I am using Windows XP.

I used to use fnorb (http://sourceforge.net/projects/fnorb), but the  
project seems to be dead. It still seems to work quite well, but I didn't  
test it on the latest Python versions.

And it does meet your requirements: since it's a Python-only ORB, it's  
really easy to install. You basically just have to put it somewhere in  
your PYTHONPATH.

> Thanks in advance.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread Benjamin Niemann
Hello,

[EMAIL PROTECTED] wrote:

> I'm trying to work with the following idea:
> 
> class animal:
>   def __init__(self, weight, colour):
> self.weight = weight
> self.colour = colour
> 
> 
> class bird(animal):
>   def __init__(self, wingspan):
> self.wingspan = wingspan
> print self.weight, self.colour, self.wingspan
> 
> class fish(animal):
>   def __init__(self, length):
> self.length = length
> print self.weight, self.colour, self.length
> 
> 
> So basically I have a base class (animal) that has certain attributes.
> When animal is inherited by a specific instance, further attributes are
> added, but I need to have access to the original attributes (weight,
> colour). When I run my code from within the derived class, self.weight
> and self.colour are not  inherited (although methods are inherited as I
> would have expected).

You'll have to invoke the __init__ method of the superclass, this is not
done implicitly. And you probably want to add the weight and colour
attributes to your subclass in order to pass these to the animal
constructor.

class fish(animal):
  def __init__(self, length, weight, colour):
animal.__init__(self, weight, colour)
self.length = length
print self.weight, self.colour, self.length


HTH

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Evaluation of Truth Curiosity

2006-09-21 Thread James Stroud
Everyone wrote:
 > [something intelligent]

Ah, clarity. My confusion can undoubtedly be traced to a non-existent 
formal training in computer programming.

Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage

[EMAIL PROTECTED] wrote:
> When I run my code from within the derived class, self.weight
> and self.colour are not  inherited (although methods are inherited as I
> would have expected).

Animal is never initialized and you're not passing weight and color
into it anyway. You need something like:

class animal: # (object): # <- new-style class
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour

class bird(animal):
  def __init__(self, weight, color, wingspan):
#super(bird, self).__init__(weight, color) # <- new-style init
animal.__init__(self, weight, color) # <- old-style init
self.wingspan = wingspan
print self.weight, self.colour, self.wingspan

class fish(animal):
  def __init__(self, weight, color, length):
#super(fish, self).__init__(weight, color)
animal.__init__(self, weight, color)
self.length = length
print self.weight, self.colour, self.length

HTH,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Priority based concurrent execution

2006-09-21 Thread Willi Richert
Hi,

I have a simulation application (PlayerStage) in which the robot is asked 
every ~200ms for an action. In the meantime the robot has to do some 
calculation with the perception. As the calculation gets more and more time 
consuming I am thinking about outsourcing it into a concurrently running 
method. If the calculation takes too long it would be ok for the result to be 
incorporated in some future cycle of the main loop, resulting in the 
calculation being done less and less often and the main loop executing some 
stop behavior.
My question: Is there a possibility in Python (either with the threading 
module or with Twisted's non-threading style) to prioritize the two 
(pseudo-)concurrent methods so that the main tread is further on executed 
every ~200ms and the calculation thread being executed only in "idle" time 
slots?

Thanks,
wr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: view page source or save after load

2006-09-21 Thread James Stroud
Gabriel Genellina wrote:
> At Thursday 21/9/2006 02:26, alex23 wrote:
> 
>> page = urllib.urlopen('http://some.address')
> 
> add .read() at the end
> 
>> open('saved_page.txt','w').write(page).close()
> 
> write() does not return the file object, so this won't work; you have to 
> bind the file to a temporary variable to be able to close it.

Strictly speaking, "have to" is not perfectly correct. The ".close()" 
part can simply be eliminated as the file should close via garbage 
collection once leaving the local namespace.

James
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread LorcanM
Thanks for the reply.

I think there's a basic misunderstanding about the nature of
inheritance on my side.

What I want to do is instantiate the sub class (derived class) from
within the animal class. I then expect the sub class to have inherited
some basic properties that it knows it has (weight, colour). If I can
expand the example I gave previously to try to make this a little
clearer:

class animal:
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour

  def describeMyself(self, type, measurement):
if type == 'bird':
  myanimal = bird(measurement)
elif type == 'fish':
  myanimal = fish(measurement)

class bird(animal):
  def __init__(self, wingspan):
self.wingspan = wingspan
print "I'm a bird, weight %s, colour %s, wingspan %s" %
(self.weight, self.colour, self.wingspan)

class fish(animal):
  def __init__(self, length):
self.length = length
print "I'm a fish, weight %s, colour %s, length %s" % (self.weight,
self.colour, self.length)


It seems from what you say that the attributes (member variables) will
have to be passed forward explicitly like any other function call. This
of course is sensible, 'bird' or 'fish' are not tied to a specific
instance of 'animal' when they are instantiated.

Thanks for the help,


 Lorcan.


Benjamin Niemann wrote:


> You'll have to invoke the __init__ method of the superclass, this is not
> done implicitly. And you probably want to add the weight and colour
> attributes to your subclass in order to pass these to the animal
> constructor.
>
> class fish(animal):
>   def __init__(self, length, weight, colour):
> animal.__init__(self, weight, colour)
> self.length = length
> print self.weight, self.colour, self.length
>

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread Gabriel Genellina

At Thursday 21/9/2006 06:52, [EMAIL PROTECTED] wrote:


class animal:
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour


class bird(animal):
  def __init__(self, wingspan):
self.wingspan = wingspan
print self.weight, self.colour, self.wingspan

class fish(animal):
  def __init__(self, length):
self.length = length
print self.weight, self.colour, self.length


So basically I have a base class (animal) that has certain attributes.
When animal is inherited by a specific instance, further attributes are
added, but I need to have access to the original attributes (weight,
colour). When I run my code from within the derived class, self.weight
and self.colour are not  inherited (although methods are inherited as I
would have expected).


You have to call the base __init__ too. If a bird is some kind of 
animal, it has a weight and a colour, and you have to provide them too:


class bird(animal):
  def __init__(self, weight, colour, wingspan):
animal.__init__(self, weight, colour)
self.wingspan = wingspan
print self.weight, self.colour, self.wingspan


It seems from reading the newsgroups that a solution might be to
declare weight and colour as global variables in the class animal:


You can declare them as class attributes inside animal; this way they 
act like a default value for instance attributes.


class animal:
  weight = 0
  colour = ''
  ...


I'm not very experienced with OOP techniques, so perhaps what I'm
trying to do is not sensible. Does Python differ with regard to
inheritance of member variables from C++ and Java?


They are not called "member variables" but "instance attributes". 
They *are* inherited [1] but you have to set their value somewhere. 
Any object can hold virtually any attribute - this is *not* usually 
determined by the object's class.
Base constructors ("initializer" actually) are *not* invoked 
automatically, so you must call them explicitely.


Read the Python Tutorial, it's easy and will teach you a lot of 
things about the language. You can read it online at 



[1] kinda... remember that classes don't determine the available 
attributes; class attributes are inherited, and any attribute you set 
on an instance will be accessible by any method of the object, even 
above in the hierarchy.




Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can I inherit member variables?

2006-09-21 Thread Gabriel Genellina

At Thursday 21/9/2006 07:34, LorcanM wrote:


I think there's a basic misunderstanding about the nature of
inheritance on my side.

What I want to do is instantiate the sub class (derived class) from
within the animal class. I then expect the sub class to have inherited
some basic properties that it knows it has (weight, colour). If I can
expand the example I gave previously to try to make this a little
clearer:


As an analogy: a certain animal, a given individual, is of a kind 
"from birth". You don't have an abstract, unshaped, animal, that by 
some kind of magic later becomes a bird, or a mammal...
When you construct an object instance, it is of a certain type from 
that precise moment, and you can't change that afterwards.
So, you construct a bird, which is a kind of animal (class 
inheritance is the way of modelling that "is a kind of" relationship).


Hope it becomes clearer now.



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can I inherit member variables?

2006-09-21 Thread Benjamin Niemann
LorcanM wrote:

> Benjamin Niemann wrote:
> 
>> You'll have to invoke the __init__ method of the superclass, this is not
>> done implicitly. And you probably want to add the weight and colour
>> attributes to your subclass in order to pass these to the animal
>> constructor.
>>
>> class fish(animal):
>>   def __init__(self, length, weight, colour):
>> animal.__init__(self, weight, colour)
>> self.length = length
>> print self.weight, self.colour, self.length
>
> Thanks for the reply.
> 
> I think there's a basic misunderstanding about the nature of
> inheritance on my side.
> 
> What I want to do is instantiate the sub class (derived class) from
> within the animal class. I then expect the sub class to have inherited
> some basic properties that it knows it has (weight, colour). If I can
> expand the example I gave previously to try to make this a little
> clearer:
> 
> class animal:
>   def __init__(self, weight, colour):
> self.weight = weight
> self.colour = colour
> 
>   def describeMyself(self, type, measurement):
> if type == 'bird':
>   myanimal = bird(measurement)
> elif type == 'fish':
>   myanimal = fish(measurement)
> 
> class bird(animal):
>   def __init__(self, wingspan):
> self.wingspan = wingspan
> print "I'm a bird, weight %s, colour %s, wingspan %s" %
> (self.weight, self.colour, self.wingspan)
> 
> class fish(animal):
>   def __init__(self, length):
> self.length = length
> print "I'm a fish, weight %s, colour %s, length %s" % (self.weight,
> self.colour, self.length)

Do you really want one animal instance to act both as bird and fish?
Wouldn't it be more sensible to instanciate either bird or fish (animal
being what is called an abstract class in other OOP languages)? bird and
fish would then have their own implementation of describeMyself() with
the 'print "I'm a..."' statement.

I must admit that I don't really understand what you are trying to
achieve...


-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect baudrate and mode settings

2006-09-21 Thread Ganesan Rajagopal
> Bryce Bolton <[EMAIL PROTECTED]> writes:

> In short, setting of critical parameters is unclear under pexpect's
> documentation, but may be obvious to those more familiar with os.open or
> other filesystem internals.

Try using "stty" program on Linux to set these parameters before you use
pexpect. 

Ganesan

-- 
Ganesan Rajagopal

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python on a 64-Bit OS

2006-09-21 Thread Nico Grubert
> Several changes have been made to Python 2.4 and 2.5 to support
> AMD64-Linux better, and not all of these changes have been
> incorporated into Python 2.3, as this software is no longer
> maintained.

> As others have said: you should really try to use the python 2.4
> that comes with the operating system. Can you share the reason why
> you have to use Python 2.3?

I actually should use the Python 2.3.5 for an application server called 
  "Zope" and a Zope product that officially does not support the latest 
Zope version yet. The latest stable Zope version requires > Python 2.4.2 
so I'll installed Python 2.4.3. and I am trying to get it running.

Thanks for the tips.

Nico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get process id...

2006-09-21 Thread Chris
SpreadTooThin wrote:
> How does one get the process id?
> Is there a method for windows and unix (mac os x etc...)
> 

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442477

hth
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-21 Thread rodmc
Thanks to everyone for their help. I had tried OmniORB and while the
base library worked ok, the Python bit OmniORBpy seems to dislike
working... Perhaps there is something wrong with my settings.

I will also try the Python only suggestion.

cheers,

rod

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: naming objects from string

2006-09-21 Thread Terry Reedy

"James Stroud" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Depends on your namespace, but for the local namespace, you can use this:
>
> py> a = object()
> py> a
> 
> py> locals()['bob'] = a
> py> bob
> 

If you put this code within a function, it probably will not work. 
locals() is usually a *copy* of the local namespace and writes do not write 
back to the namespace itself.

tjr



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage
Hi Lorcan,

Mabye thinking of it like this will help: birds and fishes (I love that
word, even if it is incorrect) can _do_ all the things that all animals
have in common: eat, drink, die, reproduce, &c; but that is generic.

class animal(object):
  def eat(self, food): pass
  ...
class bird(animal): pass
class fish(animal): pass

If you want to talk about a specific bird or fish, then you have to say
more than just that it is an animal. Now, if all animals have a weight
and a color, but not all have the same weight or color, then you want
to say that this bird or fish is an animal which is colored X and
weighes Y.

class animal(object):
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour
class bird(animal): pass # __init__ from animal is called implicitly
class fish(animal): pass

Now what if a bird and a fish have other attributes that not all
animals share (or at least specialized versions)? Well then you need to
say this bird is an animal which is colored X and weighs Y, but unlike
other animals, has a wingspan or length of Z.

class animal(object):
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour
class bird(animal):
  # override __init__ so we can say what _this_ animal is like
  def __init__(self, weight, color, wingspan):
super(bird, self).__init__(weight, color)
self.wingspan = wingspan
class fish(animal):
  def __init__(self, weight, color, length):
super(fish, self).__init__(weight, color)
self.length = length

Does this make more sense?

Regards,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread LorcanM
Thanks a lot folks for all the help. Its a lot clearer now.

If I could summarise my original misunderstanding about inheritance:

I belived that a sub class inherited a *specific instance* of the super
class.

This is clearly not right - the misunderstanding arose as I was
instantiating the super class from within the base class. As people
have pointed out it seems strange to instantiate an 'animal' and then
only later decide that it is a 'fish' or a 'bird'. Obviously my code is
an analogy to the problem I'm tackling. What I'm doing is a bit more
abstract: I'm instantiating a 'world' (as a super class) and then
various 'worldviews' as sub-classes. The 'worldviews' must know about
various aspects of the 'world' from which they are instantiated to be
able to do what they need to do (as the 'bird' needs to know about
'weight' and 'colour' to be able to describe itself).

Passing these aspects forward to the constructor of the sub class is
the solution I've implemented and it works and looks sensible.

Thanks again to all,


 Lorcan.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Pocoo (bulletin board software) 0.1 beta released

2006-09-21 Thread robin
Georg Brandl <[EMAIL PROTECTED]> wrote:
>The 0.1 release is not meant to be feature complete. It's more like a preview
>to show off what's already there. If you like the idea, *feel free to join us!*

Looks very nice so far. Will fill an important gap in Python apps.

Oh, and you've been blogged:
http://diagrammes-modernes.blogspot.com/

-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread bearophileHUGS
MonkeeSage:

If you have multiple inheritance do you need the old style init anyway?

class Animal1(object):
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour

class Animal2(object):
  def __init__(self, name):
self.name = name

class Bird(Animal1, Animal2):
  def __init__(self, weight, color, wingspan, name):
super(Bird, self).__init__(weight, color) # Animal1
Animal2.__init__(self, name)
self.wingspan = wingspan
print self.weight, self.colour, self.wingspan, self.name

al = Bird(12, "White", 2, "Albatross")

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage

[EMAIL PROTECTED] wrote:
> If you have multiple inheritance do you need the old style init anyway?

I guess so, I'm not really sure. This page
 talks about super() and MRO and such,
but I have only glanced over it the other day. I will read it more
fully sometime. I tend not to use multiple inheritance very often, and
when I do I usually don't need to initialize the superclasses. So I've
never really thought about it or researched into it. Someone smarter
than me would probably know (hey wait a second -- you're smarter than
me! I've seen your code golf score, buddy! ;) ).

Regards,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Changing behaviour of namespaces

2006-09-21 Thread Mikael Olofsson
Hi!

This is in Python 2.3.4 under WinXP.

I have a situation where I think changing the behaviour of a namespace 
would be very nice. The goal is to be able to run a python file from 
another in a separate namespace in such a way that a NameError is not 
raised if a non-existing variable is used in the file. The file that I 
want to run is taken out of context, and some needed variables may be 
missing that are normally there when used in the intended context. OK! 
When I run it out of context, I do not want the execution to stop 
half-way through the file based on NameErrors, instead a predefined 
dummy variable should be used. The question is: Can I achieve that?

Google didn't give me much, so I experimented a bit: First, I created a 
dummy object, which is meant to be used when a variable is missing:

class dummyClass(object):
pass
dummyObject = dummyClass()

The actual dummy object is supposed to be a bit more complicated than 
that. The next step was to subclass dict:

class forgivingDict(dict):
def __init__(self,*args,**kwargs):
dict.__init__(self,*args,**kwargs)
def __getitem__(self,key):
print 'Getting', key
try:
return dict.__getitem__(self,key)
except KeyError:
return dummyObject
def __setitem__(self,key,value):
print 'Setting', key, 'to', value
dict.__setitem__(self,key,value)
def __contains__(self,item):
return True
def __repr__(self):
return 'forgivingDict(%s)' % (dict.__repr__(self),)

Then I tried to execute a file using a forgivingDict() as namespace:

ns = forgivingDict()
execfile(filePath, ns)

A file containing the following passes perfectly OK:

a = 0
b = a

But a file containing the following produces a NameError:

b = a

The error traceback for the interested:

Traceback (most recent call last):
  File "//charm/mikael/My 
Documents/Programmering/Python/Tester/voidTest.py", line 130, in ?
execfile('test2.py', ns)
  File "test2.py", line 1, in ?
b = a
NameError: name 'a' is not defined

Now, that is exactly what is to expect if ns is a dict(), but I was 
hoping that b would have ended up as dummyObject when ns is a 
forgivingDict(). One thing: Nothing is printed out when execfile-ing the 
files, which means that the methods forgivingDict.__getitem__ and 
forgivingDict.__setitem__ are never used. My guess was that the 
execution done by execfile uses dict.__getitem__(ns, key) and 
dict.__setitem__(ns,key,value) instead of ns[key] and ns[key]=value when 
getting and setting variables. That is probably intentional from the 
developers and done that way for a good reason.

Alternative test: I've tried to replace __builtin__.dict with my 
forgivingDict, slightly modified to make sure that the inheritance still 
works, which didn't change anything. So it seams that the execution done 
by execfile does *not* use dict.__getitem__(ns, key) and 
dict.__setitem__(ns,key,value) after all, but something else. Probably 
the original dict is around somewhere else, and execfile uses the 
corresponding methods of that.

My approach seems flawed. Any ideas? Can I somehow execute a complete 
file even if there are non-existent variables used somewhere? A 
try-except around the execfile statement is not an alternative, since 
that stops the execution where the error occurs.

Should I perhaps read up on the compiler module? I mean: Using the 
compiler module to analyze the content of the file, and based on that 
updating my namespace before executing the file.

/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Priority based concurrent execution

2006-09-21 Thread [EMAIL PROTECTED]

Willi Richert wrote:
> Hi,
>
> I have a simulation application (PlayerStage) in which the robot is asked
> every ~200ms for an action. In the meantime the robot has to do some
> calculation with the perception. As the calculation gets more and more time
> consuming I am thinking about outsourcing it into a concurrently running
> method. If the calculation takes too long it would be ok for the result to be
> incorporated in some future cycle of the main loop, resulting in the
> calculation being done less and less often and the main loop executing some
> stop behavior.
> My question: Is there a possibility in Python (either with the threading
> module or with Twisted's non-threading style) to prioritize the two
> (pseudo-)concurrent methods so that the main tread is further on executed
> every ~200ms and the calculation thread being executed only in "idle" time
> slots?
>
> Thanks,
> wr

Hi,

I suggest taking a look a PEP 342
http://www.python.org/dev/peps/pep-0342/. The new coroutines capability
in Python 2.5 seems to be intended for exactly what you are doing.

--
Doug Fort, Consulting Programmer
http://www.dougfort.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Working with email and mailbox module

2006-09-21 Thread Nirnimesh
I want to extract emails from an mbox-type file which contains a number
of individual emails.

I tried the python mailbox and email modules individually, but I'm
unable to combine them to get what I want. Mailbox allows me to iterate
over all the mails but doesn't give me access the individual messages
of a multipart mail. The email.Message module provides this, but I'm
unable to iterate through all the messages with this module.

Here's what I want:

Get a list of all messages from mbox-file
For each message, be able to read the header or body individually (so
that I can apply some operation)

Does someone have experience in doing something of this sort?

-- 
http://mail.python.org/mailman/listinfo/python-list


mxCGIPython

2006-09-21 Thread Oleg Broytmann
Hello!

   For quite some time I was a maintainer of mxCGIPython. Now I am going
to stop. There will no be mxCGIPython for Python 2.5. Python is quite
popular these days, it is hard to find hosting without it. Original author
abandoned mxCGIPython long ago, and I only provided some simple patches to
port mxCGI to Python 2.3 and 2.4. But still mxCGIPython requires more work,
and I'd rather abandon it too than maintain an old broken package. Also I
have lost access to SPARK computer, and can only provide binaries for
pretty uninteresting platforms - Linux and FreeBSD.

   Well, enough excuses. Is there anyone who wants to strip me of the
burden, take the maintainance, compile new binaries and host them? Please
copy the existing binaries and write me - I will put a redirect page.

WHAT IS mxCGIPython
---

   See: http://www.egenix.com/files/python/mxCGIPython.html
http://phd.pp.ru/Software/Python/misc/mxCGI/

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread Bruno Desthuilliers
Gabriel Genellina wrote:
(snip)
> When you construct an object instance, it is of a certain type from that
> precise moment, and you can't change that afterwards.

Err... Actually, in Python, you can. It's even a no-brainer.

(snip)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using py2exe to wrap a service?

2006-09-21 Thread MaR

Tim Golden wrote:
[snip..]
> At this point there are several options open to us:
>
> (in no particular order)
> 1) You could nudge the code at line 217 to make use of
> that suggestion.
> 2) I could do that and send you the result.
> 3) I could alter the module so it doesn't use gencache
> at all. I don't seem to be using any constants so the
> Dispatch might as well be dynamic.
> 4) None of the above.
>
> I'm happy to do (3) and send it to you privately if you're
> willing to try. Of course, it might not be the cause
> of the problem in any case!
>
> TJG

Really appreciate!
Reading the page you indicate, I tried solution 3 as it seemed to be
the favored one by the author.. I simply added the lines, doing the
import and the setting the flag, in a copy of the active_directory
module.
But maybe you thought of some other nudging?
Some kind of progress anyway, I guess (see below).
Maybe your offer to do your option (3) is worthwhile after all?

//M

The instance's SvcRun() method failed
  File "win32serviceutil.pyc", line 785, in SvcRun
  File "MailProxySvc.pyc", line 132, in SvcDoRun
  File "MailProxySvc.pyc", line 100, in setup
  File "AddressDB.pyc", line 55, in loadPersonsFromAD
  File "active_directory_M.pyc", line 369, in search
  File "active_directory_M.pyc", line 219, in query
  File "win32com\client\gencache.pyc", line 536, in EnsureDispatch
  File "win32com\client\gencache.pyc", line 520, in EnsureModule
  File "win32com\client\gencache.pyc", line 287, in
MakeModuleForTypelib
  File "win32com\client\makepy.pyc", line 223, in
GenerateFromTypeLibSpec
  File "win32com\client\gencache.pyc", line 141, in GetGeneratePath
exceptions.IOError: [Errno 2] No such file or directory:
'D:\\projects\\MailProxy\\dist\\library.zip\\win32com\\gen_py\\__init__.py'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text representation of HTML

2006-09-21 Thread Ksenia Marasanova
Sorry for the late reply... better too late than never :)
Thanks to all for the tips. Stripogram is the winner, since it is the
most configurable and accept line-length parameter, which is handy for
email...

Ksenia.

On 7/19/06, Laurent Rahuel <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I guess stripogram would be more pythonic :
> http://sourceforge.net/project/showfiles.php?group_id=1083
>
> Regards,
>
> Laurent
>
> Diez B. Roggisch wrote:
>
> > Ksenia Marasanova wrote:
> >
> >> Hi,
> >>
> >> I am looking for a library that will give me very simple text
> >> representation of HTML.
> >> For example
> >> TitleThis is a test
> >>
> >> will be transformed to:
> >>
> >> Title
> >>
> >> This is a
> >> test
> >>
> >>
> >> i want to send plain text alternative of html email, and would prefer
> >> to do it automatically from HTML source.
> >> Any hints?
> >
> > html2text is a commandline tool. You can invoke it from python using
> > subprocess.
> >
> > Diez
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: naming objects from string

2006-09-21 Thread Roberto Bonvallet
manstey wrote:
[...]
> bob_apple=()
> bob_orange=()
> ..
> pete_red=()
> 
> I then populate the 9 tuples with data [...]

You cannot "populate" a tuple.  If you want to insert the values
individually, you have to use a list.  If you insert them all together,
like this:  bob_apple = (1, 2, ..., 9), you don't need to initialize
bob_apple with an empty tuple.

-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread Bruno Desthuilliers
LorcanM wrote:
(snip)

> What I'm doing is a bit more
> abstract: I'm instantiating a 'world' (as a super class) and then
> various 'worldviews' as sub-classes. The 'worldviews' must know about
> various aspects of the 'world' from which they are instantiated to be
> able to do what they need to do 

Mmmm... I suspect that you're falling into the good'ole trap of abusing
inheritance here. The fact that Worlview instances needs to know about a
World instance is usually modeled by composition, ie WorldViews are
instanciated with a world instance and keep a reference to it:

class World(object):
   pass

class WorldView(object):
  __metaclass__ = WorldViewMeta
  def __init__(self, world, *args, **kw):
self.world = world

world = World()
wv = WorldView(world)


If you need/want to get WorldViews from the world itself, it's not much
more difficult:

class World(object):
  def get_view(self, viewtype):
return viewtype(self)


world = World()
wv = world.get_view(WorldView)


And if you really need/want to be able to do the same thing but with the
WorldView name instead of the class itself:

class World(object):
  _viewtypes = {}

  @classmethod
  def register_view_type(cls, viewtype):
  cls._viewtypes[viewtype.__name__] = viewtype

  def get_view(self, typename, *args, **kw):
if isinstance(typename, basestring):
  return self._viewtypes[typename](self, *args, **kw)
else: # assume it's the class
  return typename(self, *args, **kw)

  def dothis(self):
 return "dothis"

  def dothat(self, bar):
 return bar + bar

class WorldViewMeta(type):
  def __init__(cls, classname, bases, dic):
World.register_view_type(cls)

class WorldView(object):
  __metaclass__ = WorldViewMeta
  def __init__(self, world, *args, **kw):
self.world = world

class SomeWorldView(WorldView):
  def __init__(self, world, foo, parrot=False):
WorldView.__init__(self, world)
self.foo = foo
self.parrot = parrot

world = World()
some_view = world.get_view("SomeWorldView", 42, parrot=True)
# or
some_view = world.get_view(SomeWorldView, 42, parrot=True)


Also, if you want to be able to use the WorldViews like it was the world
itself, you can easily delegate:

class DelegateWorldView(WorldView):
  def __init__(self, world):
WorldView.__init__(self, world)

  # 'override' World.dothat:
  def dothat(self, bar):
 bar = bar * 3
 return self.world.dothat(bar)

  # automagically delegate other stuff:
  def __getattr__(self, name):
return getattr(self.world, name)

HTH

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread Wildemar Wildenburger
Bruno Desthuilliers wrote:
> Gabriel Genellina wrote:
>> When you construct an object instance, it is of a certain type from that
>> precise moment, and you can't change that afterwards.
> 
> Err... Actually, in Python, you can. It's even a no-brainer.

Oh yeah, let's confuse the newbie, shall we :)

The art of teaching lies in what you *don't* tell the teachee in the 
first run.
But factually, you're right. In the course of this OO lesson, however: 
sss!

;)
wildemar

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing behaviour of namespaces

2006-09-21 Thread Peter Otten
Mikael Olofsson wrote:

> This is in Python 2.3.4 under WinXP.

To feed an arbitrary mapping object to execfile() you need to upgrade to
Python 2.4.

http://docs.python.org/dev/lib/built-in-funcs.html#l2h-26

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Decorator cllass hides docstring from doctest?

2006-09-21 Thread Berthold Höllmann
Saving the following code to a file and running the code through
python does not give the expected error. disableling the "@decor" line
leads to the expected error message. Is this a bug or an overseen
feature?


--- snip dectest.py ---
class decor(object):
def __init__(self, f):
self.f = f
def __call__(self, *args, **kw):
return self.f(*args, **kw)

@decor
def f(a, b):
"""
>>> f(1,2)
False
>>> f(2,2)
False
"""
return a == b

def _test():
import doctest
doctest.testmod()

if __name__ == "__main__":
_test()
--- snip dectest.py ---

Our Python is:

Python 2.4.2 (#1, Dec  5 2005, 10:13:23) 
[GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.


Thanks
Berthold
-- 
__   Address:
 G /  \ L Germanischer Lloyd
phone: +49-40-36149-7374 -++- Vorsetzen 35   P.O.Box 111606
fax  : +49-40-36149-7320   \__/   D-20459 HamburgD-20416 Hamburg

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Priority based concurrent execution

2006-09-21 Thread Jean-Paul Calderone
On 21 Sep 2006 04:56:46 -0700, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>Willi Richert wrote:
>> Hi,
>>
>> I have a simulation application (PlayerStage) in which the robot is asked
>> every ~200ms for an action. In the meantime the robot has to do some
>> calculation with the perception. As the calculation gets more and more time
>> consuming I am thinking about outsourcing it into a concurrently running
>> method. If the calculation takes too long it would be ok for the result to be
>> incorporated in some future cycle of the main loop, resulting in the
>> calculation being done less and less often and the main loop executing some
>> stop behavior.
>> My question: Is there a possibility in Python (either with the threading
>> module or with Twisted's non-threading style) to prioritize the two
>> (pseudo-)concurrent methods so that the main tread is further on executed
>> every ~200ms and the calculation thread being executed only in "idle" time
>> slots?
>>
>> Thanks,
>> wr
>
>Hi,
>
>I suggest taking a look a PEP 342
>http://www.python.org/dev/peps/pep-0342/. The new coroutines capability
>in Python 2.5 seems to be intended for exactly what you are doing.

Note that the title of the PEP is misleading and coroutines have not been
introduced in Python 2.5.

Generators (either pre-2.5 or post-2.5) can be used as an application
API to an implementation of something like what the poster is requesting,
inasmuch as many people find them to be a useful way to split a task up
into small pieces.  However, aside from syntactic convenience, they don't
really bring anything fundamentally different to the table.

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested Looping SQL Querys

2006-09-21 Thread Carsten Haese
On Thu, 2006-09-21 at 01:12, Dennis Lee Bieber wrote:
> On Wed, 20 Sep 2006 13:21:54 -0400, Steve Holden <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> > .execute() is a cursor method, not a connection method. Some DB API 
> > modules do implement it as a connection method, but that makes it 
> > impossible for several cursors to share the same connection (which is 
> > allowed by some modules).
> >
>   It struck me that the original wasn't using a cursor just after the
> messages posted.

It doesn't look like the OP is using anything even remotely DB-API
compliant:

"""
import cmi

import hermes
conn = hermes.db()


pubID=cgiForm.getvalue('pubID')
pubName=cgiForm.getvalue('pubName','Unknown Publication')

sqlcheck1 = "SELECT pub_type FROM medusa.cmi_publication WHERE pub_id =
'"+pubID+"'"
overseas1 = conn.query(sqlcheck1)
pubType = cmi.fetch_rows(overseas1)
"""

hermes is apparently some wrapper that magically can connect to a
well-known database (via the argumentless db()) call. Who knows what
kind of animal the 'conn' object is that comes out of that db() call.
Apparently it's an object with a query() method that returns something
like a cursor that can be passed into cmi.fetch_rows(). At this point I
wonder why the responsibility of fetching rows is in a module separate
from the responsibility of establishing a database connection.

Legacy code, indeed.

-Carsten


-- 
http://mail.python.org/mailman/listinfo/python-list


http://mail.python.org/pipermail/python-list/2006-January/320434.html

2006-09-21 Thread filippo randello
Hello,

if after your command:
ie.Document.login_form.submit() 

I write:
doc = ie.Document
s = doc.documentElement.outerHTML
print s

I can see the HTML of the document before the submit
command, but I would like to see the HTML of the page
after the submit command: do you know how to solve
this problem?

Cheers.




form:
http://mail.python.org/pipermail/python-list/2006-January/320434.html



# Quick and dirty script example

from win32com.client import DispatchEx
import time

def wait(ie):

while ie.Busy:
time.sleep(0.1)
while ie.Document.ReadyState != 'complete':

time.sleep(0.1)

#instaniate a new ie object so you can call it's
methods and properties...etc..
ie = DispatchEx('InternetExplorer.Application')

# You need to make it Visible
ie.Visible = 1

# Navigate to the page
ie.Navigate('mail.yahoo.com')

wait(ie) # important to wait for the doc to load


# Enter User info and submit the form since it uses
submit # If the button had a name attribute # You
could also use 
ie.Document.login_form.buttonName.Click

# ieObject.Document.FormName.TexboxName.value ="??"
ie.Document.login_form.username.value="MyName"
ie.Document.login_form.passwd.value="Mypasswd"
ie.Document.login_form.submit()


Enjoy
Rob M
http://pamie.sourceforge.net



__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-21 Thread Diez B. Roggisch
rodmc wrote:

> Thanks to everyone for their help. I had tried OmniORB and while the
> base library worked ok, the Python bit OmniORBpy seems to dislike
> working... Perhaps there is something wrong with my settings.

Omniorb is very actively developed, try and post your problems on the
mailing list:

http://www.omniorb-support.com/mailman/listinfo/omniorb-list

AFAIK Fnorb also had license issues - I'm not entirely sure of that, but
better check it.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator cllass hides docstring from doctest?

2006-09-21 Thread Duncan Booth
[EMAIL PROTECTED] (Berthold =?iso-8859-15?Q?H=F6llmann?=) wrote:

> Saving the following code to a file and running the code through
> python does not give the expected error. disableling the "@decor" line
> leads to the expected error message. Is this a bug or an overseen
> feature?
> 
It's a problem with your implementation of the decorator. In fact it is two 
problems: the decorated 'f' is a class instance so doctest ignores it, and 
it doesn't have a docstring so doctest ignores it.

If you rewrite the decorator so that the decorated 'f' is still a function 
and preserve the docstring then it works as you might expect. e.g.

def decor(f):
def wrapper(*args, **kw):
return f(*args, **kw)
wrapper.__doc__ = f.__doc__
wrapper.__name__ = f.__name__
return wrapper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator cllass hides docstring from doctest?

2006-09-21 Thread Felipe Almeida Lessa
2006/9/21, Berthold Höllmann <[EMAIL PROTECTED]>:
> Saving the following code to a file and running the code through
> python does not give the expected error. disableling the "@decor" line
> leads to the expected error message. Is this a bug or an overseen
> feature?

Try the new_decor class described below:

>>> class decor(object):
... def __init__(self, f):
... self.f = f
... def __call__(self, *args, **kw):
... return self.f(*args, **kw)
...
>>> class new_decor(object):
... def __init__(self, f):
... self.f = f
... self.__doc__ = f.__doc__
... self.__name__ = f.__name__
... def __call__(self, *args, **kw):
... return self.f(*args, **kw)
...
>>> def f(a, b):
... '''
... >>> f(1, 2)
... False
... >>> f(2, 2)
... False
... '''
... return a == b
...
>>> f.__doc__
'\n\t>>> f(1, 2)\n\tFalse\n\t>>> f(2, 2)\n\tFalse\n\t'
>>> decor(f).__doc__ == f.__doc__
False
>>> new_decor(f).__doc__ == f.__doc__
True


-- 
Felipe.
-- 
http://mail.python.org/mailman/listinfo/python-list

How to get ip setting, dynamic ip or static ip?

2006-09-21 Thread kode4u
How to use python get my windows box's ip setting type? Dynamic ip, or
static ip?

If it's static ip, what's the exact value?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to run an external program

2006-09-21 Thread Larry Bates
Brant Sears wrote:
> Hi. I'm new to Python and I am trying to use the latest release (2.5) on
> Windows XP.
> 
> What I want to do is execute a program and have the results of the
> execution assigned to a variable. According to the documentation the way
> to do this is as follows:
> 
> import commands
> x = commands.getstatusoutput('dir')
> 
> This should assign "x" to be the output of the command "dir". However,
> when I run this (or any other command), x ends up being:
> 
> (1, "'{' is not recognized as an internal or external command,\noperable
> program or batch file.")
> 
> From looking through the documentation, I'm believing that the
> implementation of commands.getstatusoutput is actually some multi-step
> thing that starts with issuing the bracket character that is being
> choked on. This leads me to believe that Python or perhaps just the
> commands module is not setup correctly on my computer.
> 
> I installed Python using the Python2-5.msi link that I found at:
> http://www.python.org/download/releases/2.5/
> 
> I left everything the default during installation, so Python was
> installed to C:\Python25. The only other thing I did was add this PATH
> variable on my computer.
> 
> Any ideas on what I might do to troubleshoot this?
> 
> Thanks!
> 
> Brant Sears

Others have answered your specific question, but on a more general note:

If you want directory information use os.listdir or glob.glob instead.
No reason to shell out to do a dir.  If you were using dir as an example,
please disregard.

-Larry Bates


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing behaviour of namespaces - solved, I think

2006-09-21 Thread Mikael Olofsson
Peter Otten wrote:
> To feed an arbitrary mapping object to execfile() you need to upgrade to
> Python 2.4.

Thanks! As clear as possible. I will do that.

FYI: I think I managed to achieve what I want in Py2.3 using the 
compiler module:

def getNamesFromAstNode(node,varSet):
if node.__class__ in (compiler.ast.Global,compiler.ast.Import):
varSet.union_update(node.names)
if node.__class__ in (compiler.ast.Name,):
varSet.add(node.name)
for subNode in node.getChildNodes():
getNamesFromAstNode(subNode,varSet)

# Get all variable names that are referenced in the file:
varSet = sets.Set()
mainNode = compiler.parseFile(filePath)
getNamesFromAstNode(mainNode,varSet)

# Define a namespace and update it:
ns = {}
for varName in varSet:
ns[varName] = dummyObject

# Execute the file without NameErrors:
execfile(filePath,ns)

Batteries included!

/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread [EMAIL PROTECTED]
Dennis Lee Bieber wrote:
> On Thu, 21 Sep 2006 15:34:21 +0800, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>   
>> Is it possible that the program can save all running data to a file when 
>> I want it to stop, and can reload the data and continue to run from 
>> where it stops when the computer is free ?
>>
>> 
>   You'd have to write the code to save state, which means you'd have
> to be at a known resumable point... I suspect that, if you're nested
> into a recursive function, that will not be possible as you'd have to
> recreate the calling stack along with populating all know data.
>
>   It should be pointed out that "chaos theory" sort of got its start
> from an attempt at doing something similar -- saving a massive data
> array for later reloading. It turns out the saved data didn't have the
> full resolution of the computations, so the restart from the saved data
> diverged rapidly from where the prior run had been heading. (As I
> recall, it was a weather simulation in the late 60s early 70s, and the
> data was saved in single-precision text format -- meaning round-off
> errors on output/input; these days it would be the equivalent of the
> losses inherent in doing a long computation in 80-bit IEEE, but saving
> intermediates [for reload] in 64-bit IEEE).
>
>   The other option may not be available under most operating system...
> Namely a snapshot of the entire "core" of memory, so you can restore the
> machine /exactly/ to the state it had been at the time of the snapshot
> (this would probably affect everything on the machine -- all other
> programs, etc.)
>
>
>   Though if someone else have more information contradicting me, I'd
> be happy to hear it... 
>   
Thank you all!

Can objects be saved and reloaded by "Pickle"  ?  I have tried but no
success.

One of my friends tell me that VMware can save the current state of a
virtual machine by suspending it, and can restore the identical state
later. When a virtual machine is suspended , a file with a .vmss
extension is created(about 20M), which  contains the entire state of the
virtual machine. When you resume the virtual machine, its state is
restored from the .vmss file.

So can this method be implemented with python ?

I have another idea. When python is running, it uses about 10M memory.
So can I just save a copy of the memory used by python and restore it
later ?

Regards,

xiaojf

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage
Ps. Aristotle can rest easy tonight:

class mortal(object): pass
class man(mortal): pass
Socrates = man()
all_men  = mortal()
if Socrates == all_men:
  print "Socrates == all_man"
else:
  print "Undistributed Middle is indeed a fallacy"

;)

Regards,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I have a program which will continue to run for several days. When it is
> running, I can't do anything except waiting because it takes over most
> of the CUP time.
> 
> Is it possible that the program can save all running data to a file when
> I want it to stop, and can reload the data and continue to run from
> where it stops when the computer is free ?
> 
> Regards,
> 
> xiaojf
> 
You can save the state of Python objects and reload them at a later time/date by
using Zope's ZODB.

http://www.zope.org/Wikis/ZODB/FrontPage

-Larry Bates

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator cllass hides docstring from doctest?

2006-09-21 Thread Michele Simionato
Berthold Höllmann wrote:
> Saving the following code to a file and running the code through
> python does not give the expected error. disableling the "@decor" line
> leads to the expected error message. Is this a bug or an overseen
> feature?

Others have already pointed out the mistake. I wrote a module to avoid
this kind of issues, so you
may want to check it out:

http://www.phyast.pitt.edu/~micheles/python/documentation.html

Michele Simionato

-- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.5 WinXP AMD64

2006-09-21 Thread Brendan
Hello,
I just tried to use the Windows XP installer for Python 2.5 AMD64 but I
get the error message: "Installation package not supported by processor
type"

I am running Windows XP Pro on an AMD Athon 64 Processor.

Do I need to have a 64-bit OS to use this version?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and CORBA

2006-09-21 Thread Paul McGuire
"rodmc" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Thanks to everyone for their help. I had tried OmniORB and while the
> base library worked ok, the Python bit OmniORBpy seems to dislike
> working... Perhaps there is something wrong with my settings.
>
> I will also try the Python only suggestion.
>
> cheers,
>
> rod
>

Give OmniORB another shot, it is quite fully featured, including 
NamingService, Trader, idl compiler.  I found the Python integration with 
OmniORBpy worked for me, too.

-- Paul


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decorator cllass hides docstring from doctest?

2006-09-21 Thread Peter Otten
Berthold Höllmann wrote:

> Saving the following code to a file and running the code through
> python does not give the expected error. disableling the "@decor" line
> leads to the expected error message. Is this a bug or an overseen
> feature?

Neither, I'd say. Just an unfortunate interaction between doctest and
function decoration. For the most common case where one function is wrapped
by another, Python 2.5 has grown a "meta-decorator"

>>> import functools
>>> def deco(f):
... @functools.wraps(f)
... def g():
... f()
... return g
...
>>> @deco
... def f():
... "yadda yadda"
...
>>> f.__doc__
'yadda yadda'

but with callable objects you're on your own, I think. 
I came up with:

def register_doctest(name, doc):
global __test__
if doc:
try:
__test__
except NameError:
__test__ = {name: doc}
else:
if name in __test__:
raise ValueError("name clash")
__test__[name] = doc

class decor(object):
def __init__(self, f):
self.f = f
register_doctest(f.__name__, f.__doc__)
def __call__(self, *args, **kw):
return self.f(*args, **kw)

@decor
def f(a, b):
"""
>>> f(1,2)
False
>>> f(2,2)
False
"""
return a == b

import doctest
doctest.testmod()

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get ip setting, dynamic ip or static ip?

2006-09-21 Thread Duncan Booth
"kode4u" <[EMAIL PROTECTED]> wrote:

> How to use python get my windows box's ip setting type? Dynamic ip, or
> static ip?
> 
> If it's static ip, what's the exact value?
> 
Here's one way:

def ipinfo(interface="Local Area Connection"):
dhcpenabled = False
staticip = None
subnetmask = None
for l in os.popen('netsh interface ip show address "%s"' % interface):
l = l.strip()
if l.startswith('DHCP enabled'):
dhcpenabled = l.endswith('Yes')
if l.startswith("IP Address"):
staticip = l.rsplit(None,1)[-1]
if l.startswith("SubnetMask"):
subnetmask = l.rsplit(None,1)[-1]
return dhcpenabled, staticip, subnetmask

>>> ipinfo()
(True, None, None)
>>> ipinfo("VMware Network Adapter VMnet1")
(False, '192.168.126.1', '255.255.255.0')
-- 
http://mail.python.org/mailman/listinfo/python-list


Tk eventloop

2006-09-21 Thread swell
Hi
I try/struggle to use an ActiveX component in a Tk app. When i execute
it i can catch the first event and then when i try to change the value
of the w widget everything blocks and nothing is updated anymore.

Does someone have an idea of what is wrong and how to smartly integrate
these events with the Tk event loop.

Thx
Manu

import win32com.client
import pythoncom
import MyComponent
from Tkinter import *

class Event1(MyComponent.IEvents):
def OnUpdate(self, ItemName, UserTag):
global w
v = ptrAx.getV(ItemName)
print "%s" % v
w.configure(text='a')

root = Tk()
w = Label(root,text="test")
w.pack()

ptrAx = win32com.client.DispatchWithEvents(r'MyComponent',Event1)
ptrAx.StartUpdates()

root.mainloop()

-- 
http://mail.python.org/mailman/listinfo/python-list


How to return an "not string' error in function?

2006-09-21 Thread breakfastea
first of all I have to claim that I'm a noob so please help me don't
blame me:)

for example:

def test(s):
   if type(s) != ? :
  return
#So here I want establish a situation about that if  is not string
#then , but how should write the  ?
#Or is there any other way to do it?

Any suggestion would be appreciate

Peace

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 WinXP AMD64

2006-09-21 Thread Christophe
Brendan a écrit :
> Hello,
> I just tried to use the Windows XP installer for Python 2.5 AMD64 but I
> get the error message: "Installation package not supported by processor
> type"
> 
> I am running Windows XP Pro on an AMD Athon 64 Processor.
> 
> Do I need to have a 64-bit OS to use this version?

To be exact, you need a 64bit Windows OS on a 64bit cpu.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing behaviour of namespaces - solved, I think

2006-09-21 Thread Peter Otten
Mikael Olofsson wrote:

> Peter Otten wrote:
>> To feed an arbitrary mapping object to execfile() you need to upgrade to
>> Python 2.4.
> 
> Thanks! As clear as possible. I will do that.
> 
> FYI: I think I managed to achieve what I want in Py2.3 using the
> compiler module:
> 
> def getNamesFromAstNode(node,varSet):
> if node.__class__ in (compiler.ast.Global,compiler.ast.Import):
> varSet.union_update(node.names)
> if node.__class__ in (compiler.ast.Name,):
> varSet.add(node.name)
> for subNode in node.getChildNodes():
> getNamesFromAstNode(subNode,varSet)
> 
> # Get all variable names that are referenced in the file:
> varSet = sets.Set()
> mainNode = compiler.parseFile(filePath)
> getNamesFromAstNode(mainNode,varSet)
> 
> # Define a namespace and update it:
> ns = {}
> for varName in varSet:
> ns[varName] = dummyObject
> 
> # Execute the file without NameErrors:
> execfile(filePath,ns)
> 
> Batteries included!

Clearly more elegant than:

>>> print open(filename).read()
b = a
>>> dummy = 42
>>> names = []
>>> while 1:
... ns = dict((n, dummy) for n in names)
... try:
... execfile(filename, ns)
... except NameError, e:
... names.append(e[0][6:-16])
... else:
... break
...
>>> names
['a']

:-)

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return an "not string' error in function?

2006-09-21 Thread Tim Chase
> def test(s):
>if type(s) != ? :
>   return
> #So here I want establish a situation about that if  is not string
> #then , but how should write the  ?
> #Or is there any other way to do it?

 >>> isinstance("hello", basestring)
True
 >>> isinstance(u"hello", basestring)
True

This will return true for both regular strings and for unicode 
strings.  If that's a problem, you can use

 >>> import types
 >>> isinstance("hello", types.StringType)
True
 >>> isinstance(u"hello", types.StringType)
False
 >>> isinstance("hello", types.UnicodeType)
False
 >>> isinstance(u"hello", types.UnicodeType)
True

...or, if you don't want to qualify them with "types." each time, 
you can use

 >>> from types import StringType, UnicodeType

to bring them into the local namespace.

HTH,

-tkc






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 WinXP AMD64

2006-09-21 Thread Brendan
Thanks.

Christophe wrote:
> Brendan a écrit :
> > Hello,
> > I just tried to use the Windows XP installer for Python 2.5 AMD64 but I
> > get the error message: "Installation package not supported by processor
> > type"
> >
> > I am running Windows XP Pro on an AMD Athon 64 Processor.
> >
> > Do I need to have a 64-bit OS to use this version?
> 
> To be exact, you need a 64bit Windows OS on a 64bit cpu.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return an "not string' error in function?

2006-09-21 Thread Jean-Paul Calderone
On Thu, 21 Sep 2006 09:26:20 -0500, Tim Chase <[EMAIL PROTECTED]> wrote:
>> def test(s):
>>if type(s) != ? :
>>   return
>> #So here I want establish a situation about that if  is not string
>> #then , but how should write the  ?
>> #Or is there any other way to do it?
>
> >>> isinstance("hello", basestring)
>True
> >>> isinstance(u"hello", basestring)
>True
>
>This will return true for both regular strings and for unicode
>strings.  If that's a problem, you can use
>
> >>> import types
> >>> isinstance("hello", types.StringType)
>True
> >>> isinstance(u"hello", types.StringType)
>False
> >>> isinstance("hello", types.UnicodeType)
>False
> >>> isinstance(u"hello", types.UnicodeType)
>True
>
>...or, if you don't want to qualify them with "types." each time,
>you can use
>
> >>> from types import StringType, UnicodeType
>
>to bring them into the local namespace.

>>> str is types.StringType
True
>>> unicode is types.UnicodeType
True

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return an "not string' error in function?

2006-09-21 Thread breakfastea
Thank you so much it answers my humble question perfectly:)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread Hans Georg Krauthaeuser
[EMAIL PROTECTED] wrote:
> 
> Can objects be saved and reloaded by "Pickle"  ?  I have tried but no
> success.
> 
Yes, that's the intended use of pickle/cPickle. There are examples in
the docs:

http://docs.python.org/lib/module-pickle.html

What have you tried and what didn't work?

Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


itertools.count(-3)

2006-09-21 Thread bearophileHUGS
itertools.count docs say:
Does not currently support python long integers.
Note, count() does not check for overflow and will return negative
numbers after exceeding sys.maxint. This behavior may change in the
future.

But it seems it doesn't support negative numbers too:

>>> from itertools import count, islice
>>> list(islice(count(), 0, 5))
[0, 1, 2, 3, 4]
>>> list(islice(count(10), 0, 5))
[10, 11, 12, 13, 14]
>>> list(islice(count(-3), 0, 5))
[4294967293L, 4294967294L, 4294967295L, 0, 1]
>>> def count2(n=0):
... while True:
... yield n
... n += 1
...
>>> list(islice(count2(-3), 0, 5))
[-3, -2, -1, 0, 1]

If this isn't a bug, then maybe docs can tell about this too.

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Beautiful Soup to entangle bookmarks.html

2006-09-21 Thread robin
"George Sakkis" <[EMAIL PROTECTED]> wrote:

>Here's what I came up with:
>http://rafb.net/paste/results/G91EAo70.html. Tested only on my
>bookmarks; see if it works for you.

That URL is dead. Got another?

-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return an "not string' error in function?

2006-09-21 Thread Duncan Booth
Tim Chase <[EMAIL PROTECTED]> wrote:

> This will return true for both regular strings and for unicode 
> strings.  If that's a problem, you can use
> 
> >>> import types
> >>> isinstance("hello", types.StringType)
> True
> >>> isinstance(u"hello", types.StringType)
> False
> >>> isinstance("hello", types.UnicodeType)
> False
> >>> isinstance(u"hello", types.UnicodeType)
> True
> 
> ...or, if you don't want to qualify them with "types." each time, 
> you can use
> 
> >>> from types import StringType, UnicodeType
> 
> to bring them into the local namespace.

They already are in the builtin namespace under their more usual names of 
str and unicode respectively, so there is no need to import them, just use 
them:

>>> isinstance("hello", str)
True

... etc ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing behaviour of namespaces - solved, I think

2006-09-21 Thread Mikael Olofsson
Peter Otten wrote:
> Clearly more elegant than:
>
>   
 print open(filename).read()
 
> b = a
>   
 dummy = 42
 names = []
 while 1:
 
> ... ns = dict((n, dummy) for n in names)
> ... try:
> ... execfile(filename, ns)
> ... except NameError, e:
> ... names.append(e[0][6:-16])
> ... else:
> ... break
> ...
>   
 names
 
> ['a']
>   

That sure is nicer. My solution looks like shooting mosquitoes with an 
elephant rifle i comparison. Thanks.

/MiO
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get process id...

2006-09-21 Thread billie

Fredrik Lundh ha scritto:

> billie wrote:
>
> >> under linux, do:
>  >
> >>   import os
> >>   os.getpid()
> >
> > Under Windows:
>  >
> > import ctypes
> > ctypes.windll.kernel32.GetCurrentProcessId()
>
> getpid() works just fine on Windows too:
>
>  >>> import ctypes
>  >>> ctypes.windll.kernel32.GetCurrentProcessId()
> 1916
>  >>> import os
>  >>> os.getpid()
> 1916

I tought it doesn't work. Good

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools.count(-3)

2006-09-21 Thread Carl Banks

[EMAIL PROTECTED] wrote:
> itertools.count docs say:
> Does not currently support python long integers.
> Note, count() does not check for overflow and will return negative
> numbers after exceeding sys.maxint. This behavior may change in the
> future.
>
> But it seems it doesn't support negative numbers too:
>
> >>> from itertools import count, islice
> >>> list(islice(count(), 0, 5))
> [0, 1, 2, 3, 4]
> >>> list(islice(count(10), 0, 5))
> [10, 11, 12, 13, 14]
> >>> list(islice(count(-3), 0, 5))
> [4294967293L, 4294967294L, 4294967295L, 0, 1]
> >>> def count2(n=0):
> ... while True:
> ... yield n
> ... n += 1
> ...
> >>> list(islice(count2(-3), 0, 5))
> [-3, -2, -1, 0, 1]
>
> If this isn't a bug, then maybe docs can tell about this too.

Seems like a regression to me.  itertools was documented as taking a
sequence of integers, not necessarily positive integers.  It worked on
Python 2.4.

Looking at the source (from 2.5 rc2), it looks like they accidentally
used PyInt_FromSize_t rather than PyInt_FromSSize_t in the count
iterator.  size_t is unsigned, of course, hence the large negative
numbers.


Carl Banks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return an "not string' error in function?

2006-09-21 Thread breakfastea
Or yes that seems a handy way:)

Thanks for all wonderful people here:)

Peace


Duncan Booth wrote:
> Tim Chase <[EMAIL PROTECTED]> wrote:
>
> > This will return true for both regular strings and for unicode
> > strings.  If that's a problem, you can use
> >
> > >>> import types
> > >>> isinstance("hello", types.StringType)
> > True
> > >>> isinstance(u"hello", types.StringType)
> > False
> > >>> isinstance("hello", types.UnicodeType)
> > False
> > >>> isinstance(u"hello", types.UnicodeType)
> > True
> >
> > ...or, if you don't want to qualify them with "types." each time,
> > you can use
> >
> > >>> from types import StringType, UnicodeType
> >
> > to bring them into the local namespace.
>
> They already are in the builtin namespace under their more usual names of
> str and unicode respectively, so there is no need to import them, just use
> them:
> 
> >>> isinstance("hello", str)
> True
> 
> ... etc ...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 WinXP AMD64

2006-09-21 Thread Bjoern Schliessmann
Christophe wrote:

> To be exact, you need a 64bit Windows OS on a 64bit cpu.

Is there a reason that can be explained in a less-than-2-KB
posting? :) I mean why Python depends on the processor type that
much.

Regards,


Björn

-- 
BOFH excuse #52:

Smell from unhygienic janitorial staff wrecked the tape heads

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to return an "not string' error in function?

2006-09-21 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>Thank you so much it answers my humble question perfectly:)
>

HOWEVER, to answer you final question, yes, there is a different
and, in general, better, way.  While there's a lot to say about
good Python style and typing, I'll summarize at a high level:
you shouldn't have to check types.  I can understand that you
are working to make a particular function particularly robust, 
and are trying to account for a wide range of inputs.  This is
healthy.  In stylish Python, though, you generally don't need
type checking.  How would it be, for example, if someone passed
the number 3 to your function.  Is that an error?  Do you want
it automatically interpreted as the string "3"?  You can achieve
these results withOUT a sequence of

  if isinstance(...
  elif isinstance(...
  ...

perhaps with something as simple as

  my_input = str(my_input).

One of us will probably follow-up with a reference to a more
detailed write-up of the subject.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >