Re: Running daemon with zdaemon ... example help?

2007-08-29 Thread helloizomi
Thank you, I got it now ^.^
On Aug 25, 3:10 pm, asrenzo <[EMAIL PROTECTED]> wrote:
> Hi,
>
> This could also be a good starting 
> point:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731
>
> Regards,
>
> Laurent
>
> Genie T a écrit :
>
> > Hi all,
>
> > I'm looking atzdaemonto run my python scripts as a daemon but it
> > seems to have few example that guide me how to follow. It would be
> > great if you can give me a simple example of how to use. I'm newbie
> > here :)
>
> > Thanks


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

encoding problems

2007-08-29 Thread tool69
Hi,

I would like to transform reST contents to HTML, but got problems
with accented chars.

Here's a rather simplified version using SVN Docutils 0.5:

%-

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from docutils.core import publish_parts

class Post(object):
 def __init__(self, title='', content=''):
 self.title = title
 self.content = content

 def _get_html_content(self):
 return publish_parts(self.content,
 writer_name="html")["html_body"]
 html_content = property(_get_html_content)

# Instanciate 2 Post objects
p1 = Post()
p1.title = "First post without accented chars"
p1.content = """This is the first.
...blabla
... end of post..."""

p2 = Post()
p2.title = "Second post with accented chars"
p2.content = """Ce poste possède des accents : é à ê è"""

for post in [p1,p2]:
 print post.title, "\n" +"-"*30
 print post.html_content

%-

The output gives me :

First post without accented chars
--

This is the first.
...blabla
... end of post...


Second post with accented chars
--
Traceback (most recent call last):
File "C:\Documents and
Settings\kib\Bureau\Projets\python\dbTest\rest_error.py", line 30, in 

print post.html_content
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in 
position 39:
ordinal not in range(128)

Any idea of what I've missed ?

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


Re: tempfile.mkstemp and os.fdopen

2007-08-29 Thread Gerard Flanagan
On Aug 28, 7:55 pm, billiejoex <[EMAIL PROTECTED]> wrote:
> Hi there.
> I'm trying to generate a brand new file with a unique name by using
> tempfile.mkstemp().
> In conjunction I used os.fdopen() to get a wrapper around file
> properties (write & read methods, and so on...) but 'name' attribute
> does not contain the correct file name. Why?
>

import tempfile, os

class TempFile(object):

def __init__(self, fd, fname):
self._fileobj = os.fdopen(fd, 'w+b')
self.name = fname

def __getattr__(self, attr):
return getattr(self._fileobj, attr)

def mktempfile(dir=None, suffix='.tmp'):
return TempFile(*tempfile.mkstemp(dir=dir, suffix=suffix))





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


Re: Is it reasonably easy easy to something like this with python?

