Re: Getting pid of a remote process

2008-08-19 Thread Diez B. Roggisch

srinivasan srinivas schrieb:

HI,
I am using Solaris and subprocess.Popen to spawn a process on a remote machine.


No, you are *not* doing that. You are maybe using subproces to run SSH 
to spawn a remote process. Why don't you *show* us how you actually do that?


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


Re: Programming Languages Decisions

2008-08-19 Thread Terry Reedy



How is Python with graphics?


It depends a bit on exactly what you mean, but there are 3rd party 
packages for just about everything.  Ask a specific question, parhaps in 
a new thread, and you should a specific answer, or more.


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


Re: Getting pid of a remote process

2008-08-19 Thread Willi Richert
Hallo,

if the remote machines allow ssh login, you might try my SSHRemoteController 
(a combination of ssh and pexpect). Basically, it simulates a user typing 
something at the console. Then you can conveniently issue commands at the 
remote machine like "ps ax | grep cmd".

http://www.richert.de/free/sshrc/SSHRemoteController-0.1.tar.bz2

Regards,
wr

>  srinivasan srinivas2008-08-1906:47:44 
> HI,
> I am using Solaris and subprocess.Popen to spawn a process on a remote
> machine. Thanks,
> Srini
>
>
>
> - Original Message 
> From: Diez B. Roggisch <[EMAIL PROTECTED]>
> To: python-list@python.org
> Sent: Monday, 18 August, 2008 9:23:20 PM
> Subject: Re: Getting pid of a remote process
>
> srinivasan srinivas schrieb:
> > Hi,
> > Could you please suggest me a way to find pid of a process started on a
> > remote machine by the current process?? I should get pid in the current
> > process environment. The approach should be somewhat generic. It
> > shouldn't expect the remote process to print its pid.
>
> Without information about
>
>   - the OS you use
>
>   - the technique you use for spawning processes remote
>
> there is no answer to this.
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
>
>   Unlimited freedom, unlimited storage. Get it now, on
> http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ --
> http://mail.python.org/mailman/listinfo/python-list

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

Re: Python Substitute for PHP GD, Resizing an image on the client side

2008-08-19 Thread brahmaforces
Hi Everyone,

Thanks for your responses. Sorry I should have been clearer in my
question. Yes PHP is server side, and it seems that all image
processing using GD or ImageMagicks etc happens on the server.
Therefore Diez's suggestion of using javascript to select a rectangle
on the client side would be the best option and then upload this small
selection to the server and then process there.

Does anyone have any code that does the javascript "selecting the
rectangle bit" and uploading to the server. Also incidentally is ftp
or put the recommended way to go for uploading the reduced image to
the server?

Thanks...


On Aug 19, 11:54 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> brahmaforces schrieb:
>
> > Hi Folks,
>
> > I am using cherrypy and python. I am trying to get a user profile
> > image to resize on the client side before uploading to the server. PHP
> > has a gd library that does it it seems. Has anyone done this in a
> > python environment without uploading to the server?
>
> Everything PHP is server-side. And displaying images is *always* done
> through uploading and then displaying it.
>
> The resizing is done using JavaScript, and then communicating back the
> selected rectangle to the server - *then* GD or whatnot (PIL,
> ImageMagick) are used to resize the image.
>
> Diez

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


Re: cathing uncaught exceptions

2008-08-19 Thread Alexandru Mosoi
On Aug 18, 6:02 pm, Alexandru  Mosoi <[EMAIL PROTECTED]> wrote:
> how can I catch (globally) exception that were not caught in a try/
> catch block in any running thread? i had this weird case that an
> exception was raised in one thread, but nothing was displayed/logged.

I found that normally sys.excepthook is invoked for uncaught
exceptions. however in my case the function is not invoked (as it
should normaly do). i printed the stackframe and checked that there is
no try/catch block that handles the exception. any other idea?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Substitute for PHP GD, Resizing an image on the client side

2008-08-19 Thread Diez B. Roggisch
> Does anyone have any code that does the javascript "selecting the
> rectangle bit" and uploading to the server.

I've based my work in this field on some freely available JS, but don't know
what it was called. Google is your friend here.

> Also incidentally is ftp 
> or put the recommended way to go for uploading the reduced image to
> the server?

In the same way any other uploading is done in browsers when a website is
involved: using HTTP POST. Use the -tag, and make sure
the server-side will store a transmitted file properly. Frameworks such as
TurboGears (1 or 2) and Django will do that for you.


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


Re: Getting pid of a remote process

2008-08-19 Thread srinivasan srinivas
This is wat i am doing :

args = [ "SSH", ,  ]
I am giving this to subprocess.Popen()
Thanks,
Srini


- Original Message 
From: Diez B. Roggisch <[EMAIL PROTECTED]>
To: python-list@python.org
Sent: Tuesday, 19 August, 2008 12:26:20 PM
Subject: Re: Getting pid of a remote process

srinivasan srinivas schrieb:
> HI,
> I am using Solaris and subprocess.Popen to spawn a process on a remote 
> machine.

No, you are *not* doing that. You are maybe using subproces to run SSH 
to spawn a remote process. Why don't you *show* us how you actually do that?

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



  Unlimited freedom, unlimited storage. Get it now, on 
http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting pid of a remote process

2008-08-19 Thread Diez B. Roggisch
srinivasan srinivas wrote:

> This is wat i am doing :
> 
> args = [ "SSH", ,  ]
> I am giving this to subprocess.Popen()
> Thanks,
> Srini

Then the answer is simple: how would you figure out the remote process pid
using ssh? Once you found that out, pass that to Popen. Make sure you
capture stdout of the Popen-class to get the answer.

Something like

ps aux | grep  | grep -v grep | awk '{print $2}'

should be the command.

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

Re: Handling Property and internal ('__') attribute inheritance and creation

2008-08-19 Thread Eric Brunel

On Fri, 15 Aug 2008 20:02:36 +0200, Rafe <[EMAIL PROTECTED]> wrote:
[snip]

1) 'Declaring' attributes - I always felt it was good code practice to
declare attributes in a section of the class namespace. I set anything
that is constant but anything variable is set again  in __init__():

Class A(object):
name = "a name"
type = "a typee"
childobject = None

def __init__(self, obj):
self.childobject = object

This makes it easy to remember and figure out what is in the class.
Granted there is nothing to enforce this, but that is why I called it
'code practice'. Do you agree or is this just extra work?


To add to what others have already said, it is not only 'just extra work',  
it is also quite dangerous. See:


class A(object):
  children = []

Now *all* A instances share the *same* list, as it was defined as a class  
attribute. If you ever forget to set it to something else in __init__,  
you're in for big surprises.


What I'm doing is set all instance attributes right at the beginning of  
the __init__ with a huge comment before them, like:


class A(object):
  def __init__(self):
## INSTANCE ATTRIBUTES:
## 
self.children = []

This way, you still can 'figure out what is in the class' quite quickly,  
without the drawbacks of declaraing class attributes.


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: Handling Property and internal ('__') attribute inheritance and creation

2008-08-19 Thread Fredrik Lundh

Eric Brunel wrote:

To add to what others have already said, it is not only 'just extra 
work', it is also quite dangerous. See:


class A(object):
  children = []


the OP is aware of that, of course:

> I set anything that is constant but anything variable is set again in
> __init__()

as long as if you're aware of the issues involved (which you should be 
if you're using Python professionally), using class-level attributes is 
a perfectly valid Python style.




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


Re: searching through a string and pulling characters

2008-08-19 Thread Paul Boddie
On 19 Aug, 01:11, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Mon, 18 Aug 2008 15:34:12 -0700, Alexnb wrote:
> > Okay, well the point of this program is to steal from the OS X built-in
> > dictionary.
>
> Ah, not homework, but copyright infringement.

