Re: mysqldb duplicate entry error handling

2007-02-01 Thread John Nagle
Dennis Lee Bieber wrote:
> On 1 Feb 2007 10:17:31 -0800, "baur79" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:

>>IntegrityError: (1062, "Duplicate entry '[EMAIL PROTECTED]' for key 1")
> 
>   So show us the schema for the database... My take: Your database
> ALREADY HAS a record with that "[EMAIL PROTECTED]" value AND emails.email
> is defined as a unique key field.

Right.  That's not a bug; it's supposed to do that when you try
to add a duplicate.  What do you want to happen?

If you want to allow duplicates, remove the UNIQUE on that
field from the schema.

If you want the new entry to replace the old entry, use REPLACE
instead of INSERT.

If you just want to detect the problem, provide

import MySQLdb
kmysqlduplicateentry = 1062 # MySQL error code when INSERT finds a duplicate
try :
... # do INSERT
except MySQLdb.IntegrityError, message: 
errorcode = message[0]  # get MySQL error code
if errorcode == kmysqlduplicateentry :  # if duplicate
... # handle duplicate
else:
raise   # unexpected error, reraise


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


Re: Python does not play well with others

2007-02-01 Thread John Nagle
Paul Rubin wrote:
> Ben Finney <[EMAIL PROTECTED]> writes:
> 
>>>Python still isn't ready for prime time in the web hosting world.
>>
>>That doesn't follow. It's just as valid to say that the web hosting
>>providers (that you've interacted with so far) aren't ready to support
>>the Python functionality you want.
> 
> 
> I'd say the functionality that John wants is the same that pretty much
> everyone wants, and it's much easier to get for other languages than
> for Python.

 That's about it.

 What's so striking is that this was a surprise.  One would think
from what one reads about Python that it just works.

 I've been able to pound through these problems.  I finally
got M2Crypto, Python, and MySQLdb all working on a shared
hosting server.  But it was quite a bit of work.  I gave up on
getting the hosting provider to install current versions.

 So I just spent four hours struggling with the build procedure
for M2Crypto, to get it to build with a combination of versions of OpenSSL,
M2Crypto, and SWIG that aren't the latest, but are supposed to work.
(Hint: you need to define "__i386__" or other machine if appropriate
as a command line argument to SWIG, so that OpenSSL's older conditional
includes work right.)

 This is really a build system management and coordination issue.
Python has only two kinds of modules - nailed into the distribution,
or external and unsupported.  Whether or not something is supported
should be independent of whether it's built by the main build file.
Components which have external dependencies, like SSL, M2Crypto,
and MySQLdb don't fit well into that model.  They need to undergo
regression testing with each new Python distribution, but they don't
really need to be part of the main build.  Right now, SSL is too
far inside, while the other two are too far outside.  A middle
ground would help.

Otherwise, you get version hell.

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


Re: win32com.client

2007-02-01 Thread Tim Roberts
"vithi" <[EMAIL PROTECTED]> wrote:
>Hi,
>I use python for window. If you are saying win32com in part of the
>python then you are wrong.

Look, you aren't paying attention.  No one has said win32com is part of
Python.  What everyone has said is that win32com is part of the "Python for
Windows extensions" by Mark Hammond.  They used to be called "win32all" and
are now called "pywin32".

http://sourceforge.net/projects/pywin32

The download includes a huge number of useful Python tools for Windows
users, of which win32com is just one.

>Here is a prove:-
 import win32com
>
>Traceback (most recent call last):
>  File "", line 1, in 
>import win32com
>ImportError: No module named win32com

>
>you try in your computer

It works just fine in my computer, because I have "pywin32" installed.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading the tilde operator?

2007-02-01 Thread Ben Finney
James Stroud <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > The Python runtime parser is designed to parse Python, not some
> > arbitrary language that someone chooses to implement in Python.
>
> You haven't addressed why the limitation isn't arbitrary.

Good thing I wasn't trying to do that, then. I was pointing out the
source of the limitation.

The Python syntax parser must follow the rules of the Python
language. If you accept that premise, it follows that the '~' operator
is unary only. If you *don't* accept that premise, I have no help to
offer.

-- 
 \ "I cannot conceive that anybody will require multiplications at |
  `\   the rate of 40,000 or even 4,000 per hour ..."  -- F. H. Wales, |
_o__) 1936 |
Ben Finney

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


Re: Overloading the tilde operator?

2007-02-01 Thread George Sakkis
On Feb 2, 12:49 am, James Stroud <[EMAIL PROTECTED]> wrote:

> Ben Finney wrote:
>
> > The Python runtime parser is designed to parse Python, not some
> > arbitrary language that someone chooses to implement in Python.
>
> You haven't addressed why the limitation isn't arbitrary.

Indeed, and that's because it is arbitrary. Python has the arbitrary
limitation that it's not Perl (or C, or Lisp or what have you).

George

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


Re: Overloading the tilde operator?

2007-02-01 Thread James Stroud
Ben Finney wrote:
> James Stroud <[EMAIL PROTECTED]> writes:
> 
> 
>>Peter Otten wrote:
>>
>>>Chris wrote:
>>>
I am trying to overload the __invert__ operator (~) such that it
can take a second argument,
>>>
>>x ~ x
>>>
>>>  File "", line 1
>>>x ~ x
>>>  ^
>>>SyntaxError: invalid syntax
>>
>>Seems an arbitrary limitation. Consider
>>   - x
>>and
>>   x - y
> 
> 
> Both of which are meaningful syntax in Python, hence the Python parser
> accepts them and knows what operations to call on the objects.
> 
> 
>>Which is inconsistent with limiting ~ to a unary operation.
> 
> 
> Which is the only Python-meaningful way to use that operator, and
> translates to an appropriate call on the object.
> 
> The Python runtime parser is designed to parse Python, not some
> arbitrary language that someone chooses to implement in Python.
> 

You haven't addressed why the limitation isn't arbitrary. You have only 
told us what we already know. So your argument, therefore, is not one.

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


Re: Python, readline and OS X

2007-02-01 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 James Stroud <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> > In article <[EMAIL PROTECTED]>,
> >  James Stroud <[EMAIL PROTECTED]> wrote:
> > 
> >>Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib?
> > 
> > 
> > It wasn't, but changing it so it did didn't fix the problem.  (I didn't 
> > try recompiling Python, just running it.  I'll try rebuilding later.)
> 
> You must re-compile python, starting with configure so that configure 
> can identify the readline libraries. Otherwise it will compile with no 
> readline, which is your current situation

That did the trick.  Thanks!

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


Re: Overloading the tilde operator?

2007-02-01 Thread Ben Finney
James Stroud <[EMAIL PROTECTED]> writes:

> Peter Otten wrote:
> > Chris wrote:
> >>I am trying to overload the __invert__ operator (~) such that it
> >>can take a second argument,
> > 
> x ~ x
> >   File "", line 1
> > x ~ x
> >   ^
> > SyntaxError: invalid syntax
>
> Seems an arbitrary limitation. Consider
>- x
> and
>x - y

Both of which are meaningful syntax in Python, hence the Python parser
accepts them and knows what operations to call on the objects.

> Which is inconsistent with limiting ~ to a unary operation.

Which is the only Python-meaningful way to use that operator, and
translates to an appropriate call on the object.

The Python runtime parser is designed to parse Python, not some
arbitrary language that someone chooses to implement in Python.

-- 
 \ "You know what would make a good story? Something about a clown |
  `\who makes people happy, but inside he's real sad. Also, he has |
_o__)severe diarrhea."  -- Jack Handey |
Ben Finney

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


Spring Python 0.2.0 is released

2007-02-01 Thread gregturn
Spring Python is an offshoot of the Java-based SpringFramework and
AcegiSecurityFramework, targeted for Python. Spring provides many
useful features, and I wanted those same features available when
working with Python.

The site is http://springpython.python-hosting.com, with information
about source code, releases, and mailing lists.

The following features have been implemented.
* DatabaseTemplate - Reading from the database requires a
monotonous cycle of opening cursors, reading rows, and closing
cursors, along with exception handlers. With this template class, all
you need is the SQL query and row-handling function. Spring Python
does the rest.
* InversionOfControl - The idea is to decouple two classes at the
interface level. This lets you build many reusable parts in your
software, and your whole application becomes more pluggable.
* AspectOrientedProgramming - Spring Python provides great ways to
wrap advice around objects. It is utilized for remoting. Another use
is for debug tracers and performance tracing.
* DistributedRemoting - It is easy to convert your local
application into a distributed one. If you have already built your
client and server pieces using the IoC container, then going from
local to distributed is just a configuration change.
* PetClinic - A nice sample web application has been built
utilizing CherryPy as the web container. Go check it out for an
example of how to use this framework.
* ApplicationSecurity - Plugin security interceptors to lock down
access to your methods, utilizing both authentication and domain
authorization.
* SpringWiki - Wikis are powerful ways to store and manage
content, so we created a simple one as a demo!

For more details about implemented features, check out the tickets
tied to this baseline at: 
http://springpython.python-hosting.com/query?status=closed&milestone=0.2

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


Re: Overloading the tilde operator?

2007-02-01 Thread James Stroud
Peter Otten wrote:
> Chris wrote:
> 
> 
>>I am trying to overload the __invert__ operator (~) such that
>>it can take a second argument, other than
>>self, so that I can express:
>>
>>x ~ y
>>
>>by using:
>>
>>def __invert__(self, other): 
>>
>>for example. Is this possible?
> 
> 
> No, you will get a syntax error before python even look up the names:
> 
> 
x
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'x' is not defined
> 
x ~ x
> 
>   File "", line 1
> x ~ x
>   ^
> SyntaxError: invalid syntax
> 
> Peter

Seems an arbitrary limitation. Consider

   - x

and

   x - y

Which is inconsistent with limiting ~ to a unary operation.

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


Re: win32com.client

2007-02-01 Thread rzed
"vithi" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> Hi,
> I use python for window. If you are saying win32com in part of 
the
> python then you are wrong.

That is not what I or anyone else is saying. What we have said, 
perhaps not in words you understand, is this:

1) In your browser, enter this URL: 
http://sourceforge.net/projects/pywin32/

2) When the page comes up, find the big green box that says 
"Download Python for Windows extensions" and click on it

3) In the next page that comes up, find the big green box that 
says "Download" and click on that. That will bring up a page with 
a list of installers, each with a name that indicates what Python 
release the module goes with. If you have the 2.4 release, for 
instance, click on pywin32-210.win32-py2.4.exe to download the 
matching pywin32 installer.

4) When you have downloaded the installer, click on it in your 
Windows Explorer. This will execute the installer, and the entire 
pywin32 package will be installed, including win32com.

Try those steps, then try importing win32com again. 

-- 
rzed



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


Re: Python, readline and OS X