2007-08-29 Thread Bruno Desthuilliers
walterbyrd a écrit :
> On Aug 28, 1:31 pm, Gerardo Herzig <[EMAIL PROTECTED]> wrote:
>> walterbyrd wrote:
> 
>> The one who make that table sorteable is AJAX. Not php. The php part is
>> kind of trivial (so it would be `trivial' in python too). It just reads
>> some data and format it in an html table.
> 
> 
> Thank you, that is great to know. What if there were 1000 records, and
> the table was paginated? 
 >
> I suppose, ajax would sort the front end,

s/ajax/javascript/

You don't need ajax to sort a table, it's pure javascript dom 
manipulation (and there are quite a lot of working, correctly written 
and well-tested scripts doing so).

In your above use case (sortable, paginated, inline-editable grid), ajax 
would be used to:
- retrieve XXX records from the back-end (either as an html fragment or 
in json) via a GET request
- submit modifications (via a POST request)

All the rest is either usual javascript or usual (backend) web programming.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tempfile.mkstemp and os.fdopen

2007-08-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Michael
J. Fromberger wrote:

> ... since os.fdopen() only has access to the file descriptor, it
> does not have a convenient way to obtain the file's name.

You can do this under Linux as follows:

os.readlink("/proc/%d/fd/%d" % (os.getpid(), fileno))

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


Re: Check for dict key existence, and modify it in one step.

2007-08-29 Thread Bruno Desthuilliers
rodrigo a écrit :
> You're right of course, I was unclear. I wasn't using 'dict' to
> override the dict clas, but just as a standin for the example (the
> actual dictionary names are varied).

I guessed so, but Python's behaviour wrt/ naming can be somewhat 
surprising for newcomers, and accidentally shadowing builtins (or not 
builtins FWIW) names is a common pitfall. So better to warn newcomers 
lurking here !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: status of Programming by Contract (PEP 316)?

2007-08-29 Thread Michele Simionato
On Aug 29, 8:45 am, Russ <[EMAIL PROTECTED]> wrote:
> I get the strong impression you don't really understand what
> programming by contract is.
>
> I have not yet personally used it, but I am interested in anything
> that can help to make my programs more reliable. If you are
> programming something that doesn't really need to be correct, than you
> probably don't need it. But if you really need (or want) your software
> to be correct and reliable as possible, I think you you should be
> interested in it. You might want to read this:
>
> http://archive.eiffel.com/doc/manuals/technology/contract/ariane/page...

That paper contains only a good think: a link to the contrarian view
http://home.flash.net/~kennieg/ariane.html#s3.1.5

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


Pythonwin Install COM exceptions on Windows Vista Ultimate

2007-08-29 Thread Sandipan News
What do I do? Can't do without Python!
Any experience, advice, hope is welcome.
Thanks.
Sandipan


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


Re: encoding problems

2007-08-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, tool69 wrote:

> p2.content = """Ce poste possède des accents : é à ê è"""

My guess is this is being encoded as a Latin-1 string, but when you try to
output it it goes through the ASCII encoder, which doesn't understand the
accents. Try this:

p2.content = u"""Ce poste possède des accents : é à ê è""".encode("utf8")

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

Re: Jython 2.2 on Ubuntu

2007-08-29 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Neil Wallace wrote:

> I have used the
> GUI installer of Jython 2.2, and installed it to the default
> /root/jython2.2 directory.

You do realize that /root is the home directory of the root user, normally
off-limits to normal users?

Usually if you're installing your own packages, you would put them
in /usr/local or /opt.

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


Re: encoding problems

2007-08-29 Thread Diez B. Roggisch
tool69 wrote:

> Hi,
> 
> I would like to transform reST contents to HTML, but got problems
> with accented chars.
> 
> Here's a rather simplified version using SVN Docutils 0.5:
> 
> %-
> 
> #!/usr/bin/env python
> # -*- coding: utf-8 -*-


This declaration only affects unicode-literals.

> from docutils.core import publish_parts
> 
> class Post(object):
>  def __init__(self, title='', content=''):
>  self.title = title
>  self.content = content
> 
>  def _get_html_content(self):
>  return publish_parts(self.content,
>  writer_name="html")["html_body"]
>  html_content = property(_get_html_content)

Did you know that you can do this like this:

@property
def html_content(self):
...

?

> # Instanciate 2 Post objects
> p1 = Post()
> p1.title = "First post without accented chars"
> p1.content = """This is the first.
> ...blabla
> ... end of post..."""
> 
> p2 = Post()
> p2.title = "Second post with accented chars"
> p2.content = """Ce poste possède des accents : é à ê è"""


This needs to be a unicode-literal:

p2.content = u"""Ce poste possède des accents : é à ê è"""

Note the u in front.
 
> for post in [p1,p2]:
>  print post.title, "\n" +"-"*30
>  print post.html_content
> 
> %-
> 
> The output gives me :
> 
> First post without accented chars
> --
> 
> This is the first.
> ...blabla
> ... end of post...
> 
> 
> Second post with accented chars
> --
> Traceback (most recent call last):
> File "C:\Documents and
> Settings\kib\Bureau\Projets\python\dbTest\rest_error.py", line 30, in
> 
> print post.html_content
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
> position 39:
> ordinal not in range(128)

You need to encode a unicode-string into the encoding you want it.
Otherwise, the default (ascii) is taken.

So 

print post.html_content.encodec("utf-8")

should work.

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

Re: encoding problems

2007-08-29 Thread tool69
Lawrence D'Oliveiro a écrit :
> In message <[EMAIL PROTECTED]>, tool69 wrote:
> 
>> p2.content = """Ce poste possède des accents : é à ê è"""
> 
> My guess is this is being encoded as a Latin-1 string, but when you try to
> output it it goes through the ASCII encoder, which doesn't understand the
> accents. Try this:
> 
> p2.content = u"""Ce poste possède des accents : é à ê è""".encode("utf8")
> 

Thanks for your answer Lawrence, but I always got the error.
Any other idea ?

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

Re: Gmane's been quiet ...

2007-08-29 Thread Lawrence Oluyede
Grant Edwards <[EMAIL PROTECTED]> wrote:
> Posting that were made to mailing lists via gmane?

That, I do not know

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problems

2007-08-29 Thread tool69
Diez B. Roggisch a écrit :
> tool69 wrote:
> 
>> Hi,
>>
>> I would like to transform reST contents to HTML, but got problems
>> with accented chars.
>>
>> Here's a rather simplified version using SVN Docutils 0.5:
>>
>> %-
>>
>> #!/usr/bin/env python
>> # -*- coding: utf-8 -*-
> 
> 
> This declaration only affects unicode-literals.
> 
>> from docutils.core import publish_parts
>>
>> class Post(object):
>>  def __init__(self, title='', content=''):
>>  self.title = title
>>  self.content = content
>>
>>  def _get_html_content(self):
>>  return publish_parts(self.content,
>>  writer_name="html")["html_body"]
>>  html_content = property(_get_html_content)
> 
> Did you know that you can do this like this:
> 
> @property
> def html_content(self):
> ...
> 
> ?
> 

I only took some part of code from someone else
(an old TurboGears tutorial if I remember).

But you're right : decorators are better.

>> # Instanciate 2 Post objects
>> p1 = Post()
>> p1.title = "First post without accented chars"
>> p1.content = """This is the first.
>> ...blabla
>> ... end of post..."""
>>
>> p2 = Post()
>> p2.title = "Second post with accented chars"
>> p2.content = """Ce poste possède des accents : é à ê è"""
> 
> 
> This needs to be a unicode-literal:
> 
> p2.content = u"""Ce poste possède des accents : é à ê è"""
> 
> Note the u in front.
>  


> 
> You need to encode a unicode-string into the encoding you want it.
> Otherwise, the default (ascii) is taken.
> 
> So 
> 
> print post.html_content.encodec("utf-8")
> 
> should work.
> 

That solved it : thank you so much.

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

Error handling in file generation (Pythonic way: with / decorators?)

2007-08-29 Thread xavim
Hi everyone,

I am writing a small tool that generates a file from a list of
sources.
The function dictgen(dictfile, *sources) takes a list of sources path
and an open file object and does the processing.

I am having some problems with how to do proper error handling.
One of the requirements is that the destination file should not be
created if there is any error in the processing.

I have come out with the following code::

dictfile = file(dictpath, 'w')
try:
try:
dictgen(dictfile, *sources)
finally:
dictfile.close()
except error, e:
os.remove(dictpath)
sys.exit(str(e))
except:
os.remove(dictpath)

but it appears to me as somewhat ugly.  Is there any more Pythonic
way to abstract this kind of error handling?  Maybe 'with' or
decorators could be useful here?

Thanks,
Xavi

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


Re: Error handling in file generation (Pythonic way: with / decorators?)

2007-08-29 Thread xavim
On Aug 29, 10:58 am, xavim <[EMAIL PROTECTED]> wrote:
> (...)
> try:
> (...)
> except:
> os.remove(dictpath)

This should read::

try:
(...)
except:
os.remove(dictpath)
raise

Sorry.

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


Re: How to parse this line of code manually

2007-08-29 Thread Davy
On Aug 28, 7:28 pm, Dustan <[EMAIL PROTECTED]> wrote:
> On Aug 28, 2:59 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On 2007-08-28, Davy <[EMAIL PROTECTED]> wrote:
>
> > > On Aug 28, 11:00 am, Davy <[EMAIL PROTECTED]> wrote:
> > >> Hi all,
>
> > >> It is well known that Python is appreciated for its merit of concise.
> > >> However, I found the over concise code is too hard to understand for
> > >> me.
>
> > >> Consider, for instance,
> > >> def known_edits2(word):
> > >> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in
> > >> NWORDS)
>
> > >> Shall I understand the code in set() as
> > >> for e2 in edits1(e1) {
> > >> if e2 in NWORDS {
> > >> for e1 in edits1(word) {
> > >>  e2
> > >> }
> > >> }
>
> > >> }
>
> > > [SNIP]
> > > Hi all, I figured it myself. It is left to righ parse, right?
> > > So the above one is like
> > > for e1 in edits1(word) {
> > > for e2 in edits1(e1) {
> > > if e2 in NWORDS {
> > > push e2 to set
> > > }
> > > }
> > > }
>
> > This is correct, although I am not sure what language you are using here, it
> > looks like a strange mix of Python and C to me.
>
> > >> Any suggestions are welcome!
>
> > The idea is known as List comprehension (for lists, obviously), and comes 
> > from
> > functional programming, Bird & Wadler used it in their book.
>
> > The notation is very close to mathematics:
>
> >  { e2 | e1: edits(word), e2: edits(e1) in NWORDS }
>
> > or in LaTeX:
>
> > $\{ e_2 | \forall e_1: \mathrm{edits}(\mathrm{words}),
> >   \forall e_2: \mathrm{edits}(e_1) \in \mathrm{NWORDS} \}$
>
> > :-)
>
> > (which in words is something like: collect values e2, where e1 comes from
> > 'edits(word)', e2 comes from 'edits(e1)', and e2 in NWORDS)
>
> For more 
> examples:http://docs.python.org/tut/node7.html#SECTION00714
[SNIP]
Hi Hofkamp and Dustan,

Thank you for your help :)

Davy
>
> A 'list comprehension' with parentheses instead of square-brackets
> creates a generator instead of a list, which can be more memory-
> efficient and allows for lazy evaluation.- Hide quoted text -
>
> - Show quoted text -


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


Re: Error handling in file generation (Pythonic way: with / decorators?)

2007-08-29 Thread Marc 'BlackJack' Rintsch
On Wed, 29 Aug 2007 08:58:52 +, xavim wrote:

> I am having some problems with how to do proper error handling.
> One of the requirements is that the destination file should not be
> created if there is any error in the processing.
> 
> I have come out with the following code::
> 
> dictfile = file(dictpath, 'w')
> try:
> try:
> dictgen(dictfile, *sources)
> finally:
> dictfile.close()
> except error, e:
> os.remove(dictpath)
> sys.exit(str(e))
> except:
> os.remove(dictpath)
> 
> but it appears to me as somewhat ugly.  Is there any more Pythonic
> way to abstract this kind of error handling?  Maybe 'with' or
> decorators could be useful here?

With ``with`` you can get rid of the inner ``try``/``finally``:

dictfile = open(dictpath, 'w')
try:
with dictfile:
dictgen(dictfile, sources)
except error, e:
os.remove(dictpath)
sys.exit(str(e))
except:
os.remove(dictpath)
raise

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Haskell like (c:cs) syntax

2007-08-29 Thread Marco Mariani
Ricardo Aráoz ha scritto:

> L = ['one', 'two', 'three', 'four', 'five']
> 
> print L[0]# This would be 'head'
> print L[1:]   # This would be 'tail'
> 
> Caution : L[0] and L[1:] are COPIES of the head and tail of the list.

This might surprise people who see L[1:] = [], since changing a copy is 
not supposed to change the original.

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


Re: advice about `correct' use of decorator

2007-08-29 Thread BJörn Lindqvist
On 8/24/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Thu, 23 Aug 2007 09:20:21 -0300, BJörn Lindqvist <[EMAIL PROTECTED]>
> escribi�:
>
> > def check_user_logged_in(func):
> > def f(*args, **kwargs):
> > if global_state.the_user.is_logged_in:
> > return func(*args, **kwargs)
> > return show_login_page()
> > return f
>
> I think there is a semantic problem, perhaps we are not talking
> about the same thing. I'm considering the software complexity AS
> PERCEIVED BY THE PROGRAMMER, looking at the interactions between a
> program and a programmer who is working on some task; some people
> would say "cognitive complexity" to make it clear.

There is no semantic problem. You are just mistaken in your belief
that the complexity that the user of the decorator has to deal with is
different from the complexity in implementing the decorator.

> Which API is more complex: one in which you can play a movie with
> just a single call like PlayMovie(Title), or one on which you must
> call a zillion functions to firtly initialize the stream format,
> configure the display, disable undesired user interfase elements,
> locate the movie file, load it in chunks, etc.? The first one is
> certainly much simpler to use (simpler = less complex), and maybe
> internally it calls the same functions as the second one, but nobody
> cares.

"nobody cares" is your guess. I'd bet that the caller of the PlayMovie
function cares a lot: Is the movie played full screened? Which
encodings are supported? Can you set the title of the movie window? Is
streaming supported? Does it even work on windows? Which URI schemes
does it support?  And so on and so on.

That is why no video decoding API:s have a PlayMovie(Title) function
and why I haven't seen a single 3d engine with a
MakeReallyCoolDoomCloneFPSGame() function.

"hiding details" only works if the client programmer really doesn't
care about the details.

> Back to your example, the fact that a decorator builds a higher order
> function, does NOT make it more complex - because the programmer does not
> see that. In fact, hiding the details makes it simpler.

Yes, the programmer does see that. The example decorator I posted
requires about a zillion preconditions to work correctly and will fail
in weird ways when those preconditions are not satisfied. The
programmer is interested in the crazy failures he or she will
experience. I dare you to try and implementing the code both as a
decorator and as a function, then write the unit tests and
documentation. The complexity of those three items together
(implementation + tests + documentation) will be much higher for the
decorator choice because the complexity of the decorator
implementation is a bit higher than using a plain old function.

Note also that it is extremely rare to see well-documented or
well-tested code, which means that the programmer WILL have to analyze
the implementation which means that implementation complexity matters
a lot.


-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tempfile.mkstemp and os.fdopen

2007-08-29 Thread Nick Craig-Wood
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
>  In message <[EMAIL PROTECTED]>, Michael
>  J. Fromberger wrote:
> 
> > ... since os.fdopen() only has access to the file descriptor, it
> > does not have a convenient way to obtain the file's name.
> 
>  You can do this under Linux as follows:
> 
>  os.readlink("/proc/%d/fd/%d" % (os.getpid(), fileno))

A good idea!  You can write this slightly more succinctly as

  os.readlink("/proc/self/fd/%d" % fileno)

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Haskell like (c:cs) syntax

2007-08-29 Thread Nick Craig-Wood
Erik Jones <[EMAIL PROTECTED]> wrote:
>  front, last = l[:len(l) - 1], l[len(l) - 1]

Normally written as

  front, last = l[:-1], l[-1]

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Gmane's been quiet ...

2007-08-29 Thread Steve Holden
Lawrence Oluyede wrote:
> Grant Edwards <[EMAIL PROTECTED]> wrote:
>> Posting that were made to mailing lists via gmane?
> 
> That, I do not know
> 
Given that I have now read a reply to my post-via-gmane on gmane before 
seeing the original post appear there I shall assume they've been having 
some sort of issue.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Creating a multi-tier client/server application

2007-08-29 Thread Bruno Desthuilliers
Paul Rubin a écrit :
> Jeff <[EMAIL PROTECTED]> writes:
>> Here's a broad overview of what I need to do:  cross-platform, client-
>> side GUI apps that interact with a server backed by a database.  I'd
>> also like the possibility of having a web interface for small portions
>> of the app.  ...  any advice on anything I've mentioned
>> (or haven't?) 
> 
> Why not do the entire app as a web app, completely bagging the client
> side and just using a browser?  It will help your deployment problems
> a lot, and using https will help with security since it looks like the
> app will be transmitting sensitive data.  It also will simplify your
> networking questions a lot since you're just writing a server.
> 
(snip)
> 
> I would certainly prototype the app as a web app, and then think about
> writing a client gui only if it was clear that usability would really
> benefit from it.  Even still, the server would still look like a web
> server, translating xml requests into database actions and responding
> with xml.

I'd personnaly favor json, which is much more lightweight, perfect for 
structured data, and widely supported.

Else, and however the client is implemented (rich client or web - 
another possible solution being something based on the Mozilla platform, 
but I have no working experience with it so I can't tell if it's a good 
idea...), I'd second the suggestion to have a closer look at the http 
protocol. There's no shortage of support for writing http-based server 
applications in Python (given the context, I'd strongly suggest Pylons).

>> I want to plan this application out as thoroughly
>> as possible before writing any code, 
> 
> There is a school of thought (sometimes associated with "extreme
> programming") that this is more planning than you should really do.
> Think of a cross-country automobile trip.  Figure out the general
> route you want to take, then get in the car and go, making low-level
> decisions as you get to them, rather than trying to plan every gas and
> rest and restaurant stop before you leave.

Anyway, unless you're a genius with decades of working experience, you 
can bet you'll make lots of mistakes in your "planning", mistakes that 
you'll discover when implementing a probably over-engineered design. I'm 
of course *not* advertising a cowboy-coding approach here, and 
preliminary work is certainly mandatory for anything non-trivial, but 
take care about what you really have to worry about here. AFAICT, you 
seem to be on the right track so far (thinking about the possible 
architectures given some already known requirements), but AMHE, 
BigDesignUpFront just doesn't work, so don't overplan.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tempfile.mkstemp and os.fdopen

2007-08-29 Thread billiejoex
Gabriel Genellina wrote:

> As someone already suggested, why don't you use TemporaryFile or
> NamedTemporaryFile and avoid such problems?

Because I don't want file to be removed after closing.

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


Re: Unable to read large files from zip

2007-08-29 Thread Nick Craig-Wood
Kevin Ar18 <[EMAIL PROTECTED]> wrote:
> 
>  I posted this on the forum, but nobody seems to know the solution: 
> http://python-forum.org/py/viewtopic.php?t=5230
> 
>  I have a zip file that is several GB in size, and one of the files inside of 
> it is several GB in size.  When it comes time to read the 5+GB file from 
> inside the zip file, it fails with the following error:
>  File "...\zipfile.py", line 491, in read bytes = 
> self.fp.read(zinfo.compress_size)
>  OverflowError: long it too large to convert to int

That will be an number which is bigger than 2**31 == 2 GB which can't
be converted to an int.

It would be explained if zinfo.compress_size is > 2GB, eg

  >>> f=open("z")
  >>> f.read(2**31)
  Traceback (most recent call last):
File "", line 1, in ?
  OverflowError: long int too large to convert to int

However it would seem nuts that zipfile is trying to read > 2GB into
memory at once!

>  There have been one or more posts about 2GB limits with the zipfile
>  module, as well as this bug report:
>  http://bugs.python.org/issue1189216 Also, older zip formats have a
>  4GB limit.  However, I can't say for sure what the problem is.
>  Does anyone know if my code is wrong

Your code looks OK to me.

>  or if there is a problem with Python itself?

Looks likely.

>  If Python has a bug in it

...then you have the source and you can have a go at fixing it!

Try editing zipfile.py and getting it to print out some debug info and
see if you can fix the problem.  When you have done submit the patch
to the python bug tracker and you'll get that nice glow from helping
others! Remember python is open source and is made by *us* for *us* :-)

If you need help fixing zipfile.py then you'd probably be better off
asking on python-dev.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encoding problems

2007-08-29 Thread Ricardo Aráoz
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, tool69 wrote:
> 
>> p2.content = """Ce poste possède des accents : é à ê è"""
> 
> My guess is this is being encoded as a Latin-1 string, but when you try to
> output it it goes through the ASCII encoder, which doesn't understand the
> accents. Try this:
> 
> p2.content = u"""Ce poste possède des accents : é à ê è""".encode("utf8")
> 

is there a way to sort this string properly (sorted()?)
I mean first 'a' then 'à' then 'e' etc. (sorted puts accented letters at
the end). Or should I have to provide a comparison function to sorted?



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

self extracting zipefile (windows) and (standard module) zipefile

2007-08-29 Thread Werner
Hi,


I try to read (and extract) some "self extracting" zipefiles on a
Windows system. The standard module zipefile seems not to be able to
handle this.

>>> fName = r"C:\tmp\mySelfExtratingFile.exe"
>>> import zipfile
>>> zipefile.is_zipfile(fName))
False

Is there a wrapper or has some one experience with other libaries to
extract those files?


Thanks in advance
Werner

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


Code design problem

2007-08-29 Thread Marco Nawijn
Hello,

I have a hard time figuring out an elegant and efficient design for
the following problem.

I am working on automation of structural design problems. In the
majority of cases, this boils down to executing programs in batch in
one or more loops. The scripts to control the execution differ from
fortran to bash to python and so on. Most of them are ad hoc and what
I call 'throw away scripts'. In order to improve the situation I would
like to develop a Python module that supports the execution of
external programs. Ideally I would like to make running locally or
remote trivial for the users of the module. As an example, I would
like the following (pseudo)-code to work:

app = Application('patran')# Run on local
machine
app.start(args)


app = Application('patran', host='myhost')   # Run on remote machine
app.start(args)

The problem I face is that the implementation of the application class
is completely
different for the local and remote case. The local case is a
straightforward implemenation using the subprocess module, the remote
case is a CORBA implementation. Somehow I would like to switch from
implementation class at runtime depending on whether or not the host
parameter is specified or not.

The Application, local implementation and remote implementation all
have the same interface, so a possibility might be something like the
following:

class Interface(object):
 .
 def start(self): pass
 def stop(self): pass

class LocalImplementation(Interface):
   .

class GlobalImplementation(CorbaGlobalImplementation, Interface):
   .


class Application(Interface):

  def __init__(self, program, host=None):

if host:
   self.__impl = LocalImplementation(program)
else:
   self.__impl = GlobalImplementation(program, host)

  #  Forward all methods to the implementation class
  def start(self):
  self.__impl.start()

  def stop(self):
  self.__impl.stop()


To me forwarding each call in the Application class looks a little bit
redundant and I would like to get rid of it. Does anyone have any
comments or suggestions? Can metaclass programming come to rescue?

Kind regards,


Marco Nawijn

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


Re: Haskell like (c:cs) syntax

2007-08-29 Thread Ricardo Aráoz
Marco Mariani wrote:
> Ricardo Aráoz ha scritto:
> 
>> L = ['one', 'two', 'three', 'four', 'five']
>>
>> print L[0]# This would be 'head'
>> print L[1:]   # This would be 'tail'
>>
>> Caution : L[0] and L[1:] are COPIES of the head and tail of the list.
> 
> This might surprise people who see L[1:] = [], since changing a copy is 
> not supposed to change the original.
> 

Sorry, should have written RETURN copies instead of ARE copies.

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


Re: encoding problems

2007-08-29 Thread Diez B. Roggisch
Ricardo Aráoz wrote:

> Lawrence D'Oliveiro wrote:
>> In message <[EMAIL PROTECTED]>, tool69 wrote:
>> 
>>> p2.content = """Ce poste possède des accents : é à ê è"""
>> 
>> My guess is this is being encoded as a Latin-1 string, but when you try
>> to output it it goes through the ASCII encoder, which doesn't understand
>> the accents. Try this:
>> 
>> p2.content = u"""Ce poste possède des accents : é à ê è""".encode("utf8")
>> 
> 
> is there a way to sort this string properly (sorted()?)
> I mean first 'a' then 'à' then 'e' etc. (sorted puts accented letters at
> the end). Or should I have to provide a comparison function to sorted?

First of all: please don't hijack threads. Start a new one with your
specific question.

Second: this might be what you are looking for:

http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/

Didn't try it myself though.

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

handling tabular data in python--newbie question

2007-08-29 Thread hyena
Hi,
  Just jump in python few days. I am wondering how to store and index a 
table in python effectively and easily.I think the basic data types are not 
very straight foward to handle a table (eg, from csv or data base.)

  I have a csv file, the first row of it is column names and the rest rows 
are data. There are some tens of columns and hundreds rows in the file. I am 
planning to use the column names as variables to access data, currently I am 
thinking of using a dictionary to store this file but did not figure out a 
elegant way to start.

  Any comments and suggestions are wellcomed. Please forgive me if this 
question is too naive , and yes, I did search google  a while but did not 
find what I want.

Thanks 


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


Re: Unable to read large files from zip

2007-08-29 Thread David Bolen
Nick Craig-Wood <[EMAIL PROTECTED]> writes:

> Kevin Ar18 <[EMAIL PROTECTED]> wrote:
>> 
>>  I posted this on the forum, but nobody seems to know the solution: 
>> http://python-forum.org/py/viewtopic.php?t=5230
>> 
>>  I have a zip file that is several GB in size, and one of the files inside 
>> of it is several GB in size.  When it comes time to read the 5+GB file from 
>> inside the zip file, it fails with the following error:
>>  File "...\zipfile.py", line 491, in read bytes = 
>> self.fp.read(zinfo.compress_size)
>>  OverflowError: long it too large to convert to int
>
> That will be an number which is bigger than 2**31 == 2 GB which can't
> be converted to an int.
>
> It would be explained if zinfo.compress_size is > 2GB, eg
>
>   >>> f=open("z")
>   >>> f.read(2**31)
>   Traceback (most recent call last):
> File "", line 1, in ?
>   OverflowError: long int too large to convert to int
>
> However it would seem nuts that zipfile is trying to read > 2GB into
> memory at once!

Perhaps, but that's what the read(name) method does - returns a string
containing the contents of the selected file.  So I think this runs
into a basic issue of the maximum length of Python strings (at least
in 32bit builds, not sure about 64bit) as much as it does an issue
with the zipfile module.  Of course, the fact that the only "read"
method zipfile has is to return the entire file as a string might
be considered a design flaw.

For the OP, if you know you are going to be dealing with very large
files, you might want to implement your own individual file
extraction, since I'm guessing you don't actually need all 5+GB of the
problematic file loaded into memory in a single I/O operation,
particularly if you're just going to write it out again, which is what
your original forum code was doing.

I'd probably suggest just using the getinfo(name) method to return the
ZipInfo object for the file in question, then process the appropriate
section of the zip file directly.  E.g., just seek to the proper
offset, then read the data incrementally up to the full size from the
ZipInfo compress_size attribute.  If the files are compressed, you can
incrementally hand their data to the decompressor prior to other
processing.

E.g., instead of your original:

fileData = dataObj.read(i)
fileHndl = file(fileName,"wb")
fileHndl.write(fileData)
fileHndl.close()

something like (untested):

CHUNK = 65536# I/O chunk size

fileHndl = file(fileName,"wb")

zinfo = dataObj.getinfo(i)
compressed = (zinfo.compress_type == ZLIB_DEFLATED)
if compressed:
dc = zlib.decompressobj(-15)

dataObj.fp.seek(zinfo.header_offset+30)
remain = zinfo.compress_size
while remain:
bytes = dataObj.fp.read(min(remain, CHUNK))
remain -= len(bytes)
if compressed:
bytes = dc.decompress(bytes)
fileHndl.write(bytes)

if compressed:
bytes = dc.decompress('Z') + dc.flush()
if bytes:
fileHndl.write(bytes)

fileHndl.close()

Note the above assumes you are only reading from the zip file as it
doesn't maintain the current read() method invariant of leaving the
file pointer position unchanged, but you could add that too.  You
could also verify the file CRC along the way if you wanted to.

Might be even better if you turned the above into a generator, perhaps
as a new method on a local ZipFile subclass.  Use the above as a
read_gen method with the write() calls replaced with "yield bytes",
and your outer code could look like:

fileHndl = file(fileName,"wb")
for bytes in dataObj.read_gen(i):
fileHndle.write(bytes)
fileHndl.close()

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


Re: Code design problem

2007-08-29 Thread Marshall T. Vandegrift
Marco Nawijn <[EMAIL PROTECTED]> writes:

> The problem I face is that the implementation of the application class
> is completely different for the local and remote case. The local case
> is a straightforward implemenation using the subprocess module, the
> remote case is a CORBA implementation. Somehow I would like to switch
> from implementation class at runtime depending on whether or not the
> host parameter is specified or not.
>
> The Application, local implementation and remote implementation all
> have the same interface, so a possibility might be something like the
> following:



> To me forwarding each call in the Application class looks a little bit
> redundant and I would like to get rid of it. Does anyone have any
> comments or suggestions? Can metaclass programming come to rescue?

It sounds like you could probably get away with just a factory function:

def Application(program, host=None):
if host is None:
return LocalApplication(program)
else:
return RemoteApplication(program, host)

Then just implement the same interface and/or derive from a common base
class for LocalApplication and RemoteApplication.

HTH!,

-Marshall

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


Re: handling tabular data in python--newbie question

2007-08-29 Thread Bruno Desthuilliers
hyena a écrit :
> Hi,
>   Just jump in python few days. I am wondering how to store and index a 
> table in python effectively and easily.I think the basic data types are not 
> very straight foward to handle a table (eg, from csv or data base.)

What make you think such a thing ?

>   I have a csv file, the first row of it is column names and the rest rows 
> are data. There are some tens of columns and hundreds rows in the file. I am 
> planning to use the column names as variables to access data, currently I am 
> thinking of using a dictionary to store this file but did not figure out a 
> elegant way to start.

Use the csv module - it's in the standard lib. It has an option to use 
dicts to allow keyed access to 'columns' (look for csv.DictReader).

Anyway, if you have anything complex to do with your data, you'd 
probably better use SQLite (possibly using csv module to help importing 
your data).

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code design problem

2007-08-29 Thread Sion Arrowsmith
Marco Nawijn  <[EMAIL PROTECTED]> wrote:
>I have a hard time figuring out an elegant and efficient design for
>the following problem.

What you want is known as the factory pattern.

> [ ... ] I would
>like the following (pseudo)-code to work:
>
>app = Application('patran')  # Run on local machine
>app.start(args)
>
>app = Application('patran', host='myhost')   # Run on remote machine
>app.start(args)
>
>The Application, local implementation and remote implementation all
>have the same interface, so a possibility might be something like the
>following:
>
>class Interface(object):
> .
> def start(self): pass
> def stop(self): pass

You don't need an abstract interface like this in Python. Duck-
typing will take care of it for you. On the other hand, if you
do have common code between the local and global implementations,
it makes sense to share it in a base class. You might then want
to consider defining the methods which must be overridden as

def start(self): raise NotImplementedError
etc.

Given:

>class LocalImplementation(Interface):
>   .
>
>class GlobalImplementation(CorbaGlobalImplementation, Interface):
>   .

with suitable start and stop methods defined, all you need is
an Application factory function:

def Application(program, host=None):
if host is None:
return LocalImplementation(program)
return GlobalImplementation(program, host)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Haskell like (c:cs) syntax

2007-08-29 Thread Istvan Albert
On Aug 29, 8:12 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:

> >> Caution : L[0] and L[1:] are COPIES of the head and tail of the list.

> Sorry, should have written RETURN copies instead of ARE copies.

L[0] does not return a copy, it does what is says, returns the object
stored at index 0.

i.

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

Re: Code design problem

2007-08-29 Thread Bruno Desthuilliers
Marco Nawijn a écrit :
> Hello,
> 
> I have a hard time figuring out an elegant and efficient design for
> the following problem.
> 
> I am working on automation of structural design problems. In the
> majority of cases, this boils down to executing programs in batch in
> one or more loops. The scripts to control the execution differ from
> fortran to bash to python and so on. Most of them are ad hoc and what
> I call 'throw away scripts'. In order to improve the situation I would
> like to develop a Python module that supports the execution of
> external programs. Ideally I would like to make running locally or
> remote trivial for the users of the module. As an example, I would
> like the following (pseudo)-code to work:
> 
> app = Application('patran')# Run on local
> machine
> app.start(args)
> 
> 
> app = Application('patran', host='myhost')   # Run on remote machine
> app.start(args)
> 
> The problem I face is that the implementation of the application class
> is completely
> different for the local and remote case. The local case is a
> straightforward implemenation using the subprocess module, the remote
> case is a CORBA implementation. Somehow I would like to switch from
> implementation class at runtime depending on whether or not the host
> parameter is specified or not.

The solution is quite straightforward, and is known as the "factory" 
design pattern.

> The Application, local implementation and remote implementation all
> have the same interface, so a possibility might be something like the
> following:
> 
> class Interface(object):
>  .
>  def start(self): pass
>  def stop(self): pass

What's the use of this class ? In Python, inheritance is for 
implementation only.

> class LocalImplementation(Interface):
>.
> 
> class GlobalImplementation(CorbaGlobalImplementation, Interface):
>.
> 
> 
> class Application(Interface):
> 
>   def __init__(self, program, host=None):
> 
> if host:
>self.__impl = LocalImplementation(program)
> else:
>self.__impl = GlobalImplementation(program, host)
> 
>   #  Forward all methods to the implementation class
>   def start(self):
>   self.__impl.start()
> 
>   def stop(self):
>   self.__impl.stop()
> 

My my my... How to uselessly overcomplexify things...

class LocalApp(object):
   def __init__(self, program):
 # code here
   def start(self):
 # code here
   def stop(self):
 # code here

class RemoteApp(object):
   def __init__(self, program, host):
 # code here
   def start(self):
 # code here
   def stop(self):
 # code here

def Application(program, host=None):
   if host is None:
 return LocalApp(program)
   else:
 return RemoteApp(program, host)



> To me forwarding each call in the Application class looks a little bit
> redundant 

Indeed !-)

> and I would like to get rid of it. 

cf above. But in case you need to do proper delegation in Python, the 
magic words are "__getattr__" and "__setattr__". Here's a very basic 
example of using __getattr__ - using __setattr__ is a bit more tricky, 
but you'll find all relevant documentation in the FineManual(tm):

class Wrapper(object):
   def __init__(self, obj):
 self.__obj = obj

   def __getattr__(self, name):
 return getattr(self.__obj, name)

> Does anyone have any
> comments or suggestions? Can metaclass programming come to rescue?

May I suggest that you first learn Python bases before going into 
complex things ?

And FWIW, googling for "KISS" might help too !-)

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