It depends what the inquirer is doing and what they mean by "steal".
Given the propaganda around "unauthorised" usage of content that is
pervasive these days ("you don't own that DVD: you just have our
temporary and conditional permission to watch it, pirate!"), the
inquirer may have been led to believe that just reading from a file on
their own system rather than using the nominated application is
somehow to "steal" from that file, even though it is content which has
presumably been obtained legitimately, even paid for in the case of OS
X.

Even if the end-user licence agreement were to attempt to wash away
any "fair use" (or just common sense) rights to using the content in
the way described by the inquirer - recalling that OS X is an Apple
product, so such games wouldn't be beneath that particular vendor - I
can't see how it does much good to dignify such antics with
unqualified cries of "copyright infringement". Indeed, for those not
acquainted with copyright and licensing, it probably just serves to
reinforce the dishonest message that they have to pay over and over
for content they already have and not to question what it is they're
paying for.

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


WindowsXP / CTypes Module - unable to access function in a dll

2008-08-19 Thread dudeja . rajat
Hi,

I'm using the CTYPES module of python to load a dll. My dll contains a
Get_Version function as:
long __stdcall af1xEvdoRDll_GetVersion(long version[4]);

This function accepts a long array of 4 elements.

Following is the python code I've written:

from ctypes import *
abc =  windll.af1xEvdoRDll
GetVersion = abc.af1xEvdoRDll_GetVersion
print GetVersion
versionArr = c_long * 4#array of 4 longs
version = versionArr(0, 0, 0, 0) # initializing all elements to 0
GetVersion(version)#calling dll function
print version

I'm getting the following output:
<_FuncPtr object at 0x00A1EB70>
<__main__.c_long_Array_4 object at 0x00A86300>

But I'm not getting the desired output which I expect as : 2.1.5.0


Please suggest what am I missig?
--
http://mail.python.org/mailman/listinfo/python-list


Re: WindowsXP / CTypes Module - unable to access function in a dll

2008-08-19 Thread dudeja . rajat
On Tue, Aug 19, 2008 at 11:04 AM,  <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm using the CTYPES module of python to load a dll. My dll contains a
> Get_Version function as:
> long __stdcall af1xEvdoRDll_GetVersion(long version[4]);
>
> This function accepts a long array of 4 elements.
>
> Following is the python code I've written:
>
> from ctypes import *
> abc =  windll.af1xEvdoRDll
> GetVersion = abc.af1xEvdoRDll_GetVersion
> print GetVersion
> versionArr = c_long * 4#array of 4 longs
> version = versionArr(0, 0, 0, 0) # initializing all elements to 0
> GetVersion(version)#calling dll function
> print version
>
> I'm getting the following output:
> <_FuncPtr object at 0x00A1EB70>
> <__main__.c_long_Array_4 object at 0x00A86300>
>
> But I'm not getting the desired output which I expect as : 2.1.5.0
>
>
> Please suggest what am I missig?
>

Sorry, the problem is resolved. The code in fact is correct and I got
the right answers. It is just that I was not priting results in a
right manner.
I added : print i in version : print i

this solved my problem.

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


Re: WindowsXP / CTypes Module - unable to access function in a dll

2008-08-19 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hi,
> 
> I'm using the CTYPES module of python to load a dll. My dll contains a
> Get_Version function as:
> long __stdcall af1xEvdoRDll_GetVersion(long version[4]);
> 
> This function accepts a long array of 4 elements.
> 
> Following is the python code I've written:
> 
> from ctypes import *
> abc =  windll.af1xEvdoRDll
> GetVersion = abc.af1xEvdoRDll_GetVersion
> print GetVersion
> versionArr = c_long * 4#array of 4 longs
> version = versionArr(0, 0, 0, 0) # initializing all elements to 0
> GetVersion(version)#calling dll function
> print version
> 
> I'm getting the following output:
> <_FuncPtr object at 0x00A1EB70>
> <__main__.c_long_Array_4 object at 0x00A86300>
> 
> But I'm not getting the desired output which I expect as : 2.1.5.0
> 
> 
> Please suggest what am I missig?

Don't print the object, print it's contents:

for i in xrange(4):
print version[i]

Might be that you can iterate over the array directly, not sure right now.

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


Re: WindowsXP / CTypes Module - unable to access function in a dll

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


print version

I'm getting the following output:
<_FuncPtr object at 0x00A1EB70>
<__main__.c_long_Array_4 object at 0x00A86300>

But I'm not getting the desired output which I expect as : 2.1.5.0


expecting that Python/ctypes should be able to figure out that you
want an array of 4 integers printed as a dot-separated string is a
bit optimistic, perhaps.  but nothing that a little explicit string 
formatting cannot fix:


>>> from ctypes import *
>>> versionArr = c_long * 4
>>> version = versionArr(1, 2, 3, 4)
>>> "%d.%d.%d.%d" % tuple(version)
'1.2.3.4'



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


WindowsXP/ CTypes - How to convert ctypes array to a string?

2008-08-19 Thread dudeja . rajat
Hi,

I've used CTYPES module to access a function from a dll. This function
provides me the version of the dll. This information is accessible to
me as an array of 4 long inetegers. information as :
2, 1, 5, 0


I want to display these elements concatenated as "v2.1.5.0". This
string ( I'm thinking of writing the above 4 array elements to a
string) is to be displayed as label in a GUI ( the GUI used is Tk)

Please suggest how can I write these elements to a string to get me
the desired results as "v2.1.5.0". And, is writing to a string is
right way?

PS: this string also needs to be displayed in the GUI label well.


FYI, the code written to access function from dll is as under:

from ctypes import *
abc =  windll.af1xEvdoRDll
GetVersion = abc.af1xEvdoRDll_GetVersion
print GetVersion
versionArr = c_long * 4
version = versionArr(0, 0, 0, 0)
GetVersion(version)
print version
for i in version: print i

*
Results are : 2, 1, 5, 0

Cheers,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting pid of a remote process

2008-08-19 Thread srinivasan srinivas
Thanks a lot.
But i am wondeing will it return correct pid if more than one instance of 
 run on the remote machine??
Thanks,
Srini



- Original Message 
From: Diez B. Roggisch <[EMAIL PROTECTED]>
To: python-list@python.org
Sent: Tuesday, 19 August, 2008 2:54:52 PM
Subject: Re: Getting pid of a remote process

srinivasan srinivas wrote:

> This is wat i am doing :
> 
> args = [ "SSH", ,  ]
> I am giving this to subprocess.Popen()
> Thanks,
> Srini

Then the answer is simple: how would you figure out the remote process pid
using ssh? Once you found that out, pass that to Popen. Make sure you
capture stdout of the Popen-class to get the answer.

Something like

ps aux | grep  | grep -v grep | awk '{print $2}'

should be the command.

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


  Cricket on your mind? Visit the ultimate cricket website. Enter 
http://in.sports.yahoo.com/cricket/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Passing an object through COM which acts like str but isn't

2008-08-19 Thread Rafe
On Aug 16, 1:25 am, Wolfgang Grafen <[EMAIL PROTECTED]>
wrote:
> Rafeschrieb:
>
> > On Aug 15, 10:27 pm, Wolfgang Grafen <[EMAIL PROTECTED]>
> > wrote:
> >>Rafeschrieb:
>
> >>> Now if I try to pass this as I would a string, roughly like so...
> >> s = StrLike("test")
> >> Application.AnObject.attribute = "test" # works fine
> >> Application.AnObject.attribute = s
> >>> ERROR : Traceback (most recent call last):
> >>>   File "

Re: WindowsXP/ CTypes - How to convert ctypes array to a string?

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


I've used CTYPES module to access a function from a dll. This function
provides me the version of the dll. This information is accessible to
me as an array of 4 long inetegers. information as :
2, 1, 5, 0

I want to display these elements concatenated as "v2.1.5.0". This
string ( I'm thinking of writing the above 4 array elements to a
string) is to be displayed as label in a GUI ( the GUI used is Tk)

Please suggest how can I write these elements to a string to get me
the desired results as "v2.1.5.0". And, is writing to a string is
right way?


any special reason why you're not reading replies to your previous post?

here's what I wrote last time.

expecting that Python/ctypes should be able to figure out that you
want an array of 4 integers printed as a dot-separated string is a
bit optimistic, perhaps.  but nothing that a little explicit string 
formatting cannot fix:


>>> from ctypes import *
>>> versionArr = c_long * 4
>>> version = versionArr(1, 2, 3, 4)
>>> "%d.%d.%d.%d" % tuple(version)
'1.2.3.4'

inserting a "v" in the format string gives you the required result:

>>> "v%d.%d.%d.%d" % tuple(version)
'v1.2.3.4'



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


Re: Handling Property and internal ('__') attribute inheritance and creation

2008-08-19 Thread Bruno Desthuilliers

Fredrik Lundh a écrit :

Eric Brunel wrote:

To add to what others have already said, it is not only 'just extra 
work', it is also quite dangerous. See:


class A(object):
  children = []


the OP is aware of that, of course:

 > I set anything that is constant but anything variable is set again in
 > __init__()

as long as if you're aware of the issues involved (which you should be 
if you're using Python professionally), using class-level attributes is 
a perfectly valid Python style.


Using class attributes is perfectly valid Python style, indeed. But in 
this case - ie: using class attributes as a pseudo-declaration of 
instance attributes -, I would not call this good style : it's a waste 
of time, a violation of DRY, and a potential source of confusion for the 
class's users / maintainers.

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


How to stop iteration with __iter__() ?

2008-08-19 Thread ssecorp
I want a parse a file of the format:
movieId
customerid, grade, date
customerid, grade, date
customerid, grade, date
etc.

so I could do with open file as reviews and then for line in reviews.

but first I want to take out the movie id so I use an iterator.

then i want to iterate through all the rows, but how can I do:
while movie_iter != None:

because that doesn't work, itraises an exception, StopItreation, which
according to the documentation it should. But catching an exception
can't be the standard way to stop iterating right?
--
http://mail.python.org/mailman/listinfo/python-list


Re: WindowsXP/ CTypes - How to convert ctypes array to a string?

2008-08-19 Thread dudeja . rajat
On Tue, Aug 19, 2008 at 12:20 PM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
>> I've used CTYPES module to access a function from a dll. This function
>> provides me the version of the dll. This information is accessible to
>> me as an array of 4 long inetegers. information as :
>> 2, 1, 5, 0
>>
>> I want to display these elements concatenated as "v2.1.5.0". This
>> string ( I'm thinking of writing the above 4 array elements to a
>> string) is to be displayed as label in a GUI ( the GUI used is Tk)
>>
>> Please suggest how can I write these elements to a string to get me
>> the desired results as "v2.1.5.0". And, is writing to a string is
>> right way?
>
> any special reason why you're not reading replies to your previous post?
>
> here's what I wrote last time.
>
> expecting that Python/ctypes should be able to figure out that you
> want an array of 4 integers printed as a dot-separated string is a
> bit optimistic, perhaps.  but nothing that a little explicit string
> formatting cannot fix:
>
 from ctypes import *
 versionArr = c_long * 4
 version = versionArr(1, 2, 3, 4)
 "%d.%d.%d.%d" % tuple(version)
> '1.2.3.4'
>
> inserting a "v" in the format string gives you the required result:
>
 "v%d.%d.%d.%d" % tuple(version)
> 'v1.2.3.4'
>
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Fredrik,
My apology for any confusion created.
I read all the replies. In fact I'm thankful to you all guys who are
responding so quickly to all questions.

I also add the letter 'v' same as you suggested. However, I'm looking
to store this into some variable ( that variable could be be a string,
tuple or anything, Im not sure which is the suited one) so that I can
access it in some other module that will then display this version
information in a Label Widet in GUI.

So, what is the best way to store 'v1.2.3.4' in a variable? And, what
type of variable is most suited (so as able to be used in other module
probably, as string there)?

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


Code for locking a resource

2008-08-19 Thread tarun
Hello All,

I've a configuration.ini file. This particular can be accessed by several
threads of my application. Each thread can read/write configuration
parameters from/to the configuration.ini file. I am using threading (Rlock)
to lock the resource (configuration.ini file) while accessing it from any
thread. I use the file available at
http://www.voidspace.org.uk/python/configobj.html for read/write.
(configobj.py)

I've used RLock to lock the resource.

I see this error while accessing variables of the configuration.ini file

Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Python25\lib\threading.py", line 460, in __bootstrap
self.run()
  File "F:\abc.py", line 229, in run
option1 = conf['OPT1']
  File "F:\configobj.py", line 551, in __getitem__
val = dict.__getitem__(self, key)
KeyError: 'OPT1'

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python25\lib\threading.py", line 460, in __bootstrap
self.run()
  File "F:\def.py", line 130, in run
option2 = self.conf['OPT2']
  File "F:\configobj.py", line 551, in __getitem__
val = dict.__getitem__(self, key)
KeyError: 'OPT2'

Can any one help me with a code for locking a resource across threads.

One more observation. I tried the following code on Python Idle

>>> import threading
>>> threading.RLock()
<_RLock(None, 0)>
>>> threading.Lock()


Why does threading.RLock() return None

Thanks In Advance,
Tarun
--
http://mail.python.org/mailman/listinfo/python-list

Re: How to stop iteration with __iter__() ?

2008-08-19 Thread Jeff
On Aug 19, 7:39 am, ssecorp <[EMAIL PROTECTED]> wrote:
> I want a parse a file of the format:
> movieId
> customerid, grade, date
> customerid, grade, date
> customerid, grade, date
> etc.
>
> so I could do with open file as reviews and then for line in reviews.
>
> but first I want to take out the movie id so I use an iterator.
>
> then i want to iterate through all the rows, but how can I do:
> while movie_iter != None:
>
> because that doesn't work, itraises an exception, StopItreation, which
> according to the documentation it should. But catching an exception
> can't be the standard way to stop iterating right?

No.  If you are defining the iterator, then the iterator raises
StopIteration when it is complete.  It is not an exception you
normally catch; you use a for loop to iterate, and the machinery of
the for loop uses the StopIteration exception to tell it when to
break.  A file-like object is itself a line iterator, so:

def review_iter(file_obj):
  for line in file_obj:
if matches_some_pattern(line):
  yield line

Then, to use it:

file_obj = open('/path/to/some/file.txt')
try:
  for review in review_iter(file_obj):
do_something(review)
finally:
  file_obj.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to stop iteration with __iter__() ?

2008-08-19 Thread Jon Clements
On Aug 19, 12:39 pm, ssecorp <[EMAIL PROTECTED]> wrote:
> I want a parse a file of the format:
> movieId
> customerid, grade, date
> customerid, grade, date
> customerid, grade, date
> etc.
>
> so I could do with open file as reviews and then for line in reviews.
>
> but first I want to take out the movie id so I use an iterator.
>
> then i want to iterate through all the rows, but how can I do:
> while movie_iter != None:
>
> because that doesn't work, itraises an exception, StopItreation, which
> according to the documentation it should. But catching an exception
> can't be the standard way to stop iterating right?

Given your example, why not just open the file and call .next() on it
to discard the first row, then iterate using for as usual?

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


Re: How to stop iteration with __iter__() ?

2008-08-19 Thread Leo Jay
On Tue, Aug 19, 2008 at 7:39 PM, ssecorp <[EMAIL PROTECTED]> wrote:
> I want a parse a file of the format:
> movieId
> customerid, grade, date
> customerid, grade, date
> customerid, grade, date
> etc.
>
> so I could do with open file as reviews and then for line in reviews.
>
> but first I want to take out the movie id so I use an iterator.
>
> then i want to iterate through all the rows, but how can I do:
> while movie_iter != None:
>
> because that doesn't work, itraises an exception, StopItreation, which
> according to the documentation it should. But catching an exception
> can't be the standard way to stop iterating right?
>

you can use for loop:
for line in movie_iter:
   ...



-- 
Best Regards,
Leo Jay
--
http://mail.python.org/mailman/listinfo/python-list


Question regarding the standard library?

2008-08-19 Thread Hussein B
Hey,
Is the standard library of Python is compiled (you know, the pyc
thing)?
Is it allowed to edit the source code of the standard library?
I'm not talking about submitting the modified code to Python source
code repository, I'm just asking if some one can edit the source code
in his own machine.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: WindowsXP/ CTypes - How to convert ctypes array to a string?

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


I also add the letter 'v' same as you suggested. However, I'm looking
to store this into some variable ( that variable could be be a string,
tuple or anything, Im not sure which is the suited one)


the expression gives you a string object; you'll store it in a variable 
in the same way as you'd store any other expression result in Python.


   version = "v%d.%d.%d.%d" % tuple(version)

but when you find yourself getting stuck on things like this, it might a 
good idea to take a step back and read the tutorial again:


http://docs.python.org/tut/tut.html

pay special attention to the parts that discuss how variables work in 
Python.


if you prefer some other entry level tutorial, the following is said to 
be really good:


http://www.ibiblio.org/g2swap/byteofpython/read/



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


Re: Question regarding the standard library?

2008-08-19 Thread Fredrik Lundh

Hussein B wrote:


Is the standard library of Python is compiled (you know, the pyc
thing)?
Is it allowed to edit the source code of the standard library?
I'm not talking about submitting the modified code to Python source
code repository, I'm just asking if some one can edit the source code
in his own machine.


Python ships with the library sources, and you can of course edit them 
in exactly the same way as you'll edit any other Python file.  modules 
in the standard library are no different from your own modules in that 
respect.


whether it's a good idea to edit them (unless you're trying to track 
down bugs or provide patches to the maintainers) is a different issue.




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