2007-02-01 Thread James Stroud
Ron Garret wrote:
> In article <[EMAIL PROTECTED]>,
>  James Stroud <[EMAIL PROTECTED]> wrote:
> 
>>Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib?
> 
> 
> It wasn't, but changing it so it did didn't fix the problem.  (I didn't 
> try recompiling Python, just running it.  I'll try rebuilding later.)

You must re-compile python, starting with configure so that configure 
can identify the readline libraries. Otherwise it will compile with no 
readline, which is your current situation

>>Bash (OSX default) and similar shells use this silly 2 part syntax:
>>
>>   LD_LIBRARY_PATH=/sw/lib
>>   export LD_LIBRARY_PATH
 >
> Actually you can do it in one line: export LD_LIBRARY_PATH=whatever

Ok. Now I'll switch to bash.

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


Re: need help on a data structure problem

2007-02-01 Thread Ben Finney
"Dongsheng Ruan" <[EMAIL PROTECTED]> writes:

> Not quite related with Python. But my Data Structure course is
> experiemented on python and there is no data structure group, So I
> have to post here:

Better, you should discuss it in your class, with your teacher.

-- 
 \ "As we enjoy great advantages from the inventions of others, we |
  `\  should be glad to serve others by any invention of ours; and |
_o__)  this we should do freely and generously."  -- Benjamin Franklin |
Ben Finney

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


Re: python executing windows exe

2007-02-01 Thread Kiran
On Feb 1, 6:25 pm, "aspineux" <[EMAIL PROTECTED]> wrote:
> First look if your .exe will accept to work that way !
> try in a DOS prompt
>
> > echo yourfilename | nec2d.exe
>
> or if the program expect more input, write them all in a file
> ( myinputs.txt ) and try :
>
> > nec2d.exe < myinputs.txt
>
> If it works looks for module subprocess and more precisely object
> subprocess.popen and method comunicate
>
> On 1 fév, 23:57, "Kiran" <[EMAIL PROTECTED]> wrote:
>
> > Hi everybody,
> >   I am making python run an executable using the os module.  Here is
> > my question.  The executable, once it is running, asks the user to
> > input a filename that it will process.  Now, my question is how do i
> > automate this.  let me make this clear, it is not an argument you pass
> > in when you type in the exe.  An example below illustrates:
>
> > THIS IS NOT WHAT YOU DO:
Hi everybody,
  What you guys said helped out a lot and I got it to do what I
wanted.

thanks!,
Kiran

> > nec2d.exe couple1.nec # couple1.nec is the
> > file you want to prcess
>
> > rather, what you do is in windows cmd:
>
> > nec2d.exe
> >  PROGRAM PRINTS OUT STUFF*
> >  PROGRAM PRINTS OUT STUFF*
> >  PROGRAM PRINTS OUT STUFF*
> >  PROGRAM PRINTS OUT STUFF*
> > Please enter input file:  <- THIS IS WHERE THE USER IS ASKED
> > TO TYPE IN THE FILENAME
>
> > everybody thanks for your help
> > -- Kiran


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


Re: need help on a data structure problem

2007-02-01 Thread Tom Plunket
Dongsheng Ruan wrote:

> Not quite related with Python. But my Data Structure course is experiemented 
> on python and there is no data structure group, So I have to post here:
> 
> Write a procedure (in pseudocode!) to increase the number of buckets in a 
> (closed) hash table. Analyze its time and space complexity. 

What is the question about this problem that you would like to have
answered?  Certainly you don't want us to actually give you the answers
to your homework?!?

Here's some Python code to get us started with the discussion:

class HashTable:
   def __init__(self):
  self.buckets = [ [] ]

   @staticmethod
   def Hash(object):
  return 0

   def InsertItem(self, item):
  self.buckets[Hash(item)].append(item)

The more I think about it, the more I realize you could probably just
cut'n'paste that code and that should suffice for your answer!  Good
luck in Computer Science!


-tom!

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


Re: Python does not play well with others

2007-02-01 Thread Ben Finney
John Nagle <[EMAIL PROTECTED]> writes:

> Python is the only major open source project I've encountered where
> there's so much hostility to bug reports.

Bear in mind that if you send a message only to this mailing list,
that's not a bug report. That's a discussion, which may be worth
having, but not one you can reasonably expect to result in a fix for a
bug.

A bug report should be sent to the bug tracker for the software
against which you're reporting a bug. Only at that point does it
become something on which you can comment about attitude toward bug
reports, because before that point the bug report doesn't exist in a
useful form.

> For a while, I tried submitting long, detailed bug reports showing
> where in the C code a problem lies, and pointing out ways to fix it.

That's great. I hope your attention to detail was well received.

> But I don't want to take over maintenance on the SSL package; it's
> too delicate.

That's fair enough. But if no-one maintains it to your satisfaction,
you do get what you pay for. If it's important to you, it should be
worth an investment of *some* kind from you, to ensure it is
maintained.

-- 
 \"The Bermuda Triangle got tired of warm weather. It moved to |
  `\Alaska. Now Santa Claus is missing."  -- Steven Wright |
_o__)  |
Ben Finney

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


Re: Python, readline and OS X

2007-02-01 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 James Stroud <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> > I have installed Python 2.5 on my new Intel Mac but I can't for the life 
> > of me get readline to work.  I have libreadline installed, I've tried 
> > copying readline.so from my Python 2.3 installation into 2.5, I've 
> > searched the web, and no joy.  Could someone please give me a clue?
> > 
> > rg
> 
> Where have you installed libreadline?

/usr/local/lib

> Is LD_LIBRARY_PATH pointing to the directory libreadline.dylib?

It wasn't, but changing it so it did didn't fix the problem.  (I didn't 
try recompiling Python, just running it.  I'll try rebuilding later.)

> Did you install libreadline with fink?

No, I just got the source from the FSF and did ./configure ; make install

> Bash (OSX default) and similar shells use this silly 2 part syntax:
> 
>LD_LIBRARY_PATH=/sw/lib
>export LD_LIBRARY_PATH

Actually you can do it in one line: export LD_LIBRARY_PATH=whatever

:-)

> Do a "locate libreadline.dylib" and set the LD_LIBRARY_PATH to the 
> containing directory and then
> 
>make clean
>./configure
>make
>make install
> 
> or similar.

I'll give that a whirl.  Thanks.

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


Re: Python, readline and OS X

2007-02-01 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Irmen de Jong <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> > I have installed Python 2.5 on my new Intel Mac but I can't for the life 
> > of me get readline to work.  I have libreadline installed, I've tried 
> > copying readline.so from my Python 2.3 installation into 2.5, I've 
> > searched the web, and no joy.  Could someone please give me a clue?
> > 
> > rg
> 
> Does the info in a blog article that I wrote help?
> 
> http://www.razorvine.net/frog/user/irmen/article/2006-05-08/87

No, because I'm not using Fink.  But maybe I can adapt your solution.

> I used this when I compiled my Python 2.5 on my mac, and
> it seemed to work ;-)
> 
> I'm now using the python.org binary distribution though and that seems to
> contain a working readline as well ?

I'll try that too.

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


need help on a data structure problem

2007-02-01 Thread Dongsheng Ruan
Not quite related with Python. But my Data Structure course is experiemented 
on python and there is no data structure group, So I have to post here:

Write a procedure (in pseudocode!) to increase the number of buckets in a 
(closed) hash table. Analyze its time and space complexity. 


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


Re: Python does not play well with others

2007-02-01 Thread skip

John>  From Aplus.net tech support:
John> "No, db connectivity with Python is not supported. Modules for
John> Python can't be installed by request on shared hosting."

John> And these are companies that say they support Python.

John> Python still isn't ready for prime time in the web hosting world.

Why do you lay the blame at the feet of the Python developers?  Find another
hosting service.

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


Re: Python does not play well with others

2007-02-01 Thread msoulier
On Jan 24, 2:59 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> Python is the only major open source project I've encountered where
> there's so much hostility to bug reports.

Try telling the Perl community that their debugger is broken. That
didn't go well. ;-)

Mike

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


Re: Python does not play well with others

2007-02-01 Thread msoulier
On Jan 23, 8:50 pm, John Nagle <[EMAIL PROTECTED]> wrote:
>The major complaint I have about Python is that the packages
> which connect it to other software components all seem to have
> serious problems.  As long as you don't need to talk to anything
> outside the Python world, you're fine.

As one who has attempted to develop a wxPython application with an
sqlite backend, developing on both Linux and Windows, I would conclude
that the problem is version skew between third-party components and
the core.

Python 1.5.2 touted a simple core language that made Python easy to
learn. I would argue that the core is no longer simple, and it is very
easy to write modules that are not backwards-compatible. This results
in third-party components that you may need but are either not updated
against the new version of Python that you're using, or are not
compatible with the older version of Python that you shipped with.

I found it quite a frustrating experience. Love the language but I'd
rather it not keep reinventing itself quite so quickly, permitting
maintainers to keep up, especially when said maintenance is a
volunteer effort.

Mike

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


Re: Python does not play well with others

2007-02-01 Thread Paul Rubin
Ben Finney <[EMAIL PROTECTED]> writes:
> > Python still isn't ready for prime time in the web hosting world.
> That doesn't follow. It's just as valid to say that the web hosting
> providers (that you've interacted with so far) aren't ready to support
> the Python functionality you want.

I'd say the functionality that John wants is the same that pretty much
everyone wants, and it's much easier to get for other languages than
for Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A* search implementation in Python

2007-02-01 Thread Steven D'Aprano
On Thu, 01 Feb 2007 18:21:57 -0800, bearophileHUGS wrote:

> Reid Priedhorsky:
>> I'm looking for an open-source Python implementation of A* search for use
>> in a mapping application.
> 
> You can try this one:
> http://aima.cs.berkeley.edu/python/search.html

To paraphrase a wise saying:

If you give a man a link, you satisfy his need for one day.
But if you teach a man to search, you satisfy his need forever.

Given that Reid had problems formulating a good search (because * is an
operator in Google) what did you do?



-- 
Steven D'Aprano 

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


Re: Sorting a list

2007-02-01 Thread Steven D'Aprano
On Thu, 01 Feb 2007 14:52:03 -0500, John Salerno wrote:

> Bruno Desthuilliers wrote:
> 
>> You don't tell how these lines are formatted, but it's possible that you 
>> don't even need a regexp here. But wrt/ sorting, the list of tuples with 
>> the sort key as first element is one of the best solutions.
> 
> Ah, so simply using sort() will default to the first element of each tuple?

No. It isn't that sort() knows about tuples. sort() knows how to sort a list
by asking the list items to compare themselves, whatever the items are.
Tuples compare themselves by looking at the first element (if any), and
in the event of a tie going on to the second element, then the third, etc.



-- 
Steven D'Aprano 

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


Re: "Correct" db adapter

2007-02-01 Thread Alejandro Dubrovsky
Bruno Desthuilliers wrote:

> king kikapu a écrit :
>> Thanks for the replies.
>> 
>> I think i do not need something like ORM, but just a db-module that i
>> can "work" the database with it.
> 
> FWIW, SQLAlchemy is not an ORM, but an higher-level API for SQL
> integration. The ORM part is an optional feature built on top of this
> API. But I'm not sure SQLAlchemy supports SQL Server anyway !-)
> 
>> I just want to know if pyodbc is the "correct" solution to do so or if
>> it is another db-module that is more
>> usefull for this job.
> 
> AFAICT:
> 
> * there's an experimental MS SQL Server db-module:
> http://www.object-craft.com.au/projects/mssql/
> 
> * the Win32 extensions offers support for ADO, but then it's not db-api
> compliant
> 
> * unless you use adodbapi, but I don't know if it's still supported
> (last release is 3+ years old):
> http://adodbapi.sourceforge.net/
> 
> HTH

There's also pymssql  which works well
enough most of the time.

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


Re: Overloading the tilde operator?

2007-02-01 Thread bearophileHUGS
Peter Otten:
> No, you will get a syntax error before python even look up the names:

There are some tricks that allow the use of "undefined" symbols in
Python too, but they are probably just toys. I have recently posted a
recipe in the cookbook for that.

Bye,
bearophile

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


Re: Calculating future dates

2007-02-01 Thread Ben Finney
"Toine" <[EMAIL PROTECTED]> writes:

> On Feb 1, 4:54 pm, "Dan Bishop" <[EMAIL PROTECTED]> wrote:
> > str(datetime.date.today() + datetime.timedelta(31))
>
> Your example gave me a few errors but I was able to adapt it into
> this:
>
> str(date.today() + timedelta(31))

That only works if you're importing 'date' and 'timedelta' into the
current namespace. It's better to keep them in the 'datetime'
namespace, so it's clear what comes from where.

>>> import datetime
>>> str(datetime.date.today() + datetime.timedelta(31))

-- 
 \ "How many people here have telekenetic powers? Raise my hand."  |
  `\-- Emo Philips |
_o__)  |
Ben Finney

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


Re: A* search implementation in Python

2007-02-01 Thread bearophileHUGS
Reid Priedhorsky:
> I'm looking for an open-source Python implementation of A* search for use
> in a mapping application.

You can try this one:
http://aima.cs.berkeley.edu/python/search.html

Bye,
bearophile

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


Re: Help me with this!!!

2007-02-01 Thread Steven D'Aprano
On Thu, 01 Feb 2007 08:53:55 -0800, Ravi Teja wrote:

>> > > It search a text inside that hex value.
>> > > It works perfecly on a txt file but if I open a binary file (.exe,.bin
>> > > ecc...) with the same value it wont work, why?
>> > > Please help!
>>
>> > Because the pattern isn't in the file, perhaps.
>>
>> This pattern IS in the file (I made it and I double check with an hex
>> editor).
>> It display the file correcltly (print line) but...
> 
> No! Peter is right. Regular expressions match ASCII representation of
> data, not hex. In simple terms, do you see your pattern when you open
> the file in notepad (or other text editor)? You do not use regex to
> search binary files.

I don't see why not.

>>> pattern = "NULL\0"
>>> source = "\0\01\02-more-bytes-here-NULL\0-more-bytes"
>>> m = re.search(pattern, source)
>>> m.group()
'NULL\x00'
>>> m.span()
(20, 25)

Here's the Original Poster's code again:


regex = re.compile(r"(?si)(\x8B\xF0\x85\xF6)(?P.*)
(\xC6\x44\x24)",re.IGNORECASE)
file = open(fileName, "rb")
for line in file:
  if (match):
  print line
file.close()

I suggest that the reason it doesn't work is because he never actually
uses the regex. Presumably the name "match" was assigned somewhere else to
a false value, and so the code simply walks through the file doing nothing.


-- 
Steven D'Aprano 

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


Re: Python does not play well with others

2007-02-01 Thread Ben Finney
John Nagle <[EMAIL PROTECTED]> writes:

> Just a followup.  I'm still trying to get Python, MySQL, MySQLdb,
> M2Crypto, and maybe mod_python to work on a shared hosting server.

>From your description in the rest of the message, it seems that it's
the *hosting providers* who are unable to do this, not you.

> And these are companies that say they support Python.
>
> Python still isn't ready for prime time in the web hosting world.

That doesn't follow. It's just as valid to say that the web hosting
providers (that you've interacted with so far) aren't ready to support
the Python functionality you want.

-- 
 \  "To be is to do"  -- Plato |
  `\"To do is to be"  -- Aristotle |
_o__) "Do be do be do"  -- Sinatra |
Ben Finney

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