Re: self extracting zipefile (windows) and (standard module) zipefile

2007-08-29 Thread Hyuga
First of all, there's really no such thing as a "self extracting
zipefile".  I mean, obviously you have to do something to unzip it.  A
file doesn't just execute itself.  What you're dealing with is not a
_zip file_.  It's an executable that has a zip file bundled with it,
and the code to unzip it, most likely into your current directory
(though some such executables allow you to provide a path to unzip
to).  You'll have to execute it--there's no way you can operate on it
like a normal zip file.

On Aug 29, 7:53 am, Werner <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I try to read (and extract) some "self extracting" zipefiles on a
> Windows system. The standard module zipefile seems not to be able to
> handle this.
>
> >>> fName = r"C:\tmp\mySelfExtratingFile.exe"
> >>> import zipfile
> >>> zipefile.is_zipfile(fName))
>
> False
>
> Is there a wrapper or has some one experience with other libaries to
> extract those files?
>
> Thanks in advance
> Werner

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


Re: Pythonwin Install COM exceptions on Windows Vista Ultimate

2007-08-29 Thread kyosohma
On Aug 28, 8:20 pm, "Sandipan News" <[EMAIL PROTECTED]> wrote:
> What do I do? Can't do without Python!
> Any experience, advice, hope is welcome.
> Thanks.
> Sandipan