Re: WindowsXP/ CTypes - How to convert ctypes array to a string?

2008-08-19 Thread dudeja . rajat
On Tue, Aug 19, 2008 at 12:40 PM,  <[EMAIL PROTECTED]> wrote:
> On Tue, Aug 19, 2008 at 12:20 PM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>
>>> I've used CTYPES module to access a function from a dll. This function
>>> provides me the version of the dll. This information is accessible to
>>> me as an array of 4 long inetegers. information as :
>>> 2, 1, 5, 0
>>>
>>> I want to display these elements concatenated as "v2.1.5.0". This
>>> string ( I'm thinking of writing the above 4 array elements to a
>>> string) is to be displayed as label in a GUI ( the GUI used is Tk)
>>>
>>> Please suggest how can I write these elements to a string to get me
>>> the desired results as "v2.1.5.0". And, is writing to a string is
>>> right way?
>>
>> any special reason why you're not reading replies to your previous post?
>>
>> here's what I wrote last time.
>>
>> expecting that Python/ctypes should be able to figure out that you
>> want an array of 4 integers printed as a dot-separated string is a
>> bit optimistic, perhaps.  but nothing that a little explicit string
>> formatting cannot fix:
>>
> from ctypes import *
> versionArr = c_long * 4
> version = versionArr(1, 2, 3, 4)
> "%d.%d.%d.%d" % tuple(version)
>> '1.2.3.4'
>>
>> inserting a "v" in the format string gives you the required result:
>>
> "v%d.%d.%d.%d" % tuple(version)
>> 'v1.2.3.4'
>>
>> 
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> Fredrik,
> My apology for any confusion created.
> I read all the replies. In fact I'm thankful to you all guys who are
> responding so quickly to all questions.
>
> I also add the letter 'v' same as you suggested. However, I'm looking
> to store this into some variable ( that variable could be be a string,
> tuple or anything, Im not sure which is the suited one) so that I can
> access it in some other module that will then display this version
> information in a Label Widet in GUI.
>
> So, what is the best way to store 'v1.2.3.4' in a variable? And, what
> type of variable is most suited (so as able to be used in other module
> probably, as string there)?
>
> Thanks,
> Rajat
>

Googled and found :

s = "v%d.%d.%d.%d" % tuple(version)
print s

it's working.

Result is : v1.2.3.4

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


optparse escaping control characters

2008-08-19 Thread wannymahoots
optparse seems to be escaping control characters that I pass as
arguments on the command line.  Is this a bug?  Am I missing
something?  Can this be prevented, or worked around?

This behaviour doesn't occur with non-control characters.

For example, if this program (called test.py):
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-d", dest="delimiter", action="store")
(options, args) = parser.parse_args()
print options

is run as follows:
python test.py -d '\t'

it outputs:
{'delimiter': '\\t'}

i.e. the \t has had an escape character added to give \\t.

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


ANN: Resolver One 1.2 released

2008-08-19 Thread [EMAIL PROTECTED]
We are proud to announce the release of Resolver One, version 1.2 -
the largest IronPython application in the world, we think, at 38,000
lines of production code backed up by 150,000 lines of unit and
functional tests.

Resolver One is a Rapid Application Development tool for analysing and
presenting business data, using a familiar spreadsheet interface
combined with a powerful IronPython-based scripting capability that
allows you to insert your own code directly into the recalculation
loop.

For version 1.2, we have on big headline feature; a new function
called
RunWorkbook that allows you to "call" one spreadsheet from another,
passing in parameters and pulling out results - just like functions,
but
without having to code the function by hand.  This allows you to mix
spreadsheet-based and code-based logic, using the best paradigm for
the job in hand.

We've also added a whole bunch of usability enhancements - the full
(long!) changelist is up on our website, or you can see a screencast:
 

It's free for non-commercial use, so if you would like to take a
look,
you can download it from our website:
 (registration no longer
required).


Best regards,

Giles
--
Giles Thomas
MD & CTO, Resolver Systems Ltd.
[EMAIL PROTECTED]
+44 (0) 20 7253 6372

Try out Resolver One! 

17a Clerkenwell Road, London EC1M 5RD, UK
VAT No.: GB 893 5643 79 Registered in England and Wales as company
number 5467329.
Registered address: 843 Finchley Road, London NW11 8NA, UK
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse escaping control characters

2008-08-19 Thread Hrvoje Niksic
[EMAIL PROTECTED] writes:

> optparse seems to be escaping control characters that I pass as
> arguments on the command line.  Is this a bug?  Am I missing
> something?  Can this be prevented, or worked around?

It has nothing to do with optparse, it's how Python prints strings:

$ python -c 'import sys; print sys.argv' '\t'
['-c', '\\t']

Note that you're not really passing a control character to Python,
you're passing a two-character string consisting of \ and t.  When
representing the string inside a data structure, Python escapes the \
to avoid confusion with a real control character such as \t.

If you try printing the string itself, you'll see that everything is
correct:

$ python -c 'import sys; print sys.argv[1]' '\t'
\t
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting pid of a remote process

2008-08-19 Thread Diez B. Roggisch
srinivasan srinivas wrote:

> Thanks a lot.
> But i am wondeing will it return correct pid if more than one instance of
>  run on the remote machine?? Thanks,

What do you *think*? How about *trying* that out first? 

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


Re: optparse escaping control characters

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


optparse seems to be escaping control characters that I pass as
arguments on the command line.  Is this a bug?  Am I missing
something?


you're missing the distinction between the content of a string object, 
and how the corresponding string literal looks.


>>> x = {'delimiter': '\\t'}
>>> x
{'delimiter': '\\t'}
>>> x["delimiter"]
'\\t'
>>> print x["delimiter"]
\t
>>> len(x["delimiter"])
2



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


Re: optparse escaping control characters

2008-08-19 Thread Dan Halligan
On Aug 19, 1:45 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] writes:
> > optparse seems to be escaping control characters that I pass as
> > arguments on the command line.  Is this a bug?  Am I missing
> > something?  Can this be prevented, or worked around?
>
> It has nothing to do with optparse, it's how Python prints strings:
>
> $ python -c 'import sys; print sys.argv' '\t'
> ['-c', '\\t']
>
> Note that you're not really passing a control character to Python,
> you're passing a two-character string consisting of \ and t.  When
> representing the string inside a data structure, Python escapes the \
> to avoid confusion with a real control character such as \t.
>
> If you try printing the string itself, you'll see that everything is
> correct:
>
> $ python -c 'import sys; print sys.argv[1]' '\t'
> \t

Thanks for the reply, much clearer now, just one more question.  How
would I pass a control character to python on the command line?

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


Re: Question regarding the standard library?

2008-08-19 Thread Hussein B
On Aug 19, 7:16 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Hussein B wrote:
> > Is the standard library of Python is compiled (you know, the pyc
> > thing)?
> > Is it allowed to edit the source code of the standard library?
> > I'm not talking about submitting the modified code to Python source
> > code repository, I'm just asking if some one can edit the source code
> > in his own machine.
>
> Python ships with the library sources, and you can of course edit them
> in exactly the same way as you'll edit any other Python file.  modules
> in the standard library are no different from your own modules in that
> respect.
>
> whether it's a good idea to edit them (unless you're trying to track
> down bugs or provide patches to the maintainers) is a different issue.
>
> 

Thanks.
Is the standard library compiled?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question regarding the standard library?

2008-08-19 Thread George Sakkis
On Aug 19, 8:16 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> Hussein B wrote:
> > Is the standard library of Python is compiled (you know, the pyc
> > thing)?
> > Is it allowed to edit the source code of the standard library?
> > I'm not talking about submitting the modified code to Python source
> > code repository, I'm just asking if some one can edit the source code
> > in his own machine.
>
> Python ships with the library sources, and you can of course edit them
> in exactly the same way as you'll edit any other Python file.  modules
> in the standard library are no different from your own modules in that
> respect.
>
> whether it's a good idea to edit them (unless you're trying to track
> down bugs or provide patches to the maintainers) is a different issue.
>
> 

A less invasive approach is monkey-patching [1], i.e. extend or modify
the runtime behavior without altering the original source code. For
instance I recently needed to patch the bug posted at
http://bugs.python.org/issue1651995 and I didn't have write access to
the standard library, so I monkeypatched SGMLParser:

# XXX: monkeypatch SGMLParser to fix bug introduced in 2.5
# http://bugs.python.org/issue1651995
if sys.version_info[:2] == (2,5):
from sgmllib import SGMLParser
SGMLParser.convert_codepoint = lambda self,codepoint:
unichr(codepoint)


HTH,
George

[1] http://en.wikipedia.org/wiki/Monkey_patch
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse escaping control characters

2008-08-19 Thread John Machin
On Aug 19, 10:35 pm, [EMAIL PROTECTED] wrote:
> optparse seems to be escaping control characters that I pass as
> arguments on the command line.  Is this a bug?  Am I missing
> something?  Can this be prevented, or worked around?
>
> This behaviour doesn't occur with non-control characters.
>
> For example, if this program (called test.py):
> from optparse import OptionParser
> parser = OptionParser()
> parser.add_option("-d", dest="delimiter", action="store")
> (options, args) = parser.parse_args()
> print options
>
> is run as follows:
> python test.py -d '\t'
>
> it outputs:
> {'delimiter': '\\t'}
>
> i.e. the \t has had an escape character added to give \\t.

You are inputting a TWO-byte string composed of a backslash and a
lowercase t, and feeding that to OptionParser.

C:\junk>type test.py
import sys; a = sys.argv[1]; d = {'delimiter': a}
print len(a), a, str(a), repr(a)
print d

# Note: this is Windows, where the shell quote is ", not '
C:\junk>python test.py "\t"
2 \t \t '\\t'
{'delimiter': '\\t'}

The extra backslash that you see is caused by the (implicit) use of
repr() to display the string.

If you want/need to enter a literal TAB character in the command line,
consult the manual for your shell.

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: searching through a string and pulling characters

2008-08-19 Thread Wojtek Walczak
On Mon, 18 Aug 2008 15:34:12 -0700 (PDT), Alexnb wrote:

> Also, on a side-note, does anyone know a very simple dictionary site, that
> isn't dictionary.com or yourdictionary.com.

This one is my favourite: http://www.lingro.com/


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


View this blogspot

2008-08-19 Thread srinu
http://indianmasalavideos4u.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


View this blogspot

2008-08-19 Thread srinu
http://indianmasalavideos4u.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Eggs and Gems

2008-08-19 Thread Hussein B
Hey,
Are Python eggs and RubyGems do the same thing (of course Gems is for
Ruby and eggs is for Python)?
If yes, is it outstanding as the RubyGems?
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question regarding the standard library?

2008-08-19 Thread Fredrik Lundh

Hussein B wrote:


Is the standard library compiled?


the portions are written in Python are compiled to PYC files, just like 
modules you write yourself are automatically compiled to PYC files when 
you import them.


(why not just look in the Python installation tree?  it's all there for 
you to tinker with.)




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