OSS and ALSA

2007-02-01 Thread Silver Rock

Hi all,

I've seen that python comes by default with a module for communication with
OSS.

I've looked for a ALSA module too (pyalsa) but it seems to handle only
limited operations.

Can anyone confirm or point wrong the impression that a newbie should use
the ossaudiodev module?

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

Re: win32com.client

2007-02-01 Thread Gabriel Genellina
En Thu, 01 Feb 2007 22:18:49 -0300, vithi <[EMAIL PROTECTED]> escribió:

> If you are saying win32com in part of the  python then you are wrong.

Uh, what is so difficult to understand?

vithi wrote:
>> Any one tell me where I can get (or download) python modules win32com

On Jan 31, 1:45 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
>> You want the "python for windows" extension, available from
>>  http://sourceforge.net/projects/pywin32/

You didn't believe him, so I wrote:
>> Yes. You get the win32com module from the above url. It's part of that
>> package, by Mark Hammond, and a lot of people uses it.

rzed <[EMAIL PROTECTED]> wrote:
>> I think the ActiveState distro includes it as part of its package.

vithi wrote:
 import win32com
>
> Traceback (most recent call last):
>   File "", line 1, in 
> import win32com
> ImportError: No module named win32com


Sure, you don't have it installed, else you would not be asking here.

> you try in your computer

Why should I?

-- 
Gabriel Genellina

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


A* search implementation in Python

2007-02-01 Thread Reid Priedhorsky
Hi folks,

I'm looking for an open-source Python implementation of A* search for use
in a mapping application.

As the star is an operator in Google, I haven't figured out how to
formulate a useful search. :/

Any help would be very much appreciated.

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


script not opening applications

2007-02-01 Thread elrondrules
hi

i have a html as follows:






my hello.py is as follows



import os

os.system ("export DISPLAY=10.0.1.1:0.0")
os.system ("./Test &") #Testtool opens a new window



What I expected this to do was once I click "Run Test" it should run
the hello.py script and open a new window for the Test application.
both the hello.py and the test application are in the cgi-bin
directory

If I run the hello.py in the command line it works fine but not
through the html...

Any idea as to whats missing..

Thanks

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


Re: coping directories

2007-02-01 Thread Gabriel Genellina
En Thu, 01 Feb 2007 21:33:03 -0300, Gigs_ <[EMAIL PROTECTED]> escribió:

> class CVisitor(FileVisitor):
>  def __init__(self, fromdir, todir):
>  self.fromdirLen = len(fromdir) + 1# here is my problem
>  self.todir = todir
>  FileVisitor.__init__(self, fromdir)
>  def visitdir(self, dirpath):
>  topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
>  os.mkdir(topath)
>  def visitfile(self, filepath):
>  topath = os.path.join(self.todir, filepath[self.fromdirLen:])
>  cpfile(filepath, topath)#copy contents from filepath to
> topath[/code]
>
>
> When I copy contents from C:\IronPython to C:\temp
> its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this
> self.fromdirLen = len(fromdir) + 1
> but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen
> = len(fromdir) i get contents copied to C:\ (actually to parent dir)

Instead of actually doing os.mkdir and cpfile, use a print statement to  
output the involved variables, and try with and without +1. You'll see  
yourself what happens.

-- 
Gabriel Genellina

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


Re: win32com.client

2007-02-01 Thread vithi
Hi,
I use python for window. If you are saying win32com in part of the
python then you are wrong.
Here is a prove:-

IDLE 1.2



>>> import win32com


Traceback (most recent call last):
  File "", line 1, in 
import win32com
ImportError: No module named win32com

>>>


you try in your computer



vithi

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


Re: win32com.client

2007-02-01 Thread vithi
On Jan 31, 6:35 pm, rzed <[EMAIL PROTECTED]> wrote:
> "vithi" <[EMAIL PROTECTED]> wrote innews:[EMAIL PROTECTED]:
>
> > Hi
> > Any one tell me where I can get (or download) python modules
> > win32com or win32com.client because I have to use "Dispatch"
> > thanks
>
> What distribution are you using? If you are using Windows and have
> downloaded the Python.org one, then, as Gary has told you:
> "You want the "python for windows" extension, available from  
> http://sourceforge.net/projects/pywin32/";
>
> I think the ActiveState distro includes it as part of its package.
>
> I don't know if any of this applies if you are using Linux, VMS, etc.
>
> --
> rzed


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


Re: win32com.client

2007-02-01 Thread vithi
Hi,
If you are saying win32com in part of the  python then you are wrong.
Here is a prove:-

IDLE 1.2
>>> import win32com

Traceback (most recent call last):
  File "", line 1, in 
import win32com
ImportError: No module named win32com
>>>

you try in your computer



On Jan 31, 7:17 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Wed, 31 Jan 2007 22:17:10 -0300, vithi <[EMAIL PROTECTED]> escribió:
>
> > This is not I was looking for. There is a module call
> > "win32com.client" in python some people used it If any body know about
> > it let me know.
>
> > On Jan 31, 1:45 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> >> vithi wrote:
> >> > Hi
> >> > Any one tell me where I can get (or download) python modules win32com
> >> > or win32com.client because I have to use "Dispatch"  thanks
>
> >> You want the "python for windows" extension, available from
> >>  http://sourceforge.net/projects/pywin32/
>
> Yes. You get the win32com module from the above url. It's part of that  
> package, by Mark Hammond, and a lot of people uses it.
>
> --
> Gabriel Genellina


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


Re: Calculating future dates

2007-02-01 Thread Toine
On Feb 1, 4:54 pm, "Dan Bishop" <[EMAIL PROTECTED]> wrote:
> On Feb 1, 6:51 pm, "Toine" <[EMAIL PROTECTED]> wrote:
>
> > Hello,
>
> > I'm new to Python so please bare with me...
>
> > I need to calculate a date that is exactly 31 days from the current
> > date in -MM-DD format. I know that date.today() returns the
> > current date, but how can I add 31 days to this result? I'm sure this
> > task is simple, but I haven't been able to figure it out.
>
> > Thanks
>
> str(datetime.date.today() + datetime.timedelta(31))

Your example gave me a few errors but I was able to adapt it into
this:

str(date.today() + timedelta(31))

Thanks for your help

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


Re: Calculating future dates

2007-02-01 Thread Irmen de Jong
Toine wrote:
> Hello,
> 
> I'm new to Python so please bare with me...
> 
> I need to calculate a date that is exactly 31 days from the current
> date in -MM-DD format. I know that date.today() returns the
> current date, but how can I add 31 days to this result? I'm sure this
> task is simple, but I haven't been able to figure it out.

 >>> import datetime
 >>> print datetime.date.today()+datetime.timedelta(days=31)
2007-03-05
 >>>


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


Re: Calculating future dates

2007-02-01 Thread Dan Bishop
On Feb 1, 6:51 pm, "Toine" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm new to Python so please bare with me...
>
> I need to calculate a date that is exactly 31 days from the current
> date in -MM-DD format. I know that date.today() returns the
> current date, but how can I add 31 days to this result? I'm sure this
> task is simple, but I haven't been able to figure it out.
>
> Thanks

str(datetime.date.today() + datetime.timedelta(31))

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


Calculating future dates

2007-02-01 Thread Toine
Hello,

I'm new to Python so please bare with me...

I need to calculate a date that is exactly 31 days from the current
date in -MM-DD format. I know that date.today() returns the
current date, but how can I add 31 days to this result? I'm sure this
task is simple, but I haven't been able to figure it out.

Thanks

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


Re: Python, readline and OS X

2007-02-01 Thread Irmen de Jong
Ron Garret wrote:
> I have installed Python 2.5 on my new Intel Mac but I can't for the life 
> of me get readline to work.  I have libreadline installed, I've tried 
> copying readline.so from my Python 2.3 installation into 2.5, I've 
> searched the web, and no joy.  Could someone please give me a clue?
> 
> rg

Does the info in a blog article that I wrote help?

http://www.razorvine.net/frog/user/irmen/article/2006-05-08/87

I used this when I compiled my Python 2.5 on my mac, and
it seemed to work ;-)

I'm now using the python.org binary distribution though and that seems to
contain a working readline as well ?

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


Re: Python does not play well with others

2007-02-01 Thread John Nagle
Just a followup.  I'm still trying to get Python, MySQL, MySQLdb,
M2Crypto, and maybe mod_python to work on a shared hosting server.
This is amazingly difficult, because of all the version incompatibility issues.
Python, MySQL, MySQLdb, SWIG, OpenSSL, and gcc all have to have the
right versions, and those aren't necessarily the versions shipping
in some major Linux distros.

 From EZpublishing tech support:
"To make matters worse, we can't run the newer version of openSSL on any of our 
current servers. It's a standard redhat rpm and redhat hasn't upgraded it. We 
can install it on dedicated servers, but it is too risky for other users to be 
installed on a shared environment."

 From Aplus.net tech support:
"No, db connectivity with Python is not supported. Modules for Python
can't be installed by request on shared hosting."

And these are companies that say they support Python.

Python still isn't ready for prime time in the web hosting world.

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


coping directories

2007-02-01 Thread Gigs_
hi people

I have problem with this example, not actually the problem, but
[code]
class FileVisitor(object):
 def __init__(self, data=None):
 self.context = data
 def run(self, startdir=os.curdir):
 os.path.walk(startdir, self.visitor, None)
 def visitor(self, data, dirname, filesindir):
 self.visitdir(dirname)
 for fname in filesindir:
 fpath = os.path.join(dirname, fname)
 if not os.path.isdir(fpath):
 self.visitfile(fpath)
 def visitdir(self, dirpath):# override or extend this 
method
 print dirpath, '...'
 def visitfile(self, filepath):  # override or extend this 
method
 print self.fcount, '=>', filepath
#
class CVisitor(FileVisitor):
 def __init__(self, fromdir, todir):
 self.fromdirLen = len(fromdir) + 1# here is my problem
 self.todir = todir
 FileVisitor.__init__(self, fromdir)
 def visitdir(self, dirpath):
 topath = os.path.join(self.todir, dirpath[self.fromdirLen:])
 os.mkdir(topath)
 def visitfile(self, filepath):
 topath = os.path.join(self.todir, filepath[self.fromdirLen:])
 cpfile(filepath, topath)#copy contents from filepath to 
topath[/code]


When I copy contents from C:\IronPython to C:\temp
its all goes fine when self.fromdirLen = len(fromdir) + 1 is like this 
self.fromdirLen = len(fromdir) + 1
but when I change self.fromdirLen = len(fromdir) + 1 to self.fromdirLen 
= len(fromdir) i get contents copied to C:\ (actually to parent dir)

Can anyone explain me that?

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


Re: how to add class attributes in __new__