You need to post the error traceback along with some more information
so the community can help.

Mike

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


Re: Creating a multi-tier client/server application

2007-08-29 Thread Jeff
Thanks for the quick responses.

I was really hoping to avoid an entirely web-based app, for a few
reasons, not the least of which is that I've been working almost
entirely on web apps for the past few years, and I am getting mighty
sick of it.  A lot of that is due to the language (PHP, which I have
since grown to hate) I had to use.  I've worked on a site for my self
in Python (using Pylons, actually--which is excellent) which was
vastly easier and more fun.  But I'd really like to try something
different.

Now, of course, that's not enough reason to force such a thing onto my
clients (when I say clients, I mean the ones that are paying for this,
but they're really within my same department, so they actually have
working technical knowledge.)  Some reasons for them would be (in no
particular order): 1) More responsive and user-friendly interfaces, 2)
Much better ability to sort, export, import, and print data (very
important), 3) Easier to "lock down" who's using the program by only
installing it on certain machines.

Paul, I've read through a bunch your conversation with Chris--for
simple applications, yes, you're right, why not use the browser?  But
for a lot of this I have to agree with him (although I don't
particularly agree with his tone, but that's irrelevant.)  This will
be a complex enough application that certainly simple HTML & CSS won't
be enough, and the thought of the sheer amount of AJAX trickery (yes,
trickery) that I'll need to use just to get it even *close* to the
usability of a desktop app is rather frightening.  I've done plenty of
stuff with AJAX, and it certainly has its purpose, but it gets
incredibly bloated and fragile *very* quickly.

This application will be used by hundred of people (some of them will
be using it more or less constantly) across several departments in a
large university (Rutgers, if you're interested.)  Because of that, it
needs to work, and last for years--with changes over that time, of
course, but no rewrites--a lot of their current systems are FileMaker
Pro databases... all I can say is, "the horror".  They've used some of
these systems for the past *ten* years with their "databases" breaking
several times a *week*.  Now, they want something that *works*.

Which leads me to the discussion of planning:  if this were a basic
application for myself, I'd plan out the basic objects and database
tables I'd need, and how they should interact--maybe to some extent
what the user interface should work/look like.  But I'd certainly be
flexible.  In this situation, however, I have no such luxury.

This system will be used, often, to figure out how much people should
be paid (and then interface directly with the University's payroll
system), and store lovely things like SSNs, and will also have to have
somewhat crazy business logic to track when hourly workers are
eligible for raises, if they took enough training classes, etc.  There
are a lot of people with a stake in this system, and I will need to
work with them very closely on how this should work, and they sure as
hell don't want any surprises.  My manager even wants use cases (if
you've never had to deal with use cases, consider yourself a lucky,
lucky person) which I am going to attempt to argue as that is even
going *too* far.

So, long story short (too late), no Extreme Programming for me.
Hopefully, the amount of planning will be somewhere in between that
and the bureaucratic nightmare of documenting up front what each
module, class and function will do.

Thanks again for your advice--I really appreciate it.

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


Re: Haskell like (c:cs) syntax

2007-08-29 Thread Steve Holden
Istvan Albert wrote:
> On Aug 29, 8:12 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
> 
 Caution : L[0] and L[1:] are COPIES of the head and tail of the list.
> 
>> Sorry, should have written RETURN copies instead of ARE copies.
> 
> L[0] does not return a copy, it does what is says, returns the object
> stored at index 0.
> 
Well, if we're going to get picky it actually returns a reference to the 
object referenced by the list item indexed by 0. What was your point?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Python molecular viewer

2007-08-29 Thread Andy Cheesman
Dear People,

I was wondering if people could recommend a simple molecular viewing
package written in python. I'm working in Theoretical chemistry and I'm
not after an all-singing dancing molecular rendering package(pymol does
that rather well) but a program which reads XYZ files and displays
simple structures which can be rotated in 3D

Thanks

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


What's the difference ?

2007-08-29 Thread Alex
Hye,

I was just wondering what is the difference between

>> if my_key in mydict:
>> ...

and

>> if mydict.has_keys(my_key):
>> ...

I've search a bit in the python documentation, and the only things I
found was that they are "equivalent".

But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
Cookbook/Python/Recipe/59875" ), there is difference between the two
notation.

Thanks in advance

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


Re: Creating a multi-tier client/server application

2007-08-29 Thread Bruno Desthuilliers
Jeff a écrit :
> Thanks for the quick responses.
> 
> I was really hoping to avoid an entirely web-based app, for a few
> reasons, not the least of which is that I've been working almost
> entirely on web apps for the past few years, and I am getting mighty
> sick of it.  A lot of that is due to the language (PHP, which I have
> since grown to hate) I had to use.  I've worked on a site for my self
> in Python (using Pylons, actually--which is excellent) which was
> vastly easier and more fun.  But I'd really like to try something
> different.
> 
> Now, of course, that's not enough reason to force such a thing onto my
> clients (when I say clients, I mean the ones that are paying for this,
> but they're really within my same department, so they actually have
> working technical knowledge.)  Some reasons for them would be (in no
> particular order): 1) More responsive and user-friendly interfaces,

You could explore something like a custom-made GUI client app 
communicating thru the http protocol with a web-server app. http is just 
a protocol, and it doesn't necessarily imply using html and a browser... 
IIRC, some GUI toolkits uses XML description files for the UI.

(snip)

> 3) Easier to "lock down" who's using the program by only
> installing it on certain machines.

Not a very reliable security scheme IMHO !-)

(snip)

> Which leads me to the discussion of planning:  
(snip)

> This system will be used, often, to figure out how much people should
> be paid (and then interface directly with the University's payroll
> system), and store lovely things like SSNs, and will also have to have
> somewhat crazy business logic to track when hourly workers are
> eligible for raises, if they took enough training classes, etc.  There
> are a lot of people with a stake in this system, and I will need to
> work with them very closely on how this should work, and they sure as
> hell don't want any surprises.  My manager even wants use cases (if
> you've never had to deal with use cases, consider yourself a lucky,
> lucky person) which I am going to attempt to argue as that is even
> going *too* far.
> 
> So, long story short (too late), no Extreme Programming for me.

Extreme Programming doesn't mean "no preparation", and makes heavy use 
of use cases. Of course you need to have some - hopefully accurate - 
functional specs. The point was mostly along the lines of "don't try to 
have full-featured detailed design before you start coding, because 
chances are it will be wrong".

> Hopefully, the amount of planning will be somewhere in between that
> and the bureaucratic nightmare of documenting up front what each
> module, class and function will do.

Which would be totally non-sensical. I don't believe anyone on earth 
could come up with such a thing - done right - *before* the application 
is written.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to free memory ( ie garbage collect) at run time with Python 2.5.1(windows)

2007-08-29 Thread M�ta-MCI \(MVP\)
Hi! 

I've send the soft.
But, I have no news ; good news? 

@+

Michel Claveau

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


Re: Pythonwin Install COM exceptions on Windows Vista Ultimate

2007-08-29 Thread Larry Bates
Sandipan News wrote:
> What do I do? Can't do without Python!
> Any experience, advice, hope is welcome.
> Thanks.
> Sandipan
> 
> 
If you are asking if you can run COM objects created in Python on Windows Vista 
Ultimate, the answer is yes.  I have several.

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


Re: Getting subprocesses to be hidden on Windows