Re: optparse escaping control characters

2008-08-19 Thread Steven D'Aprano
On Tue, 19 Aug 2008 05:35:27 -0700, wannymahoots wrote:

> optparse seems to be escaping control characters that I pass as
> arguments on the command line.  Is this a bug?  Am I missing something? 
> Can this be prevented, or worked around?

You are misinterpreting the evidence. Here's the short explanation:

optparse isn't escaping a control character, because you're not supplying 
it with a control character. You're supplying it with two normal 
characters, which merely *look* like five (including the quote marks) 
because of Python's special handling of backslashes.


If you need it, here's the long-winded explanation.

I've made a small change to your test.py file to demonstrate:

# test.py (modified)
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-d", dest="delimiter", action="store")
(options, args) = parser.parse_args()
print "Options:", options
print "str of options.delimiter =", str(options.delimiter)
print "repr of options.delimiter =", repr(options.delimiter)
print "len of options.delimiter =", len(options.delimiter)


Here's what it does when I call it:

$ python test.py -d '\t'
Options: {'delimiter': '\\t'}
str of options.delimiter = \t
repr of options.delimiter = '\\t'
len of options.delimiter = 2


When you pass '\t' in the command line, the shell sends a literal 
backslash followed by a lowercase t to Python. That is, it sends the 
literal string '\t', not a control character.

Proof: pass the same string to the "wc" program using "echo". Don't 
forget that echo adds a newline to the string:

$ echo 't' | wc  # just a t
  1   1   2
$ echo '\t' | wc  # a backslash and a t, not a control character
  1   1   3


That's the first half of the puzzle. Now the second half -- why is Python 
adding a *second* backslash to the backslash-t? Actually, it isn't, but 
it *seems* to be adding not just a second backslash but also two quote 
marks.

The backslash in Python is special. If you wanted a literal backslash t 
in a Python string, you would have to type *two* backslashes:

'\\t'

because a single backslash followed by t is escaped to make a tab 
character.

But be careful to note that even though you typed five characters (quote, 
backslash, backslash, t, quote) Python creates a string of length two: a 
single backslash and a t.

Now, when you print something using the str() function, Python hides all 
that complexity from you. Hence the line of output that looks like this:

str of options.delimiter = \t

The argument is a literal backslash followed by a t, not a tab character.

But when you print using the repr() function, Python shows you what you 
would have typed -- five characters as follows:

repr of options.delimiter = '\\t'

But that's just the *display* of a two character string. The actual 
string itself is only two characters, despite the two quotes and the two 
backslashes.

Now for the final piece of the puzzle: when you print most composite 
objects, like the OptParse Value objects -- the object named "options" in 
your code -- Python prints the internals of it using repr() rather than 
str().



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


Re: Question regarding the standard library?

2008-08-19 Thread Hussein B
On Aug 19, 8:10 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Aug 19, 8:16 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hussein B wrote:
> > > Is the standard library of Python is compiled (you know, the pyc
> > > thing)?
> > > Is it allowed to edit the source code of the standard library?
> > > I'm not talking about submitting the modified code to Python source
> > > code repository, I'm just asking if some one can edit the source code
> > > in his own machine.
>
> > Python ships with the library sources, and you can of course edit them
> > in exactly the same way as you'll edit any other Python file.  modules
> > in the standard library are no different from your own modules in that
> > respect.
>
> > whether it's a good idea to edit them (unless you're trying to track
> > down bugs or provide patches to the maintainers) is a different issue.
>
> > 
>
> A less invasive approach is monkey-patching [1], i.e. extend or modify
> the runtime behavior without altering the original source code. For
> instance I recently needed to patch the bug posted 
> athttp://bugs.python.org/issue1651995and I didn't have write access to
> the standard library, so I monkeypatched SGMLParser:
>
> # XXX: monkeypatch SGMLParser to fix bug introduced in 2.5
> #http://bugs.python.org/issue1651995
> if sys.version_info[:2] == (2,5):
> from sgmllib import SGMLParser
> SGMLParser.convert_codepoint = lambda self,codepoint:
> unichr(codepoint)
>
> HTH,
> George
>
> [1]http://en.wikipedia.org/wiki/Monkey_patch

Hmmm, nice to know about it :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting pid of a remote process

2008-08-19 Thread Miles
On Mon, Aug 18, 2008 at 9:34 AM, srinivasan srinivas wrote:
> Could you please suggest me a way to find pid of a process started on a 
> remote machine by the current process??

If ps + grep (or the more robust tool pgrep) won't work because you're
running more than one instance at once, try this: instead of running
the process via SSH directly, write a small wrapper script which runs
the process locally and saves the PID to a file on the machine (or
prints it to stdout if the program itself has no output), and then run
that wrapper remotely.

For example:

import subprocess, sys
f = open(sys.argv[1], 'w')
p = subprocess.Popen(sys.argv[2:])
print >>f, p.pid
f.close()

You may have to be careful with the quoting of the arguments, since
OpenSSH uses a shell to execute the command.  You could then obtain
the pid with something along the lines of:

int(subprocess.Popen(['ssh', , 'cat', ],
stdout=subprocess.PIPE).stdout.read())

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


Re: ANN: Resolver One 1.2 released

2008-08-19 Thread km
Hi,
sounds great - but disappointing to find it only available on window$.
Is there any Linux release in near future ???
KM

~~
On Tue, Aug 19, 2008 at 6:10 PM, [EMAIL PROTECTED] <
[EMAIL PROTECTED]> wrote:

> We are proud to announce the release of Resolver One, version 1.2 -
> the largest IronPython application in the world, we think, at 38,000
> lines of production code backed up by 150,000 lines of unit and
> functional tests.
>
> Resolver One is a Rapid Application Development tool for analysing and
> presenting business data, using a familiar spreadsheet interface
> combined with a powerful IronPython-based scripting capability that
> allows you to insert your own code directly into the recalculation
> loop.
>
> For version 1.2, we have on big headline feature; a new function
> called
> RunWorkbook that allows you to "call" one spreadsheet from another,
> passing in parameters and pulling out results - just like functions,
> but
> without having to code the function by hand.  This allows you to mix
> spreadsheet-based and code-based logic, using the best paradigm for
> the job in hand.
>
> We've also added a whole bunch of usability enhancements - the full
> (long!) changelist is up on our website, or you can see a screencast:
>  
>
> It's free for non-commercial use, so if you would like to take a
> look,
> you can download it from our website:
>  (registration no longer
> required).
>
>
> Best regards,
>
> Giles
> --
> Giles Thomas
> MD & CTO, Resolver Systems Ltd.
> [EMAIL PROTECTED]
> +44 (0) 20 7253 6372
>
> Try out Resolver One! 
>
> 17a Clerkenwell Road, London EC1M 5RD, UK
> VAT No.: GB 893 5643 79 Registered in England and Wales as company
> number 5467329.
> Registered address: 843 Finchley Road, London NW11 8NA, UK
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: optparse escaping control characters

2008-08-19 Thread wannymahoots
Thanks for all the responses!
--
http://mail.python.org/mailman/listinfo/python-list


Re: optparse escaping control characters

2008-08-19 Thread Hrvoje Niksic
Dan Halligan <[EMAIL PROTECTED]> writes:

> How would I pass a control character to python on the command line?

It depends on which command line you are using.  Most Unix-like shells
will allow you to input a control character by preceding it with ^V.
Since \t is the TAB character, you should be able to input it like
this:

$ python -c 'import sys; print sys.argv' '^V'
['-c', '\t'] # note single backslash
--
http://mail.python.org/mailman/listinfo/python-list


How to use win32com to convert a MS WORD doc to HTML ?

2008-08-19 Thread Lave
Hi, all !

I'm a totally newbie huh:)

I want to convert MS WORD docs to HTML, I found python windows
extension win32com can make this. But I can't find the method, and I
can't find any document helpful.

Can anyone help me? Thank in advance.
--
http://mail.python.org/mailman/listinfo/python-list


RE: How to use win32com to convert a MS WORD doc to HTML ?

2008-08-19 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Lave
> Sent: Tuesday, August 19, 2008 10:06 AM
> To: python-list@python.org
> Subject: How to use win32com to convert a MS WORD doc to HTML ?
> 
> Hi, all !
> 
> I'm a totally newbie huh:)
> 
> I want to convert MS WORD docs to HTML, I found python windows
> extension win32com can make this. But I can't find the method, and I
> can't find any document helpful.
> 

Word Object Model:  
http://msdn.microsoft.com/en-us/library/bb244515.aspx

Specifically look at Document's SaveAs method.

*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA621


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


who to call a list of method inside the class itself

2008-08-19 Thread maduma
Hi,

Is the following code is ok. who to call all method.
It is working but the call to m() without a reference to self seems
strange

Thanks for your help

class CustomMethod:
def method1(self):

def method2(self):

def method3(self):
   

def getAllMethod(self):
return [self.method1, self.method2, self.method3]

def applyAll(self):
for m in self.getAllMethod():
# how to call all methods ?
# is it correct
m()

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


Re: who to call a list of method inside the class itself

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


Is the following code is ok. who to call all method.
It is working but the call to m() without a reference to self seems
strange

Thanks for your help

class CustomMethod:
def method1(self):

def method2(self):

def method3(self):
   

def getAllMethod(self):
return [self.method1, self.method2, self.method3]

def applyAll(self):
for m in self.getAllMethod():
# how to call all methods ?
# is it correct
m()


what happens when you run the code?



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


HTML Tables

2008-08-19 Thread Amie
Hi,
Thanks for your help so far. Ok here's a scenario: I have to create a
site that displays 34 html  tables.
In each of these tables the following information has to be displayed:
logo (image), site name, date, time.
Remember: in all of these 34 tables. the information displayed on each
of these tables is retrieved from the database. I did write a mysql
query, I just don't know how to link it with the for loop that has to
display all these tables. If anyone can, can you roughly show me how
to go about doing this.
Thanks in advance


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


Display the results of a query to an html table

2008-08-19 Thread Amie
Hi,
how do you display the results of an sql query and display it onto the
html form or html table

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


Re: Handling Property and internal ('__') attribute inheritance and creation