2007-02-01 Thread aspineux
On 1 fév, 17:50, "jeremito" <[EMAIL PROTECTED]> wrote:
> I am subclassing the array class and have __new__ to initialize and
> create my class.  In that class I create not only do I create an array
> object, but I also create some other data in __new__ I want to have
> access to outside of __new__.  I tried
>
> self.mydata = mydata
>
> but that didn't work.
>
> Can someone point me in the right direction?
> Thanks,
> Jeremy

self ? in __new__ ?

What about with this ?

def __new__(cls, *args, **kw):
newobj=object.__new__(cls)
newobj.foo='bar'
return newobj

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


Re: how to make a python windows service know it's own identity

2007-02-01 Thread Larry Bates
Chris Curvey wrote:
> On Feb 1, 2:10 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
>> Chris Curvey wrote:
>>> Hi all,
>>> I have used the win32com libraries to set up a service called
>>> MyService under Windows.  So far, so good.  Now I need to run multiple
>>> copies of the service on the same machine.  I also have that working.
>>> For monitoring and logging, I'd like each instance of the service to
>>> know it's own identity (MyService1, MyService2, etc.)
>>> But I can't quite seem to grasp how to do this.  In the code below,
>>> the command line parameter "-i" gives the service an identity, but how
>>> do I get the service to understand it's identity when it is started?
>>> Many thanks!
>>> class MyService(win32serviceutil.ServiceFramework):
>>> """NT Service."""
>>> _svc_name_ = "MyService"
>>> _svc_display_name_ = "My Service"
>>> _id_ = ''
>>> def SvcDoRun(self):
>>> provider = MyServiceClass(identifier=self._id_)
>>> provider.start()
>>> # now, block until our event is set...
>>> win32event.WaitForSingleObject(self.stop_event,
>>> win32event.INFINITE)
>>># __init__ and SvcStop snipped
>>> ###
>>> if __name__ == '__main__':
>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-i", "--identifier", dest="identifier")
>>> (opts, args) = parser.parse_args()
>>> if opts.number is not None:
>>> MyService._svc_name_ += opts.identifier
>>> MyService._svc_display_name_ += opts.identifier
>>> MyService._provider_id_ = opts.identifier
>>> win32serviceutil.HandleCommandLine(MyService,
>>> customInstallOptions="i:")
>> What is your use case for this?  Why not make a single server
>> process multiple providers (store them in a list or other
>> container)?
>>
>> -Larry Bates
> 
> The use case is that I have a queue of jobs that need to run.  My
> service connects to a central "distributor" server, which hands out
> jobs to complete.  I'd like to be able to run multiple copies of the
> distributed service so that I can make the most use of each machine
> where they run.  (I'm not certain of the thread safety of some of the
> libraries I'm using, so I'm leery of going the multi-threaded route)
> Anyway, when my service gets a job to process, I'd like to know which
> copy of the service is working on which job.  So I want my log
> messages to look like this:
> 
> Job 123:  Host: alpha  Service: MyService A
> Job 124:  Host: alpha  Service: MyService B
> Job 124:  Host: beta  Service: MyService C
> 
> Is that clear, or have I muddied the waters?
> 
Ok, makes more sense now.  You will be running each service on a different
computer.  If I'm understanding all you need is to supply an attribute
to the service that represents its internal name (the one you will use
to do the logging).  If I wanted to do this I would create a .INI file
and read it (using ConfigParser) during service class __init__ method.
Assign self.servicename=.  Then use self.servicename
to do my logging.  I have a service somewhat like you describe and this
works fine for me.

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


Re: python executing windows exe

2007-02-01 Thread aspineux
First look if your .exe will accept to work that way !
try in a DOS prompt

> echo yourfilename | nec2d.exe

or if the program expect more input, write them all in a file
( myinputs.txt ) and try :

> nec2d.exe < myinputs.txt

If it works looks for module subprocess and more precisely object
subprocess.popen and method comunicate


On 1 fév, 23:57, "Kiran" <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>   I am making python run an executable using the os module.  Here is
> my question.  The executable, once it is running, asks the user to
> input a filename that it will process.  Now, my question is how do i
> automate this.  let me make this clear, it is not an argument you pass
> in when you type in the exe.  An example below illustrates:
>
> THIS IS NOT WHAT YOU DO:
> nec2d.exe couple1.nec # couple1.nec is the
> file you want to prcess
>
> rather, what you do is in windows cmd:
>
> nec2d.exe
>  PROGRAM PRINTS OUT STUFF*
>  PROGRAM PRINTS OUT STUFF*
>  PROGRAM PRINTS OUT STUFF*
>  PROGRAM PRINTS OUT STUFF*
> Please enter input file:  <- THIS IS WHERE THE USER IS ASKED
> TO TYPE IN THE FILENAME
>
> everybody thanks for your help
> -- Kiran


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


Re: Odd import behavior

2007-02-01 Thread Gabriel Genellina
En Thu, 01 Feb 2007 19:33:50 -0300, Gregory Piñero <[EMAIL PROTECTED]>  
escribió:

> I didn't realize Python behaved like this.  Is there an FAQ I can read  
> on this?
>
> FILE module1.py:
> VAR1='HI'
>
> FILE MAIN.py:
> from module1 import *
> import module1
>
> print VAR1
> print module1.VAR1
>
> VAR1='bye'
> print VAR1
> print module1.VAR1
>
> And the results are:
>
 HI
> HI
> bye
> HI
>
> It seems to use module1.VAR1 for VAR1 until I assign something to VAR1
> in which case they become seperate.

There is no magic here. It's like this:

class Module: pass

module1 = Module()   # this is like `import module1`
module1.VAR1 = 'HI'

VAR1 = module1.VAR1  # this is like `from module1 import VAR1`

print VAR1
print module1.VAR1

VAR1='bye'
print VAR1
print module1.VAR1

-- 
Gabriel Genellina

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


Re: Python, readline and OS X

2007-02-01 Thread James Stroud
Ron Garret wrote:
> I have installed Python 2.5 on my new Intel Mac but I can't for the life 
> of me get readline to work.  I have libreadline installed, I've tried 
> copying readline.so from my Python 2.3 installation into 2.5, I've 
> searched the web, and no joy.  Could someone please give me a clue?
> 
> rg

Where have you installed libreadline? Is LD_LIBRARY_PATH pointing to the 
directory libreadline.dylib? Did you install libreadline with fink? If 
so, try

   setenv LD_LIBRARY_PATH /sw/lib

before compiling (csh).

Bash (OSX default) and similar shells use this silly 2 part syntax:

   LD_LIBRARY_PATH=/sw/lib
   export LD_LIBRARY_PATH

Do a "locate libreadline.dylib" and set the LD_LIBRARY_PATH to the 
containing directory and then

   make clean
   ./configure
   make
   make install

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


Re: python executing windows exe

2007-02-01 Thread Gabriel Genellina
En Thu, 01 Feb 2007 19:57:59 -0300, Kiran <[EMAIL PROTECTED]> escribió:

>   I am making python run an executable using the os module.  Here is
> my question.  The executable, once it is running, asks the user to
> input a filename that it will process.  Now, my question is how do i
> automate this.  let me make this clear, it is not an argument you pass
> in when you type in the exe.  An example below illustrates:

You can use the subprocess module, or any of the Popen2 variants. Usually  
they work fine - but depending on how the application behaves, it may not  
work.

-- 
Gabriel Genellina

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


Re: python executing windows exe

2007-02-01 Thread Larry Bates
Kiran wrote:
> Hi everybody,
>   I am making python run an executable using the os module.  Here is
> my question.  The executable, once it is running, asks the user to
> input a filename that it will process.  Now, my question is how do i
> automate this.  let me make this clear, it is not an argument you pass
> in when you type in the exe.  An example below illustrates:
> 
> THIS IS NOT WHAT YOU DO:
> nec2d.exe couple1.nec # couple1.nec is the
> file you want to prcess
> 
> rather, what you do is in windows cmd:
> 
> nec2d.exe
>  PROGRAM PRINTS OUT STUFF*
>  PROGRAM PRINTS OUT STUFF*
>  PROGRAM PRINTS OUT STUFF*
>  PROGRAM PRINTS OUT STUFF*
> Please enter input file:  <- THIS IS WHERE THE USER IS ASKED
> TO TYPE IN THE FILENAME
> 
> everybody thanks for your help
> -- Kiran
> 
Not exactly a Python question, but here goes.  Normally I do this
by piping the response into the executable.  Something like:

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


Re: Ubunu - Linux - Unicode - encoding

2007-02-01 Thread Alan Franzoni
Il Thu, 01 Feb 2007 20:57:53 +0100, Franz Steinhäusler ha scritto:

> If I copy files with german umlauts (äöü and strong 's' ß), these
> filenames are not copied properly, and that characters are replaces
> by little square symbols.

Yes... I, myself, am italian, and I found no problem in using accented
letter (òèàìù). Since you say there's a problem as well in Nautilus and
other Ubuntu software, I suppose there's something wrong with your linux
setup, not with Python.

Or, at least: you should try solving that problem first, then check what
happens with python.

Try appending this options in your fstab as hda1 mount options:

iocharset=iso8859-15

unmount & remount and check what does happen.

-- 
Alan Franzoni <[EMAIL PROTECTED]>
-
Togli .xyz dalla mia email per contattarmi.
Remove .xyz from my address in order to contact me.
-
GPG Key Fingerprint (Key ID = FE068F3E):
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LDAP/LDIF Parsing

2007-02-01 Thread aspineux

The tree hierarchy is defined by the DN of each object, the types of
the object is specified by its objectClass.
Just collect all items (or do it dynamically by tunning the scope and
the base of your search request)


On 1 fév, 18:22, "Cruelemort" <[EMAIL PROTECTED]> wrote:
> All,
>
> I am hoping someone would be able to help me with a problem. I have an
> LDAP server running on a linux box, this LDAP server contains a
> telephone list in various groupings, the ldif file of which is -
>
> dn: dc=example,dc=com
> objectClass: top
> objectClass: dcObject
> objectClass: organization
> dc: example
> o: Example Organisation
>
> dn: ou=groupa,dc=example,dc=com
> ou: groupa
> objectClass: top
> objectClass: organizationalUnit
> description: Group A
>
> dn: cn=johnsmith,ou=groupa,dc=example,dc=com
> cn: johnsmith
> objectClass: top
> objectClass: person
> sn: Smith
> telephoneNumber: 112
>
> dn: cn=davesteel,ou=groupa,dc=example,dc=com
> cn: davesteel
> objectClass: top
> objectClass: person
> sn: Steel
> telephoneNumber: 113
>
> dn: ou=groupb,dc=example,dc=com
> ou: groupb
> objectClass: top
> objectClass: organizationalUnit
> description: Group B
>
> dn: cn=williamdavis,ou=groupb,dc=example,dc=com
> cn: williamdavis
> objectClass: top
> objectClass: person
> sn: Davis
> telephoneNumber: 122
>
> dn: cn=jamesjarvis,ou=groupb,dc=example,dc=com
> cn: jamesjarvis
> objectClass: top
> objectClass: person
> sn: Jarvis
> telephoneNumber: 123
>
> I am creating a python client program that will display the telephone
> list in the same directory structure as is on the LDAP server (i.e. it
> starts with buttons of all the groups, when you click on a group it
> comes up with buttons of all the numbers or groups available, and you
> can continually drill down).
>
> I was wondering the best way to do this? I have installed and used the
> python-ldap libraries and these allow me to access and search the
> server, but the searches always return a horrible nesting of lists,
> tuples and dictionaries, below is an example of returning just one
> record -
>
> ('dc=example,dc=com', {'objectClass': ['top', 'dcObject',
> 'organization'], 'dc': ['example'], 'o': ['Example Organisation']})
>
> Basically i think i need to parse the search results to create objects
> and build the python buttons around this, but i was hoping someone
> would be able to point me in the correct direction of how to do this?
> Is there a parser available? (there is an ldif library available but
> it is not obvious how this works, i cannot see much documentation, and
> it seems to be deprecated...).
>
> Many thanks.
>
> Ian


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


python executing windows exe

2007-02-01 Thread Kiran
Hi everybody,
  I am making python run an executable using the os module.  Here is
my question.  The executable, once it is running, asks the user to
input a filename that it will process.  Now, my question is how do i
automate this.  let me make this clear, it is not an argument you pass
in when you type in the exe.  An example below illustrates:

THIS IS NOT WHAT YOU DO:
nec2d.exe couple1.nec # couple1.nec is the
file you want to prcess

rather, what you do is in windows cmd:

nec2d.exe
 PROGRAM PRINTS OUT STUFF*
 PROGRAM PRINTS OUT STUFF*
 PROGRAM PRINTS OUT STUFF*
 PROGRAM PRINTS OUT STUFF*
Please enter input file:  <- THIS IS WHERE THE USER IS ASKED
TO TYPE IN THE FILENAME

everybody thanks for your help
-- Kiran

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


imaplib: support for more cyrus extension : expire

2007-02-01 Thread aspineux
setacl and getacl look to be already "Cyrus" specific (according the
doc),
why not to extend imaplib a little bit more ?

Here are some code I wrote and tested to support cyrus "expire" that
manage how long a message
can stay into a mailbox.
This is usefull for NEWS server !

The code is preceded by lot of sample.
I wrote the 2 generic functions getannotation and setannotation that
coul be used with any IMAP server.
And use them to access the Cyrus extensions !
I tried to use http://www.potaroo.net/ietf/all-ids/draft-daboo-imap-
annotatemore-00.txt
but used a lot TCPDUMP to compare with cyradm :-)

Any chances to see this small part of me into the official python
release ?

"""IMAP4 Client

Extend default python imaplib to include ANNOTATION as described in
http://www.potaroo.net/ietf/all-ids/draft-daboo-imap-annotatemore-00.txt

This extention is used by cyrus imap, for exemple to manage
automatique
removale of expired mail based on '/vendor/cmu/cyrus-imapd/expir'
annotation
"""

"""
Some usage

>>> i.getannotation('user/[EMAIL PROTECTED]', '"*"', '"value.shared"')
>>> i.getannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>> '"value.shared"')
('OK', ['"user/[EMAIL PROTECTED]" "/vendor/cmu/cyrus-imapd/
expire" ("value.shared" "44")'])
>>> i.getannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>> '("value.shared")')
('OK', ['"user/[EMAIL PROTECTED]" "/vendor/cmu/cyrus-imapd/
expire" ("value.shared" "44")'])
>>> i.getannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>> '("*")')
('OK', ['"user/[EMAIL PROTECTED]" "/vendor/cmu/cyrus-imapd/
expire" ("value.shared" "44" "content-type.shared" "text/plain"
"size.shared" "2" "modifiedsince.shared" "1156264470")'])
>>> i.getannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>> '("value.shared" "content-type.shared")')
('OK', ['"user/[EMAIL PROTECTED]" "/vendor/cmu/cyrus-imapd/
expire" ("value.shared" "44" "content-type.shared" "text/plain")'])
>>> i.setannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>>  '("value.shared" "44")')
('OK', [None])
>>> i.setannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>>  '("value.shared" NIL)')
('OK', [None])
>>> i.getannotation('user/[EMAIL PROTECTED]', '/vendor/cmu/cyrus-imapd/expire', 
>>> '("value.shared")')
('OK', [None])

some more

>>> i=cyrusimap.CYRUSIMAP4('localhost')
>>> i.login('manager', 'password')
('OK', ['User logged in'])
>>> i.getcyrusexpire("user/[EMAIL PROTECTED]")
('OK', 0)
>>> i.setcyrusexpire("user/[EMAIL PROTECTED]", 88)
('OK', [None])
>>> i.getcyrusexpire("user/[EMAIL PROTECTED]")
('OK', 88)
>>> i.setcyrusexpire("user/[EMAIL PROTECTED]", None)
('OK', [None])
>>> i.getcyrusexpire("user/[EMAIL PROTECTED]")
('OK', 0)


"""


import imaplib

imaplib.Commands.update(
   {
'GETANNOTATION': ('AUTH', 'SELECTED'),
'SETANNOTATION': ('AUTH', 'SELECTED'),
})

class CYRUSIMAP4(imaplib.IMAP4):

def getannotation(self, root, entry, attrib):
"""Get annotation

(typ, [data]) = .getannotation(self, root, entry,
attrib)
"""
typ, dat = self._simple_command('GETANNOTATION', root, entry,
attrib)
return self._untagged_response(typ, dat, 'ANNOTATION')

def setannotation(self, root, entry, value):
"""Set annotation value.

(typ, [data]) = .setannotation(root, limits)
"""
typ, dat = self._simple_command('SETANNOTATION', root, entry,
value)
return self._untagged_response(typ, dat, 'ANNOTATION')

def getcyrusexpire(self, root):
"""Get cyrus 'expire' annotation value.

(typ, [data]) = .getcyrusexpire(root)
"""

typ, dat=self.getannotation(root, '/vendor/cmu/cyrus-imapd/
expire', '("value.shared")')
if typ!='OK':
return typ, dat

if dat[0]==None:
return typ, 0

# ['"user/[EMAIL PROTECTED]" "/vendor/cmu/cyrus-imapd/
expire" ("value.shared" "44")'])
v=int(dat[0].split(None,2)[2].strip('()').split(None,1)
[1].strip('"'))
return typ, v

def setcyrusexpire(self, root, value):
"""Get cyrus 'expire' annotation value.

(typ, [data]) = .setcyrusexpire(root, value)
"""
if value==None or value==0:
v='NIL'
else:
v='"%d"' % (value,)

return self.setannotation(root, '/vendor/cmu/cyrus-imapd/
expire', '("value.shared" %s)'%(v,))

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


Re: Newbie question: replacing nulls in CSV with preceding value

2007-02-01 Thread Matt Waite
Thanks everyone for your help. I got Skip's answer to work (mine is
pasted below):

import sys
import csv

last = {}
reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb"))
writer = csv.DictWriter(open("/home/mwaite/test/test3.csv", "wb"),
['ZONE','CITY','EVENT'], dialect='excel')
for row in reader:
for key in row:
if not row[key]:
row[key] = last.get(key, "")
writer.writerow(row)
last = row


On Feb 1, 3:37 pm, [EMAIL PROTECTED] wrote:
> Matt> I have a CSV file, exported from Excel, that has blank records in
> Matt> it, and I need to fill them in with the values from the record
> Matt> just above it until it hits a non-blank value.
>
> Try something like:
>
> #!/usr/bin/env python
>
> import sys
> import csv
>
> last = {}
> reader = csv.DictReader(open("test1.csv", "rb"))
> writer = csv.DictWriter(open("test2.csv", "wb"),
> sys.stdout, fieldnames="Zone City Event".split())
> for row in reader:
> for key in row:
> if not row[key]:
> row[key] = last.get(key, "")
> writer.writerow(row)
> last = row
>
> Skip


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


Odd import behavior

2007-02-01 Thread Gregory Piñero
I didn't realize Python behaved like this.  Is there an FAQ I can read on this?

FILE module1.py:
VAR1='HI'

FILE MAIN.py:
from module1 import *
import module1

print VAR1
print module1.VAR1

VAR1='bye'
print VAR1
print module1.VAR1

And the results are:

>>> HI
HI
bye
HI

It seems to use module1.VAR1 for VAR1 until I assign something to VAR1
in which case they become seperate.

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


Setting IP TOS fields

2007-02-01 Thread Tulpule Naren-MGI2846
Hi,
  I don't see the ToS field that I set, in the generated IP packets
captured via Ethereal/WireShark. What step am I missing in the code
below?
 
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((sIntf, sPort))
tos = 64 # I also tried tos = struct.pack("B", 64)
s.setsockopt(socket.SOL_IP, socket.IP_TOS, tos)
# at this point, s.getsockopt(socket.SOL_IP, socket.IP_TOS,1) returns
'@' i.e. chr(64)
...
s.sendto(data, 0, dAddr) # 0 here is for 'flags' argument...
 
-- Naren.
 
Narendra C. Tulpule   Principal Firmware Engineer, Staff
6450 Sequence Dr  +1-858-404-2650
San Diego, CA 92121   [EMAIL PROTECTED]
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list

imaplib : error reporting use 'randomly' exception or return value

2007-02-01 Thread aspineux
imaplib use exception to report errors,  but some problems must be
detected by checking the return value !
For example, when trying to append into a mailbox with wrong ACL,
imaplib return 'NO', but dont raise any exception (I give a sample at
the end).
This make error handling more complicate, because any imap statement
is supposed to be followed by a test of the returned value!

Why not report all problems using exceptions ?

It easy to modify imaplib.py to manage this because most of the imap
call are made through function
_simple_command this way :

def _simple_command(self, name, *args):
return self._command_complete(name, self._command(name,
*args))

I propose to replace it by something like :

def _simple_command(self, name, *args):
typ, dat=self._command_complete(name, self._command(name,
*args))
if typ!='OK':
raise self.error(dat[-1])
return typ, dat

Any comment ?

Here is an example, append  on a mailbox with the wrong ACL fail by
returning a 'NO'

import imaplib

server='localhost'
login='[EMAIL PROTECTED]'
passwd='password'

c=imaplib.IMAP4(server)
c.login(login, passwd)
c.setacl('INBOX', login, '') # set wrong ACL, removing 'i'
typ, dat=c.append('INBOX', None, None, "From: [EMAIL PROTECTED]: %s
\nSubject: test append\n\nHello\n" % (login))
print typ, dat

output:

NO ['Permission denied']

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


Re: xml.dom.minidom memory usage

2007-02-01 Thread Jonathan Curran
Dan,
Take a look at http://www.xml.com/pub/a/2003/03/12/py-xml.html. It's a 
starting point to output XML data via use of SAX. Bruno also mentioned 
Genshi. I haven't used Genshi myself, but it'd be worth it to take a look at 
what it has to offer.

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


Re: LDAP/LDIF Parsing

2007-02-01 Thread Bruno Desthuilliers
Cruelemort a écrit :
> All,
> 
> I am hoping someone would be able to help me with a problem. I have an
> LDAP server running on a linux box, this LDAP server contains a
> telephone list in various groupings, the ldif file of which is -
> 
(snip)
> 
> I am creating a python client program that will display the telephone
> list in the same directory structure as is on the LDAP server (i.e. it
> starts with buttons of all the groups, when you click on a group it
> comes up with buttons of all the numbers or groups available, and you
> can continually drill down).
> 
> I was wondering the best way to do this? I have installed and used the
> python-ldap libraries and these allow me to access and search the
> server, but the searches always return a horrible nesting of lists,
> tuples and dictionaries, below is an example of returning just one
> record -
> 
> ('dc=example,dc=com', {'objectClass': ['top', 'dcObject',
> 'organization'], 'dc': ['example'], 'o': ['Example Organisation']})

What's your problem ? That's exactly what your ldap record should look 
like. A (base_dn, record) tuple, where the record is a dict of 
attribute_name:[values, ...]

> Basically i think i need to parse the search results to create objects

Q&D wrapper:

class LdapObject(object):
   def __init__(self, ldapentry):
 self.dn, self._record = ldapentry

   def __getattr__(self, name):
 try:
   data = self._record[name]
 except KeyError:
   raise AttributeError(
 "object %s has no attribute %s" % (self, name)
)
 else:
   # all LDAP attribs are multivalued by default,
   # even when the schema says they are monovalued
   if len(data) == 1:
  return data[0]
   else:
  return data[:]

   def isa(self, objectClass):
 return objectClass in self.objectClass:

root = LdapObject(
   ('dc=example,dc=com',
{'objectClass': ['top', 'dcObject','organization'],
 'dc': ['example'],
 'o': ['Example Organisation']}
   ))

root.o
=> 'Example Organisation'
root.objectClass
=> ['top', 'dcObject','organization']
root.isa('organization')
=> True

FWIW, I once started writing an higher-level LDAP api (kind of an 
Object-LDAP Mapper...) using descriptors for ldap attribute access, but 
I never finished the damned thing, and it's in a very sorry state. I'll 
have to get back to it one day...

>  and build the python buttons around this, but i was hoping someone
> would be able to point me in the correct direction of how to do this?
> Is there a parser available? 

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


Re: pil, histogram, mask

2007-02-01 Thread Daniel Nogradi
> > I don't need the histogram really, only the mean color
> > value, but as far as I can see the 'mean' attribute only applies to an
> > image and a mask can not be specified.
>
> You can slice parts of the image, and then use the
> ImageStat.Stat(im).mean
> On it.
>
> Bye,
> bearophile

Okay, I'll try that, thanks a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list

2007-02-01 Thread Ben Finney
John Salerno <[EMAIL PROTECTED]> writes:

> Ah, so simply using sort() [on a list of tuples] will default to the
> first element of each tuple?

More precisely, list.sort will ask the elements of the list to compare
themselves. Those elements are tuples; two tuples will compare based
on comparison of their corresponding elements.

-- 
 \ "The cost of a thing is the amount of what I call life which is |
  `\   required to be exchanged for it, immediately or in the long |
_o__)run."  -- Henry David Thoreau |
Ben Finney

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


Re: OT: Variant name spellings (Re: how to "free" an object/var ?)

2007-02-01 Thread Ben Finney
greg <[EMAIL PROTECTED]> writes:

> Or Mr. Luxury-Yacht, which as we all know is pronounced
> Throatwarbler-Mangrove. With a silent hyphen.

You're a very silly person and I'm not going to interview you anymore.

-- 
 \ "When I turned two I was really anxious, because I'd doubled my |
  `\   age in a year. I thought, if this keeps up, by the time I'm six |
_o__)   I'll be ninety."  -- Steven Wright |
Ben Finney

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


Python, readline and OS X

2007-02-01 Thread Ron Garret
I have installed Python 2.5 on my new Intel Mac but I can't for the life 
of me get readline to work.  I have libreadline installed, I've tried 
copying readline.so from my Python 2.3 installation into 2.5, I've 
searched the web, and no joy.  Could someone please give me a clue?

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


Re: division by 7 efficiently ???

2007-02-01 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Krypto wrote:

> The correct answer as told to me by a person is
> 
> (N>>3) + ((N-7*(N>>3))>>3)

How could it be correct if it uses `-`?  You ruled out `-` and `/` in your
first post.

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


Re: Sorting a list

2007-02-01 Thread Bruno Desthuilliers
John Salerno a écrit :
(snip)

> Oh I didn't sort then reverse, I just replaced sort with reverse. Maybe 
> that's why!

Hmmm... Probably, yes...

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


Re: Question about a single underscore.

2007-02-01 Thread Bruno Desthuilliers
Steven W. Orr a écrit :
> On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers:
> 
(snip)

> =>irrational_const = const.__class__()
> =>even_const = const.__class__()
> =>
> =>Now while I find this hack interesting, it's also totally unpythonic 
> =>IMHO. The usual convention is to use ALL_UPPER names for (pseudo) 
> =>symbolic constants, and I don't see any reason to forcefit B&D languages 
> =>concepts into Python.
> 
> Ok. Now *maybe* we're getting to where I want to be. My const.py now looks 
> like this:
> 
> class _const:
> class ConstError(TypeError): pass
> def __setattr__(self,name,value):
> if self.__dict__.has_key(name):
> raise self.ConstError, "Can't rebind const(%s)"%name
> self.__dict__[name]=value
> 
> import sys
> sys.modules[__name__]=_const()
> 
> and in a seperate module call key_func_consts I say:
> 
> import const
> # Define constants for Key Function Field.
> KeyFuncConst   = const.__class__()
> KeyFuncConst.NotDefined= 0x00
> 
> And in my main module I have
> #! /usr/bin/python
> import const

Note that you don't need it if you don't use it directly.

> import key_func_consts
> print KeyFuncConst.MSK
> 
> 
> but the last print fails with 

A NameError, of course. key_func_consts is the module, KeyFuncConst is 
an attribute of this module. You either need to

1/ use a fully qualified name:

import key_func_consts
print key_func_consts.KeyFuncConst.MSK

or
2/ import the KeyFuncConst name directly:

from key_func_consts import KeyFuncConst
print KeyFuncConst.MSK

or
3/ use the same dirty hack as in the const module - but this is starting 
to be very ugly and unpythonic, so I won't give an implementation 
example !-)