2007-08-29 Thread kyosohma
On Aug 28, 1:13 pm, geoffbache <[EMAIL PROTECTED]> wrote:
> On 28 Aug, 18:18, Larry Bates <[EMAIL PROTECTED]> wrote:
>
>
>
> > geoffbache wrote:
> > > Hi,
>
> > > As part of my efforts to write a test tool that copes with GUIs
> > > nicely, I'm trying to establish how I can start a GUI process on
> > > Windows that will not bring up the window. So I try to hide the window
> > > as follows:
>
> > > info = subprocess.STARTUPINFO()
> > > info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
> > > info.wShowWindow = subprocess.SW_HIDE
>
> > > proc = subprocess.Popen(..., startupinfo=info)
>
> > > This works, in a way, but doesn't work recursively. I.e. if the
> > > started process itself starts a window, that second window will not be
> > > hidden. This even applies to dialog boxes within the application. So
> > > instead of a lot of windows popping up I now get a lot of disembodied
> > > dialogs appearing, which is a slight improvement but not much.
>
> > > Also, certain processes (e.g. tkdiff) seem to ignore the directive to
> > > be hidden altogether.
>
> > > This is dead easy on UNIX with virtual displays like Xvfb. Can someone
> > > shed any light if it's possible on Windows from python?
>
> > > Regards,
> > > Geoff Bache
>
> > While I'm not entirely sure I understand what you want, I think you can
> > accomplish it by using win32CreateProcess instead of subprocess.  You can 
> > run
> > the application minimized or perhaps in a REALLY small window.  If you have
> > modal dialog boxes, I don't think you can do anything as they don't run in 
> > the
> > parent windows frame but rather outside (I could be wrong about this).
>
> > -Larry
>
> Hi Larry,
>
> I don't know if that would help. I've tried running minimized from the
> command line as
> suggested by Mike and that has the same issue (child windows and
> dialogs don't get minimized)
> So the question is moving away from how to technically achieve this in
> Python to whether
> Windows even supports it...
>
> Geoff

I just discovered Tim Golden's recipe for running processes minimized:
http://tgolden.sc.sabren.com/python/wmi_cookbook.html#run-process-minimised

I haven't tested it, but his stuff usually works. However, it may have
the same issues with modal dialogs that my other suggestion had.

Mike

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


Re: Code design problem

2007-08-29 Thread Marco Nawijn
On Aug 29, 3:03 pm, "Marshall T. Vandegrift" <[EMAIL PROTECTED]>
wrote:
> Marco Nawijn <[EMAIL PROTECTED]> writes:
> > The problem I face is that the implementation of the application class
> > is completely different for the local and remote case. The local case
> > is a straightforward implemenation using the subprocess module, the
> > remote case is a CORBA implementation. Somehow I would like to switch
> > from implementation class at runtime depending on whether or not the
> > host parameter is specified or not.
>
> > The Application, local implementation and remote implementation all
> > have the same interface, so a possibility might be something like the
> > following:
>
> 
>
> > To me forwarding each call in the Application class looks a little bit
> > redundant and I would like to get rid of it. Does anyone have any
> > comments or suggestions? Can metaclass programming come to rescue?
>
> It sounds like you could probably get away with just a factory function:
>
> def Application(program, host=None):
> if host is None:
> return LocalApplication(program)
> else:
> return RemoteApplication(program, host)
>
> Then just implement the same interface and/or derive from a common base
> class for LocalApplication and RemoteApplication.
>
> HTH!,
>
> -Marshall

Thanks! This makes perfect sense. (In these moments I always wonder
why I didn't come up
with this idea...)

Thanks again.

Regards,

Marco

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


Re: Gmane's been quiet ...

2007-08-29 Thread Grant Edwards
On 2007-08-29, Steve Holden <[EMAIL PROTECTED]> wrote:
> Lawrence Oluyede wrote:
>> Grant Edwards <[EMAIL PROTECTED]> wrote:
>>> Posting that were made to mailing lists via gmane?
>> 
>> That, I do not know
>> 
> Given that I have now read a reply to my post-via-gmane on gmane before 
> seeing the original post appear there I shall assume they've been having 
> some sort of issue.

New articles are showing up on gmane's NNTP server now, though
the one posting I made via that server yesterday appears to
have been lost.

-- 
Grant Edwards   grante Yow! MERYL STREEP is my
  at   obstetrician!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: handling tabular data in python--newbie question

2007-08-29 Thread Steve Holden
hyena wrote:
> Hi,
>   Just jump in python few days. I am wondering how to store and index a 
> table in python effectively and easily.I think the basic data types are not 
> very straight foward to handle a table (eg, from csv or data base.)
> 
>   I have a csv file, the first row of it is column names and the rest rows 
> are data. There are some tens of columns and hundreds rows in the file. I am 
> planning to use the column names as variables to access data, currently I am 
> thinking of using a dictionary to store this file but did not figure out a 
> elegant way to start.
> 
>   Any comments and suggestions are wellcomed. Please forgive me if this 
> question is too naive , and yes, I did search google  a while but did not 
> find what I want.
> 
> Thanks 
> 
> 
One way would be to store each row as a dictionary. Suppose your data 
file is called "myfile.txt" and, for simplicity, that columns are 
separated by whitespace. Please note the following code is untested.

f = open("myfile.txt", "r")
names = file.next().split()

So now names contains a list of the field names you want to use. Let's 
store the rows in a dictionary of dictionaries, using the first column 
to index each row.

rows = {}
for line in file:
   cols = line.split()
   rdict =  dict(zip(names, cols))
   rows[cols[0]] = rdict

dict(zip(names, cols)) should create a dictionary where each field is 
stored against its column name. I assume that cols[0] is unique for each 
row, otherwise you will suffer data loss unless you check for that 
circumstance. You can check this kind of thing in the interactive 
interpreter:

 >>> names = ["first", "second", "third"]
 >>> dict(zip(names, [1, 2, 3])
... )
{'second': 2, 'third': 3, 'first': 1}
 >>>

Another alternative, however, would be to create an object for each row 
where the columns are stored as attributes. This approach would be 
useful if the column names are predictable, but rather less so if each 
of your data files were to use different column names. Let us know and 
if appropriate someone can point you at the "bunch" class.

Welcome to Python!

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: self extracting zipefile (windows) and (standard module) zipefile

2007-08-29 Thread kyosohma
On Aug 29, 6:53 am, Werner <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I try to read (and extract) some "self extracting" zipefiles on a
> Windows system. The standard module zipefile seems not to be able to
> handle this.
>
> >>> fName = r"C:\tmp\mySelfExtratingFile.exe"
> >>> import zipfile
> >>> zipefile.is_zipfile(fName))
>
> False
>
> Is there a wrapper or has some one experience with other libaries to
> extract those files?
>
> Thanks in advance
> Werner

Since it's an executable, why not just use the subprocess module?

I did find this set of scripts, but I don't know if they will help:
http://www.example-code.com/python/zip.asp

I did find how to extract via the command line, which you could use in
conjunction with the subprocess module:
http://help.globalscape.com/help/cutezip2/Creating_and_extracting_archives.htm

Mike

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


Re: What's the difference ?

2007-08-29 Thread kyosohma
On Aug 29, 8:39 am, Alex <[EMAIL PROTECTED]> wrote:
> Hye,
>
> I was just wondering what is the difference between
>
> >> if my_key in mydict:
> >> ...
>
> and
>
> >> if mydict.has_keys(my_key):
> >> ...
>
> I've search a bit in the python documentation, and the only things I
> found was that they are "equivalent".
>
> But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
> Cookbook/Python/Recipe/59875" ), there is difference between the two
> notation.
>
> Thanks in advance

Weird. Hetland's book, "Beginning Python" states that it's a matter of
taste. Martelli's "Python Cookbook 2nd Ed." says to use the get()
method instead as you never know if a key is in the dict.  However, I
can't seem to find any reference to has_key in his book.

According to Chun in "Core Python Programming", has_key will be
obsoleted in future versions of Python, so he recommends using "in" or
"not in".

There's your non-answer. Hope that helps.

Mike

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


Re: What's the difference ?

2007-08-29 Thread Marc 'BlackJack' Rintsch
On Wed, 29 Aug 2007 13:39:27 +, Alex wrote:

> Hye,
> 
> I was just wondering what is the difference between
> 
>>> if my_key in mydict:
>>> ...
> 
> and
> 
>>> if mydict.has_keys(my_key):
>>> ...
> 
> I've search a bit in the python documentation, and the only things I
> found was that they are "equivalent".
> 
> But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
> Cookbook/Python/Recipe/59875" ), there is difference between the two
> notation.

The comments in this recipes source code are misleading.  Difference is
not the ``in`` but that it is used on ``another_dict.keys()`` in the "bad"
example.  That is a linear search on a list with all keys instead asking
the dictionary directly like you did above.

The difference in your code above is that  ``in`` works on other types too
that implement `__contains__()`, like lists or sets for example, and that
it is a bit faster as the second example has to look up the `has_key()`
method on the object first.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


strange list comprehension on generator

2007-08-29 Thread Roland Puntaier
def changeOne(aa,idx):
  aa[idx]=not aa[idx]
  yield aa
  for i in range(idx):
for x in changeOne(aa,i):
  yield x

def changeOneOrder(aa):
  yield aa
  for i in range(len(aa)): 
for x in changeOne(aa,i):
  yield x

a=[False]*3
og=changeOneOrder(a)
#this does not return the way I would expect. why?
list(og)
#returns
#[[False, False, True], [False, False, True], [False, False, True], 
[False, False, True], [False, False, True], [False, False, True], [False, 
False, True], [False, False, True]]


#this works as expected
a=[False]*3
og=changeOneOrder(a)
og.next()
og.next()
...

#this works as expected
def ty():
  yield 1
  yield 2
  yield 3

tg=ty()
list(tg)

cheers, Roland

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


Re: status of Programming by Contract (PEP 316)?

2007-08-29 Thread Aahz
In article <[EMAIL PROTECTED]>,
Russ  <[EMAIL PROTECTED]> wrote:
>
>I just stumbled onto PEP 316: Programming by Contract for Python
>(http://www.python.org/dev/peps/pep-0316/). This would be a great
>addition to Python, but I see that it was submitted way back in 2003,
>and its status is "deferred." I did a quick search on comp.lang.python,
>but I don't seem to see much on it. Does anyone know what the real
>status is of getting this into standard Python? Thanks.

The way to get this into Python is to get people to use it as a
stand-alone module.  It's already in PyPI, so now it's time for some
marketing.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: non-blocking communication with imaplib

2007-08-29 Thread Igor V. Rafienko
[ Lawrence D'Oliveiro ]

[ ... ]

> According to the documentation
> , you can override
> the "read" and "readline" methods. How about replacing them with
> routines that use select.select on the socket() object to implement
> a timeout?


Sounds like a plan. I'll try that. Thank you.





ivr
-- 
<+Kaptein-Dah> igorr: for få parenteser
<+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon
<+Kaptein-Dah> igorr: velkjent
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: self extracting zipefile (windows) and (standard module) zipefile

2007-08-29 Thread Grant Edwards
On 2007-08-29, Hyuga <[EMAIL PROTECTED]> wrote:

>> I try to read (and extract) some "self extracting" zipefiles
>> on a Windows system. The standard module zipefile seems not to
>> be able to handle this. [...]
>
> First of all, there's really no such thing as a "self
> extracting zipefile".

Perhaps there isn't "really such a thing," but that's the
commonly used name for the type of file the OP is dealing with.

> [...] You'll have to execute it--there's no way you can
> operate on it like a normal zip file.

Executing the file is a huge, huge security risk.

Other zip tools (e.g. the "unzip" utility for Linux) seem know
how to work with self-extracting zipfiles.  Unfortunately there
are multiple slightly different zip formats along with mutlple
"self-extracting zip file" formats. Nonetheless, I've never run
across one I couldn't unzip without executing it.  On Linux,
I'd probably just try exec'ing the "unzip" program.  

Another option is to search through the file from the beginning
looking for whatever signature matches the beginning of a
"normal" zip file.  The self-extracting zipfiles that I've
dissected are just an executable image concatenated with a
"normal" zipfile.  If you just start searching from the
beginning of the file, it's simple to find the actual zip data
and copy it into a separate file which then can be unzipped
like any other plain zipfile.  I haven't done that for many
years since the normal zip tools that I use can operate on
self-extracting files.

-- 
Grant Edwards   grante Yow! NEWARK has been
  at   REZONED!!  DES MOINES has
   visi.combeen REZONED!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a multi-tier client/server application

2007-08-29 Thread Jeff
> You could explore something like a custom-made GUI client app
> communicating thru the http protocol with a web-server app. http is just
> a protocol, and it doesn't necessarily imply using html and a browser...
> IIRC, some GUI toolkits uses XML description files for the UI.

That, or something similar, may be what I do.  It would mean, however,
developing my own method for transferring objects across the network,
which, as far as I can tell, is what things like Pyro are supposed to
take care of.


> > 3) Easier to "lock down" who's using the program by only
> > installing it on certain machines.
>
> Not a very reliable security scheme IMHO !-)

You are 100% correct.  That will most certainly *not* be the only
means of security.  There will be user authentication against a
central LDAP server, SSL for all connections, and possibly IP address
based blocking as well.  I need to clarify what I meant (I didn't want
to bore everyone with the tedious details)--while this system will
mostly be used by supervisors/managers, the employees will also be
using it to sign into their shifts.  The managers want the employees
to only be able to sign in from designated machines, while at the same
time they want them to be able to look up their schedules from a web
interface, but *not* use that to sign in.  That wasn't the best point,
but I think there's something to be said of the *perceived* security
of desktop vs. web apps.

> Extreme Programming doesn't mean "no preparation", and makes heavy use
> of use cases. Of course you need to have some - hopefully accurate -
> functional specs. The point was mostly along the lines of "don't try to
> have full-featured detailed design before you start coding, because
> chances are it will be wrong".
>
> > Hopefully, the amount of planning will be somewhere in between that
> > and the bureaucratic nightmare of documenting up front what each
> > module, class and function will do.
>
> Which would be totally non-sensical. I don't believe anyone on earth
> could come up with such a thing - done right - *before* the application
> is written.

I'm not looking to layout how the GUI should look, or even how
individual parts of it should work.  What I need to do, though, is
write very detailed specs with my clients on the data that will be
used, and plan out as thoroughly as possible the architecture of the
project as far as tiers and such.  I don't have much choice in this
aspect, sadly.  But, in my experience, the more detail (and agreement
on those details) I have up front, the less painful the rest of the
process will be.

Thanks again!

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


Re: Creating a multi-tier client/server application

2007-08-29 Thread Goldfish
Perhaps Spring Python can help you out (http://springpython.python-
hosting.com). It reuses technologies like Pyro for remoting, offers
database templates, has a plugable security component, an AOP solution
should the need arise, an IoC container, and has a couple of web-app
demos using CherryPy. Of course, you can use whatever web stack you
want. I just picked CherryPy to demo things.

Each component of Spring Python is optional, and you can use it
through the IoC container, or programatically. This might help you
leverage development of an enterprise app.

BTW, I have plans to implement a wxPython front end sample app. I just
haven't done it yet.