2008-08-19 Thread Rafe
On Aug 16, 1:22 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Rafea écrit :
>
> > Hi,
>
> > I've been thinking in circles about these aspects of Pythonic design
> > and I'm curious what everyone else is doing and thinks. There are 3
> > issues here:
>
> > 1) 'Declaring' attributes
>
> There's nothing like "declaration" of variables/attributes/whatever in
> Python.
>
> > - I always felt it was good code practice to
> > declare attributes in a section of the class namespace. I set anything
> > that is constant but anything variable is set again  in __init__():
>
> > Class A(object):
> > name = "a name"
> > type = "a typee"
> > childobject = None
>
> > def __init__(self, obj):
> > self.childobject = object
>
> > This makes it easy to remember and figure out what is in the class.
> > Granted there is nothing to enforce this, but that is why I called it
> > 'code practice'. Do you agree or is this just extra work?
>
> It's not only extra work, it's mostly a WTF. You create class attributes
> for no other reasons than to mimic some other mainstream languages. If I
> was to maintain such code, I'd loose valuable time wondering where these
> class attributes are used.
>
>
>
> > 2) Internal attributes (starting with 2x'_') aren't inherited.
>
> Yes they are. But you need to manually mangle them when trying to access
> them from a child class method. FWIW, that *is* the point of
> __name_mangling  : making sure these attributes won't be accidentally
> overwritten in a child class.
>
> > Do you
> > just switch to a single '_' when you want an "internal" attribute
> > inherited? These are attributes I want the classes to use but not the
> > user of these classes. Of course, like anything else in Python, these
> > aren't really private. It is just a convention, right? (The example
> > for #3 shows this.)
>
> Yes. The (*very* strong) convention is that
> _names_with_simple_leading_underscore denote implementation attributes.
>
>
>
> > 3) It isn't possible to override a piece of a Property Descriptor. To
> > get around this, I define the necessary functions in the class but I
> > define the descriptor in the __new__() method so the inherting class
> > can override the methods. Am I overlooking some basic design principle
> > here? This seems like a lot of work for a simple behavior. Example:
>
> > class Base(object):
> > def __new__(cls):
> > setattr(cls,
> > "state",
> > property(fget = cls._Get_state,
> >  fset = cls._Set_state,
> >  fdel = None,
> >  doc  = cls._doc_state))
>
> > obj = super(Base, cls).__new__(cls)
> > return obj
>
> > state = None# Set in __new__()
> > _state = True
> > _doc_state = "The state of this object"
> > def _Get_state(self): return self._state
> > def _Set_state(self, value): self._state = value
>
> pep08 : attribute names (including methods) should be all_lower.
>
> > class Child(Base):
> > def _Get_state(self):
> > # Do some work before getting the state.
> > print "Getting the state using the child's method"
> > return self._state
>
> > print Child().state
>
> How often do you really need to override a property ? (hint : as far as
> I'm concerned, it never happened so far). Now you have two solutions :
> either redefine the whole property in the derived class, or, if you
> really intend your property to be overriden, provide a "template method"
> hook.
>
> I'd say you're making things much more complicated than they need to be.


Thanks Bruno, and everyone ! These are exactly the type of hard
answers I was hoping for. I'm mostly converted but my brain still
needs a Pythonic push from time to time. Looks like have some some
clean up to perform...with confidence.

I'm interested to see the implementation of getter, etc overrides in
2.6/3.0. I have two classes that could be simplified with this. For
example, I have a class which does a lot of work and has about 5 key
properties. I want to inherit it, and just trigger an event (update
something only stored in the child) after 4 of these attributes are
finished being set. I was thinking about using a callback which is
empty in the parent or __setattr__() (but I hat using this unless I
have to, it is still troublesome to me).

- Rafe


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


Re: How to access an Array and a struct within a struct wrapped by Swig ?

2008-08-19 Thread jparker104
On Aug 17, 11:30 pm, [EMAIL PROTECTED] wrote:
> Anish Chapagain, I already know how to use structure, as my example
> shown it.
> I had trouble only with the nested structures, and it was coz of
> missing typedef (ie: Swig need C struct declaration, not C++).
>
> And I still cannot find how to get my arrays... :-S

I was having the same problem with arrays and found a workaround here:
http://www.swig.org/papers/PyTutorial97/PyTutorial97.pdf
slide 39, "Helper Functions" I got it to work, hope this helps
--
http://mail.python.org/mailman/listinfo/python-list


Re: who to call a list of method inside the class itself

2008-08-19 Thread maduma
On Aug 19, 4:33 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Is the following code is ok. who to call all method.
> > It is working but the call to m() without a reference to self seems
> > strange
>
> > Thanks for your help
>
> > class CustomMethod:
> > def method1(self):
> > 
> > def method2(self):
> > 
> > def method3(self):
> >
>
> > def getAllMethod(self):
> > return [self.method1, self.method2, self.method3]
>
> > def applyAll(self):
> > for m in self.getAllMethod():
> > # how to call all methods ?
> > # is it correct
> > m()
>
> what happens when you run the code?
>
> 
The code it is running fine but i just wondering if it's the syntax is
correct (avoid any side effect)

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


Re: who to call a list of method inside the class itself

2008-08-19 Thread Edwin . Madari

[EMAIL PROTECTED] wrote:
> Hi,
> 
> Is the following code is ok. who to call all method.
> It is working but the call to m() without a reference to self seems
> strange
> 
> Thanks for your help
> 
> class CustomMethod:
> def method1(self):
> 
> def method2(self):
> 
> def method3(self):
>
> 
> def getAllMethod(self):
> return [self.method1, self.method2, self.method3]
> 
> def applyAll(self):
> for m in self.getAllMethod():
> # how to call all methods ?
> # is it correct
> m()

1. return string names of required methods in getAllMethod
return ['method1', 'method2', 'method3']
2. use gettattr on self and then exetute methods in applyAll
def applyAll(self):
for method_name in self.getAllMethod():
method = gettattr(self,method_name)
  method() #execute method now

regards.
Edwin   




The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.


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


Re: who to call a list of method inside the class itself

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


def getAllMethod(self):
return [self.method1, self.method2, self.method3]
def applyAll(self):
for m in self.getAllMethod():
# how to call all methods ?
# is it correct
m()

what happens when you run the code?



The code it is running fine but i just wondering if it's the syntax is
correct (avoid any side effect)


It's the same thing as explicitly calling the three methods from inside 
the applyAll method.  You'll still get side effects if the methods have 
side effects, of course.


self.method1 and friends are "bound methods", that is, callable objects 
that are bound to both the object instance (self) and the actual method. 
   They're no different from the temporary bound methods that are used 
to carry out an ordinary method call ("self.method1()" is evaluated as 
"tmp = self.method1; tmp()" on the inside, where tmp is an internal 
variable)




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


Re: Display the results of a query to an html table

2008-08-19 Thread Marco Nawijn
On Aug 19, 4:35 pm, Amie <[EMAIL PROTECTED]> wrote:
> Hi,
> how do you display the results of an sql query and display it onto the
> html form or html table
>
> Thanks

Hello,

You might want to take a look at:
sqlobject http://www.sqlobject.org/
or
sqlalchemy http://www.sqlalchemy.org/

These can assist in translating SQL query results into Python objects.

For generating the html forms and tables out of the sql results data
you
can try:
genshi: http://genshi.edgewall.org/
kid: http://www.kid-templating.org/

I hope this helps.

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


Re: Eggs and Gems

2008-08-19 Thread Mike Driscoll
On Aug 19, 8:19 am, Hussein B <[EMAIL PROTECTED]> wrote:
> Hey,
> Are Python eggs and RubyGems do the same thing (of course Gems is for
> Ruby and eggs is for Python)?
> If yes, is it outstanding as the RubyGems?
> Thanks.

I've never used Ruby, so I can't say for sure, but I think they're
close. Read up on it and find out! Here are some good places to start:

http://peak.telecommunity.com/DevCenter/PythonEggs
http://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/
http://www.ibm.com/developerworks/library/l-cppeak3.html

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


Re: who to call a list of method inside the class itself

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


1. return string names of required methods in getAllMethod
return ['method1', 'method2', 'method3']
2. use gettattr on self and then exetute methods in applyAll
def applyAll(self):
for method_name in self.getAllMethod():
method = gettattr(self,method_name)
  method() #execute method now


why?



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


Cash Master

2008-08-19 Thread hello_mox_10
Cash Master
 
I've made £1260 in one week using this system and you could too.
Now in its fifth year, this Best Seller continues to transform thousands 
of ordinary peoples lives, and you can join them!

NO prior knowledge or experience in the betting industry.

A basic internet connection, dial-up will do!

Normal internet skills!

NO extra software required, this runs in Windows.

No need to visit high street bookies! You can do this all online.

Click here : http://easylnk.com/?6881
--
http://mail.python.org/mailman/listinfo/python-list

datetime.datetime.now() in military time

2008-08-19 Thread korean_dave
import datetime

def main():
timenow = datetime.datetime.now()
print(str(timenow.hour))


if __name__ == "__main__":
main()

If the time was, say, 2pm, how can I make output of timenow.hour "14"
instead of "2"?

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


Re: Factory for Struct-like classes

2008-08-19 Thread eliben
On Aug 18, 11:16 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> On 13 ago, 14:46, eliben <[EMAIL PROTECTED]> wrote:
>
> > On Aug 13, 7:30 pm, Christian Heimes <[EMAIL PROTECTED]> wrote:
>
> > > eliben wrote:
> > > > Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html)
> > > > does this. I suppose it can be done with 'exec', but is there a more
> > > > Pythonic way ?
>
> > > Try named tuplehttp://code.activestate.com/recipes/500261/
>
> > 1) I see this is done with exec anyway, so there's no more pythonic
> > way.
>
> It doesn't *have* to be done with exec - I think there are other
> variants using metaclasses instead.
>

Can you suggest an alternative, without exec ?

Eli


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


Re: who to call a list of method inside the class itself

2008-08-19 Thread Edwin . Madari
[EMAIL PROTECTED] wrote:
> 
> [EMAIL PROTECTED] wrote:
> 
> > 1. return string names of required methods in getAllMethod
> > return ['method1', 'method2', 'method3']
> > 2. use gettattr on self and then exetute methods in applyAll
> > def applyAll(self):
> > for method_name in self.getAllMethod():
> > method = gettattr(self,method_name)
> >   method() #execute method now
> 
> why?

ensure instance's method invocation with all state information to that point, 
rather than relying on implemenation.

regards.
Edwin


The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.


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


Re: How to use win32com to convert a MS WORD doc to HTML ?

2008-08-19 Thread Tim Golden

Lave wrote:

Hi, all !

I'm a totally newbie huh:)

I want to convert MS WORD docs to HTML, I found python windows
extension win32com can make this. But I can't find the method, and I
can't find any document helpful.


You have broadly two approaches here, both
involving automating Word (ie using the
COM object model it exposes, referred to
in another post in this thread).

1) Use the COM model to have Word load your
doc, and SaveAs it in HTML format. Advantage:
it's relatively straightforward. Disadvantage:
you're at the mercy of whatever HTML Word emits.

2) Use the COM model to iterate over the paragraphs
in your document, emitting your own HTML. Advantage:
you get control. Disadvantage: the more complex your
doc, the more work you have to do. (What do you do with
images, for example? Internal links?)

To do the first, just record a macro in Word to
do what you want and then reproduce the macro
in Python. Something like this:


import win32com.client

doc = win32com.client.GetObject ("c:/data/temp/songs.doc")
doc.SaveAs (FileName="c:/data/temp/songs.html", FileFormat=8)
doc.Close ()



To do the second, you have to roll your own html
doc. Crudely, this would do it:


import codecs
import win32com.client
doc = win32com.client.GetObject ("c:/data/temp/songs.doc")
with codecs.open ("c:/data/temp/s2.html", "w", encoding="utf8") as f:
  f.write ("")
  for para in doc.Paragraphs:
text = para.Range.Text
style = para.Style.NameLocal
f.write ('%(text)s\n' % locals ())

doc.Close ()



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


Re: How to use win32com to convert a MS WORD doc to HTML ?

2008-08-19 Thread Simon Brunning
2008/8/19 Lave <[EMAIL PROTECTED]>:
> Hi, all !
>
> I'm a totally newbie huh:)
>
> I want to convert MS WORD docs to HTML, I found python windows
> extension win32com can make this. But I can't find the method, and I
> can't find any document helpful.

This should be a useful starting point:
.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: who to call a list of method inside the class itself

2008-08-19 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


ensure instance's method invocation with all

> state information to that point, rather than
> relying on implemenation.

Did you read the stuff I wrote about "bound methods" in the other post? 
 That's a fundamental Python feature, not an implementation artifact.


For some more details, see the section "User-defined methods" on this page:

   http://docs.python.org/ref/types.html



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


Re: who to call a list of method inside the class itself

2008-08-19 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> [EMAIL PROTECTED] wrote:
>> 
>> [EMAIL PROTECTED] wrote:
>> 
>> > 1. return string names of required methods in getAllMethod
>> > return ['method1', 'method2', 'method3']
>> > 2. use gettattr on self and then exetute methods in applyAll
>> > def applyAll(self):
>> > for method_name in self.getAllMethod():
>> > method = gettattr(self,method_name)
>> > method() #execute method now
>> 
>> why?
> 
> ensure instance's method invocation with all state information to that
> point, rather than relying on implemenation.

Erm, that makes no sense. The OP's code was perfectly fine - for some reason
he seemed to think it wasn't.

Your additional indirection doesn't add anything beyond clutter, as 

name = "foo"
getattr(instance, name) == instance.foo

holds.

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


Re: datetime.datetime.now() in military time

2008-08-19 Thread Mike Driscoll
On Aug 19, 10:42 am, korean_dave <[EMAIL PROTECTED]> wrote:
> import datetime
>
> def main():
>     timenow = datetime.datetime.now()
>     print(str(timenow.hour))
>
> if __name__ == "__main__":
>     main()
>
> If the time was, say, 2pm, how can I make output of timenow.hour "14"
> instead of "2"?
>
> Thanks.
> -Dave