Also, note that since you did not define KeyFuncConst.MSK in the 
key_func_const module, you'll then have an AttributeError !-)

> The goal is to be able to create classes of global constants.

Then just define your "constants" in the module and import it:

# key_func_const.py
NOT_DEFINED = 0x00
MSK = 42

# main.py
import key_func_const
print key_func_const.NOT_DEFINED
print key_func_const.MSK


> Do I need to get the KeyFuncConst object into sys.modules somehow? I know 
> I'm close.

Nope. You're going the wrong direction. It's a typical case of arbitrary 
overcomplexification. Please re-read the last paragraph of my previous 
post. By convention, in Python, ALL_UPPER names means "constant value, 
dont touch". The example I give you above is the Pythonic way of doing 
things, it's dead simple, and *it just works* - so why bother messing 
with sys.modules hacks ?

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


Re: Sorting a list

2007-02-01 Thread John Salerno
Bruno Desthuilliers wrote:

>> One more thing. What if I want them in reverse chronological order? I 
>> tried reverse() but that seemed to put them in reverse alphabetical 
>> order based on the second element of the tuple (not the year).
> 
> Really ?
> 
>  >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), 
> ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')]
>  >>> lines.sort()
>  >>> lines
> [('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc'), ('1996', 'aaa'), 
> ('1996', 'ccc'), ('1997', 'aaa'), ('1997', 'bbb')]
>  >>> lines.reverse()
>  >>> lines
> [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), 
> ('1995', 'ccc'), ('1995', 'bbb'), ('1995', 'aaa')]
>  >>>

Oh I didn't sort then reverse, I just replaced sort with reverse. Maybe 
that's why!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive zipping of Directories in Windows

2007-02-01 Thread Larry Bates
Jandre wrote:
> Hi
> 
> I am a python novice and I am trying to write a python script (most of
> the code is borrowed) to Zip a directory containing some other
> directories and files. The script zips all the files fine but when it
> tries to zip one of the directories it fails with the following
> error:
> "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'"
> 
> The script I am using is:
> 
> import zipfile, os
> 
> def toZip( directory, zipFile ):
> """Sample for storing directory to a ZipFile"""
> z = zipfile.ZipFile(
> zipFile, 'w', compression=zipfile.ZIP_DEFLATED
> )
> def walker( zip, directory, files, root=directory ):
> for file in files:
> file = os.path.join( directory, file )
> # yes, the +1 is hacky...
> archiveName = file[len(os.path.commonprefix( (root,
> file) ))+1:]
> zip.write( file, archiveName, zipfile.ZIP_DEFLATED )
> print file
> os.path.walk( directory, walker, z  )
> z.close()
> return zipFile
> 
> 
> if __name__ == "__main__":
> toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' )
> 
> I have tried to set the permissions on the folder, but when I check
> the directory permissions it is set back to "Read Only"
> 
> Any suggestions?
> 
> Thanks
> Johan Balt
> 
Couple of quick suggestions that may help:

1) don't use 'file' as a variable name. It will mask
the builtin file function.  If it hasn't bitten you before
it will if you keep doing that.

2) If you put the target .zip file in the directory you are
backing what do you expect the program to do when it comes
to the file you are creating as you walk the directory?  You
haven't done anything to 'skip' it.

3) Your commonprefix and +1 appears to result in same
information that the easier to use os.path.basename()
would give you.  Double check me on that.

I don't see anything that references C:\\aaa\temp in your
code.  Does it exist on your hard drive?  If so does it
maybe contain temp files that are open?  zipfile module
can't handle open files.  You must use try/except to
catch these errors.

Hope info helps.

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


Re: Sorting a list

2007-02-01 Thread Bruno Desthuilliers
Steven Bethard a écrit :
> Bruno Desthuilliers wrote:
> 
>> If you want to prevent this from happening and don't mind creating a 
>> copy of the list, you can use the sorted() function with the key and 
>> reverse arguments and operator.itemgetter:
>>
(snip)
> 
> You don't need to use sorted() -- sort() also takes the key= and 
> reverse= arguments::
> 
Yeps - thanks for the reminder.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml.dom.minidom memory usage

2007-02-01 Thread Bruno Desthuilliers
Dan a écrit :
> I'm using python's xml.dom.minidom module to generate xml files, and
> I'm running into memory problems. The xml files I'm trying to create
> are relatively flat, with one root node which may have millions of
> direct child nodes.

Woops ! You're looking for trouble.

> 
> So, my questions are (1) am I doing something dumb in the script

Yes : using minidom !-)

> that
> stops python from collecting temp garbage? 

That's not the problem. The problem is with how xml dom APIs work: they 
build the whole damn tree in memory.

> (2) If not, is there
> another reasonable module to generate xml (as opposed to parsing it),
> or should I just implement my own xml generation solution?

You should have a look at Genshi:
http://genshi.edgewall.org/

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


Re: Newbie question: replacing nulls in CSV with preceding value

2007-02-01 Thread Bruno Desthuilliers
Matt Waite a écrit :
> My first post, my first real python use, please be gentle:
> 
> I have a CSV file, exported from Excel, that has blank records in it,
> and I need to fill them in with the values from the record just above
> it until it hits a non-blank value. Here's an example of the data,
> which is in a file called test2.csv:
> 
> Zone,City,Event
> 1,Anytown,Event
> ,,Event1
> ,,Event2
> ,,Event44
> 2,Anothertown,Event3
> ,,Event5
> ,,Event7
> 
> What I need it to look like is:
> 
> Zone,City,Event
> 1,Anytown,Event1
> 1,Anytown,Event2
> 1,Anytown,Event44
> 2,Anothertown,Event3
> 2,Anothertown,Event5
> 2,Anothertown,Event7
> 
> Pretty much everything I've tried has failed, and I've been searching
> for hours for something similar and haven't found anything. The best
> I've come up with --which is half baked and I don't even know if it
> works -- is this:
> 
> import csv
> citynew=''
> reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb"))
> for row in reader:
> row['CITY'] == citynew
> else:
> citynew=row['CITY']
> 
> The logic here -- in this case trying to fill in the city information
> -- would seem to work, but I'm not sure.

Did you actually tried it ? And itf yes, do you really think it 'works'?

Ok, the solution is quite easy - assuming the very first data row has no 
blank values, and that either both Zone and City are blank or both are 
filled:

prev_zone = prev_city = ''
for row in reader:
   if row['Zone']:
 prev_zone, prev_city = row['Zone'], row['City']
   else:
 row['Zone'], row['City'] = prev_zone, prev_city
   # now do something with row...

> And I'm not sure how to write
> the results of this back to the file.

look for csv.DictWriter.writerow

NB : note that you cannot "write back to the file" - just write to 
*another* file (then eventually os.rename(olfile, newfile))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list

2007-02-01 Thread Steven Bethard
Bruno Desthuilliers wrote:
> If you want to prevent this from happening and don't mind creating a 
> copy of the list, you can use the sorted() function with the key and 
> reverse arguments and operator.itemgetter:
> 
>  >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), 
> ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')]
>  >>> from operator import itemgetter
>  >>> sorted(lines, key=itemgetter(0), reverse=True)
> [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), 
> ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]