Good luck!

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


Re: strange list comprehension on generator

2007-08-29 Thread Bjoern Schliessmann
No greeting, no text? Pity.

Roland Puntaier wrote:

> def changeOne(aa,idx):
>   aa[idx]=not aa[idx]
>   yield aa
>   for i in range(idx):
> for x in changeOne(aa,i):
>   yield x
> 
> def changeOneOrder(aa):
>   yield aa
>   for i in range(len(aa)):
> for x in changeOne(aa,i):
>   yield x

Okay, two generator definitions.
 
> a=[False]*3
> og=changeOneOrder(a)
> #this does not return the way I would expect. why?

What do you expect? You created a generator object and bound it
to "og".

Please always state what you expect and what really happens. Fortune
telling is not one of my hobbies (and I think I'm not alone with
that).

Regards,


Björn

-- 
BOFH excuse #284:

Electrons on a bender

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


Re: strange list comprehension on generator

2007-08-29 Thread Martin v. Löwis
> #this does not return the way I would expect. why?

You yield the very same list object all the times. So
when you make a later change, all earlier results will
get changed, too (since they are the same object).
Of course, it won't affect the terminal output, so you
don't see that the older values changed in the example
that you think works as expected.

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


Re: What's the difference ?

2007-08-29 Thread Alex Martelli
Alex <[EMAIL PROTECTED]> wrote:

> Hye,
> 
> I was just wondering what is the difference between
> 
> >> if my_key in mydict:
> >> ...
> 
> and
> 
> >> if mydict.has_keys(my_key):

Mis-spelled (no final s in the method name).

> >> ...
> 
> I've search a bit in the python documentation, and the only things I
> found was that they are "equivalent".