Use the strftime() method to convert the time. Something like this:

print timenow.strftime('%H')

See also: http://docs.python.org/lib/module-time.html

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


Re: ANN: Resolver One 1.2 released

2008-08-19 Thread Giles Thomas

2008/8/19 km <[EMAIL PROTECTED]>

   Hi,
   sounds great - but disappointing to find it only available on window$.
   Is there any Linux release in near future ???
   KM


Not in the near future, unfortunately - but we're looking at getting it 
running under Mono in the medium term.  The big problem is that we'll 
have to change (or even recode) our grid component.



Best regards,

Giles

--
Giles Thomas
MD & CTO, Resolver Systems Ltd.
[EMAIL PROTECTED]
+44 (0) 20 7253 6372

Try out Resolver One! 

17a Clerkenwell Road, London EC1M 5RD, UK
VAT No.: GB 893 5643 79 
Registered in England and Wales as company number 5467329.

Registered address: 843 Finchley Road, London NW11 8NA, UK


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

What parts of C:\Python25 are important?

2008-08-19 Thread Robert Dailey
Hi,

I've currently embedded the python interpreter into a C++ application of
mine. I want to bundle the python core library with my application so the
user does not have to install python to use my application. What files do I
need to copy over? Help is appreciated, thank you.
--
http://mail.python.org/mailman/listinfo/python-list

exception handling in complex Python programs

2008-08-19 Thread eliben
Python provides a quite good and feature-complete exception handling
mechanism for its programmers. This is good. But exceptions, like any
complex construct, are difficult to use correctly, especially as
programs get large.

Most of the issues of exceptions are not specific to Python, but I
sometimes feel that Python makes them more acute because of the free-n-
easy manner in which it employs exceptions for its own uses and allows
users to do the same.

Now, what do I mean more specifically... When a program starts growing
large, I find myself a bit scared of all the exceptions that might be
thrown: Python's exceptions as a result of runtime-detection of errors
(Python's dynamic typing also comes into play here), exceptions from
libraries used by the code, and exceptions from my lower-level
classes.
Python doesn't allow to specify which exceptions are thrown (C++'s
feature adding 'throw' after a function/method declaration specifying
the exceptions that can be thrown), and this leaves me at loss - what
should be caught and where ? Which errors should be left to
propagate ?

I've tried looking around the Python blogosphere, but there doesn't
seem to be much concern with this topic.

Apologies for the not-too-coherent post, but I suspect you feel the
pain too and can understand my meaning.

Eli

P.S. There's a common case where a method is passed a filename, to do
something with a file (say, read data). Should the method catch the
errors possibly thrown by open(), or leave it to the caller ?

P.P.S. There's a great post on conditions (Common Lisp's exceptions)
here:
http://dlweinreb.wordpress.com/2008/03/24/what-conditions-exceptions-are-really-about/
Not really CL specific, and can apply to Python's exceptions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What parts of C:\Python25 are important?

2008-08-19 Thread Fredrik Lundh

Robert Dailey wrote:

I've currently embedded the python interpreter into a C++ application of 
mine. I want to bundle the python core library with my application so 
the user does not have to install python to use my application. What 
files do I need to copy over? Help is appreciated, thank you.


off the top of my head:

- python25.dll (from \windows\system32, usually)

- any extension PYD:s and DLL:s you're using (from \python25\DLLs)

- either the contents of the standard library (\python25\Lib)
  in PY and/or PYC form, or a zipped archive that contains all
  the PYC files in there (zipped relative to \python25\Lib).

- (optional) MSVCR71.dll (but that's usually already installed, afaik)

you also need to make sure that your application sets an appropriate 
path before it starts importing things, either by munging sys.path via 
embedded Python code, or via a call to Py_SetPythonHome.  the comment 
block at the top of


   http://svn.python.org/projects/python/trunk/PC/getpathp.c

explains how the default path is created on Windows.

in some cases, it helps to tell Python not to import the "site" module 
by itself, and then import site when you've set everything up.  to do 
that, insert "-S" in the argv buffer before calling PySys_SetArgv.  you 
may also want to remove any PYTHON-related environment variables from 
the local environment, before initializing Python.




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


Re: Programming Languages Decisions

2008-08-19 Thread Lie
On Aug 19, 1:45 pm, "E.D.G." <[EMAIL PROTECTED]> wrote:
> "Terry Reedy" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > Rather than explain further, I suggest that you visit python.org and read
> > some of the tutorial to see what *you* think.
> >http://docs.python.org/tut/tut.html
>
> My original programs were mostly in Basic.  When it became obvious that I
> needed a more powerful language I took a look at Python, Ruby, and a number
> of other languages.
>
> To get started with this work I decided to go with Perl because it will do a
> lot of things and is highly flexible.  And, it got the job done.  But now
> that this application is up and running I am trying to collect opinions
> regarding what languages more serious programmers might want to use with
> future work for the application.  And for independent researchers, Python
> might be the one they would choose.  For government and university
> researchers who have more resources and their own computer programmers
> available it is sounding like one of the "C" family of languages might be
> the one they would  like.
>
> How is Python with graphics?

pygame for graphic with SDL library (e.g. fullscreen apps, hardware
accelerated)
Tkinter for basic GUI that can run on any python with no dependencies
(except python vm)
wxWidget, etc for more advanced GUI and if you allow dependencies
--
http://mail.python.org/mailman/listinfo/python-list


Re: exception handling in complex Python programs

2008-08-19 Thread Chris Mellon
On Tue, Aug 19, 2008 at 12:19 PM, eliben <[EMAIL PROTECTED]> wrote:
> Python provides a quite good and feature-complete exception handling
> mechanism for its programmers. This is good. But exceptions, like any
> complex construct, are difficult to use correctly, especially as
> programs get large.
>
> Most of the issues of exceptions are not specific to Python, but I
> sometimes feel that Python makes them more acute because of the free-n-
> easy manner in which it employs exceptions for its own uses and allows
> users to do the same.
>

Lots of people seem to have this fear. They treat exceptions like they
would treat error codes, trying to handle any possible case around any
particular call.

This is the wrong thing to do, and it only leads to more fragile code.
There are only 2 reasonable things to do with an exception:
1) handle it, by which I mean catch the exception knowing what error
condition it signifies, and take an appropriate action to correct the
error and
2) pass it up so something else has a chance at it.

Catching an exception when you don't know exactly what to do to fix it
is an error. At best, it will make debugging a program harder (because
you're losing context information about the error) and at worst it
adds bugs to your program. The way Javas checked exceptions encourage
empty or otherwise useless exception handlers is a major problem with
them.

There's some fear about presenting exceptions to the end user. That's
a user interface issues, not a software quality or engineering issue,
and it's resolvable with top-level handlers that log tracebacks
somewhere a user can't see them if desired.


> Now, what do I mean more specifically... When a program starts growing
> large, I find myself a bit scared of all the exceptions that might be
> thrown: Python's exceptions as a result of runtime-detection of errors
> (Python's dynamic typing also comes into play here), exceptions from
> libraries used by the code, and exceptions from my lower-level
> classes.
> Python doesn't allow to specify which exceptions are thrown (C++'s
> feature adding 'throw' after a function/method declaration specifying
> the exceptions that can be thrown), and this leaves me at loss - what
> should be caught and where ? Which errors should be left to
> propagate ?
>

You should catch anything that you can correct. If you don't have a
specific answer for a specific exception, don't catch it.

> I've tried looking around the Python blogosphere, but there doesn't
> seem to be much concern with this topic.
>
> Apologies for the not-too-coherent post, but I suspect you feel the
> pain too and can understand my meaning.
>
> Eli
>
> P.S. There's a common case where a method is passed a filename, to do
> something with a file (say, read data). Should the method catch the
> errors possibly thrown by open(), or leave it to the caller ?
>

Same rules apply. The only sort-of exception (no pun intended) is that
sometimes you want to re-raise as a different type of exception. Make
sure that you preserve all of the original information (including the
original traceback) if you do this.

> P.P.S. There's a great post on conditions (Common Lisp's exceptions)
> here:
> http://dlweinreb.wordpress.com/2008/03/24/what-conditions-exceptions-are-really-about/
> Not really CL specific, and can apply to Python's exceptions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: exception handling in complex Python programs

2008-08-19 Thread Rafe
On Aug 20, 12:19 am, eliben <[EMAIL PROTECTED]> wrote:
> Python provides a quite good and feature-complete exception handling
> mechanism for its programmers. This is good. But exceptions, like any
> complex construct, are difficult to use correctly, especially as
> programs get large.
>
> Most of the issues of exceptions are not specific to Python, but I
> sometimes feel that Python makes them more acute because of the free-n-
> easy manner in which it employs exceptions for its own uses and allows
> users to do the same.
>
> Now, what do I mean more specifically... When a program starts growing
> large, I find myself a bit scared of all the exceptions that might be
> thrown: Python's exceptions as a result of runtime-detection of errors
> (Python's dynamic typing also comes into play here), exceptions from
> libraries used by the code, and exceptions from my lower-level
> classes.
> Python doesn't allow to specify which exceptions are thrown (C++'s
> feature adding 'throw' after a function/method declaration specifying
> the exceptions that can be thrown), and this leaves me at loss - what
> should be caught and where ? Which errors should be left to
> propagate ?
>
> I've tried looking around the Python blogosphere, but there doesn't
> seem to be much concern with this topic.
>
> Apologies for the not-too-coherent post, but I suspect you feel the
> pain too and can understand my meaning.
>
> Eli
>
> P.S. There's a common case where a method is passed a filename, to do
> something with a file (say, read data). Should the method catch the
> errors possibly thrown by open(), or leave it to the caller ?
>
> P.P.S. There's a great post on conditions (Common Lisp's exceptions)
> here:http://dlweinreb.wordpress.com/2008/03/24/what-conditions-exceptions-...
> Not really CL specific, and can apply to Python's exceptions.

Maybe I am oversimplifying (and I am here to learn), but I catch all
exceptions which otherwise would be hard to understand as a user. In
other words, when a better error message is useful.

Again, this is probably too simple to help, but the only way to ignore
certain types of exceptions, as far as I know, is to catch them and
pass.
e.g. this ignores type errors...

try:
somethingBad()
except TypeError, err:
pass
except Exception, err:
raise TypeError(err)


I suppose you could write a decorator to do this if you want it at the
function level, but that seems a bit to broad. Shouldn't exceptions be
on a case-by-case basis to add protection and return information
exactly where it is needed?

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


Re: HTML Tables

2008-08-19 Thread Mensanator
On Aug 19, 9:33 am, Amie <[EMAIL PROTECTED]> wrote:
> Hi,
> Thanks for your help so far. Ok here's a scenario: I have to create a
> site that displays 34 html  tables.
> In each of these tables the following information has to be displayed:
> logo (image), site name, date, time.

You want 34 tables each with one row?

Or one table with 34 rows?

> Remember: in all of these 34 tables. the information displayed on each
> of these tables is retrieved from the database.

So, you're building a web page dynamically, not static?

> I did write a mysql
> query,

The data you want to display is reurned as a list of tuples?
The logo is a URL that points to the image?

> I just don't know how to link it with the for loop that has to
> display all these tables.

I assume you already have the code to compose the rest of the page?

> If anyone can, can you roughly show me how
> to go about doing this.
> Thanks in advance
>
> Amie

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


Re: cathing uncaught exceptions

2008-08-19 Thread Rafe
On Aug 18, 10:02 pm, Alexandru  Mosoi <[EMAIL PROTECTED]> wrote:
> how can I catch (globally) exception that were not caught in a try/
> catch block in any running thread? i had this weird case that an
> exception was raised in one thread, but nothing was displayed/logged.

Any chance you might have missed the word "raise", e.g.

except Exception, err:
Exception(err)

vs.

except Exception, err:
raise Exception(err)


This is from the list of stupid things I have done myself,

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


Re: exception handling in complex Python programs

2008-08-19 Thread Fredrik Lundh

Rafe wrote:


Again, this is probably too simple to help, but the only way to ignore
certain types of exceptions, as far as I know, is to catch them and
pass.
e.g. this ignores type errors...

try:
somethingBad()
except TypeError, err:
pass
except Exception, err:
raise TypeError(err)


so what kind of code are you writing where *type errors* are not 
considered programming errors?  (catching them and proceeding is one 
thing, but catching them and ignoring them?)


I'd be really worried if I found that in a piece of source code I had to 
maintain.




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


Re: adding properties dynamically (how to?)

2008-08-19 Thread Rafe
On Aug 17, 7:51 pm, André <[EMAIL PROTECTED]> wrote:
> I didn't want to hijack the original thread but I have basically the
> same request...
>
> On Aug 17, 7:09 am, Bruno Desthuilliers<[EMAIL PROTECTED]> wrote:
> > akonsu a écrit :> hello,
>
> [SNIP]
>
>
>
> > Wrong solution to your problem, I'd say. Let's start again:
>
> > """
> >  > i need to add properties to instances dynamically during run time.
> >  > this is because their names are determined by the database contents.
> > """
>
> > Care to elaborate ? I may be wrong, but I suspect you're trying to roll
> > your own python/database mapper. If so, there are quite a couple Python
> > ORMs around. Else, please tell us more.
>
> I'm not the original poster, but I'd like to do the same thing (for a
> different reason).
>
> I have a program (crunchy) that is extensible via plugins.  New
> options available via plugins can be turned on or off (or selected
> among a list of options).  I have a module for user preferences (let's
> call it prefs.py) that allows the setting of these options (and do
> error checking, automatic saving of the options selected for future
> sessions, etc.).  These options are implemented as properties.
>
> Currently I have it simplified so that only two lines need to be added
> to prefs.py to add new options; something like
> options = { ...
> 'new_option': [value1, value2, ..., valueN],
> ...}
>
> and
> class Preferences(object):
> ...
>
>new_option = make_property('new_option', 'some nicely worded help
> string')
>
> ===
> make_property is a custom define function that return fgets, fsets,
> fdel and doc.
>
> Ideally, I'd like to be able to define new would-be properties from
> the plugin and add them to the class prior to creating instances.  In
> other words, have something like
>
> ===
> for option in options_defined_in_plugins:
>add_option_as_property_to_Preferences(Preferences, option, ...)
>
> user_preferences = Preferences()
>
> Performance in this case would not be an issue.
>
> Cheers,
>
> André

You can dynamicly add properties to a class just before returning the
instance using __new__():

class AClass(object):
def __new__(cls):

setattr(cls,"active", property(fget = ...,
fset = ...,
fdel = ...,
doc  = ...))

obj = super(BaseGroup, cls).__new__(cls)
return obj


You can put this in a for loop and add a property per option, etc.

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


Re: adding properties dynamically (how to?)

2008-08-19 Thread Rafe
On Aug 17, 7:51 pm, André <[EMAIL PROTECTED]> wrote:
> I didn't want to hijack the original thread but I have basically the
> same request...
>
> On Aug 17, 7:09 am, Bruno Desthuilliers<[EMAIL PROTECTED]> wrote:
> > akonsu a écrit :> hello,
>
> [SNIP]
>
>
>
> > Wrong solution to your problem, I'd say. Let's start again:
>
> > """
> >  > i need to add properties to instances dynamically during run time.
> >  > this is because their names are determined by the database contents.
> > """
>
> > Care to elaborate ? I may be wrong, but I suspect you're trying to roll
> > your own python/database mapper. If so, there are quite a couple Python
> > ORMs around. Else, please tell us more.
>
> I'm not the original poster, but I'd like to do the same thing (for a
> different reason).
>
> I have a program (crunchy) that is extensible via plugins.  New
> options available via plugins can be turned on or off (or selected
> among a list of options).  I have a module for user preferences (let's
> call it prefs.py) that allows the setting of these options (and do
> error checking, automatic saving of the options selected for future
> sessions, etc.).  These options are implemented as properties.
>
> Currently I have it simplified so that only two lines need to be added
> to prefs.py to add new options; something like
> options = { ...
> 'new_option': [value1, value2, ..., valueN],
> ...}
>
> and
> class Preferences(object):
> ...
>
>new_option = make_property('new_option', 'some nicely worded help
> string')
>
> ===
> make_property is a custom define function that return fgets, fsets,
> fdel and doc.
>
> Ideally, I'd like to be able to define new would-be properties from
> the plugin and add them to the class prior to creating instances.  In
> other words, have something like
>
> ===
> for option in options_defined_in_plugins:
>add_option_as_property_to_Preferences(Preferences, option, ...)
>
> user_preferences = Preferences()
>
> Performance in this case would not be an issue.
>
> Cheers,
>
> André


Hi,

You can dynamically add properties to a class just before returning
the
instance using __new__():

class AClass(object):
def __new__(cls):

setattr(cls,"propName", property(fget = ...,
 fset = ...,
 fdel = ...,
 doc  = ...) )

obj = super(AClass, cls).__new__(cls)
return obj

You can put this in a for loop and add a property per option, etc. You
can also do this with your own descriptor if you make a custom one.

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


Re: how to add property "dynamically"?

2008-08-19 Thread Rafe
On Aug 17, 5:09 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> akonsu a écrit :> hello,
>
> > i need to add properties to instances  dynamically during run time.
> > this is because their names are determined by the database contents.
> > so far i found a way to add methods on demand:
>
> > class A(object) :
> > def __getattr__(self, name) :
> > if name == 'test' :
> > def f() : return 'test'
> > setattr(self, name, f)
> > return f
> > else :
> > raise AttributeError("'%s' object has no attribute '%s'" %
> > (self.__class__.__name__, name))
>
>  > this seems to work and i can invoke method test() on an object.
>
> Nope. This adds per-instance *function* attributes - not *methods*.
>
> class A(object) :
>  def __getattr__(self, name) :
>  if name == 'test' :
>  def f(self) :
>  return "%s.test" % self
>  setattr(self, name, f)
>  return f
>  else :
>  raise AttributeError(
>  "'%s' object has no attribute '%s'" \
>  % (self.__class__.__name__, name)
>  )
>
> a = A()
> a.test()
> => Traceback (most recent call last):
>  File "", line 1, in 
>TypeError: f() takes exactly 1 argument (0 given)
>
> To add methods on a per-instance basis, you have to manually invoke the
> descriptor protocol's implementation of function objects:
>
> class A(object) :
>  def __getattr__(self, name) :
>  if name == 'test' :
>  def f(self) :
>  return "%s.test" % self
>  m = f.__get__(self, type(self))
>  setattr(self, name, m)
>  return m
>  else :
>  raise AttributeError(
>  "'%s' object has no attribute '%s'" \
>  % (self.__class__.__name__, name)
>  )
>
> > it
> > would be nice to have it as property though.   so i tried:
>
> > class A(object) :
> > def __getattr__(self, name) :
> > if name == 'test' :
> > def f() : return 'test'
> > setattr(self, name, property(f))
> > return f
> > else :
> > raise AttributeError("'%s' object has no attribute '%s'" %
> > (self.__class__.__name__, name))
>
> > but this does not work, instance.test returns a callable but does not
> > call it.
>
> Properties must be class attributes. The only way (the only way I know)
> to get them to work as instance-attributes is to overload
> __getattribute__, which is tricky and may have pretty bad impact on
> lookup perfs - and ruins the whole point of using properties FWIW.
>
> > i am not an expert in python, would someone please tell me what i am
> > doing wrong?
>
> Wrong solution to your problem, I'd say. Let's start again:
>
> """
>  > i need to add properties to instances dynamically during run time.
>  > this is because their names are determined by the database contents.
> """
>
> Care to elaborate ? I may be wrong, but I suspect you're trying to roll
> your own python/database mapper. If so, there are quite a couple Python
> ORMs around. Else, please tell us more.

I posted this to another thread, but...


You can dynamically add properties (or anything else) to a CLASS just
before returning the
instance using __new__():

class AClass(object):
def __new__(cls):
setattr(cls,"propName", property(fget = ...,
 fset = ...,
 fdel = ...,
 doc  = ...) )

obj = super(AClass, cls).__new__(cls)
return obj


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


Re: exception handling in complex Python programs

2008-08-19 Thread [EMAIL PROTECTED]
On Aug 19, 10:19 am, eliben <[EMAIL PROTECTED]> wrote:

> P.S. There's a common case where a method is passed a filename, to do
> something with a file (say, read data). Should the method catch the
> errors possibly thrown by open(), or leave it to the caller ?

You want to look up Easier to Ask Forgivness than Permission (EAFP)
which is touted as the "canonical" error-handling paradigm for Python.
This would give rise to the following function:

  def do_something(filename):
try:
  f = open(filename)
except IOError:
  return err("File %s not found" % filename)
...

where err is a function that generates an error object that your
application understands. I personally think this is sloppy because you
have to couple the exception type with the function --- between file()
and open() in Python 2 and 3, a NameError is thrown with open() in
Python 3 and an IOError is thrown in the other three cases . The alternative is

  def do_something(filename):
if not os.access(filename,os.R_OK):
  return err(...)
f = open(filename)
...

or, (and this last one I actually used for a web application)

  def do_something(filename):
if not os.access(filename,os.R_OK):
  raise MyApplicationsExceptionType("File not found...")
f = open(filename)
...

The last one has the advantage that you can write a request handler
like this

  def handle_http_request(...):
func = specific_handler_func(...)
try:
  response = func(...)
  return response
except MyApplicationsExceptionType as exc: #3.0 syntax
  return error_response(exc,...)

Exceptions you don't expect (i.e. bugs) will get handled by the web
app framework, but you get to handle your own exceptions. Raising your
own exception type can also be employed with the EAFP approach like
this:

  def do_something(filename):
try:
  f = open(filename)
except IOError:
  raise MyApplicationsExceptionType("File %s not found" %
filename)
...

If you are writing a library (for instance using a file for persistent
storage), then the answer to your question is "don't catch the
exception." Clients will expect the usual exception to be thrown when
a bad file name is passed.

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


Re: Programming Languages Decisions

2008-08-19 Thread E.D.G.
"Lie" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

How is Python with graphics?


pygame for graphic with SDL library (e.g. fullscreen apps, hardware
accelerated)
Tkinter for basic GUI that can run on any python with no dependencies
(except python vm)
wxWidget, etc for more advanced GUI and if you allow dependencies


Thanks for the comments.

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


Graphics Contexts and DCs explanations?

2008-08-19 Thread RgeeK
Experimenting with graphics in an app: it's AUI based with a few panes, 
one of which has a panel containing a few sizers holding UI elements. 
One sizer contains a panel that needs some basic line-drawing graphics 
in it.


I use the wxPython demo app heavily to figure this stuff out, and my 
experiments seem to work, but I'm flying blind somewhat.


Can someone englighten me about the wx.GraphicsContext versus wx.PaintDC 
  (BTW what does PaintDC stand for? Drawing Context perhaps?)


The scrolledWindow and GraphicsContext examples are helpful, but it 
appears I can draw a rectangles, lines and text in either just a 
straight wxPaintDC, or can do:


dc = wx.PaintDC(self)
gc = wx.GraphicsContext.Create(dc)

...and do the same drawing with gc.DrawText etc...

Can someone clarify the differences or added value of the gc over the 
dc, and is using the dc alone a valid approach?  Where will it end up 
biting me - I don't mean which body part :)  Perhaps I should say in 
which situation will it bite...


Thx,
Ross.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Graphics Contexts and DCs explanations?

2008-08-19 Thread Chris Mellon
On Tue, Aug 19, 2008 at 1:16 PM, RgeeK <[EMAIL PROTECTED]> wrote:
> Experimenting with graphics in an app: it's AUI based with a few panes, one
> of which has a panel containing a few sizers holding UI elements. One sizer
> contains a panel that needs some basic line-drawing graphics in it.
>
> I use the wxPython demo app heavily to figure this stuff out, and my
> experiments seem to work, but I'm flying blind somewhat.
>
> Can someone englighten me about the wx.GraphicsContext versus wx.PaintDC
>  (BTW what does PaintDC stand for? Drawing Context perhaps?)
>
> The scrolledWindow and GraphicsContext examples are helpful, but it appears
> I can draw a rectangles, lines and text in either just a straight wxPaintDC,
> or can do:
>
> dc = wx.PaintDC(self)
> gc = wx.GraphicsContext.Create(dc)
>
> ...and do the same drawing with gc.DrawText etc...
>
> Can someone clarify the differences or added value of the gc over the dc,
> and is using the dc alone a valid approach?  Where will it end up biting me
> - I don't mean which body part :)  Perhaps I should say in which situation
> will it bite...
>

This is probably better suited to the wxPython ML instead of c.l.p,
because it's so specific.

In short: wxDC (and friends) are traditional raster based drawing
contexts. wxGraphicsContext is a vector/path based API. If you're
doing drawing that's suited for a vector format (like line drawing
probably is), using wxGraphicsContext will give you better image
quality as well as the general vector features like free scaling,
rotation, transforms, etc,
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python encoding

2008-08-19 Thread Joan Pallarès
Sorry,

The problem is the OblecjtListView doesn't show some characters correctly.

In the image attached, in the "partidos list" in the grey line, where a
square is showed it must be a Ç
And in the second line where a | is showed it should be a ª

Why this happen? maybe OLV doesn`t manage well the encoding?

The list OLV uses to show info is forme by this class:

class Partido:
def 
__init__(self,idPartido,nombreLocal,nombreVisitante,fechaHora,idLocal,idVisitante):
self.idPartido = int(idPartido)
self.nombreLocal = *unicode(nombreLocal, 'iso-8859-1')* #aún así no
muestra bien los caracteres
self.nombreVisitante = *unicode(nombreVisitante, 'iso-8859-1')*
self.fechaHora = fechaHora
self.idLocal = int(idLocal)
self.idVisitante = int(idVisitante)

Thank you, I expect now is clear
<>--
http://mail.python.org/mailman/listinfo/python-list

Re: cathing uncaught exceptions

2008-08-19 Thread Gabriel Genellina
En Mon, 18 Aug 2008 12:02:29 -0300, Alexandru Mosoi <[EMAIL PROTECTED]> 
escribió:

> how can I catch (globally) exception that were not caught in a try/
> catch block in any running thread? i had this weird case that an
> exception was raised in one thread, but nothing was displayed/logged.

Each thread should handle its own exceptions. If any exception escapes from 
Threading.run(), it is printed on sys.stderr (sys.excepthook isn't involved); 
see the threading.py module for details.
Maybe you had a bare try/except that did nothing? or maybe you redirected 
sys.stderr?

-- 
Gabriel Genellina

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


displaying my randomly selected numbers in a colorful interface.

2008-08-19 Thread Goksie Aruna

dear all,

i have arrays of number of size lets  say 4000 i.e.  201000..2013999

now i want to do the following.

first print all the numbers to a colorful console. be it wx,  tk, or web 
based.


then pick a winning number from the range which will now be printed at 
the center of the page.


how can i achieve this?

goksie

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


Re: Getting pid of a remote process

2008-08-19 Thread Kurt Mueller

srinivasan srinivas schrieb:

Thanks a lot.
But i am wondeing will it return correct pid if more than one instance of 
 run on the remote machine??
Thanks,
Srini


On UNIX-like OS:

If you start the process in the background, you can
get the PID with:

:~> ssh  'ls -l & echo PID=$!'  | grep PID
PID=30596
:~>



see:
man bash
-> Special Parameters



Grüessli
--
Kurt Müller, [EMAIL PROTECTED]

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


Re: HTML Tables

2008-08-19 Thread Stefan Behnel
Amie wrote:
> Thanks for your help so far. Ok here's a scenario: I have to create a
> site that displays 34 html  tables.
> In each of these tables the following information has to be displayed:
> logo (image), site name, date, time.
> Remember: in all of these 34 tables. the information displayed on each
> of these tables is retrieved from the database. I did write a mysql
> query, I just don't know how to link it with the for loop that has to
> display all these tables. If anyone can, can you roughly show me how
> to go about doing this.

This might get you going:

http://codespeak.net/lxml/lxmlhtml.html#creating-html-with-the-e-factory

Try something like this:

tables = []
for row in rows_returned_by_the_query:
tables.append(
 E.TABLE( ... )
)

html_body = E.BODY( *tables )

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


Re: Python Query: Related to locking a resource in a multithreaded environment

2008-08-19 Thread Nils Oliver Kröger
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi,

I don't think the global interpreter lock is what you need ... read here
for reference:

http://docs.python.org/api/threads.html

My approach what be to write one class for reading and writing to the
configuration and make that class thread-safe using the RLock.

Then you create one and only one instance of this class and let all your
threads use (not import) that one instance.

You could achieve that "one and only one" either by having a main
program which creates the instance and pass the reference to each thread
via its __init__ or you implement the Configuration class as a singleton
like this:


class Singleton(object):
"""
A simple example implementing the singleton design pattern in
python
"""
#we need two class attributes (which translate to static
attributes in java)
__lock = Lock() #a lock for thread safety
__instance = None #and to remember the one instance

#first of all: make pythons usual way of creating objects   
# unusable because we cannot just hide them as one would in java
# or C++
def __new__(cls, *args, **kwargs):
pass

def __init__(self):
pass

@classmethod
def getInstance(cls, *args, **kwargs):
"""
The famous gatInstance method which resturns the one instance of
our
class.

params:
cls - reference to the class
*args - the tuple of arguments paassed by position
**kwargs - the dictionary of arguments passed by keyword
"""
#enter critical section
cls.__lock.acquire()
try:
if cls.__instance is None:
#use the superclasses __new__ for creation
cls.__instance = object.__new__(cls, *args, 
**kwargs)

#place initialisation code (everything which
#would usually
happen in __init__) here
cls.__instance.SomeInt = 1
finally:
#leave critical section
cls.__lock.release()

return cls.__instance


Add your methods for accessing as instance methods to this class and get
the same instance of this class in each thread by calling
Singleton.getInstance().

Hope that helps

Regards

Nils

tarun schrieb:
> I think I need something called global interpreter lock which is
> accessible to all the threads. But I am not sure how to implement this.
> 
>  
> On Tue, Aug 19, 2008 at 11:28 AM, tarun <[EMAIL PROTECTED]
> > wrote:
> 
> Hello All,
>  
> I've a configuration.ini file. This particular can be accessed by
> several threads of my application. Each thread can read/write
> configuration parameters from/to the configuration.ini file. I am
> using threading (Rlock) to lock the resource (configuration.ini
> file) while accessing it from any thread. I use the file available
> at http://www.voidspace.org.uk/python/configobj.html for read/write.
>  
> I did the following in one of my files:
>  
> import threading
> class Synchronization:
>   def __init__(self):
> self.mutex = threading.RLock()
>  
> Now this I can create instances of the class Synchronization and use
> acquire/release to work on the shared resource. But every thread
> would need to import this class and hence each thread would create a
> separate instance of the class. This means several lock variables.
> But I think we need a global lock flag that is accessible across all
> the threads.
>  
> How do i do this?
>  
> Please let me know ASAP.
>  
> Thanks In Advance,
> Tarun
> 
> 
> 
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
-BEGIN PGP SIGNATURE-

iD8DBQFIqxfCzvGJy8WEGTcRApe+AJ9MNqWI9FOsJIKuTKxy8ZNSGYTy2gCdHtGc
clDPMMAPRoIxsBvVm4ygi6U=
=vIPW
-END PGP SIGNATURE-
begin:vcard
fn;quoted-printable:Nils Oliver Kr=C3=B6ger
n;quoted-printable:Kr=C3=B6ger;Nils Oliver
email;internet:[EMAIL PROTECTED]
version:2.1
end:vcard

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

Re: How to stop iteration with __iter__() ?

2008-08-19 Thread Terry Reedy



ssecorp wrote:

I want a parse a file of the format:
movieId
customerid, grade, date
customerid, grade, date
customerid, grade, date
etc.

so I could do with open file as reviews and then for line in reviews.

but first I want to take out the movie id so I use an iterator.

then i want to iterate through all the rows, but how can I do:
while movie_iter != None:

because that doesn't work, itraises an exception, StopItreation, which
according to the documentation it should. But catching an exception
can't be the standard way to stop iterating right?


Catching StopIteration *is* the usual way to stop iterating with an 
iterator.  Using while, one must be explicit:


it = iter(iterable)
try:
  while True:
item = next(iter) # 2.6,3.0
f(item)
except StopIteration:
  pass

but the main reason to write the above is to show the advantage of 
simply writing the equivalent (and implicit)


for item in iterable:
  f(item)

;-)

In your case, the standard Python idiom, as Jon said, is

it = iter(iterable)
next(it) # 2.6, 3.0
for for item in iterable:
  f(item)

The alternative is a flag variable and test

first = True
for for item in iterable:
  if first:
first = False
  else:
f(item)

This takes two more lines and does an unnecessary test for every line 
after the first.  But this approach might be useful if, for instance, 
you needed to skip every other line (put 'first = True' after f(item)).


Terry Jan Reedy

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


Re: displaying my randomly selected numbers in a colorful interface.

2008-08-19 Thread Mike Driscoll
On Aug 19, 1:02 am, Goksie Aruna <[EMAIL PROTECTED]> wrote:
> dear all,
>
> i have arrays of number of size lets  say 4000 i.e.  201000..2013999
>
> now i want to do the following.
>
> first print all the numbers to a colorful console. be it wx,  tk, or web
> based.
>
> then pick a winning number from the range which will now be printed at
> the center of the page.
>
> how can i achieve this?
>
> goksie


I would recommend learning wx, tk, pyGTK, or HTML/CSS. If you go with
wxPython, there are many pre-built widgets that can display colored
text, including HTML. Some of them use Scintilla. I would look
especially at wx.RichTextCtrl, wx.StyledTextCtrl, FancyText or
wx.HtmlWindow. There's a demo you can download to check these out
here: http://wxpython.org/download.php

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


Newbie question about sending and receiving data to the command prompt.

2008-08-19 Thread aditya shukla
Hello folks,

I am using windows vista and i am trying to send data to the command prompt
,this is what is done.

import subprocess
proc =subprocess.Popen('cmd.exe',stdin=subprocess.PIPE)
proc.communicate('abc')
when i run this the command prompt just blinks and disappears , can anyone
explain what's going on?

Similarly when i am trying to receive data from the command prompt the same
thing happens.This is what i have done.

proc = subprocess.Popen('cmd.exe',stdout=subprocess.PIPE, )
stdout_value = proc.communicate()[0]
print '\tstdout:', repr(stdout_value)

-command prompt blinks and disappears.Please explain what's happening.

Thanks in advance.

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

Idle is not accepting backslashes on some Mac OSX keyboards

2008-08-19 Thread mounty
Hi list,

I am using a German keyboard on Mac OS X 10.4.11. Idle 1.2.2 is constantly 
blocking entering the backslash character '\'
which is for instance  perfectly accepted by my mail application, as you can 
see for yourself. If I switch to an US,
Australian or English keyboard layout the backslash can be entered. 
Unfortunately this key position is the pound- sign
'#' on a German keyboard. The same applies to (German) Switzerland and Austrian 
keyboards as well.

google lists several inquiries like this one:
http://bugs.python.org/issue3493

It seems to me that the backslash is hard coded to the physical key in Idle. 
However this key position is occupied by
the '#' pound-sign in the lower-case position of the German keyboard layout. 
The upper case letter for this physical key
is a single quote "'". If I copy the backslash character from a different 
application into idle, the character will be
processed. And as there is no input problem with the terminal program which is 
shipped with OS X, the problem should be
somewhere in Idle. IMHO of course.

Here is a photo of the German keyboard layout:
http://de.wikipedia.org/wiki/Bild:2007_09_30_de_Apple-Tastatur.jpg

If anybody is curious about how we have to enter a backslash, it's 
"Alt-Shift-7" no matter if you are using OS X,
Windows or Linux.

Can anyone advise how to proceed. Many thanks
Ulf


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


  1   2   >