You don't need to use sorted() -- sort() also takes the key= and 
reverse= arguments::

 >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'),
 ...  ('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'),
 ...  ('1996', 'aaa')]
 >>> from operator import itemgetter
 >>> lines.sort(key=itemgetter(0), reverse=True)
 >>> lines
 [('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'),
 ('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]

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


Re: Question about a single underscore.

2007-02-01 Thread Steven W. Orr
On Thursday, Feb 1st 2007 at 21:45 +0100, quoth Bruno Desthuilliers:

=>Steven W. Orr a écrit :
=>> I saw this and tried to use it:
=>> 
=>> --><8--- const.py-
=>> class _const:
=>> class ConstError(TypeError): pass
=>> def __setattr__(self,name,value):
=>> if self.__dict__.has_key(name):
=>> raise self.ConstError, "Can't rebind const(%s)"%name
=>> self.__dict__[name]=value
=>> 
=>> import sys
=>> sys.modules[__name__]=_const()
=>> --><8--- const.py-
=>> 
=>> Then when I go to try to use it I'm supposed to say:
=>> 
=>> const.pi= 3.14159
=>> const.e = 2.7178
=>> 
=>> 
=>> Two questions:
=>> 
=>> 1. Why do I not have to say
=>> 
=>> _const.pi= 3.14159
=>> _const.e = 2.7178
=>
=>Because of the last two lines of module const. sys.modules is a dict of 
=>already imported modules (yes, Python's modules are objects too), which 
=>avoids modules being imported twice or more. __name__ is a magic 
=>variable that is set either to the name of the module - when it's 
=>imported - or to '__main__' - when it's being directly executed as the 
=>main program. Here, when you first do 'import const', the module's code 
=>itself sets sys.modules['const'] to an instance of _const, so what you 
=>import in your namespace as 'const' is not the const module instance but 
=>a _const instance.
=>
=>> and is this in the tutorial?
=>
=>Hmmm... Not sure. FWIW, it's mostly a hack !-)
=>
=>> 2. Can I make this behave in such a way that I can create my constants 
=>> with a classname
=>
=>s/classname/name/
=>
=>> that is different for different uses? e.g.,
=>> 
=>> irrational_const.pi= 3.14159
=>> irrational_const.e = 2.7178
=>> 
=>> even_const.first= 2
=>> even_const.firstPlus= 4
=>
=>irrational_const = const.__class__()
=>even_const = const.__class__()
=>
=>Now while I find this hack interesting, it's also totally unpythonic 
=>IMHO. The usual convention is to use ALL_UPPER names for (pseudo) 
=>symbolic constants, and I don't see any reason to forcefit B&D languages 
=>concepts into Python.

Ok. Now *maybe* we're getting to where I want to be. My const.py now looks 
like this:

class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()

and in a seperate module call key_func_consts I say:

import const
# Define constants for Key Function Field.
KeyFuncConst   = const.__class__()
KeyFuncConst.NotDefined= 0x00

And in my main module I have
#! /usr/bin/python
import const
import key_func_consts
print KeyFuncConst.MSK


but the last print fails with 

The goal is to be able to create classes of global constants.

561 > t_const.py 
Traceback (most recent call last):
  File "./t_const.py", line 6, in ?
print KeyFuncConst.MSK
NameError: name 'KeyFuncConst' is not defined

Do I need to get the KeyFuncConst object into sys.modules somehow? I know 
I'm close.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net-- 
http://mail.python.org/mailman/listinfo/python-list

RE: division by 7 efficiently ???

2007-02-01 Thread skip

Michael> I think it is off by 1 in small numbers, off by a little more
Michael> with large numbers:
...

Sorta makes you think using the DIV instruction in the CPU is the way to
go. ;-)

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


Re: Sorting a list

2007-02-01 Thread Bruno Desthuilliers
John Salerno a écrit :
> John Salerno wrote:
> 
>> Bruno Desthuilliers wrote:
>>
>>> John Salerno a écrit :
>>>
 Hi everyone. If I have a list of tuples, and each tuple is in the form:

 (year, text) as in ('1995', 'This is a citation.')

 How can I sort the list so that they are in chronological order 
 based on the year?
>>>
>>>
>>> Calling sort() on the list should just work.
>>
>>
>> Amazing, it was that easy. :)
> 
> 
> One more thing. What if I want them in reverse chronological order? I 
> tried reverse() but that seemed to put them in reverse alphabetical 
> order based on the second element of the tuple (not the year).

Really ?

 >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), 
('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')]
 >>> lines.sort()
 >>> lines
[('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc'), ('1996', 'aaa'), 
('1996', 'ccc'), ('1997', 'aaa'), ('1997', 'bbb')]
 >>> lines.reverse()
 >>> lines
[('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), 
('1995', 'ccc'), ('1995', 'bbb'), ('1995', 'aaa')]
 >>>

As you see, the list is being sorted on *both* items - year first, then 
sentence. And then of course reversed, since we asked for it !-)

If you want to prevent this from happening and don't mind creating a 
copy of the list, you can use the sorted() function with the key and 
reverse arguments and operator.itemgetter:

 >>> lines = [('1995', 'aaa'), ('1997', 'bbb'), ('1995', 'bbb'), 
('1997', 'aaa'), ('1995', 'ccc'), ('1996', 'ccc'), ('1996', 'aaa')]
 >>> from operator import itemgetter
 >>> sorted(lines, key=itemgetter(0), reverse=True)
[('1997', 'bbb'), ('1997', 'aaa'), ('1996', 'ccc'), ('1996', 'aaa'), 
('1995', 'aaa'), ('1995', 'bbb'), ('1995', 'ccc')]

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


RE: division by 7 efficiently ???

2007-02-01 Thread Michael Yanowitz
  I think it is off by 1 in small numbers, off by a little more with large
numbers:
>>> def div7 (N):
...return (N>>3) + ((N-7*(N>>3))>>3)
...
>>> div7 (70)
9
>>> div7 (77)
10
>>> div7 (700)
98
>>> div7 (7)
0
>>> div7 (10)
1
>>> div7 (14)
1
>>> div7 (21)
2
>>> div7 (700)
98
>>> div7 (7000)
984

Michael Yanowitz

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Krypto
Sent: Thursday, February 01, 2007 3:25 PM
To: python-list@python.org
Subject: Re: division by 7 efficiently ???


The correct answer as told to me by a person is

(N>>3) + ((N-7*(N>>3))>>3)


The above term always gives division by 7

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


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


Re: division by 7 efficiently ???

2007-02-01 Thread Paul Rubin
"Krypto" <[EMAIL PROTECTED]> writes:

> The correct answer as told to me by a person is
> 
> (N>>3) + ((N-7*(N>>3))>>3)
> 
> 
> The above term always gives division by 7

Well, not exactly:

[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(N): return (N>>3) + ((N-7*(N>>3))>>3)
... 
>>> f(7)
0
>>> f(70)
9
>>> f(700)
98
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: replacing nulls in CSV with preceding value

2007-02-01 Thread Laszlo Nagy

> import csv
> citynew=''
> reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb"))
> for row in reader:
> row['CITY'] == citynew
> else:
> citynew=row['CITY']
>
> The logic here -- in this case trying to fill in the city information
> -- would seem to work, but I'm not sure. And I'm not sure how to write
> the results of this back to the file.
>   
I recommend that you create a writer and a new file. After you processed 
the input, you can delete the original file and replace it with the new 
one. My experience is that this is highly efficient and works with very 
large files. I would do something like this (not tested)

import csv
import os
import shutil
fin = file("/home/mwaite/test/test2.csv", "rb")
reader = csv.DictReader(fin)
fout = file(fin.name + '.tmp',"wb+")
writer = csv.writer(fout)
prev = {}
columns = ('CITY','ZIP','NAME')
for curr in reader:
   foreach col in columns:
  if (not curr.has_key(col)) or (curr[col] == ''):
if prev.has_key(col):
   curr[col] = prev[col]
else:
   curr[col] = ''
   row = [curr[col] for col in columns ]
   writer.write(row)
   prev = curr
os.unlink(fin.name)
fout.close()
shutil.rename(fout.name,fin.name)

I really did not test it, but you can get the idea.

Best,

   Laszlo



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


Re: Newbie question: replacing nulls in CSV with preceding value

2007-02-01 Thread skip

Matt> I have a CSV file, exported from Excel, that has blank records in
Matt> it, and I need to fill them in with the values from the record
Matt> just above it until it hits a non-blank value.

Try something like:

#!/usr/bin/env python

import sys
import csv

last = {}
reader = csv.DictReader(open("test1.csv", "rb"))
writer = csv.DictWriter(open("test2.csv", "wb"),
sys.stdout, fieldnames="Zone City Event".split())
for row in reader:
for key in row:
if not row[key]:
row[key] = last.get(key, "")
writer.writerow(row)
last = row

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


Re: Sorting a list

2007-02-01 Thread Bruno Desthuilliers
John Salerno a écrit :
> Bruno Desthuilliers wrote:
> 
>> John Salerno a écrit :
>>
>>> Hi everyone. If I have a list of tuples, and each tuple is in the form:
>>>
>>> (year, text) as in ('1995', 'This is a citation.')
>>>
>>> How can I sort the list so that they are in chronological order based 
>>> on the year?
>>
>>
>> Calling sort() on the list should just work.
> 
> 
> Amazing, it was that easy. :)

A very common Python idiom is "decorate/sort/undecorate", which is just 
what you've done here. It's usually faster than passing a custom 
comparison callback function (cf a recent thread named "Sorting a List 
of Lists, where Paddy posted a link to a benchmark).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list

2007-02-01 Thread Bruno Desthuilliers
John Salerno a écrit :
> Bruno Desthuilliers wrote:
> 
>> You don't tell how these lines are formatted, but it's possible that 
>> you don't even need a regexp here. But wrt/ sorting, the list of 
>> tuples with the sort key as first element is one of the best solutions.
> 
> 
> Ah, so simply using sort() will default to the first element of each tuple?

Yes. Then on the second value if the first compares equal, etc...

> The citations are like this:
> 
> lastname, firstname. (year). title. other stuff.

Then you theoretically don't even need regexps:

 >>> line = "lastname, firstname. (year). title. other stuff."
 >>> line.split('.')[1].strip().strip('()')
'year'

But since you may have a dot in the "lastname, firstname" part, I'd 
still go for a regexp here just to make sure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml.dom.minidom memory usage