Semantically they are, but `in' is faster, more concise, & readable.


> But in this (quiet old) sample ( "http://aspn.activestate.com/ASPN/
> Cookbook/Python/Recipe/59875" ), there is difference between the two
> notation.

What that example is pointing to as "wrong way" is a NON-equivalent
approach that's extremely slow:
  if my_key in mydict.keys():

The call to keys() takes time and memory to build a list of all keys,
after which the ``in'' operator, having a list as the RHS operand, is
also quite slow (O(N), vs O(1)!).  So, never use that useless and silly
call to keys() in this context!


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


Re: What's the difference ?

2007-08-29 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> Weird. Hetland's book, "Beginning Python" states that it's a matter of
> taste.

If your taste is for more verbose AND slower notation without any
compensating advantage, sure.

> Martelli's "Python Cookbook 2nd Ed." says to use the get()
> method instead as you never know if a key is in the dict.  However, I
> can't seem to find any reference to has_key in his book.

.get is not a direct alternative to ``in'' (it's an alternative to an
idiom where you key into the dict if the key is present and otherwise
supply a default value, and it's MUCH better in that case).  has_key is
probably not even mentioned in the Cookbook (2nd edition) since there is
never a good need for it in the Python versions it covers (2.2 and up),
but you can probably find traces in the 1st edition (which also covered
Python back to 1.5.2, where has_key *was* needed); the Nutshell (2nd ed)
mentions it briefly in a table on p. 60.


> According to Chun in "Core Python Programming", has_key will be
> obsoleted in future versions of Python, so he recommends using "in" or
> "not in".

Yes, we're removing has_key in Python 3.0 (whose first alpha will be out
reasonably soon, but is not going to be ready for production use for
quite a bit longer), among other redundant things that exist in 2.* only
for legacy and backwards compatibility reasons.  This makes 3.0 simpler
(a little closer to the "only one obvious way" ideal).

But you should use ``in'' and ``not in'' anyway, even if you don't care
about 3.* at all, because they only have advantages wrt has_key, without
any compensating disadvantage.


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


Re: Jython 2.2 on Ubuntu

2007-08-29 Thread Neil Wallace
Thanks Tim,

I subscribed to the Jython group hosted by sourceforge, and they are a 
great bunch of guys/gals.

Here's what I did to fix my problem.

1. removed Jython 2.1 (using Synaptic)jytho
2. added the following lines (as root) to /etc/profile
 # set PATH for Jython
 PATH=$PATH:/home/neil/jython2.2
 export PATH

I had to restart X, that's it solved!!

Neil


Tim Couper wrote:
> you need to ensure that the correct jython executable is in a directory 
> which is on your on your path.
> 
> I've just successfully test-subscribed to 
> https://lists.sourceforge.net/lists/listinfo/jython-users. Maybe you 
> could try again.
> 
> Tim
> 
> Dr Tim Couper
> CTO, SciVisum Ltd
> 
> www.scivisum.com
> 
> 
> 
> Neil Wallace wrote:
>> Hi all,
>>
>> I am a novice Python/Jython programmer, and Ubuntu user.
>>
>> Ubuntu still only supports only version 2.1 of Jython. I have used the 
>> GUI installer of Jython 2.2, and installed it to the default 
>> /root/jython2.2 directory. The install went without issues.
>>
>> However, typing jython --version
>> in a teminal still gives me    Jython 2.1 on java (JIT: null)
>>
>> What else do I need to do?
>>
>> regards
>> Neil.
>>
>> p.s. I posted this to the jython group hosted by sourceforge, but it 
>> bounced. :-(
>>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: handling tabular data in python--newbie question

2007-08-29 Thread hyena
Thanks Bruno and Steve for the quick answer!

>What make you think such a thing ?
I am also using R and java from time to time, and think it is very covinient 
that in R tables are handled as matrixs or data frames. Thus I expect python 
has something similiar. :)

And I went for Steve's first suggestion, which is just what I want at this 
moment.

Thanks again. 


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


replacing xml elements with other elements using lxml

2007-08-29 Thread Ultrus
Hello,
I'm attempting to generate a random story using xml as the document,
and lxml as the parser. I want the document to be simplified before
processing it further, and am very close to accomplishing my goal.
Below is what I have so far. Any ideas on how to move forward?

The goal:
read and edit xml file, replacing random elements with randomly picked
content from within

Completed:
[x] read xml
[x] access first random tag
[x] pick random content within random item
[o] need to replace  tag with picked contents

xml sample:
Here is some content.

   Here is some random content.
   Here is some more random content.

Here is some content.

Python code:
from lxml import etree
from StringIO import StringIO
import random

theXml = "Here is some content.Here is some random content.Here is some more random content.Here is some content."

f = StringIO(theXml)
tree = etree.parse(f)
r = tree.xpath('//random')

if len(r) > 0:
   randInt = random.randInt(0,(len(r[0]) - 1))
   randContents = r[0][randInt][0]
   #replace parent random tag with picked content here

now that I have the contents tag randomly chosen, how do I delete the
parent  tag, and replace it to look like this:

final xml sample (goal):
Here is some content.
Here is some random content.
Here is some content.

Any idea on how to do this? So close! Thanks for the help in
advance. :)

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


Re: strange list comprehension on generator

2007-08-29 Thread [EMAIL PROTECTED]
On Aug 29, 6:50 am, Roland Puntaier <[EMAIL PROTECTED]
automation.com> wrote:
> def changeOne(aa,idx):
>   aa[idx]=not aa[idx]
>   yield aa
>   for i in range(idx):
> for x in changeOne(aa,i):
>   yield x
>
> def changeOneOrder(aa):
>   yield aa
>   for i in range(len(aa)):
> for x in changeOne(aa,i):
>   yield x
>
> a=[False]*3
> og=changeOneOrder(a)
> #this does not return the way I would expect. why?
> list(og)
> #returns
> #[[False, False, True], [False, False, True], [False, False, True],
> [False, False, True], [False, False, True], [False, False, True], [False,
> False, True], [False, False, True]]


If you want the "intermediate" states of 'a' in
list(og), then you need to yield a copy of that list,
instead of the list itself:

def changeOne(aa, idx):
aa[idx] = not aa[idx]
yield aa[:] # <--- a copy
for i in range(idx):
for x in changeOne(aa, i):
yield x

def changeOneOrder(aa):
yield aa[:] # <--- a copy
for i in range(len(aa)):
for x in changeOne(aa, i):
yield x

a = [False] * 3
og = changeOneOrder(a)
print list(og)

Otherwise, as you've already noticed, you can
loop over the iterator and do something
with the "instantaneous" state of 'a'.

--
Hope this helps,
Steven


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


Re: What's the difference ?

2007-08-29 Thread kyosohma
On Aug 29, 9:44 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> <[EMAIL PROTECTED]> wrote:
>
>...
>
> > Weird. Hetland's book, "Beginning Python" states that it's a matter of
> > taste.
>
> If your taste is for more verbose AND slower notation without any
> compensating advantage, sure.
>
> > Martelli's "Python Cookbook 2nd Ed." says to use the get()
> > method instead as you never know if a key is in the dict.  However, I
> > can't seem to find any reference to has_key in his book.
>
> .get is not a direct alternative to ``in'' (it's an alternative to an
> idiom where you key into the dict if the key is present and otherwise
> supply a default value, and it's MUCH better in that case).  has_key is
> probably not even mentioned in the Cookbook (2nd edition) since there is
> never a good need for it in the Python versions it covers (2.2 and up),
> but you can probably find traces in the 1st edition (which also covered
> Python back to 1.5.2, where has_key *was* needed); the Nutshell (2nd ed)
> mentions it briefly in a table on p. 60.
>
> > According to Chun in "Core Python Programming", has_key will be
> > obsoleted in future versions of Python, so he recommends using "in" or
> > "not in".
>
> Yes, we're removing has_key in Python 3.0 (whose first alpha will be out
> reasonably soon, but is not going to be ready for production use for
> quite a bit longer), among other redundant things that exist in 2.* only
> for legacy and backwards compatibility reasons.  This makes 3.0 simpler
> (a little closer to the "only one obvious way" ideal).
>
> But you should use ``in'' and ``not in'' anyway, even if you don't care
> about 3.* at all, because they only have advantages wrt has_key, without
> any compensating disadvantage.
>
> Alex

Martelli,

I kind of figured .get wasn't a direct alternative to "in", but I
thought the OP might be able to use it since (s)he didn't mention what
they wanted to do.

Mike

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


Re: encoding problems

2007-08-29 Thread Damjan
> 
> is there a way to sort this string properly (sorted()?)
> I mean first 'a' then 'à' then 'e' etc. (sorted puts accented letters at
> the end). Or should I have to provide a comparison function to sorted?

After setting the locale...

locale.strcoll()


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

general function for sorting a matrix

2007-08-29 Thread Xah Lee
A couple years ago, i posted a programing problem, about writing a
function that will sort a arbitrarily dimentioned matrix in any
possible way to sort it.

Such a function, is rather typical in functional programing
languages.  I wrote a version in 1999 in perl for practical purposes,
since sorting a matrix (i.e. list of lists) is rather common. With
this function, i can have a single interface to deal with any list
(including list of lists).

It is ideal, that a language's function for sort actually are of this
generality.
(See “What is Expressiveness in a Computer Language”, Xah Lee, 2005.
http://xahlee.org/perl-python/what_is_expresiveness.html
)

The advantage of such a generality, is that a programer don't need to
write a sorting code every time she encounters a list.

Anyway, so i wrote it in 1999 in perl for practical purposes, and have
used it in industrial coding often.  In 2005, while i was learning
Python, i wrote a python version as a exercise.  Today, i actually
need it again, while coding in python. So i looked at my code and
spruced up the documentation.

Here's the function spec:


Today we'll write a function that can sort a matrix in all possible
ways. Following is the specification. Take a day to see if you can
write such a function in your favorite language. Perl and Python
solutions are at the end of this page.

sort_matrix( matrix, [[n1, s1, d1], [n2, s2, d2], [n3, s3, d3], ...])
returns a sorted matrix by n1 th column, if tie, then by n2 th
column ... and so on.

The first argument is a list, whose elements are lists of equal
lengths.

s1, s2, s3... are booleans. If True, then the corresponding column are
interpreted as a string and the ordering is lexicographical.

d1, d2, d3... are booleans. If True, the sort for the corresponding
column are ascending.

Example:.

myMatrix =
 [
   [3, 99, 'a'],
   [2, 77, 'a'],
   [1, 77, 'a']
 ];

sort_matrix(myMatrix,[[3,True,True],[2,False,True]])

This means sort by 3th column, regarding it as strings, and in
ascending order. If tie, sort by 2th column, regarding it as number,
in ascending order. It returns:

[[2,77,'a'],
 [1,77,'a'],
 [3,99,'a']]



While reviewing this code, there's something interesting of note.

Namely, in my perl solution, the approach is drastically different
than the python version. Instead of sorting by looping thru the
sorting directives, it parses the directives then generate the
complete sort code, then eval it in one shot. This is more of a pure
functional approach.

I thought it is of interest.

The Perl and Python solutions are at:
General Function For Matrix Sorting
http://xahlee.org/perl-python/sort_matrix.html

It would be interesting, to see a python version using the approach
i've done in the Perl version, and a Perl version using imperative
approach without using eval().

A solution in lisp (emacs lisp, common lisp, scheme) would be
relatively trivial, similarly for Haskell and Mathematica. In fact, i
think the sort function as specified above are not very useful in
practice in these languages to various degress (depending on the
lang). Because a functional language usually have powerful,
generalized functions and constructs that solve the above in a few
trivial lines that are rather ideomatic to the language.

Nevertheless, it would be interesting to see a solution in the above
languages.

For the languages i'm personally involved, a major difficulty would be
Java. In my opinion, it would be a very difficult (if not impossible)
to construct this sort function Java, C, C++, C#.

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: What's the difference ?

2007-08-29 Thread Alexandre Badez
Thanks for all you information.

I'll continue to use 'in' instead of 'has_key' for a "faster, more
concise, & readable" code (^L^ )

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


python + gcov

2007-08-29 Thread labrach
Hi
I want to profile (and analyse coverage) some  c++ code imported as a
python module
I've compiled python (2.4.2) with gcc 3.4.3 and flags=-Wall -fprofile-
arcs -ftest-coverage in order to use gcov. However, the python binary
does not generate any coverage file (such than *.gcno, gcda) during
execution.
any tips ?
or may be another method to profile c++ wrapped modules within
python ?

thanks

laurent

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


Re: Creating a multi-tier client/server application

2007-08-29 Thread Bruno Desthuilliers
Jeff a écrit :
>> You could explore something like a custom-made GUI client app
>> communicating thru the http protocol with a web-server app. http is just
>> a protocol, and it doesn't necessarily imply using html and a browser...
>> IIRC, some GUI toolkits uses XML description files for the UI.
> 
> That, or something similar, may be what I do.  It would mean, however,
> developing my own method for transferring objects across the network,

Why transfering "objects" ? You only need to transfer data.

(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: general function for sorting a matrix

2007-08-29 Thread Marc 'BlackJack' Rintsch
On Wed, 29 Aug 2007 08:47:27 -0700, Xah Lee wrote:

> While reviewing this code, there's something interesting of note.
> 
> Namely, in my perl solution, the approach is drastically different
> than the python version. Instead of sorting by looping thru the
> sorting directives, it parses the directives then generate the
> complete sort code, then eval it in one shot. This is more of a pure
> functional approach.

I don't see why that is more functional.  After all you iterate in both
versions through the directives.  In Perl to build the code, in Python to
sort the list multiple times.  Here's a Python function that sorts the
list just once:

def sort_matrix(matrix, directives):
tmp = [(column - 1, str if as_string else float, 1 if ascending else -1)
   for (column, as_string, ascending) in directives]

def cmp_func(row_a, row_b):
for column, convert_func, factor in tmp:
result = cmp(convert_func(row_a[column]),
 convert_func(row_b[column])) * factor
if result:
return result
return 0

matrix.sort(cmp=cmp_func)

There's no return value as your reference implementation sorts in place
too.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing xml elements with other elements using lxml

2007-08-29 Thread Stefan Behnel
Ultrus wrote:
> I'm attempting to generate a random story using xml as the document,
> and lxml as the parser. I want the document to be simplified before
> processing it further, and am very close to accomplishing my goal.
> Below is what I have so far. Any ideas on how to move forward?
> 
> The goal:
> read and edit xml file, replacing random elements with randomly picked
> content from within
> 
> Completed:
> [x] read xml
> [x] access first random tag
> [x] pick random content within random item
> [o] need to replace  tag with picked contents
> 
> xml sample:
> Here is some content.
> 
>Here is some random content.
>Here is some more random content.
> 
> Here is some content.

Hmm, this is not well-formed XML, so I assume you stripped the example. The
root element is missing.


> Python code:
> from lxml import etree
> from StringIO import StringIO
> import random
> 
> theXml = "Here is some content. contents>Here is some random content. contents>Here is some more random content. contents>Here is some content."
> 
> f = StringIO(theXml)
> tree = etree.parse(f)

 ^
This would raise an exception if the above really *was* your input.


> r = tree.xpath('//random')
> 
> if len(r) > 0:
>randInt = random.randInt(0,(len(r[0]) - 1))
>randContents = r[0][randInt][0]
>#replace parent random tag with picked content here
> 
> now that I have the contents tag randomly chosen, how do I delete the
> parent  tag, and replace it to look like this:
> 
> final xml sample (goal):
> Here is some content.
> Here is some random content.
> Here is some content.

what about:

   r.getparent().replace(r, random.choice(r))

?

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


Re: Gmane's been quiet ...

2007-08-29 Thread Robert Marshall
On Wed, 29 Aug 2007, Steve Holden wrote:

> 
> Lawrence Oluyede wrote:
>> Grant Edwards <[EMAIL PROTECTED]> wrote:
>>> Posting that were made to mailing lists via gmane?
>>
>> That, I do not know
>>
> Given that I have now read a reply to my post-via-gmane on gmane
> before seeing the original post appear there I shall assume they've
> been having some sort of issue.
> 

See http://news.gmane.org/gmane.discuss for some discussion of this...

Robert
-- 
La grenouille songe..dans son château d'eau
Links and things http://rmstar.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: general function for sorting a matrix

2007-08-29 Thread Stefan Behnel
Xah Lee wrote:
[undermotivated blah stripped]

don't feed the troll.

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


Re: Gmane's been quiet ...

2007-08-29 Thread Grant Edwards
On 2007-08-29, Robert Marshall <[EMAIL PROTECTED]> wrote:

>> Given that I have now read a reply to my post-via-gmane on gmane
>> before seeing the original post appear there I shall assume they've
>> been having some sort of issue.
>
> See http://news.gmane.org/gmane.discuss for some discussion of this...

A day's worth of e-mail messages was lost (both incoming and
outgoing apparently).

-- 
Grant Edwards   grante Yow! In Newark the
  at   laundromats are open 24
   visi.comhours a day!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: status of Programming by Contract (PEP 316)?

2007-08-29 Thread Chris Mellon
On 8/29/07, Russ <[EMAIL PROTECTED]> wrote:
> On Aug 28, 10:58 pm, Michele Simionato <[EMAIL PROTECTED]>
> wrote:
>
> > Why do you think that would ad a strong positive capability?
> > To me at least it seems a big fat lot of over-engineering, not
> > needed in 99% of programs. In the remaining 1%, it would still not
> > be needed since Python provides out of the box very powerful
> > metaprogramming capabilities so that you can implement
> > yourself the checks you need, if you really need them.
>
> I get the strong impression you don't really understand what
> programming by contract is.
>

Don't be condescending.

> I have not yet personally used it, but I am interested in anything
> that can help to make my programs more reliable.

The entire issue of software reliability, exactly what metrics you
should use to measure it, and whether any specific technique results
in more of it are very much in debate. If you want to experiment with
these techniques, you can do so without them being in the Python core.
Python has all the support you need to play with them right now.

>If you are
> programming something that doesn't really need to be correct, than you
> probably don't need it. But if you really need (or want) your software
> to be correct and reliable as possible, I think you you should be
> interested in it. You might want to read this:
>

You don't want your software to KILL BABIES, do you? If you don't want
your programs to KILL BABIES then you should use our technique, so you
don't KILL BABIES.

There are ways to make correct programs besides DBC. It may not even
help in the general case - just as with unit testing and type proving,
you're going to be limited by what you don't think to assert or
document or test, and I've seen no evidence that DBC is any better
than anything else at preventing unwritten assumptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


cgi

2007-08-29 Thread Gigs_
i have simple page and form that ask for name and color and cgi script that 
print that name in another page and background in chosen color

all the time this error pop:
Error response

Error code 501.

Message: Can only POST to CGI scripts.

Error code explanation: 501 = Server does not support this operation.

i run it on windows xpand this is server that i use:

webdir = '.'
port   = 80

import os, sys
from BaseHTTPServer import HTTPServer
from CGIHTTPServer  import CGIHTTPRequestHandler

os.chdir(webdir)
srvraddr = ("", port)
srvrobj  = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()

can someone help me?



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


Re: Creating a multi-tier client/server application

2007-08-29 Thread Jeff
Goldfish--thanks, I'll check it out.

> > That, or something similar, may be what I do.  It would mean, however,
> > developing my own method for transferring objects across the network,
>
> Why transfering "objects" ? You only need to transfer data.

I suppose I don't need to transfer objects, it just seems like it
would make it far easier (certainly less repetition of code) to
program the client-side app.




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


Re: general function for sorting a matrix

2007-08-29 Thread Neil Cerutti
On 2007-08-29, Xah Lee <[EMAIL PROTECTED]> wrote:
> A couple years ago, i posted a programing problem, about
> writing a function that will sort a arbitrarily dimentioned
> matrix in any possible way to sort it.
>
> Such a function, is rather typical in functional programing
> languages.  I wrote a version in 1999 in perl for practical
> purposes, since sorting a matrix (i.e. list of lists) is rather
> common. With this function, i can have a single interface to
> deal with any list (including list of lists).
>
> It is ideal, that a language's function for sort actually are
> of this generality.
> (See ?What is Expressiveness in a Computer Language?, Xah Lee, 2005.
> http://xahlee.org/perl-python/what_is_expresiveness.html
> )
>
> The advantage of such a generality, is that a programer don't
> need to write a sorting code every time she encounters a list.

The advantage of such a richly implemented language as Python, is
that a programmer don't need to write a general sorting algorithm
at all.

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


Accessing docstrings at runtime?

2007-08-29 Thread Kenneth Love
How do I print the docstring for a class property?

When I run the code below, I get the docstring for the string module
and not the one I set for the property.

-
# NOTE: Found in Python docs defining built-in functions (such as
#   property()).  FIXED: Bug in getx, setx, and delx where "__x"
#   was misreferenced as "_x".
class C(object):
def __init__(self):
self.__x = None
def getx(self):
return self.__x
def setx(self, value):
self.__x = value
def delx(self):
del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")

if __name__ == "__main__"
y = C()
y.x = 'test'
print y.x
print y.x.__doc__
-

I get the following output:

-
test
str(object) -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
-

What am I doing wrong?

adTHANKSvance,
Kenneth Love

P.S. If I want a docstring and I do not want a delete function,
 do I just pass 'None' (minus quotes) for that parameter?

-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-  
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

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


Re: Accessing docstrings at runtime?

2007-08-29 Thread Chris Mellon
On 8/29/07, Kenneth Love <[EMAIL PROTECTED]> wrote:
> How do I print the docstring for a class property?
>
> When I run the code below, I get the docstring for the string module
> and not the one I set for the property.
>
> -
> # NOTE: Found in Python docs defining built-in functions (such as
> #   property()).  FIXED: Bug in getx, setx, and delx where "__x"
> #   was misreferenced as "_x".
> class C(object):
> def __init__(self):
> self.__x = None
> def getx(self):
> return self.__x
> def setx(self, value):
> self.__x = value
> def delx(self):
> del self.__x
> x = property(getx, setx, delx, "I'm the 'x' property.")
>
> if __name__ == "__main__"
> y = C()
> y.x = 'test'
> print y.x
> print y.x.__doc__
> -
>
> I get the following output:
>
> -
> test
> str(object) -> string
>
> Return a nice string representation of the object.
> If the argument is a string, the return value is the same object.
> -
>
> What am I doing wrong?
>

You're looking at an instance, not at the class. y.x is going through
the descriptor lookup and is returning the string, so the __doc__ is
the the __doc__ of the string object, as you see.

If you want to look at the property directly, look it up in the class object:

C.x.__doc__
-- 
http://mail.python.org/mailman/listinfo/python-list


copying files

2007-08-29 Thread Brian McCann
Hi,
 
with the code below I set a variable TEST_HOME to a path and the variable m to 
a path
in my current dir. 
I have a symbolic link setting m>lib
when I run the script I get no errors and the lib dir with its 20 files does 
not get copied to /v01/test_home
any help would be greatly appreciated
 
--Brian

#!/usr/bin/python
import string
import os
import sys
import errno
import shutil
import tarfile
 
TEST_HOME = "/v01/test_home"
m = "./lib"
os.system("cp -r m TEST_HOME")
#os.system("tar -cvf viziant-ingestion.tar /v01/")

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

RE: copying files

2007-08-29 Thread Brian McCann
 
 
one thing I just noticed is that when I run the script I get a new symbolic link
created in my current dir  TEST_HOME-->lib
--Brian
 



From: [EMAIL PROTECTED] on behalf of Brian McCann
Sent: Wed 8/29/2007 2:40 PM
To: python-list@python.org
Subject: copying files 


Hi,
 
with the code below I set a variable TEST_HOME to a path and the variable m to 
a path
in my current dir. 
I have a symbolic link setting m>lib
when I run the script I get no errors and the lib dir with its 20 files does 
not get copied to /v01/test_home
any help would be greatly appreciated
 
--Brian

#!/usr/bin/python
import string
import os
import sys
import errno
import shutil
import tarfile
 
TEST_HOME = "/v01/test_home"
m = "./lib"
os.system("cp -r m TEST_HOME")


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

Re: Creating a multi-tier client/server application

2007-08-29 Thread Bruno Desthuilliers
Jeff a écrit :
> Goldfish--thanks, I'll check it out.
> 
> 
>>>That, or something similar, may be what I do.  It would mean, however,
>>>developing my own method for transferring objects across the network,
>>
>>Why transfering "objects" ? You only need to transfer data. 
> 
> I suppose I don't need to transfer objects, it just seems like it
> would make it far easier (certainly less repetition of code) 

Why so ???

> to
> program the client-side app.


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


Re: Accessing docstrings at runtime?

2007-08-29 Thread Bruno Desthuilliers
Chris Mellon a écrit :
> On 8/29/07, Kenneth Love <[EMAIL PROTECTED]> wrote:
> 
>>How do I print the docstring for a class property?
(snip)
> You're looking at an instance, not at the class. y.x is going through
> the descriptor lookup and is returning the string, so the __doc__ is
> the the __doc__ of the string object, as you see.
> 
> If you want to look at the property directly, look it up in the class object:
> 
> C.x.__doc__

Or type(y).x.__doc__ if you don't know the class of y.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copying files

2007-08-29 Thread Ricardo Aráoz
Brian McCann wrote:
> Hi,
>  
> with the code below I set a variable TEST_HOME to a path and the
> variable m to a path
> in my current dir.
> I have a symbolic link setting m>lib
> when I run the script I get no errors and the lib dir with its 20 files
> does not get copied to /v01/test_home
> any help would be greatly appreciated
>  
> --Brian
> 
> #!/usr/bin/python
> import string
> import os
> import sys
> import errno
> import shutil
> import tarfile
>  
> TEST_HOME = "/v01/test_home"
> m = "./lib"
> os.system("cp -r m TEST_HOME")
> #os.system("tar -cvf viziant-ingestion.tar /v01/")
>  

Maybe os.system("cp -r " + m + TEST_HOME) ?

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


Re: copying files

2007-08-29 Thread Ricardo Aráoz
Brian McCann wrote:
> Hi,
>  
> with the code below I set a variable TEST_HOME to a path and the
> variable m to a path
> in my current dir.
> I have a symbolic link setting m>lib
> when I run the script I get no errors and the lib dir with its 20 files
> does not get copied to /v01/test_home
> any help would be greatly appreciated
>  
> --Brian
> 
> #!/usr/bin/python
> import string
> import os
> import sys
> import errno
> import shutil
> import tarfile
>  
> TEST_HOME = "/v01/test_home"
> m = "./lib"
> os.system("cp -r m TEST_HOME")
> #os.system("tar -cvf viziant-ingestion.tar /v01/")
>  

Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME)


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


Re: cgi

2007-08-29 Thread Fabio Z Tessitore
Il Wed, 29 Aug 2007 19:24:54 +0200, Gigs_ ha scritto:

> i have simple page and form that ask for name and color and cgi script
> that print that name in another page and background in chosen color
> 
> all the time this error pop:
> Error response
> 
> Error code 501.
> 
> Message: Can only POST to CGI scripts.
> 

I think this should be your problem,

change GET with POST in the form

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


Re: copying files

2007-08-29 Thread kyosohma
On Aug 29, 1:51 pm, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
> Brian McCann wrote:
> > Hi,
>
> > with the code below I set a variable TEST_HOME to a path and the
> > variable m to a path
> > in my current dir.
> > I have a symbolic link setting m>lib
> > when I run the script I get no errors and the lib dir with its 20 files
> > does not get copied to /v01/test_home
> > any help would be greatly appreciated
>
> > --Brian
>
> > #!/usr/bin/python
> > import string
> > import os
> > import sys
> > import errno
> > import shutil
> > import tarfile
>
> > TEST_HOME = "/v01/test_home"
> > m = "./lib"
> > os.system("cp -r m TEST_HOME")
> > #os.system("tar -cvf viziant-ingestion.tar /v01/")
>
> Sorry, meant : os.system("cp -r " + m + " " + TEST_HOME)

Did you try using the shutil module?

Mike

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

Unzip: Memory Error

2007-08-29 Thread mcl
I am trying to unzip an 18mb zip containing just a single 200mb file
and I get a Memory Error.  When I run the code on a smaller file 1mb
zip, 11mb file, it works fine.

I am running on a hosted Apache web server

I am using some code I found on the web somewhere.


def unzip_file_into_dir(file, dir):
#os.mkdir(dir, 0777)
zfobj = zipfile.ZipFile(file)
for name in zfobj.namelist():
if name.endswith('/'):
os.mkdir(os.path.join(dir, name))
else:
outfile = open(os.path.join(dir, name), 'wb')
outfile.write(zfobj.read(name))
outfile.close()


Error Traceback: Line 357 gives the Memory Error
I have removed paths from file references
==

MemoryError Python 2.3.4: /usr/bin/python
Wed Aug 29 19:38:22 2007

A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.

/qlunzip.py
   58
   59
   60 if __name__ == "__main__" :
   61 unzipMain()
   62
unzipMain = 

/qlunzip.py in unzipMain()
   53 destdir = getDestDir()
   54 print destdir, gv.nl
   55 unzip_file_into_dir(zips, destdir)
   56
   57
global unzip_file_into_dir = , zips = '/
pcodes.zip', destdir = '/pcodes/'

/qlunzip.py in unzip_file_into_dir(file='pcodes.zip', dir='pcodes/')
   34 else:
   35 outfile = open(os.path.join(dir, name),
'wb')
   36 outfile.write(zfobj.read(name))
   37 outfile.close()
   38
outfile = , outfile.write =
, zfobj = , zfobj.read = >, name = 'pcodes.lst'

 /usr/lib/python2.3/zipfile.py in read(self=, name='pcodes.lst')
  355 # zlib compress/decompress code by Jeremy Hylton of
CNRI
  356 dc = zlib.decompressobj(-15)
  357 bytes = dc.decompress(bytes)
  358 # need to feed in unused pad byte so that zlib won't
choke
  359 ex = dc.decompress('Z') + dc.flush()
bytes = '\xc4\x9d]\x93\xab8\x92\x86\xef7b\xff\x83\xa3/\xf6f\xba
\xa7\xe7\xa2g#vwf6\x8a\x02\xc3\xd04\x8d\r\x1e\x7f\xdclP\xb6\xcav\x1c
\xca\xd4`\xfbx...; \xb7jp\x06V{\xaf\xc3\xa5\xa7;\xdd\xd2\xaaD\x7f)c
\xc6\x9d\x0f\xf2\xff-\xc9\x92\xc3\x1d\xa4`\xe0\xb8\x06)\x188\x9cA\n
\x06\x8e\x1bPc\xf8\xf0\x1f', dc = ,
dc.decompress = 

MemoryError:
  args = ()


Any help much appreciated

Richard

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


Re: Creating a multi-tier client/server application

2007-08-29 Thread askel
On Aug 29, 1:31 pm, Jeff <[EMAIL PROTECTED]> wrote:
> Goldfish--thanks, I'll check it out.
>
> > > That, or something similar, may be what I do.  It would mean, however,
> > > developing my own method for transferring objects across the network,
>
> > Why transfering "objects" ? You only need to transfer data.
>
> I suppose I don't need to transfer objects, it just seems like it
> would make it far easier (certainly less repetition of code) to
> program the client-side app.

If you prefer to deal with RPC-like protocol, take a look at Ice by
ZeroC (http://www.zeroc.com/).

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


sys.argv is munging my command line options

2007-08-29 Thread Chris Allen
The command line syntax for my program is as follows:

action key=value key=value...

Where action is a required string (ie. 'backup', 'init', 'restore',
etc) and the program can accept one or more key value pairs.  I know
this syntax isn't standard, but I think it works great for my program
as each key can override an identically named field in a configuration
file, that way the user doesn't have to have two different syntaxes to
do the same thing.  I could do this with --key value, but key=value is
cleaner IMHO because it matches the config file syntax.

But I'm running into a problem with this which is that sys.argv splits
my key=value options.  I need to know the option associations, and
there's no way to know this by inspecting sys.argv.  Can I get access
to the command line string as python saw it before it split it into
sys.argv or is there another way?  Thanks.

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


Re: cgi

2007-08-29 Thread Gigs_
Fabio Z Tessitore wrote:
> Il Wed, 29 Aug 2007 19:24:54 +0200, Gigs_ ha scritto:
> 
>> i have simple page and form that ask for name and color and cgi script
>> that print that name in another page and background in chosen color
>>
>> all the time this error pop:
>> Error response
>>
>> Error code 501.
>>
>> Message: Can only POST to CGI scripts.
>>
> 
> I think this should be your problem,
> 
> change GET with POST in the form
> 
> bye
it is post in form.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.argv is munging my command line options

2007-08-29 Thread Ant
On Aug 29, 8:11 pm, Chris Allen <[EMAIL PROTECTED]> wrote:
...
> But I'm running into a problem with this which is that sys.argv splits
> my key=value options.  I need to know the option associations, and
> there's no way to know this by inspecting sys.argv.  Can I get access
> to the command line string as python saw it before it split it into
> sys.argv or is there another way?  Thanks.

Could you show us some example code that demonstrates this? The
following works as expected for me on win32:

# test.py
import sys

for arg in sys.argv[1:]:
print arg

>From the command prompt:

C:\0>test.py action key=value key=value
action
key=value
key=value

--
Ant.

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


Re: sys.argv is munging my command line options

2007-08-29 Thread Chris Allen
Thanks for the reply. Oops...  I forget that I was calling the program
from a shell script, the shell script was responsible for goofing up
my command line options.  Solved.  Thanks again.


On Aug 29, 12:28 pm, Ant <[EMAIL PROTECTED]> wrote:
> On Aug 29, 8:11 pm, Chris Allen <[EMAIL PROTECTED]> wrote:
> ...
>
> > But I'm running into a problem with this which is that sys.argv splits
> > my key=value options.  I need to know the option associations, and
> > there's no way to know this by inspecting sys.argv.  Can I get access
> > to the command line string as python saw it before it split it into
> > sys.argv or is there another way?  Thanks.
>
> Could you show us some example code that demonstrates this? The
> following works as expected for me on win32:
>
> # test.py
> import sys
>
> for arg in sys.argv[1:]:
> print arg
>
> >From the command prompt:
>
> C:\0>test.py action key=value key=value
> action
> key=value
> key=value
>
> --
> Ant.


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


re compiled object result caching?

2007-08-29 Thread Dan

I find myself often using regular expressions in the following
pattern:

foo_re = re.compile(r"foo(bar)")
# . . .
re_result = foo_re.search(line)
if re_result:
bar = re_result.group(1)
# . . .

But, I keep thinking this is awkward, and I would kind of like to have
the re object to cache its result; along the lines of:

foo_re = re.compile(r"foo(bar)")
# . . .
if foo_re.search(line):
foo_re.last_result().group(1)

I realize I could do this with a wrapper object (I'm not sure if I can
subclass the re object..), but I was wondering what the community
thought of this. Good idea? Bad? Would it be difficult to add to the
standard re module? The only real downside I can think of is thread
safety. The other practical benefit I can think of is situations like
the following:

if unlikely_condition and foo_re.search(line):
   # . . .

With the current implementation I think you would either have to do
the search even if unlikely_condition is False, or you would have to
do an annoying nested if. Is there another way to achieve this that
I'm not thinking of?

-Dan

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


  1   2   >