2007-02-01 Thread Dan
On Feb 1, 3:12 pm, Jonathan Curran <[EMAIL PROTECTED]> wrote:
> Dan,
> The DOM (Document Object Model) is such that it loads all the 
> elements of the
> XML document into memory before you can do anything with it. With your file
> containing millions of child nodes this will eat up as much memory as you
> have. A solution to this is to use the SAX method of parsing XML documents
> and working on it. SAX is such that it only reads the XML doc. a node (or a
> few nodes) at a time.
>
> Unfortunately, the use of DOM or SAX completely depends on what kind of
> processing you need to be done on the XML document. If it is editing a record
> at a time (from what I've gathered from your code) it would be wise to use
> SAX. I highly suggest looking into this method of processing.
>
> - Jonathan Curran

Jonathan,

Thanks for the response. I'm comfortable using SAX for parsing, but
I'm unsure how it helps me with XML generation. To clarify in my
example code, with the DOM document, I can call doc.toxml() or
doc.toprettyxml(), and get the desired output (an xml file). AFAIK,
SAX has no analog, it just does parsing. Is there a way to do XML
generation with SAX that I'm unaware of?

-Dan

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


Re: division by 7 efficiently ???

2007-02-01 Thread Krypto
The correct answer as told to me by a person is

(N>>3) + ((N-7*(N>>3))>>3)


The above term always gives division by 7

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


Re: xml.dom.minidom memory usage

2007-02-01 Thread Jonathan Curran
Dan,
I jumped the gun and didn't read your entire post. I ended up skipping 
a lot 
of parts, especially where you say that you are creating a document (for some 
reason I thought you were reading it). I looked at the setAttribute function 
and thought: ah he's writing it out.
Sorry about all that. I'd still ask you to look into SAX though :) 
Especially 
when dealing with really large XML documents, whether it be reading or 
writing them.

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


Re: Quad Perspective Transformation

2007-02-01 Thread Gabriel Genellina
En Thu, 01 Feb 2007 13:46:37 -0300, Kamilche <[EMAIL PROTECTED]>  
escribió:

> I have a need to tile a bitmap across an arbitrary quadrilateral, and
> apply perspective to it.
> The Python Imaging Library (PIL) has an undocumented function that
> might work, but I can't figure out how to make it work. You're
> supposed to pass it 8 parameters, a b c d e f g h .

I don't know exactly how it's implemented, but the usual perspective  
transformation matrix has exactly 8 non zero parameters. Any text on  
computer graphics should cover it. My first hit on Google:  
http://bishopw.loni.ucla.edu/AIR5/2Dperspective.html

-- 
Gabriel Genellina

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


Re: Question about a single underscore.

2007-02-01 Thread Bruno Desthuilliers
Steven W. Orr a écrit :
> I saw this and tried to use it:
> 
> --><8--- const.py-
> class _const:
> class ConstError(TypeError): pass
> def __setattr__(self,name,value):
> if self.__dict__.has_key(name):
> raise self.ConstError, "Can't rebind const(%s)"%name
> self.__dict__[name]=value
> 
> import sys
> sys.modules[__name__]=_const()
> --><8--- const.py-
> 
> Then when I go to try to use it I'm supposed to say:
> 
> const.pi= 3.14159
> const.e = 2.7178
> 
> 
> Two questions:
> 
> 1. Why do I not have to say
> 
> _const.pi= 3.14159
> _const.e = 2.7178

Because of the last two lines of module const. sys.modules is a dict of 
already imported modules (yes, Python's modules are objects too), which 
avoids modules being imported twice or more. __name__ is a magic 
variable that is set either to the name of the module - when it's 
imported - or to '__main__' - when it's being directly executed as the 
main program. Here, when you first do 'import const', the module's code 
itself sets sys.modules['const'] to an instance of _const, so what you 
import in your namespace as 'const' is not the const module instance but 
a _const instance.

> and is this in the tutorial?

Hmmm... Not sure. FWIW, it's mostly a hack !-)

> 2. Can I make this behave in such a way that I can create my constants 
> with a classname

s/classname/name/

> that is different for different uses? e.g.,
> 
> irrational_const.pi= 3.14159
> irrational_const.e = 2.7178
> 
> even_const.first= 2
> even_const.firstPlus= 4

irrational_const = const.__class__()
even_const = const.__class__()

Now while I find this hack interesting, it's also totally unpythonic 
IMHO. The usual convention is to use ALL_UPPER names for (pseudo) 
symbolic constants, and I don't see any reason to forcefit B&D languages 
concepts into Python.

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


Re: xml.dom.minidom memory usage

2007-02-01 Thread Jonathan Curran
Dan,
The DOM (Document Object Model) is such that it loads all the elements 
of the 
XML document into memory before you can do anything with it. With your file 
containing millions of child nodes this will eat up as much memory as you 
have. A solution to this is to use the SAX method of parsing XML documents 
and working on it. SAX is such that it only reads the XML doc. a node (or a 
few nodes) at a time.

Unfortunately, the use of DOM or SAX completely depends on what kind of 
processing you need to be done on the XML document. If it is editing a record 
at a time (from what I've gathered from your code) it would be wise to use 
SAX. I highly suggest looking into this method of processing.

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


Newbie question: replacing nulls in CSV with preceding value

2007-02-01 Thread Matt Waite
My first post, my first real python use, please be gentle:

I have a CSV file, exported from Excel, that has blank records in it,
and I need to fill them in with the values from the record just above
it until it hits a non-blank value. Here's an example of the data,
which is in a file called test2.csv:

Zone,City,Event
1,Anytown,Event
,,Event1
,,Event2
,,Event44
2,Anothertown,Event3
,,Event5
,,Event7

What I need it to look like is:

Zone,City,Event
1,Anytown,Event1
1,Anytown,Event2
1,Anytown,Event44
2,Anothertown,Event3
2,Anothertown,Event5
2,Anothertown,Event7

Pretty much everything I've tried has failed, and I've been searching
for hours for something similar and haven't found anything. The best
I've come up with --which is half baked and I don't even know if it
works -- is this:

import csv
citynew=''
reader = csv.DictReader(open("/home/mwaite/test/test2.csv", "rb"))
for row in reader:
row['CITY'] == citynew
else:
citynew=row['CITY']

The logic here -- in this case trying to fill in the city information
-- would seem to work, but I'm not sure. And I'm not sure how to write
the results of this back to the file.

Any help anyone can offer is greatly appreciated. I'm trying hard to
learn, but have been frustrated by this problem.

Matt

Matthew Waite
www.mattwaite.com

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


Recursive zipping of Directories in Windows

2007-02-01 Thread Jandre
Hi

I am a python novice and I am trying to write a python script (most of
the code is borrowed) to Zip a directory containing some other
directories and files. The script zips all the files fine but when it
tries to zip one of the directories it fails with the following
error:
"IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'"

The script I am using is:

import zipfile, os

def toZip( directory, zipFile ):
"""Sample for storing directory to a ZipFile"""
z = zipfile.ZipFile(
zipFile, 'w', compression=zipfile.ZIP_DEFLATED
)
def walker( zip, directory, files, root=directory ):
for file in files:
file = os.path.join( directory, file )
# yes, the +1 is hacky...
archiveName = file[len(os.path.commonprefix( (root,
file) ))+1:]
zip.write( file, archiveName, zipfile.ZIP_DEFLATED )
print file
os.path.walk( directory, walker, z  )
z.close()
return zipFile


if __name__ == "__main__":
toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' )

I have tried to set the permissions on the folder, but when I check
the directory permissions it is set back to "Read Only"

Any suggestions?

Thanks
Johan Balt

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


Re: Ubunu - Linux - Unicode - encoding

2007-02-01 Thread Franz Steinh�usler
On 1 Feb 2007 08:24:07 -0800, "Paul Boddie" <[EMAIL PROTECTED]>
wrote:

>On 1 Feb, 16:02, Franz Steinhaeusler <[EMAIL PROTECTED]>
>wrote:
>>
>> The case:
>> I have a file on a WindowsXP partition which has as contents german
>> umlauts and the filename itself has umlauts like iÜüäßk.txt
>>
>> If I want to append this file to a list, I get somehow latin-1, cannot
>> decode 'utf-8'.
>
>You mean that you expect the filename in UTF-8, but it arrives as
>ISO-8859-1 (Latin1)? How do you get the filename? Via Python standard
>library functions or through a GUI toolkit? What does
>sys.getfilesystemencoding report?

Hello Paul,

I set the sysencoding already to 'latin-1', but obviously the value
is ignored and it takes 'utf-8' (?)

I get it with
thelist = os.listdir(directory) and the directory is a string, not
unicode.

>
>[...]
>
>> Why is this setdefaultencoding otherwise not working on linux?
>
>My impression was that you absolutely should not change the default
>encoding. 

Aha.


>Instead, you should react to encoding information provided
>by your sources of data. For example, sys.stdin.encoding tells you
>about the data from standard input.
>
>> (Also Filemanagers like Nautilus or Krusader cannot display the files
>> correctly).
>
>This sounds like a locale issue...

Hm, a setting in linux.

>
>> Is there a system wide linux language setting (encoding), which I have
>> to install and adjust?
>
>I keep running into this problem when installing various
>distributions. Generally, the locale needs to agree with the encoding
>of the filenames in your filesystem, so that if you've written files
>with UTF-8 filenames, you'll only see them with their proper names if
>the locale you're using is based on UTF-8 - things like en_GB.utf8 and
>de_AT.utf8 would be appropriate. Such locales are often optional
>packages, as I found out very recently, and you may wish to look at
>the language-pack-XX and language-pack-XX-base packages for Ubuntu
>(substituting XX for your chosen language). Once they are installed,
>typing "locale -a" will let you see available locales, and I believe
>that changing /etc/environment and setting the LANG variable there to
>one of the available locales may offer some kind of a solution.

Ah thank you very much for that enlightment!

>
>Another thing I also discovered very recently, after doing a
>debootstrap installation of Ubuntu, was that various terminals
>wouldn't reproduce non-ASCII characters without an appropriate (UTF-8)
>locale being set up, even though other desktop applications were happy
>to accept and display the characters.

That sound familar to me! ;)

> I thought this was a keyboard
>issue, compounded by the exotic nested X server plus User Mode Linux
>solution I was experimenting with, but I think locales were the main
>problem.
>
>Paul

So that is not exactly simple. :)

Thank you very much for this precise answer!
-- 
Franz Steinhaeusler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistent list/pointer problem

2007-02-01 Thread Gabriel Genellina
En Thu, 01 Feb 2007 10:23:16 -0300, Doug Stell <[EMAIL PROTECTED]>  
escribió:

> I am having a problem with the corruption of a list. It occurs only
> the first time that I call a function and never happens on subsequent
> calls. Any suggestions would be appreciated.
>
> I call the function, passing in a list as the input data. The function
> must manipulate and operate on a copy of that list's data, without
> altering the list in the calling routine.
>
> def myFunc(listA):
> listB = listA
> work on & modify listB
> return(listB)

This article will help you understanding this behavior:
http://effbot.org/zone/python-objects.htm

-- 
Gabriel Genellina

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


RE: Sorting a list

2007-02-01 Thread Carroll, Barry
> -Original Message-
> From: John Salerno [mailto:[EMAIL PROTECTED]
> Sent: Thursday, February 01, 2007 11:54 AM
> To: python-list@python.org
> Subject: Re: Sorting a list
> 
> Bruno Desthuilliers wrote:
> > John Salerno a écrit :
> >> Hi everyone. If I have a list of tuples, and each tuple is in the form:
> >>
> >> (year, text) as in ('1995', 'This is a citation.')
> >>
> >> How can I sort the list so that they are in chronological order based
> >> on the year?
> >
> > Calling sort() on the list should just work.
> 
> Amazing, it was that easy. :)
Hello, John.

Yeah.  That's one of the things that drew me to Python: so many things you want 
to do are just so *easy* in Python.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: Question about a single underscore.

2007-02-01 Thread Bruno Desthuilliers
Paul Rubin a écrit :
> "Steven W. Orr" <[EMAIL PROTECTED]> writes:
> 
>>AttributeError: _const instance has no attribute '_const'
>>
>>What am I missing here? (Sorry if it should be obvious)
> 
> 
> Oh I see.  No it's not obvious.  module "const" has gotten overwritten
> by the _const instance.  I think that module author was too clever for
> his or her own good.

Not necessarily - given the intent, it's just smart IMHO. But the 
workaround is quite obvious anyway:

 >>> import const
 >>> # so what is const ?
 >>> const

 >>> # ok, it's an instance, so it should refer to it's class:
 >>> Const = const.__class__
 >>> Const

 >>> # Bingo. Let's have another _const instance:
 >>> c = Const()
 >>> c

 >>> c.pi = 42
 >>> c.pi = 33
Traceback (most recent call last):
   File "", line 1, in ?
   File "const.py", line 5, in __setattr__
 raise self.ConstError, "Can't rebind const(%s)"%name
const.ConstError: Can't rebind const(pi)
 >>>

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


Re: Sorting a list

2007-02-01 Thread John Salerno
John Salerno wrote:
> Bruno Desthuilliers wrote:
>> John Salerno a écrit :
>>> Hi everyone. If I have a list of tuples, and each tuple is in the form:
>>>
>>> (year, text) as in ('1995', 'This is a citation.')
>>>
>>> How can I sort the list so that they are in chronological order based 
>>> on the year?
>>
>> Calling sort() on the list should just work.
> 
> Amazing, it was that easy. :)

One more thing. What if I want them in reverse chronological order? I 
tried reverse() but that seemed to put them in reverse alphabetical 
order based on the second element of the tuple (not the year).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ubunu - Linux - Unicode - encoding

2007-02-01 Thread Franz Steinh�usler
On Thu, 1 Feb 2007 16:42:02 +0100, Alan Franzoni
<[EMAIL PROTECTED]> wrote:

>Il Thu, 01 Feb 2007 16:02:52 +0100, Franz Steinhaeusler ha scritto:
>
>> The case:
>> I have a file on a WindowsXP partition which has as contents german
>> umlauts and the filename itself has umlauts like iÜüäßk.txt
>
>Could you please tell us a) which filesystem is that partition using (winxp
>may be installed on fat32 or ntfs partitions) and b) which driver are you
>using to read that partition (may be vfat, ntfs or fuse/ntfs-3g) and, last
>but not least, c) which options are passed to that driver?

Hallo Alan, thank you for answering.

a) FAT32
b) hm, don't know, I mounted it in fstab as FAT32#
in fstab there is:
c)/dev/hda1   /winxp  autorw,user,auto0   

One problem is still, and is a little OT perhaps here, but
nevertheless,:

If I copy files with german umlauts (äöü and strong 's' ß), these
filenames are not copied properly, and that characters are replaces
by little square symbols.

Is there anythin to set up on ubuntu to copy this properly.
I have only installed the english language, maybe that is the problem.
-- 
Franz Steinhaeusler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a list

2007-02-01 Thread John Salerno
John Salerno wrote:
> Bruno Desthuilliers wrote:
>> John Salerno a écrit :
>>> Hi everyone. If I have a list of tuples, and each tuple is in the form:
>>>
>>> (year, text) as in ('1995', 'This is a citation.')
>>>
>>> How can I sort the list so that they are in chronological order based 
>>> on the year?
>>
>> Calling sort() on the list should just work.
> 
> Amazing, it was that easy. :)

Here's what I did:

import re

file = open('newrefs.txt')
text = file.readlines()
file.close()

newfile = open('sortedrefs.txt', 'w')
refs = []

pattern = re.compile('\(\d{4}\)')

for line in text:
 year = pattern.search(line).group()
 refs.append((year, line))

refs.sort()

for ref in refs:
 newfile.write(ref[1])

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


  1   2   3   >