Re: embedding console in wxpython app

2006-08-07 Thread placid

Philippe Martin wrote:
> Janto Dreijer wrote:
>
> > I'm writing a Linux filemanager using wxPython. I'd like to embed a
> > bash console inside it. I have found the Logilab pyqonsole
> > (http://www.logilab.org/projects/pyqonsole), but it uses PyQT.
> >
> > Does anyone know how to do this from wx?
> > Is it possible to embed a PyQT widget inside wxPython?
> >
> > Thanks!
> > Janto
>
>
> How about just using bash and rerouting stdin/stdout ?

What is that thing in Software Engineering (SE) ? that it is hard to
find simple solutions (or any problem in life for that matter)

I remember last year at uni we had to write this program (get
information from user save it somewhere) for a SE assignment. And half
the teams went off and used MySql to save data retrieved from the user
via a GUI. And in no part of the requirements document did it write ;

* Customer requires GUI frontend
* Customer needs MySql databases server usage to store data

So my team created a Command Line Program (i.e cmd module in python) as
the UI and used object Serialization (pickling in python) to files. So
we finished in half the time that other teams took (and many had to
drop the database server usage in the end) and stressed like tomorow
was Judgement Day. Oh yeah we designed our application so that it was
easy to create a GUI or change the Serialization to saving stuff into a
database and we had one of the top marks out of all the teams.

So OP, if you really dont need to embed bash inside wxPython, then dont
and use what Philippe suggested, unless its in the requirements :)

Cheers

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


How to check n/w shared dir existance using py script?

2006-08-07 Thread - C Saha -
Hi Python Gurus      I have a python script that is supposed to check to see if a folder exists in a computer on a network,   but python always seems to return false.        for example:  1)  folder_path = “shared-dir\\packages\\hwmanager\\4.00.1.16”  if os.path.isdir(folder_path):          print “Yes”     2)  folder_path = r“\\shared-dir\packages\hwmanager\4.00.1.16”  if os.path.isdir(folder_path):          print “Yes”     If you are directly running it from python prompt it’s giving the right result, but from a script it’s always giving false.     If anyone of you have any idea about
 this. Please help me out ...     Thanks  ChirantanThanks a lot to all in advance Thanks & Regards CSaha 
	
	
		Want to be your own boss? Learn how on  Yahoo! Small Business. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Proposal: [... for ... while cond(x)]

2006-08-07 Thread Duncan Booth
Diez B. Roggisch wrote:

>> No, the list comprehension lets you write an expression directly
>> avoiding a function call, and it also allows you to add in a
>> condition which can be used to filer the sequence. Your proposal adds
>> nothing. 
> 
> It does. Consider this:
> 
> whatever = [x for x in xrange(10) while  x < 10]
> 
> 
> That would run only in a splitsecond of what the whole listcomp would.

Except that the comparable listcomp today is:

whatever = [x for x in takewhile(lambda x: x < 10, xrange(10))]

which also runs in a split second.

Actually, the OP was correct, it does add something: it removes the need 
for a function or lambda in the takewhile just as the original listcomp 
removes a function or lambda compared with the map version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: testing array of logicals

2006-08-07 Thread H J van Rooyen

 "Janto Dreijer" <[EMAIL PROTECTED]> wrote:


|
| Janto Dreijer wrote:
| > John Henry wrote:
| > > Simon Forman wrote:
| > > > >
| > > > > False not in logflags
| > > > >
| > > >
| > > > Or, if your values aren't already bools
| > > >
| > > > False not in (bool(n) for n in logflags)
| > >
| > > Very intriguing use of "not in"...
| >
| > Is there a reason why you didn't write
| >  True in (bool(n) for n in logflags)
|
|  doh! Never mind.
|

 *lol* - don't feel bad about this - real programmers make this mistake with a
varying frequency -
>From once every six days or so if you are no good, to once in a lifetime if
you are brilliant, and never only if you are a genius...

First time it bit me I was an apprentice writing in Cobol.

- Hendrik


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


Re: Is there an obvious way to do this in python?

2006-08-07 Thread H J van Rooyen

"Dennis Lee Bieber" <[EMAIL PROTECTED]> wrote:


| On Sat, 5 Aug 2006 11:20:59 +0200, "H J van Rooyen"
| <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
|
| >
| > no such luck - reality will probably be Linux for server, and a horrible mix
of
| > windoze machines on the client side - from 95 through 98 and 2000 to XP...
will
| > have to get SAMBA running at least - and it could be tricky with some of the
| > older hardware/software around - but that is another fight, that I would
have to
| > solve anyway.
| >
| Well, other than the security differences -- which may not apply
| when the clients are mounting a share, only when the define a shareable
| partition -- I think the Windows side may be similar all the way
| through.
|
| > This is more the kind of thing I had in mind - but I was not thinking in
terms
| > of having the redirecting done by the OS and network file sharing - stupid I
| > suppose...
| >
|
| Not really -- if one first is thinking in terms of "internet", which
| means unsecured global operations, instead of an internal-only, behind
| firewall, system.

*grin* you are being too kind - I was at no stage thinking internet...

|
| > | add the "share" to the pythonpath (hence you want a uniform system
| > | configuration so each machine mounts the share on the same name).
| > |
| >
| > I will have to think of a solution to this *shudders*  - config files,
maybe...
| >
| I think Windows can be set to "reconnect on start-up", but it may be
| better just to add a BAT file to the client machines' system start-up
| directory containing the command line that mounts such a share.
|
|

This is a good idea - thanks

- Hendrik

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


Re: Proposal: [... for ... while cond(x)]

2006-08-07 Thread Duncan Booth
Slawomir Nowaczyk wrote:

> #> No, the list comprehension lets you write an expression directly
> #> avoiding a function call, and it also allows you to add in a
> #> condition which can be used to filer the sequence. 
> 
> I am not sure if I understand you correctly, but... Does it?
> 
 a = [0,1,2,3,7,8,9]
 [x for x in takewhile(lambda x: x in a, range(10))]
> [0, 1, 2, 3]
 [x for x in takewhile(x in a, range(10))]
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: 'bool' object is not callable
> 
> Did I miss something?

Yes, you missed out a lambda (so I was wrong, your suggestion would 
actually gain you more than 3 characters of typing)

Try:

>>> a = [0,1,2,3,7,8,9]
>>> [x for x in takewhile(lambda x:x in a, range(10))]
[0, 1, 2, 3]

For this particular expression you could also write:

>>> [x for x in takewhile(a.__contains__, range(10))]
[0, 1, 2, 3]

or with Python 2.5 we can avoid referencing __contains__ with the following 
variant:

>>> from itertools import takewhile
>>> from functools import partial
>>> from operator import contains
>>> a = [0,1,2,3,7,8,9]
>>> [x for x in takewhile(partial(contains,a), range(10))]
[0, 1, 2, 3]
>>>

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


Re: Python Projects Continuous Integration

2006-08-07 Thread Ziga Seilnacht
Dave Potts wrote:
> Hi,
>
> I'm just starting a development project in Python having spent time in
> the Java world.  I was wondering what tool advice you could give me
> about setting up a continuous integration environment for the python
> code: get the latest source, run all the tests, package up, produce the
> docs, tag the code repository.  I'm used to things like Maven and
> CruiseControl in the Java world.
>
> Cheers,
>
> Dave.

Buildbot might be what you are looking for:
http://buildbot.sourceforge.net/

Hope this helps,
Ziga

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


Re: Python Projects Continuous Integration

2006-08-07 Thread Ant

Harry George wrote:
> [snip stuff about how to set emacs up as your IDE]

Not sure which post you read, but the OP of this thread was asking
about continuous integration, not integrated development environments.
i.e. tools to *automatically* check out code when the repository has
changed, build it if necessary (perhaps if there are C modules in the
case of python) and run the unit tests.

To the OP: you could of course simply continue to use cruise - it's
only a tool after all, and won't require any additional learning if you
are already having to learn a new language with all the associated
libraries and idioms.

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


Re: Is there an obvious way to do this in python?

2006-08-07 Thread H J van Rooyen

"Bruno Desthuilliers" <[EMAIL PROTECTED]>


H J van Rooyen a écrit :
>  "Dennis Lee Bieber" <[EMAIL PROTECTED]> wrote:
>
(snip)
> | If you go the web application route, each "login" would use a cookie
> | to control session, so the application server can determine what
> | functions to present to the user. You might even be able to use
> | something like Plone to build the application server; it already has
> | capability to present different views based upon login.
>
> Know squat about Plone - another thing to add to my list of reading *sigh*

Well, actually, I would not bother too much reading about Plone here -
Plone is (fairly complex and somewhat slow) CMS built on top of Zope,
which is itself a web application server that's not easy to get started
with and is (IMHO) definitively much more suited to CMS than to
accounting apps.

*deletes the reference to Plone from the little text file*

- Thanks

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


Re: Question about using python as a scripting language

2006-08-07 Thread Jordan Greenberg
Terry Reedy wrote:
> "heavydada" <[EMAIL PROTECTED]> wrote in message 

>> I just need some way of
>> being able to read from the file what function the program needs to
>> call next. Any help is appreciated.
> 
> Suppose you have a file actions.py with some action functions:
> def hop(self): ...
> def skip(self): ...
> def jump(self)

> Terry Jan Reedy

Another convenient way if, for some reason, you're not creating objects
for your creatures would be using a dictionary to look up functions, like:

def hop(x):
return x+1
def skip(x):
return x+2
def jump(x):
return x+3

actionlookup={"hop": hop, "skip": skip, "jump": jump}
action=actionlookup["hop"]
action() #this will call hop()

Please note that I'm only including this for completeness, for any
larger project (or medium sized, or anything more then a few lines,
really) this gets really unwieldy really quickly (imagine if you had
thousands of functions! Madness!) Terry's suggestion is a much better
solution then this. If this looks easier, consider changing the rest of
your program before kludging something hideous like this together.

Good luck,
-Jordan Greenberg

-- 
Posted via a free Usenet account from http://www.teranews.com

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


How to get hours and minutes from 'datetime.timedelta' object?

2006-08-07 Thread Lad
Hello,
what is the best /easest  way how to get number of hours and minutes
from a timedelta object?
Let's say we have
aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000)
bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000)
so
c=bb-aa
will be
datetime.timedelta(5, 6339, 437000)

I can easily get days ( c.days)
 but
I still can not figure out how easily to get hours and minutes
Any idea?
Thank you for help
L.

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


Re: How to get hours and minutes from 'datetime.timedelta' object?

2006-08-07 Thread John Machin
Lad wrote:
> Hello,
> what is the best /easest  way how to get number of hours and minutes
> from a timedelta object?
> Let's say we have
> aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000)
> bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000)
> so
> c=bb-aa
> will be
> datetime.timedelta(5, 6339, 437000)
>
> I can easily get days ( c.days)
>  but
> I still can not figure out how easily to get hours and minutes
> Any idea?


WTF^H^H^H ... You got an answer to this question  5 days ago .
[thread copied below]
8<---
Lad wrote:
> Sybren Stuvel wrote:
> > Lad enlightened us with:
> > > How can I find days and minutes difference between two datetime
> > > objects?
> > > For example If I  have
> > > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)
> > > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)

> > diff = b - a

> Ok, I tried

> >>> diff=b-a
> >>> diff
> datetime.timedelta(0, 52662, 922000)
> >>> diff.min
> datetime.timedelta(-9)

Reread the manual:

1. "min" is minIMUM, not minUTES

2. You need:

>>> diff.days
0
>>> diff.seconds
52662
>>> diff.microseconds
922000
>>> minutes = (diff.seconds + diff.microseconds / 100.0) / 60.0
>>> minutes
877.715368 

8<

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


py2exe and pyparallel

2006-08-07 Thread mehdi karimi
HiI want to convert a .py file into .exe with py2exe(I use Pyparallel(import parallel) in that program)after running setup.py py2exe this massage appear:"The following modules appear to be missing: ['parallelioctl' , 'paralleljava']  "  how I can remove this Problem?thanks 
	
		See the all-new, redesigned Yahoo.com.  Check it out.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python open a named pipe == hanging?

2006-08-07 Thread Antoon Pardon
On 2006-08-07, Rochester <[EMAIL PROTECTED]> wrote:
> Thanks Alex, now I think I understand much better the fifo/pipe mechanism  
> and how Python treats them.
>
> For those who are interested, I would like to restate the problem I was  
> tring to solve and a working solution (inspired by Alex Martelli's code),  
> feel free to criticize it:
>
> The problem:
>
> I have an external program which takes two matrices (two text files) as  
> input, and produces an output to stdout, you can take diff as an example.   
> I want to call this program from within Python, without writing any  
> temporary file (for the performance reason).
>
> In Bash, this task would be best written as:
>
> #!/bin/bash
>
> diff <(step1) <(step2) | step3
>
> Where step1, step2 and step3 have to be independent external programs.
>
> Now in Python, since there is no exact equivalence of <() magic a.k.a.  
> process substitution, I figured taht the best solution should be to create  
> a pair of fifos and do something like this:
>
> #!/bin/bash
>
> mkfifo fifo1 fifo2
> step1 > fifo1 &
> step2 > fifo2 &
> diff step1 step2 | step3
>
> And a working Python equivalent code is:

I think your code only works because of an artefacts that may not work
in general.

> #!/usr/bin/python
>
> import os
>
> # do step1 and step2 in Python, say we end up with something like these:
>
> s1 = "some string\n second line."  # results from step1
> s2 = "some string\n a different line." # results from step2
>
> os.mkfifo('fifo1')
> os.mkfifo('fifo2')
>
> op = os.popen(' '.join(['diff', 'fifo1', 'fifo2'])) # this step is crucial!
> print >> open('fifo1', 'w'), s1
> print >> open('fifo2', 'w'), s2

This will not work in general. Suppose diff would open the two files
simultaneously and read the files in parralel. Since you first feed
the whole first file before you start the second, a deadlock could
occur if s1 was sufficiently large.

Something like the following instead of the two print statements
would be better IMO (not tested):

def cat(fn, st):
  fl = file(fn, 'w')
  fl.write(st)
  fl.close()

Threading.Thread(target = cat, args = ('fifo1', s1)).start()
Threading.Thread(target = cat, args = ('fifo2', s2)).start()

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


NNTPlib::xover problem

2006-08-07 Thread Helmut Jarausch
Hi

I try to regularly extract recent news from some newsgroups.
If News is an NNTP object I try
(Response,Articles)= News.xover(str(int(Last)+1),'1000')
where 'Last' is the (previously saved) number of the last
article read.
If there are no new articles I get an Exception

Traceback (most recent call last):
   File "/home/jarausch/Python_My/News", line 36, in -toplevel-
 (Response,Articles)= News.xover(str(int(Last)+1),'1000')
   File "/usr/local/lib/python2.4/nntplib.py", line 479, in xover
 resp, lines = self.longcmd('XOVER ' + start + '-' + end, file)
   File "/usr/local/lib/python2.4/nntplib.py", line 265, in longcmd
 return self.getlongresp(file)
   File "/usr/local/lib/python2.4/nntplib.py", line 236, in getlongresp
 resp = self.getresp()
   File "/usr/local/lib/python2.4/nntplib.py", line 219, in getresp
 raise NNTPTemporaryError(resp)
NNTPTemporaryError: 420 No such article


I would have expected to get an empty 'Response' or the value None
for 'Articles'.

What am I missing?

(This is Python 2.4.3)

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get hours and minutes from 'datetime.timedelta' object?

2006-08-07 Thread Ant

John Machin wrote:
> Lad wrote:
> > Hello,
> > what is the best /easest  way how to get number of hours and minutes
> > from a timedelta object?
...
> >>> diff.days
> 0
> >>> diff.seconds
> 52662
> >>> diff.microseconds
> 922000
> >>> minutes = (diff.seconds + diff.microseconds / 100.0) / 60.0
> >>> minutes
> 877.715368

I suspect what Lad wanted was something more like:

>>> def secs_mins_hours(timed):
...   total_secs = timed.seconds
...   secs = total_secs % 60
...   total_mins = total_secs / 60
...   mins = total_mins % 60
...   hours = total_mins / 60
...   return (secs, mins, hours)
>>> aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000)
>>> bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000)
>>> td = aa - bb
>>> secs_mins_hours(td)
(39, 45, 1)

I'm surprised that the timedelta class hasn't got secs, mins and hours
properties - they could be generated on the fly in a similar way.

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


Re: NNTPlib::xover problem

2006-08-07 Thread Michiel Sikma
Hi Helmut,

I guess it simply raises an exception in case there are no articles;  
this may not be what you expected, but it would seem that this is the  
way it operates. You should try catching the exception to plan out a  
course of action in case no articles are present.

Michiel

Op 7-aug-2006, om 12:50 heeft Helmut Jarausch het volgende geschreven:

> Hi
>
> I try to regularly extract recent news from some newsgroups.
> If News is an NNTP object I try
> (Response,Articles)= News.xover(str(int(Last)+1),'1000')
> where 'Last' is the (previously saved) number of the last
> article read.
> If there are no new articles I get an Exception
>
> Traceback (most recent call last):
>File "/home/jarausch/Python_My/News", line 36, in -toplevel-
>  (Response,Articles)= News.xover(str(int(Last)+1),'1000')
>File "/usr/local/lib/python2.4/nntplib.py", line 479, in xover
>  resp, lines = self.longcmd('XOVER ' + start + '-' + end, file)
>File "/usr/local/lib/python2.4/nntplib.py", line 265, in longcmd
>  return self.getlongresp(file)
>File "/usr/local/lib/python2.4/nntplib.py", line 236, in  
> getlongresp
>  resp = self.getresp()
>File "/usr/local/lib/python2.4/nntplib.py", line 219, in getresp
>  raise NNTPTemporaryError(resp)
> NNTPTemporaryError: 420 No such article
>
>
> I would have expected to get an empty 'Response' or the value None
> for 'Articles'.
>
> What am I missing?
>
> (This is Python 2.4.3)
>
> Many thanks for a hint,
>
> Helmut Jarausch
>
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Proposal: [... for ... while cond(x)]

2006-08-07 Thread Rick Zantow
Duncan Booth <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> Diez B. Roggisch wrote:
> 
>>> No, the list comprehension lets you write an expression directly
>>> avoiding a function call, and it also allows you to add in a
>>> condition which can be used to filer the sequence. Your proposal 
adds
>>> nothing. 
>> 
>> It does. Consider this:
>> 
>> whatever = [x for x in xrange(10) while  x < 10]
>> 
>> 
>> That would run only in a splitsecond of what the whole listcomp 
would.
> 
> Except that the comparable listcomp today is:
> 
> whatever = [x for x in takewhile(lambda x: x < 10, xrange
(10))]
> 
> which also runs in a split second.
> 
> Actually, the OP was correct, it does add something: it removes the 
need 
> for a function or lambda in the takewhile just as the original 
listcomp 
> removes a function or lambda compared with the map version.
> 

Consider how it would be if the situation were reversed, and
whatever = [x for x in xrange(10) while  x < 10] was the 
convention today. What advantage would there be to replacing it with 
whatever = [x for x in takewhile(lambda x: x < 10, xrange(10))]?

As a newcomer to Python, I'd find the first syntax far more readily 
graspable, and I'd have to wonder why I'd ever need takewhile and lambda 
just to do what appears to be straightforward conditioning of a loop. 

I'm not a newcomer to Python, and I wonder about that anyway. 

I also note this, using Python 2.4.2 on win32:
>>> whatever = [x for x in takewhile(lambda x: x < 10, xrange
(10))]
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'takewhile' is not defined

So in addition to the two functions, I need an import statement. It 
looks like the argument can certainly be made that simplifying the 
syntax and lightening the call load bring some advantage to the table. 
There are other arguments to be made against the proposed syntax, I'm 
sure.

-- 
rzed

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


Re: VisualStudio2005 supported in distutils

2006-08-07 Thread Martin v. Löwis
mg schrieb:
> I know the incompatibility problem to have Python compiled with one
> compiler and packages with another one. Nevertheless, in my case, Python
> is well compiled with VisualStudio2005 thank to project files provided
> by Mr Python himself. So, Python is not yet ready to support completely
> VisualStudio2005: Python can be compiled with VisualStudio2005 but a
> VisualStudio2005-compiled-Python can not  install  additional packages.

As I just wrote in a different message: Make sure DISTUTILS_USE_SDK
and MSSdk are both set, and arrange PATH to point to the compiler to
want to use; then distutils will obey you.

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


Re: VisualStudio2005 supported in distutils

2006-08-07 Thread Martin v. Löwis
Jarek Zgoda schrieb:
> Sure, but what if I succesfully compile Python with VS 2005? Hier ist
> der Hund begraben, distutils cann't handle this compiler so I'll be
> unable to compile any extension for my home-baken Python.

It sure can. Just open a "Visual Studio Command Prompt" (or whatever
its name), and make sure MSSdk and DISTUTILS_USE_SDK are both set.
Then distutils will use the compiler from PATH, rather than the
pre-configured one.

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


Re: install python on cdrom

2006-08-07 Thread Martin v. Löwis
Fabian Braennstroem schrieb:
> Thanks, but unfortunately the administrative policy does not
> allow such installation, but could it work, when I do such a
> installation in my home directory, copy everything to a
> cdrom/dvd and mount it in proper place?

Yes, that should work as well. Python won't be able to create
.pyc files, of course, but that shouldn't be a problem (plus
you could make sure they are up-to-date when you copy them
onto the CD-ROM).

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


Re: Subtyping a non-builtin type in C/C++

2006-08-07 Thread Martin v. Löwis
[EMAIL PROTECTED] schrieb:
> I am trying to create a subclass of a python class, defined in python,
> in C++, but I am having some problems.

Is the base class a classic class or a new-style class? Depending on
the answer, the code you should write varies significantly.

To create a new type, it might be easiest to do the same as the
interpreter. Take, for example, a look at the code that gets executed
for new.classobj("Foo", (), {}).

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


regex for replacing \r\n

2006-08-07 Thread abcd
I am trying to get a regex that will match \r\n in a string.
ultimately i am trying to replace all \r\n with somethign else, say
BLAH.

For example:
This is a message
on a new line

would become:
This is a messageBLAHon a new line.

any ideas?  i tried

re.compile('\r\n').match("This is a message" + os.linesep + "on a new
line") but no match.  And I am on windows, so os.linesep gives
'\r\n'

thanks

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


Re: Nice unicode -> ascii translation?

2006-08-07 Thread Martin v. Löwis
[EMAIL PROTECTED] schrieb:
> The trick is finding the right .  Has someone attempted this
> before, or am I stuck writing my own solution?

In this specific example, there is a different approach, using
the Unicode character database:

def strip_combining(s):
import unicodedata
# Expand pre-combined characters into base+combinator
s1 = unicodedata.normalize("NFD", s)
r = []
for c in s1:
# add all non-combining characters
if not unicodedata.combining(c):
r.append(c)
return u"".join(r)

py> a.strip_combining(u'B\xe9la Fleck')
u'Bela Fleck'

As the accented characters get decomposed into base character
plus combining accent, this strips off all accents in the
string.

Of course, it is still fairly limited. If you have non-latin
scripts (Greek, Cyrillic, Arabic, Kanji, ...), this approach
fails, and you would need a transliteration database for them.
There is non built into Python, and I couldn't find a
transliteration database that transliterates all Unicode characters
into ASCII, either.

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


Re: regex for replacing \r\n

2006-08-07 Thread Patrick Bothe
abcd wrote:
> [...]
> ultimately i am trying to replace all \r\n with somethign else, say
> BLAH.
> 
> For example:
> This is a message
> on a new line
> 
> would become:
> This is a messageBLAHon a new line.
Concluding from your question I think you might be happy with a simple 
string `.replace`:
 >>> s = 'This is a message\r\non a new line'
 >>> print s
This is a message
on a new line
 >>> s.replace('\r\n', 'BLAH')
 >>> print s
'This is a messageBLAHon a new line'

Regards,
 Patrick

-- 
2 does not equal 3. Even for large values of 2.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: VisualStudio2005 supported in distutils

2006-08-07 Thread Jarek Zgoda
Martin v. Löwis napisał(a):

>>Sure, but what if I succesfully compile Python with VS 2005? Hier ist
>>der Hund begraben, distutils cann't handle this compiler so I'll be
>>unable to compile any extension for my home-baken Python.
> 
> It sure can. Just open a "Visual Studio Command Prompt" (or whatever
> its name), and make sure MSSdk and DISTUTILS_USE_SDK are both set.
> Then distutils will use the compiler from PATH, rather than the
> pre-configured one.

Thanks, didn't know that.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NNTPlib::xover problem

2006-08-07 Thread Helmut Jarausch
Michiel Sikma wrote:
> Hi Helmut,
> 
> I guess it simply raises an exception in case there are no articles; 
> this may not be what you expected, but it would seem that this is the 
> way it operates. You should try catching the exception to plan out a 
> course of action in case no articles are present.

Thanks,

though the name of the exception 'nntplib.NNTPTemporaryError'
sound 'temporary'

Helmut.


> Op 7-aug-2006, om 12:50 heeft Helmut Jarausch het volgende geschreven:
> 
>> Hi
>>
>> I try to regularly extract recent news from some newsgroups.
>> If News is an NNTP object I try
>> (Response,Articles)= News.xover(str(int(Last)+1),'1000')
>> where 'Last' is the (previously saved) number of the last
>> article read.
>> If there are no new articles I get an Exception
>>
>> Traceback (most recent call last):
>>File "/home/jarausch/Python_My/News", line 36, in -toplevel-
>>  (Response,Articles)= News.xover(str(int(Last)+1),'1000')
>>File "/usr/local/lib/python2.4/nntplib.py", line 479, in xover
>>  resp, lines = self.longcmd('XOVER ' + start + '-' + end, file)
>>File "/usr/local/lib/python2.4/nntplib.py", line 265, in longcmd
>>  return self.getlongresp(file)
>>File "/usr/local/lib/python2.4/nntplib.py", line 236, in getlongresp
>>  resp = self.getresp()
>>File "/usr/local/lib/python2.4/nntplib.py", line 219, in getresp
>>  raise NNTPTemporaryError(resp)
>> NNTPTemporaryError: 420 No such article
>>
>>
>> I would have expected to get an empty 'Response' or the value None
>> for 'Articles'.
>>
>> What am I missing?
>>
>> (This is Python 2.4.3)
>>
>> Many thanks for a hint,
>>
>> Helmut Jarausch
>>
>> Lehrstuhl fuer Numerische Mathematik
>> RWTH - Aachen University
>> D 52056 Aachen, Germany
>> --http://mail.python.org/mailman/listinfo/python-list
> 


-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] rest2web 0.5.0 Beta 1 Released

2006-08-07 Thread david_wahler
I'll be out of the office until approximately August 20th. If you have any 
questions, please email [EMAIL PROTECTED]

-- David Wahler


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


Re: How to get hours and minutes from 'datetime.timedelta' object?

2006-08-07 Thread John Machin

Ant wrote:
> John Machin wrote:
> > Lad wrote:
> > > Hello,
> > > what is the best /easest  way how to get number of hours and minutes
> > > from a timedelta object?
> ...
> > >>> diff.days
> > 0
> > >>> diff.seconds
> > 52662
> > >>> diff.microseconds
> > 922000
> > >>> minutes = (diff.seconds + diff.microseconds / 100.0) / 60.0
> > >>> minutes
> > 877.715368
>
> I suspect what Lad wanted was something more like:

1. If that's what he wanted, it was a very peculiar way of asking. Do
you suspect that he needs to be shown how to conver 877.7... minutes
into hours, minutes and seconds???

2. Please consider that the order of the result would be more
conventionally presented as (hours, minutes, seconds) -- or do you
suspect that the OP needs it presented bassackwards?

>
> >>> def secs_mins_hours(timed):
> ...   total_secs = timed.seconds
> ...   secs = total_secs % 60
> ...   total_mins = total_secs / 60
> ...   mins = total_mins % 60
> ...   hours = total_mins / 60
> ...   return (secs, mins, hours)
> >>> aa=datetime.datetime(2006, 7, 29, 16, 13, 56, 609000)
> >>> bb=datetime.datetime(2006, 8, 3, 17, 59, 36, 46000)
> >>> td = aa - bb
> >>> secs_mins_hours(td)
> (39, 45, 1)
>
> I'm surprised that the timedelta class hasn't got secs, mins and hours
> properties - they could be generated on the fly in a similar way.

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


is it possible to dividing up a class in multiple files?

2006-08-07 Thread Martin Höfling
Hi there,

is it possible to put the methods of a class in different files? I just 
want to order them and try to keep the files small.

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Michiel Sikma
Hi Martin,

I don't think that's possible, since a file is executed when it is  
imported. If you load a file which contains a "partial" class, you  
will get an error because the indentation is incorrect, or the  
methods will be loaded in the wrong namespace.

Regards,
Michiel

Op 7-aug-2006, om 15:41 heeft Martin Höfling het volgende geschreven:

> Hi there,
>
> is it possible to put the methods of a class in different files? I  
> just
> want to order them and try to keep the files small.
>
> Regards
>   Martin
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Diez B. Roggisch
Martin Höfling wrote:

> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.

No, its not possible. What you can do is to create several classes and one
that inherits from all of them. 

Better yet is to not write huge classes and getting rid of strange
conventions or views that make the problem appear as such. To explain that:
I've never felt the need to spread a class over several files - au
contraire, I despise Java for forcing me to only have one top level class
per file.

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

PyGTK TreeView segmentation fault on expand_all()

2006-08-07 Thread Chris Johnson
Good morning.

I have recently begun a project using PyGTK, and part of my planned
interface has a gtk.TreeView showing a portion of the filesystem. Now,
rather than load the entire FS structure into the tree right from the
beginning, I made a lazy tree by adding blank children to rows
representing directories, and connected a call to fill in the data when
a row with blank children was expanded.

Now, this works all fine and well, in general. I can browse my entire
filesystem this way. But I noticed that hitting '*' (which I believe is
a call to expand_all(), though the documentation does not say this
explicitly) on a row representing any empty directory causes a
segmentation fault.

This problem can be alleviated by not removing the blank child after
attempting to add directory contents, but I would like to avoid this
approach.

My suspicion is that expand_all() assumes that there are children
present, and when I remove the blank row (after attempting to add any
subdirectories and files), it does not check to make sure there are
still children.

So I suppose I have a couple questions. First, can anybody confirm my
suspicions? Secondly, is this a PyGTK bug, or am I doing something that
simply should never be done? Finally, do you see any way to fix this
problem?

Code follows
--
def onExpand(self, view, iter, path):
"""Add directory contents on first expansion of its entry"""
sorted = view.get_model() # TreeModelSort
iter = sorted.convert_iter_to_child_iter(None,iter)
store = sorted.get_model() # TreeStore
child = store.iter_children(iter)
cpath = store.get(iter,1)[0][1:] # Hidden column with fs path
info
if store.get_value(child, 0) is None:
sorted.addDir(cpath,iter)
store.remove(child)

-

If any other code is necessary, I can provide my entire program.
However, I think I've isolated the problem to that last line (execution
continues beyond it, so it's not exactly the line itself), and want to
hear any recommendations for how to still remove that blank child
without causing expand_all() to fall on its face.

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Chris Johnson

Martin Höfling wrote:
> Hi there,
>
> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.
>
> Regards
>   Martin

I ran across pyp the other day. It may be what you're wanting.

http://www.freenet.org.nz/python/pyp/

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


Re: Nice unicode -> ascii translation?

2006-08-07 Thread skip

crowell> However, I'd like to see the more sensible "Bela Fleck" instead
crowell> of dropping '\xe9' entirely.  

Assuming the data are in latin-1 or can be converted to it, try my latscii
codec:

http://orca.mojam.com/~skip/python/latscii.py

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread bearophileHUGS
Martin Höfling:
> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.

Well, you can create one or more modules filled with nude methods, and
you can define a class inside another module, and then add the methods
to this last class using a little helper function.

Bye,
bearophile

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Ziga Seilnacht
Martin Höfling wrote:
> Hi there,
>
> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.
>
> Regards
>   Martin

You could use something like this:

"""
Example usage:

>>> class Person(object):
... def __init__(self, first, last):
... self.first = first
... self.last = last
...
>>> john = Person('John', 'Smith')
>>> jane = Person('Jane', 'Smith')
>>> class Person(extend(Person)):
... def fullname(self):
... return self.first + ' ' + self.last
...
>>> john.fullname()
'John Smith'
>>> jane.fullname()
'Jane Smith'
"""

def extend(cls):
extender = object.__new__(Extender)
extender.class_to_extend = cls
return extender


class Extender(object):

def __new__(cls, name, bases, dict):
# check that there is only one base
base, = bases
extended = base.class_to_extend
# names have to be equal otherwise name mangling wouldn't work
if name != extended.__name__:
msg = "class names are not identical: expected %r, got %r"
raise ValueError(msg % (extended.__name__, name))
# module is added automatically
module = dict.pop('__module__', None)
if module is not None:
modules = getattr(extended, '__modules__', None)
if modules is None:
modules = extended.__modules__ = [extended.__module__]
modules.append(module)
# replace the docstring only if it is not None
doc = dict.pop('__doc__', None)
if doc is not None:
setattr(extended, '__doc__', doc)
# now patch the original class with all the new attributes
for attrname, value in dict.items():
setattr(extended, attrname, value)
return extended


Ziga

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Bruno Desthuilliers
Martin Höfling wrote:
> Hi there,
> 
> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.

Technically, yes - but in a somewhat hackish way.

But you *really* should not have such a need at first. Smells like a
design (or coding) problem to me - FWIW, very few of my source files are
> 1 KLOC, and they usually contains many classes, functions and other
definitions.

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


Re: How to get hours and minutes from 'datetime.timedelta' object?

2006-08-07 Thread Ant

John Machin wrote:
...
> 1. If that's what he wanted, it was a very peculiar way of asking. Do
> you suspect that he needs to be shown how to conver 877.7... minutes
> into hours, minutes and seconds???

Chill dude, It wasn't an attack :-)

The datetime class has hour, minute and second attributes that give the
values of each as being in range(24) (hours) and range(60). i.e.
integers. So an educated guess leads me to the conclusion that it is
similar functionality that he wants from the timedelta class.

> 2. Please consider that the order of the result would be more
> conventionally presented as (hours, minutes, seconds) -- or do you

Very good point. That would have been a tricky issue for the OP, and
for that I apologise.

> suspect that the OP needs it presented bassackwards?

I think that you have that last word muddled. Not quite ass-backward,
but close ;-)

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


need an alternative to getattr()

2006-08-07 Thread [EMAIL PROTECTED]
Hi,

AIM: I have a config file that contains configuration under headings
like this:

heading1:


heading2:


...
...

i parse this file to get heading1, heading2, etc and then i want to
call heading1.process(), heading2.process(), etc.
What i am trying to do is: (this is not the exact code, it just
represents what i am trying to do)

import heading1
import heading2
While True:
heading = get_next_heading(file_ptr) # This func will return
"heading1", then "heading2"(on next call)
if heading = "":
break
getattr(heading, "process")(file_ptr) # The problem, as you would
have noticed, is that the first
# argument to getattr is a string!!

Is there an alternatice to getattr() that will solve my problem, or is
there another way to do it.

-pranav

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Ant

Martin Höfling wrote:
> Hi there,
>
> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.

The editor leo (http://webpages.charter.net/edreamleo/front.html) gives
you a way of handling large files in this way without actually having
to split the class between files. A bit like a more powerful form of
folding and narrowing text that some other editors have.

But like others have noted, it is probably an indication that the class
could use a bit of refactoring...

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


format a number for output

2006-08-07 Thread abcd
if i have a number, say the size of a file, is there an easy way to
output it so that it includes commas?

for example:

1890284

would be:

1,890,284

I am looking for something builtin to python, not a third party lib.

thanks

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


Re: is it possible to dividing up a class in multiple files?

2006-08-07 Thread Martin Höfling
Thanks for your suggestions, precompiling is not an option, cause I 
can't introduce extra dependencies from a precompiler.

> Better yet is to not write huge classes and getting rid of strange
> conventions or views that make the problem appear as such. To explain that:
> I've never felt the need to spread a class over several files - au
> contraire, I despise Java for forcing me to only have one top level class
> per file.

You're probably right. I'll think about it if it's possible to move some 
stuff out of the class.

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


Re: format a number for output

2006-08-07 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, abcd wrote:

> if i have a number, say the size of a file, is there an easy way to
> output it so that it includes commas?
> 
> for example:
> 
> 1890284
> 
> would be:
> 
> 1,890,284

I think this comes close:

In [23]: import locale

In [24]: locale.setlocale(locale.LC_ALL, '')
Out[24]: 'en_US.UTF-8'

In [25]: locale.format('%d', 1890284, True)
Out[25]: '1,890,284'

It's not always commas but whatever character is used to group thousands
in the active locale.

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


timeout calling local se

2006-08-07 Thread [EMAIL PROTECTED]
(Environment: RedHat Linux recent, Python 2.3.5)

We have a batch processing script that on occasion needs to send out an
email. We have a sendmail running locally.

Sometimes we get a socket timeout on sending that email. Increasing the
timeout to 30sec reduced but did not eliminate it.

It seems to happen more often when sending to some addresses in the UK,
but it's definitely not limited to that.

And, while we sometimes send a number of messages in a short period of
time, (a) it's all single-threaded, and (b) the failure is often but
not always the 1st message in the batch.

Any ideas on what's going on? I don't know much about the
thread/process model of sendmail to have any clue why this is
happening.

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


screensaver in Python

2006-08-07 Thread daniel Van der Borght
Programming a screensaver in Python, where and/or how di I start ?
Daniel VdB 


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


Re: screensaver in Python

2006-08-07 Thread Ant

daniel Van der Borght wrote:
> Programming a screensaver in Python, where and/or how di I start ?

Google for "python screensaver". The first link has a module to use...

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


Re: email client like mutt

2006-08-07 Thread cga2000
On Sun, Aug 06, 2006 at 04:15:08PM EDT, Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Fabian Braennstroem  <[EMAIL PROTECTED]> wrote:
> >
> >I am looking for a python email client for the terminal... something like
> >mutt; maybe, so powerfull ;-)
> 
> What's wrong with mutt?

Like he says it's not written in python.

Thanks

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


PyMorphic Project

2006-08-07 Thread Anders Österholm
As a part of my Master Thesis in Cognitive Science at the University of Linköping in Sweden i have created a Squeak-like system in Python called PyMorphic. Project homepage is http://pymorphic.sourceforge.net/
I am about to make a new release with minor changes.There is a tutorial for you in the Toolbar of the main screen. The major technical focus lies on the auto-reloading of classes. This means that instances can be updated with new class definitions. The code that is used for the autoreloading can be found at  
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Any comments on this project are welcome./Anders Österholm
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: need an alternative to getattr()

2006-08-07 Thread Uffe Wassmann
I think you would benefit from looking at the ConfigParser module.
I haven't tried it yet, but it looks like a nice interface for writing
and reading configuration files.

-Uffe.

On 7 Aug 2006 07:30:41 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> AIM: I have a config file that contains configuration under headings
> like this:
>
> heading1:
> 
> 
> heading2:
> 
> 
> ...
> ...
>
> i parse this file to get heading1, heading2, etc and then i want to
> call heading1.process(), heading2.process(), etc.
> What i am trying to do is: (this is not the exact code, it just
> represents what i am trying to do)
>
> import heading1
> import heading2
> While True:
>heading = get_next_heading(file_ptr) # This func will return
> "heading1", then "heading2"(on next call)
>if heading = "":
>break
>getattr(heading, "process")(file_ptr) # The problem, as you would
> have noticed, is that the first
> # argument to getattr is a string!!
>
> Is there an alternatice to getattr() that will solve my problem, or is
> there another way to do it.
>
> -pranav
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: screensaver in Python

2006-08-07 Thread daniel Van der Borght
are you Chris ? anyway : thank you...
"Ant" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
>
> daniel Van der Borght wrote:
>> Programming a screensaver in Python, where and/or how di I start ?
>
> Google for "python screensaver". The first link has a module to use...
> 


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


Re: Python open a named pipe == hanging?

2006-08-07 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Alex Martelli) wrote:

> Donn Cave <[EMAIL PROTECTED]> wrote:
> 
> > In article <[EMAIL PROTECTED]>,
> >  Rochester <[EMAIL PROTECTED]> wrote:
> > 
> > >  I just found out that the general open file mechanism doesn't work
> > >  for named pipes (fifo).  Say I wrote something like this and it
> > >  simply hangs python:
> > > 
> > > #!/usr/bin/python
> > > 
> > > import os
> > > 
> > > os.mkfifo('my fifo')
> > > 
> > > open('my fifo', 'r+').write('some strings.')
> > > x = os.popen('cat my fifo').read()
> > > 
> > > print x
> > 
> > I believe your problem is that, by the time you open the
> > pipe for read, it has already been closed by its writer.
> 
> Hmmm, no: the problem is, he never opens the pipe for write, because the
> open blocks (will not proceed until somebody opens the fifo for reading,
> which in turn won't happen here because the open blocks).
> 
> Try:
> 
> a = open('my_fifo', 'w')
> b = os.popen('cat my_fifo')
> a.write ...
> a.close()
> c = b.read()
> 
> this STILL doesn't work, since the very first statement blocks.  (I've
> also removed the 'r+' mode in favor of 'w', since opening a FIFO for
> reading AND writing produces undefined behavior, at least in all Unix
> versions and variants I'm familiar with).

But it does work.  I edited that excerpt only to complete
missing parts, and ran it on MacOS X and GNU Linux.

import os
f = '/tmp/r'
try:
os.unlink(f)
except:
pass
a = open(f, 'w')
b = os.popen('cat %s' % f)
a.write('chunks\n')
a.close()
c = b.read()
print repr(c)


> > it.  (You can't read "all" the data, though - since you still
> > have the file open, it has no end of file - so you can't
> > solve the problem exactly as stated above.)
> 
> Actually, in CPython (1.5.2 to 2.5 included, at least), _IF_ open worked
> normally then the file WOULD be closed by the statement
> 
> open('my fifo', 'r+').write('some strings.')

Sure, but now we're back to closing the pipe before the reader
gets to it.  That doesn't work.


   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: screensaver in Python

2006-08-07 Thread Ant

daniel Van der Borght wrote:
> are you Chris ? anyway : thank you...

No - I really am Ant. :-)

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


Re: need an alternative to getattr()

2006-08-07 Thread Ant

> getattr(heading, "process")(file_ptr)
...
> Is there an alternatice to getattr() that will solve my problem, or is
> there another way to do it.

How about:

eval("%s.process(%s)" % (heading, file_ptr))

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


ANNOUNCE: Mod_python 3.2.10

2006-08-07 Thread Gregory (Grisha) Trubetskoy

The Apache Software Foundation and The Apache HTTP Server Project are
pleased to announce the 3.2.10 release of mod_python. Mod_python
3.2.10 is considered a stable release, suitable for production use.

Mod_python is an Apache HTTP Server module that embeds the Python
language interpreter within the server. With mod_python you can write
web-based applications in Python that will run many times faster than
traditional CGI and will have access to advanced features such as
ability to maintain objects between requests, access to httpd
internals, content filters and connection handlers.

The 3.2.10 release has many new features, feature enhancements, fixed
bugs and other improvements over the previous version. 3.2.10 now
works with Apache HTTP Server 2.2. See Appendix A of mod_python
documentation for a complete list.

Mod_python 3.2.10 is released under Apache License version 2.0.

Mod_python 3.2.10 is available for download from:

http://httpd.apache.org/modules/python-download.cgi

More information about mod_python is available at:

http://httpd.apache.org/modules/

Many thanks to Jim Gallacher, Graham Dumpleton, Nicolas Lehuen and
everyone else who contributed to and helped test this release, without
your help it would not be possible!

Regards,

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


Re: need an alternative to getattr()

2006-08-07 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote:
> import heading1
> import heading2
> While True:
> heading = get_next_heading(file_ptr) # This func will return
> "heading1", then "heading2"(on next call)
> if heading = "":
> break
> getattr(heading, "process")(file_ptr) # The problem, as you would
> have noticed, is that the first
> # argument to getattr is a string!!
> 
> Is there an alternatice to getattr() that will solve my problem, or is
> there another way to do it.

  globals()[heading].process(file_ptr)

or

  sys.modules[heading].process(file_ptr)

but note that, unless you are checking 'heading' against a 'known
good configuration keywords' list beforehand, you are trusting the
author of the configuration file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python 2.5b2 and excepthook problem

2006-08-07 Thread Larry Bates
I have some classes that trap hook sys.excepthook and log
exceptions prior to the program exiting.  This has proven
to be an effective way to log what is going on with many
of my "lights out" processes.  I'm doing some testing with
Python 2.5b2 and can't seem to get it to work properly.
Here is a very small script that I think should work but
doesn't.

import sys

def excepthook(type, value, tb):
import traceback
print "entering my excepthook function"
tblines=traceback.format_exception(type, value, tb)
#traceback.print_tb(tb)
return

if __name__=="__main__":
sys.excepthook=excepthook
print "sys.excepthook=", sys.excepthook
a=[1,2,3]
b=a[4]

When I run this I get:

sys.excepthook= 
Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "K:\SYSCON\PYTHON\ZBKUP\junk.py", line 14, in 
b=a[4]
IndexError: list index out of range
>>>

The sys.excepthook is clearly pointing to my function, but when
the exception occurs the function isn't called because the print
statement isn't executed upon entering the function.  Has something
changed that I missed?

Thanks in advance for any assistance.

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


Re: format a number for output

2006-08-07 Thread BartlebyScrivener
abcd wrote:
> if i have a number, say the size of a file, is there an easy way to
> output it so that it includes commas?
>
> for example:
>
> 1890284
>
> would be:
> 
> 1,890,284

see also this thread:

http://tinyurl.com/qf6ew

rd

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


Re: Ann: SE 2.2b

2006-08-07 Thread Anthra Norell
If you go to http://www.python.org/pypi. you see it about in the middle of the 
recently updated packages. It's blue, so you can
click it and you're there.
  The update page shows only the twenty most recent updates. So they drop 
out at the bottom rather fast. If it's gone by the
time you check, type SE into the search template in the upper right corner.

Frederic

- Original Message -
From: "Georg Brandl" <[EMAIL PROTECTED]>
Newsgroups: comp.lang.python
To: 
Sent: Sunday, August 06, 2006 9:22 PM
Subject: Re: Ann: SE 2.2b


> [EMAIL PROTECTED] wrote:
> > Frederic> In the short period of time since I introduced SE. the
> > Frederic> feedback has been overwhelmingly postive.
> >
> > Ummm... what is it?  The last SE I had was a Mac.
>
> It is supposed to be a Stream Editor (in the spirit of sed, I think).
> However, the PyPI page provides no download or homepage links.
>
> Georg
> --
> http://mail.python.org/mailman/listinfo/python-list

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


A problem from a Vim user

2006-08-07 Thread manuhack
When I use raw_input('Please type something.\n') in the python 2.4
command line windows, it doesn't have any problem.  However, when I run
the same command in vim 7 as :py raw_input('Please type something.\n'),
there is an EOFError: EOF when reading a line.  Is there a way to use
that command within vim without raising errors?

Thanks a lot.

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


Re: Need a compelling argument to use Django instead of Rails

2006-08-07 Thread aaronwmail-usenet

Damjan wrote:
> Yes, but your mod_python programs still run with the privileges of the
> Apache process, as are all the other mod_python programs. This means that
> my mod_python program can (at least) read files belonging to you -
> including your config file holding your database password

I think a standard solution to this is to
associate each virtual host server to a
different port and have the main apache
redirect to the port.  Inetd makes sure
that the vserver apache instance only
stays alive while it's needed.  It might be
complicated to set up, but it works.
Again, something like this is probably
advisable anyway to limit the ways one
vserver can damage another generally
speaking.
  -- Aaron Watters

===
It's not the years. It's the mileage.
   -- Indiana Jones

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


Re: Static Variables in Python?

2006-08-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Paddy <[EMAIL PROTECTED]> wrote:
.
[substantial thread
with many serious
alternatives]
.
.
>You can do things with function attributes
>
>def foo(x):
>  foo.static += x
>  return foo.static
>foo.static = 0
.
.
.
My favorite variation is this:

  def accumulator(x):
  # On first execution, the attribute is not yet known.
# This technique allows use of accumulator() as a 
# function without the "consumer" having to initialize
# it.
  if not "static" in dir(accumulator):
accumulator.static = 0
  accumulator.static += x
  return accumulator.static
  
  print accumulator(3)
  print accumulator(5)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: format a number for output

2006-08-07 Thread Tim Williams
On 7 Aug 2006 07:55:11 -0700, abcd <[EMAIL PROTECTED]> wrote:
> if i have a number, say the size of a file, is there an easy way to
> output it so that it includes commas?
>
> for example:
>
> 1890284
>
> would be:
>
> 1,890,284
>

I was bored !!

>>> a = 1890284
>>> ','.join([str(a)[::-1][x:x+3] for x in range(len(str(a)))[::3]])[::-1]
'1,890,284'

Ugly !

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


Resource temporarily unavailable launching idle under cygwin

2006-08-07 Thread jcmendez
Hello everyone.  Trying to run idle from a cygwin session on Win2k
(yuk, but I must)  I'm getting the following error message.   It seems
something more Windoze-driven that Python driven, and I'm not and don't
wanna be an expert on that OS.  Since the group has a good mix of users
in different platforms, perhaps someone can help.

Python runs fine, my programs run fine, and I can edit in vim and run
my code.  However, would be nice to have idle available from time to
time

Thanks in advance!!

$ idle
  23367 [main] python2.4 1668 C:\cygwin\bin\python2.4.exe: *** fatal
error - C:\
cygwin\bin\python2.4.exe: *** unable to remap C:\cygwin\bin\tk84.dll to
same add
ress as parent(0x1889) != 0x18D2
 18 [main] python2.4 2236 fork: child 1668 - died waiting for dll
loading, e
rrno 11
Traceback (most recent call last):
  File "/usr/bin/idle", line 5, in ?
main()
  File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
1361, in mai
n
  File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
277, in open
_shell
  File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
962, in begi
n
  File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
372, in star
t_subprocess
  File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
350, in spaw
n_subprocess
  File "/usr/lib/python2.4/os.py", line 552, in spawnv
return _spawnvef(mode, file, args, None, execv)
  File "/usr/lib/python2.4/os.py", line 520, in _spawnvef
pid = fork()
OSError: [Errno 11] Resource temporarily unavailable

As a sidenote, I sent twice this message as an email to
[EMAIL PROTECTED] as instructed on the group digests,
and it bounced immediately.  Did this method of posting change?

Thanks!

Juan C.

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


Installing a Windows Printer

2006-08-07 Thread D
I would like to create a script for Windows 2000 that will create a
Standard TCP/IP printer port and install a printer (I have the
applicable printer drivers needed for the install on a network share).
My plan is to use py2exe and distribute (also via network share) the
script so that administrators, or even users, can easily install the
printer.  Is this possible?  If so, I would appreciate it if someone
could steer me in the right direction in terms of how to begin (i.e.
libraries needed, sample code).  Thanks!

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


Re: Resource temporarily unavailable launching idle under cygwin

2006-08-07 Thread jcmendez
PS:  I already tried what suggested in a previous message on the groups
"Python 2.3.2 spawn problem" - Uninstalling and reinstalling python
without luck.

Python 2.4.3 (#1, May 18 2006, 07:40:45)
[GCC 3.3.3 (cygwin special)] on cygwin

Thanks!

jcmendez wrote:
> Hello everyone.  Trying to run idle from a cygwin session on Win2k
> (yuk, but I must)  I'm getting the following error message.   It seems
> something more Windoze-driven that Python driven, and I'm not and don't
> wanna be an expert on that OS.  Since the group has a good mix of users
> in different platforms, perhaps someone can help.
>
> Python runs fine, my programs run fine, and I can edit in vim and run
> my code.  However, would be nice to have idle available from time to
> time
>
> Thanks in advance!!
>
> $ idle
>   23367 [main] python2.4 1668 C:\cygwin\bin\python2.4.exe: *** fatal
> error - C:\
> cygwin\bin\python2.4.exe: *** unable to remap C:\cygwin\bin\tk84.dll to
> same add
> ress as parent(0x1889) != 0x18D2
>  18 [main] python2.4 2236 fork: child 1668 - died waiting for dll
> loading, e
> rrno 11
> Traceback (most recent call last):
>   File "/usr/bin/idle", line 5, in ?
> main()
>   File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
> 1361, in mai
> n
>   File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
> 277, in open
> _shell
>   File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
> 962, in begi
> n
>   File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
> 372, in star
> t_subprocess
>   File "/tmp/python.340/usr/lib/python2.4/idlelib/PyShell.py", line
> 350, in spaw
> n_subprocess
>   File "/usr/lib/python2.4/os.py", line 552, in spawnv
> return _spawnvef(mode, file, args, None, execv)
>   File "/usr/lib/python2.4/os.py", line 520, in _spawnvef
> pid = fork()
> OSError: [Errno 11] Resource temporarily unavailable
>
> As a sidenote, I sent twice this message as an email to
> [EMAIL PROTECTED] as instructed on the group digests,
> and it bounced immediately.  Did this method of posting change?
> 
> Thanks!
> 
> Juan C.

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


Re: Initializing the number of slots in a dictionary

2006-08-07 Thread Jon Smirl
On Mon, 07 Aug 2006 00:33:33 -0400, Tim Peters wrote:

> ...
> 
> [Jon Smirl]
>> I know in advance how many items will be added to the dictionary. Most
>> dictionary implementations I have previously worked with are more
>> efficient if they know ahead of time how big to make their tables.
> 
> Richard Jones spent considerable time investigating whether "pre-sizing"
> lists and dicts in CPython could help, at the "Need For Speed" sprint
> earlier this year.   He didn't find a win worth getting; e.g., read the
> section "List pre-allocation" at:
> 
> http://wiki.python.org/moin/NeedForSpeed/Failures
> 
> Trying it for dicts was also part of what he did, but I don't think
> specifics about that were recorded on the Wiki.  I was at the sprint, and
> hoots of triumph from Richard's direction were conspicuous by absence
> during his dict time ;-)
> 
>> In this case I only need to do a presence test of the key, there is no
>> actual data associated with the key. The table is used for detecting
>> duplicate entries. Is there a more efficient to do this test that
>> sticking an empty string into a dict? The keys are sha1.digest().
> 
> It's probably more common to set the value to None or 1, but it doesn't
> really matter in reality.  In theory, using 1 or an empty string relies on
> the implementation accident that CPython stores those uniquely, while it's
> guaranteed that None is a singleton object.
> 
> BTW, is there a reason to use SHA instead of MD5?  I ask because the
> latter is 4 bytes shorter, and you apparently have a /lot/ of keys.

http://git.or.cz/index.html
git is the source code control tool used by the Linux kernel.  It is 
optimized for distributed development. git is what the kernel developers
wrote to replace Bitkeeper after the Bitkeeper license change.

git identifies it's change sets with sha1 hashes.

Distributed SCM is very important when working on large projects. With a 
distributed SCM nobody needs commit privs - everyone has their own
complete copy of the repository. To get a change into a distribution you
need to convince someone up the heirarchy to pull your changes into
their repository. In the Linux world Linus makes the distributions. There
are about 10 people in the next circle and about 100 in the circle after
that. You need to convince one of them to accept your changes, but that's
not very hard if your code makes sense.

Distributed also means that you can pull changes from anyone else into
your repository. So if you want to run Reiser4 and it isn't in the main
Linus tree yet, just pull a copy from the namesys git tree into your local
tree and everything will get merged.

Python is using Subversion which is way better than CVS, but Subversion is
still organized around a central repository with commit privs. If that
repository disappears in an earthquake Python may be in trouble.

If you give git a try you will also notice that it is way faster than
subversion.

> If you're using a current version of Python, you can save some memory by
> using a builtin set object instead.  The CPython implementation of sets is
> very much like its implementation of dicts, but doesn't consume any memory
> for the (non-existent) associated values.  You also get a number of
> operations useful on sets (like intersection and union).

Sets may be a good option, I'll adjust the code for the next run.

>> ...
>> Since I am rerunning the conversion over and over anything simple that
>> speeds it up is helpful.
>>
>> I already have 4GB RAM, it would take around 30GB to get everything in
>> memory.
>>
>> Dictionaries are not a big problem for me, but there are many in use and
>> they have millions of items in them.
> 
> A peculiar suggestion:  if you don't need to release system resources
> cleanly at the end of a run, try doing:
> 
> import os
> os._exit(0)
> 
> at the end.  If you have dicts with millions of entries swapped to disk,
> it /can/ consume major time just to page them all in again to decrement
> the key & value refcounts if you let "clean shutdown" code determine
> they've become trash.  Bailing ungracefully can skip all that work (but
> also skips other work, like letting the platform C I/O library close
> still-open files gracefully).

Jon Smirl
[EMAIL PROTECTED]

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


Re: format a number for output

2006-08-07 Thread Yu-Xi Lim
Tim Williams wrote:
 a = 1890284
 ','.join([str(a)[::-1][x:x+3] for x in range(len(str(a)))[::3]])[::-1]
> '1,890,284'
> 
> Ugly !
> 

 >>> b = 189028499
 >>> ','.join([str(b)[::-1][x:x+3] for x in range(len(str(b)))[::3]])[::-1]

'-,189,028,499'

 >>> c = 1890284.1
 >>> ','.join([str(c)[::-1][x:x+3] for x in range(len(str(c)))[::3]])[::-1]

'189,028,4.1'


Stick to using locale. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: format a number for output

2006-08-07 Thread Yu-Xi Lim
Yu-Xi Lim wrote:

>  >>> b = 189028499
>  >>> ','.join([str(b)[::-1][x:x+3] for x in range(len(str(b)))[::3]])[::-1]
> 
> '-,189,028,499'

Oops, mis-paste

 >>> b = -189028499
 >>> ','.join([str(b)[::-1][x:x+3] for x in range(len(str(b)))[::3]])[::-1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing the number of slots in a dictionary

2006-08-07 Thread Fuzzyman

Jon Smirl wrote:
> On Sun, 06 Aug 2006 15:33:30 -0700, John Machin wrote:
[snip..]
> >
> > Do you have an application with a performance problem? If so, what makes
> > you think inserting 1M items into a Python dict is contributing to the
> > problem?
>
> I know in advance how many items will be added to the dictionary. Most
> dictionary implementations I have previously worked with are more
> efficient if they know ahead of time how big to make their tables.
>
> In this case I only need to do a presence test of the key, there is no
> actual data associated with the key. The table is used for detecting
> duplicate entries. Is there a more efficient to do this test that sticking
> an empty string into a dict? The keys are sha1.digest().

Possibly a naive question - but would using sets be more efficient ?

They are generally used for the sort of job you are describing (testing
for duplicates rather than storing data associated with a key).

We did some limited performance tests at Resolver Systems and found use
of sets and dictionaries to be almost exactly hte same speed - but
there could be memory advantages for you. Performance is also likely to
be different for vast data sets, but I understand the hashing algorithm
to be very similar for both...

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: Installing a Windows Printer

2006-08-07 Thread Jon
Hi D,

I would suggest that you look here
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/prntspol_7mgj.asp
at AddPort and and AddPrinter. Though I have not tried to use them in
python, I would assume that using win32com
[http://www.python.net/crew/mhammond/win32/Downloads.html] or the like
you'd be able to make use of those functions.

Jon

D wrote:
> I would like to create a script for Windows 2000 that will create a
> Standard TCP/IP printer port and install a printer (I have the
> applicable printer drivers needed for the install on a network share).
> My plan is to use py2exe and distribute (also via network share) the
> script so that administrators, or even users, can easily install the
> printer.  Is this possible?  If so, I would appreciate it if someone
> could steer me in the right direction in terms of how to begin (i.e.
> libraries needed, sample code).  Thanks!

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


ST_CTIME convert to yyyymmdd

2006-08-07 Thread Hitesh
Hi,

Any hint on converting time from ST_CTIME secs into mmdd format?
sorry for one-liner stupid question.. I couldn;t find (or rather figure
out) in docs.

Thank you,
hj

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


Re: ST_CTIME convert to yyyymmdd

2006-08-07 Thread Hitesh

All right I got it. Thank you anyway...

create_date = os.stat(pathname)[ST_CTIME]
print time.strftime("%Y%m%d", time.gmtime(create_date))

Hitesh wrote:
> Hi,
>
> Any hint on converting time from ST_CTIME secs into mmdd format?
> sorry for one-liner stupid question.. I couldn;t find (or rather figure
> out) in docs.
> 
> Thank you,
> hj

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


Re: where can I find Python acceptance test suite?

2006-08-07 Thread The Eternal Squire
Thanks.

Terry Reedy wrote:
> "The Eternal Squire" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > I've been doing some hacking of the Python engine, and I've been
> > looking for
> > where the comprehensive regression tests are kept so that I can
> > determine
> > where I've broken part of the engine.
> 
> ...python2x/Lib/test

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


Re: How to get hours and minutes from 'datetime.timedelta' object?

2006-08-07 Thread John Machin

Ant wrote:
> John Machin wrote:
> ...
> > 1. If that's what he wanted, it was a very peculiar way of asking. Do
> > you suspect that he needs to be shown how to conver 877.7... minutes
> > into hours, minutes and seconds???
>
> Chill dude, It wasn't an attack :-)

I didn't think it was.

>
> The datetime class has hour, minute and second attributes that give the
> values of each as being in range(24) (hours) and range(60). i.e.
> integers. So an educated guess leads me to the conclusion that it is
> similar functionality that he wants from the timedelta class.
>
> > 2. Please consider that the order of the result would be more
> > conventionally presented as (hours, minutes, seconds) -- or do you
>
> Very good point. That would have been a tricky issue for the OP, and
> for that I apologise.
>
> > suspect that the OP needs it presented bassackwards?
>
> I think that you have that last word muddled. Not quite ass-backward,
> but close ;-)

On the contrary. It means "ass-backward, and then some". Google
"dictionary bassackwards" and read the first few hits. 

Cheers,
John

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


distutils setup.py

2006-08-07 Thread Saketh
I'm having trouble getting the data_files argument of my setup.py to
work with "python setup.py sdist" under Windows XP. Here is the
data_files argument that I pass to setup().

data_files = [\
('res','app.ico'),
('', 'preferences.xml'),
('res', glob.glob(os.path.join('res','*.png')))],
)

My setup.py is in the same directory as "preferences.xml". I use this
setup.py for both py2exe and sdist. When I use it for py2exe, the
data_files are properly copied to the target directory. However, when I
use it for sdist, none of the data_files are copied. If this were a
directory problem, then setup.py would have failed earlier when I
specified Application.py in the "scripts" argument.

How can I get the data_files copied properly without having to manually
edit the MANIFEST file?

Thanks,
Saketh

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


Re: format a number for output

2006-08-07 Thread Paul Rubin
"abcd" <[EMAIL PROTECTED]> writes:
> 1890284
> 
> would be:
> 
> 1,890,284

"To iterate is human; to recurse, divine":

def commafy(n):
   if n < 0: return '-' + commafy(-n)
   if n >= 1000: return '%s,%03d' % (commafy(n//1000), n % 1000)
   return '%s'% n

I don't like the locale solution because of how messy locales are.
-- 
http://mail.python.org/mailman/listinfo/python-list


Getting previous file name

2006-08-07 Thread Hitesh

Hi,

I have a small script here that goes to inside dir and sorts the file
by create date. I can return the create date but I don't know how to
find the name of that file...
I need file that is not latest but was created before the last file.
Any hints... I am newbiw python dude and still trying to figure out lot
of 'stuff'..


import os, time, sys
from stat import *

def walktree(path):
test1 = []
for f in os.listdir(path):
filename = os.path.join(path, f)
create_date_sces = os.stat(filename)[ST_CTIME]
create_date = time.strftime("%Y%m%d%H%M%S",
time.localtime(create_date_sces))
print create_date, " ." , f
test1.append(create_date)
test1.sort()
print test1
return test1[-2]


if __name__ == '__main__':
path = 'srv12\\c$\\backup\\my_folder\\'
prev_file = walktree(path)
print "Previous back file is ", prev_file


Thank you,
hj

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


Re: Getting previous file name

2006-08-07 Thread Larry Bates
Hitesh wrote:
> Hi,
> 
> I have a small script here that goes to inside dir and sorts the file
> by create date. I can return the create date but I don't know how to
> find the name of that file...
> I need file that is not latest but was created before the last file.
> Any hints... I am newbiw python dude and still trying to figure out lot
> of 'stuff'..
> 
> 
> import os, time, sys
> from stat import *
> 
> def walktree(path):
> test1 = []
> for f in os.listdir(path):
> filename = os.path.join(path, f)
> create_date_sces = os.stat(filename)[ST_CTIME]
> create_date = time.strftime("%Y%m%d%H%M%S",
> time.localtime(create_date_sces))
> print create_date, " ." , f
> test1.append(create_date)
> test1.sort()
> print test1
> return test1[-2]
> 
> 
> if __name__ == '__main__':
>   path = 'srv12\\c$\\backup\\my_folder\\'
>   prev_file = walktree(path)
>   print "Previous back file is ", prev_file
> 
> 
> Thank you,
> hj
> 
Just some quick ideas (not tested):

change test1.append(create_date) to test1.append((create_date, filename))
that way the filename will tag along during the sorting as a tuple in
the test1 list.

You will also need to change prev_file = walktree(path) to
create_date, prev_file = walktree(path)

Note: Your script can't handle the situation where there are zero or
one file(s) in the path (you should probably put in some code for those
edge cases).

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


Re: format a number for output

2006-08-07 Thread BartlebyScrivener

Paul Rubin wrote:

> "To iterate is human; to recurse, divine":
>
> def commafy(n):
>if n < 0: return '-' + commafy(-n)
>if n >= 1000: return '%s,%03d' % (commafy(n//1000), n % 1000)
>return '%s'% n
>
> I don't like the locale solution because of how messy locales are.

That's a keeper!

Thanks!

rd

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


Re: Design Patterns in Python

2006-08-07 Thread Gabriel Genellina

At Saturday 5/8/2006 22:22, Alex Martelli wrote:


> But does anyone know of a complete discussion/analysis of patterns in
> Python? Books, articles, web pages...


Thanks to all of you for your pointers on this subject!



Gabriel Genellina
Softlab SRL 






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


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

Re: Python Projects Continuous Integration

2006-08-07 Thread Fuzzyman

Dave Potts wrote:
> Hi,
>
> I'm just starting a development project in Python having spent time in
> the Java world.  I was wondering what tool advice you could give me
> about setting up a continuous integration environment for the python
> code: get the latest source, run all the tests, package up, produce the
> docs, tag the code repository.  I'm used to things like Maven and
> CruiseControl in the Java world.
>

Hello Dave,

At Resolver Systems we use Cruise Control .NET along with IronPython
and Subversion to provide Source Code Control and continuous
integration. The combination is *great*.

I've never had to configure it (I just poke it occassionally), but it
*looks* like it should be usable with non .NET projects: we have it
running all sorts of batch files and Python scripts as part of the
built and test process.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Cheers,
> 
> Dave.

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


do people really complain about significant whitespace?

2006-08-07 Thread infidel
Where are they-who-hate-us-for-our-whitespace?  Are "they" really that
stupid/petty?  Are "they" really out there at all?  "They" almost sound
like a mythical caste of tasteless heathens that "we" have invented.
It just sounds like so much trivial nitpickery that it's hard to
believe it's as common as we've come to believe.

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


Re: Getting previous file name

2006-08-07 Thread Tim Williams
On 7 Aug 2006 13:52:16 -0700, Hitesh <[EMAIL PROTECTED]> wrote:
>
> I have a small script here that goes to inside dir and sorts the file
> by create date. I can return the create date but I don't know how to
> find the name of that file...
> I need file that is not latest but was created before the last file.

I notice that your path is UNC & windows,   if you are running this on
a windows platform only you could let the windows DIR do the work for
you.

>>> import os
>>> i,o,e = os.popen3('dir /O-D /A-D /B')
>>> o.readlines()[1].strip()
'dnscheck.html'

I would put a try:except around the o.readlines()   bit in case
there is only 0 or 1 file in the directory.

Hints:

c:\> dir /?  (enter)

>>> i,o,e = os.popen3('dir /O-D /A-D /B)
>>>o.readlines()
['recover.tbl\n', 'dnscheck.html\n', 'v3changes.txt\n',
'V3todo.txt\n', 'fupdates.pyc\n', 'Auth_db.pyc\n']

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


Re: Python Projects Continuous Integration

2006-08-07 Thread Grig Gheorghiu
Ziga Seilnacht wrote:
> Dave Potts wrote:
> > Hi,
> >
> > I'm just starting a development project in Python having spent time in
> > the Java world.  I was wondering what tool advice you could give me
> > about setting up a continuous integration environment for the python
> > code: get the latest source, run all the tests, package up, produce the
> > docs, tag the code repository.  I'm used to things like Maven and
> > CruiseControl in the Java world.
> >
> > Cheers,
> >
> > Dave.
>
> Buildbot might be what you are looking for:
> http://buildbot.sourceforge.net/
>
> Hope this helps,
> Ziga

+1 for buildbot. It is amazingly flexible and powerful, once you get
past staring at the configuration file and trying to make sense of it.
Here's a blog post I wrote that can help you get started:
.

Hope this helps,

Grig

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


Re: Getting previous file name

2006-08-07 Thread John Machin
Hitesh wrote:
> Hi,
>
> I have a small script here that goes to inside dir and sorts the file
> by create date. I can return the create date but I don't know how to
> find the name of that file...
> I need file that is not latest but was created before the last file.
> Any hints... I am newbiw python dude and still trying to figure out lot
> of 'stuff'..
>
>
> import os, time, sys
> from stat import *

Lose that, and use ".st_ctime" instead of "[ST_CTIME]" below

>
> def walktree(path):

This function name is rather misleading. The function examines only the
entries in the nominated path. If any of those entries are directories,
it doesn't examine their contents.

> test1 = []
> for f in os.listdir(path):
> filename = os.path.join(path, f)

os.listdir() gives you directories etc as well as files. Import
os.path, and add something like this:

if not os.path.isfile(filename):
print "*** Not a file:", repr(filename)
continue

> create_date_sces = os.stat(filename)[ST_CTIME]

Do you mean "secs" rather than "sces"?

> create_date = time.strftime("%Y%m%d%H%M%S",
> time.localtime(create_date_sces))
> print create_date, " ." , f
> test1.append(create_date)

Answer to your main question: change that to
test1.append((create_date, filename))
and see what happens.

> test1.sort()

If there is any chance that multiple files can be created inside 1
second, you have a problem -- even turning on float results by using
os.stat_float_times(True) (and changing "[ST_CTIME]" to ".st_ctime")
doesn't help; the Windows result appears to be no finer than 1 second
granularity. The pywin32 package may provide a solution.

> print test1
> return test1[-2]
>
>
> if __name__ == '__main__':
>   path = 'srv12\\c$\\backup\\my_folder\\'

(1) Use raw strings. (2) You don't need the '\' on the end.
E.g.
path = r'\\srv12\c$\backup\my_folder'

>   prev_file = walktree(path)
>   print "Previous back file is ", prev_file
> 
> 

Cheers,
John

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread Jason
infidel wrote:
> Where are they-who-hate-us-for-our-whitespace?  Are "they" really that
> stupid/petty?  Are "they" really out there at all?  "They" almost sound
> like a mythical caste of tasteless heathens that "we" have invented.
> It just sounds like so much trivial nitpickery that it's hard to
> believe it's as common as we've come to believe.

I have a coworker who dislikes Python for the whitespace.  He likes the
idea that if someone is silly enough to put a whole program on one
line, they can put it back together by following the braces.  He also
likes that the compiler can compile the program even if a normal person
can't read it.

I've pointed out that we format our code with the whitespace anyway.
He points out that if some code gets accidentally dedented, it is
difficult for another programmer to determine which lines were supposed
to be in the indented block.  I pointed out that if someone
accidentally moves a curly brace, the same problem can occur.
Anecdotally, I've never had either problem.

Sadly, people who do dislike the whitespace do exist.  I have also
talked with several other programmers who were very turned off about
the white-space thing and wouldn't give the language a chance.

Eric S. Raymond wrote enthusiastically about Python, but was initially
turned off by the whitespace rules.  (See
"http://www.python.org/about/success/esr/"; for details.)

I personally love that my logically formatted code imparts information
logically to the language.

(I haven't seen a good hate-us-for-our-whitespace thread go on for
awhile.  I do remember some good "We like Python, Now Add Our Favorite
C/C++/LISP/INTERCAL Features or We'll Leave" threads on this newsgroup.)

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread crystalattice
infidel wrote:
> Where are they-who-hate-us-for-our-whitespace?  Are "they" really that
> stupid/petty?  Are "they" really out there at all?  "They" almost sound
> like a mythical caste of tasteless heathens that "we" have invented.
> It just sounds like so much trivial nitpickery that it's hard to
> believe it's as common as we've come to believe.

Actually, some of the guys I work with complained about Python when
they first had to learn it for our Zope server.  One of them is an
old-school Unix guy who spent the last 20+ years doing procedural
languages with funky syntax, like C.  The other one is a VB.NET junkie
who I don't think has much experience outside of MS languages, except
maybe Java.

One of the complaints they had for the first few weeks was the white
space issue and the fact Python doesn't have brackets or semicolons.
Obviously they learned to "deal with it" but they sure made it seem
like it was a painful transition.  I think the biggest pain was the
fact that they are forced to indent their code now so they can't be
lazy anymore.

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


Class attributes, instances and metaclass __getattribute__

2006-08-07 Thread Pedro Werneck

Hi all


I noticed something strange here while explaining decorators to someone.
Not any real use code, but I think it's worth mentioning. 

When I access a class attribute, on a class with a custom metaclass with
a __getattribute__ method, the method is used when acessing some
attribute directly with the class object, but not when you do it from
the instance.


>>> class M(type):
... def __getattribute__(cls, attr):
... print cls, attr
... return type.__getattribute__(cls, attr)
... 
>>> class C(object):
... __metaclass__ = M
... 
>>> C.x = 'foo'
>>> C.x
 x
'foo'
>>> o = C()
>>> o.x
'foo'
>>> 



Someone at freenode #python channel involved with python-dev sprint
suggested it might be a bug, worth mentioning... to me it seems like a
decision to avoid some problems with method and descriptors creation,
since someone using metaclasses and custom __getattribute__ at the same
time is asking for trouble, but... I googled for it and tried to find
something on the list but, nothing. From the source it seems like a
generic wrapper is used. What's the real case here ? 


Regards,

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread John Machin

infidel wrote:
> Where are they-who-hate-us-for-our-whitespace?  Are "they" really that
> stupid/petty?  Are "they" really out there at all?  "They" almost sound
> like a mythical caste of tasteless heathens that "we" have invented.

All societies demonise outsiders to some extent. It's an unfortunate
human (and animal) trait. In some societies, this is directed from the
top. Very fortunately, this is AFAICT not the case in the Python
community.

> It just sounds like so much trivial nitpickery that it's hard to
> believe it's as common as we've come to believe.

So just block your ears when the propaganda vans with the loud-speakers
on top drive past your dwelling :-)

...

However, meaninglessly significant whitespace at the *other* end of a
line can be annoying:

#>>> a = \
... 1
#>>> a
1
#>>> b = \
  File "", line 1
b = \
 ^
SyntaxError: invalid token

Huh? Can't see what the problem is? Maybe this exaggerated example may
help:

#>>> c = \
  File "", line 1
c = \
  ^
SyntaxError: invalid token

Cheers,
John

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread bearophileHUGS
Jason wrote:
> He points out that if some code gets accidentally dedented, it is
> difficult for another programmer to determine which lines were supposed
> to be in the indented block.  I pointed out that if someone
> accidentally moves a curly brace, the same problem can occur.

I like significant whitespace, but a forum, newsgroup manager (like
Google Groups in the beginning), email management program, blog comment
system, etc, may strip leading whitespace, and it usually doesn't
"move" braces. A language (like Python) doesn't exist alone in vacuum,
it exists in an ecosystem of many other programs/systems, and if they
don't manage leading whitespace well, such language may have some
problems :-)

Bye,
bearophile

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


Re: A problem from a Vim user

2006-08-07 Thread Luis Armendariz
manuhack wrote:
> When I use raw_input('Please type something.\n') in the python 2.4
> command line windows, it doesn't have any problem.  However, when I run
> the same command in vim 7 as :py raw_input('Please type something.\n'),
> there is an EOFError: EOF when reading a line.  Is there a way to use
> that command within vim without raising errors?
> 
> Thanks a lot.
> 

You should read :help python-input

On my version (Vim 7.0.17), it says that input() and raw_input() are
not yet supported.

So, submit a patch to the vim folks!

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


Re: Subtyping a non-builtin type in C/C++

2006-08-07 Thread johan2sson
Martin v. Löwis wrote:
> [EMAIL PROTECTED] schrieb:
> > I am trying to create a subclass of a python class, defined in python,
> > in C++, but I am having some problems.
>
> Is the base class a classic class or a new-style class? Depending on
> the answer, the code you should write varies significantly.
>
> To create a new type, it might be easiest to do the same as the
> interpreter. Take, for example, a look at the code that gets executed
> for new.classobj("Foo", (), {}).

I deleted my post once I realized that I had been setting tp_bases when
I should have been setting tp_base. As it turns out, that's not the end
of my problems.

I have looked in classobject.c, which I hope is the code you are
referring to, but that doesn't really solve my problem since it assumes
you have the correct base pointers and if I did I would be having a
different problem! Anyway, back to the current one:

The class I am trying to subclass is code.InteractiveConsole. With
tp_base set to the result of
PyMapping_GetItemString(PyModule_GetDict(code_module),
"InteractiveConsole"), PyType_Ready fails with an AttributeError with a
"value" of "mro" and looking at the structure in a debugger just before
the call to PyType_Ready makes me think it's corrupted somehow
(nonprintable name and clearly uninitialized fields).

I can however create an instance by calling PyObject_CallFunction on
that object. If I do, it's type (ob_type->tp_name) will be "instance".
Of course, I don't know the python type system that well, but I must
confess I was expecting it to be "code.InteractiveConsole". What gives?

If I then lookup the __class__ attribute of that instance I am back
full circle at the object with the unprintable name and garbage fields.
The head does seem to be valid and if it means anything to someone it's
ob_type->tp_name is "classobj". For several hours I actually wondered
why it wasn't "Type" but I guess it's just a ... subtype of Type.

I guess I should just go to bed.

Johan

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


singleton decorator

2006-08-07 Thread Andre Meyer
While looking for an elegant implementation of the singleton design pattern I came across the decorator as described in PEP318.Unfortunately, the following does not work, because decorators only work on functions or methods, but not on classes.
def singleton(cls):instances = {}def getinstance():if cls not in instances:instances[cls] = cls()
return instances[cls]return getinstance@singletonclass MyClass:...Am I missing something here? What is the preferred pythonic way of implementing singleton elegantly?Thanks for your help
André
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: singleton decorator

2006-08-07 Thread Farshid Lashkari
Andre Meyer wrote:
> Am I missing something here? What is the preferred pythonic way of 
> implementing singleton elegantly?

The "Open Issues" section of that PEP says the following:

"It's exceedingly unlikely that class decorators will be in Python 2.4"

So it might not be in the current version of python.

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread Ben Finney
"infidel" <[EMAIL PROTECTED]> writes:

> It just sounds like so much trivial nitpickery that it's hard to
> believe it's as common as we've come to believe.

As others have pointed out, these people really do exist, and they
each believe their preconception -- that significant whitespace is
intrinsically wrong -- is valid, and automatically makes Python a
lesser language.

One of the most stupid language-definition decisions that most people
have come across is the Makefile format. If you're not familiar with
it, spaces and tabs are *each* significant. Specifically, putting
spaces where a tab is required will result in a file that, while it
may be visually identical to a correctly formatted file, doesn't parse
correctly. In hindsight it's trivial to predict the needlessly painful
learning process that ensues.

This is a very painful memory for many programmers, and the general
opinion that results is "syntactically significant whitespace is
bad". This is the phrase that always gets brought out, and it's often
clear that the person hasn't considered *why* it's bad.

The issue with the Makefile format (lampooned wonderfully by the
Whitespace programming language) is that *invisible* differences in
whitespace should not be significant. In a Makefile, you *must* mix
spaces and tabs in the same file; this leaves the door wide open to
invisible differences. In Python, an admonishment of "always indent
each file consistently" suffices.

Hope that goes some way to explaining one possible reason why rational
people can consistently react in horror to the issue.

-- 
 \  "Friendship is born at that moment when one person says to |
  `\  another, 'What! You too? I thought I was the only one!'"  -- |
_o__)   C.S. Lewis |
Ben Finney

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread Jason
[EMAIL PROTECTED] wrote:
> Jason wrote:
> > He points out that if some code gets accidentally dedented, it is
> > difficult for another programmer to determine which lines were supposed
> > to be in the indented block.  I pointed out that if someone
> > accidentally moves a curly brace, the same problem can occur.
>
> I like significant whitespace, but a forum, newsgroup manager (like
> Google Groups in the beginning), email management program, blog comment
> system, etc, may strip leading whitespace, and it usually doesn't
> "move" braces. A language (like Python) doesn't exist alone in vacuum,
> it exists in an ecosystem of many other programs/systems, and if they
> don't manage leading whitespace well, such language may have some
> problems :-)
>
> Bye,
> bearophile

Certainly, you are correct.  Most of the time, I zip up any source code
for email purposes.  But newsgroup managers are certainly an issue.
For comment thingies online, the preformat tag is your friend, too.

It is annoying that certain communication channels do not respect
white-space.  I dislike using braces because I have to indicate my
intentions twice: once for the compiler and once for humans.

In the situations where I use Python, though, I haven't had a problem.
In the situations where my coworker is using Python (code updates
through CVS), he also shouldn't have a problem.

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


Re: singleton decorator

2006-08-07 Thread bearophileHUGS
Andre Meyer:
> What is the preferred pythonic way of implementing singleton elegantly?

Maybe to just use a module.

Bye,
bearophile

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


python - HTML processing - need tips

2006-08-07 Thread wipit
I need to process a HTML form in python. I'm using urllib2 and
HTMLParser to handle the html. There are several steps I need to take
to get to the specific page on the relevant site the first of which is
to log in with a username/password. The html code that processes the
login consists of 2 edit boxes (for User ID and Password) and a Submit
button which uses ASP.net client side validation as follows (formatted
for clarity):


User ID:


Valid Email
format is required



Password:


 


 

 


I've looked at all the relevant posts on this topic and already looked
at mechanize and ClientForm. It appears I can't use those for 2
reasons: 1) that they can't handle client side validation and 2) this
button doesn't actually reside in a form and I haven't been able to
find any python code that obtains a handle to a submit control and
simulates clicking on it.

I've tried sending the server a POST message as such:

loginParams = urllib.urlencode({'txtUserName': theUsername,
'txtUserPass': thePassword})
txdata = None
txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5;
Windows NT)'}
req = Request(url1, txdata, txheaders)# url1 points to the secure
page seen following login
handle = urlopen(req, loginParams)

But this doesn't work. I dont understand the use of
Page_ClientValidate( ) and haven't really found any useful
documentation on it for my purposes. I basically need to be able to
submit this information to the site, by simulating the onclick event
through python. As far as I understand I need a solution to the 2
points I mentioned above (getting past client-side validation and
simulating a click of a non-form button). Any help on this (or other
issues I might have missed but are important/relevant) would be great!

Many thanks,
Pythonner

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


Re: do people really complain about significant whitespace?

2006-08-07 Thread bearophileHUGS
Jason wrote:
> But newsgroup managers are certainly an issue.
> For comment thingies online, the preformat tag is your friend, too.

Time ago I used to add a | or something similar at the beginning of
lines, to avoid the leading whitespace stripping done by Google Groups.
Other (silly) solutions are to add explicitely the number of indents at
the beginning of a line (2 digits suffice), or to even add explicit
#end comments just under the dedents, so a script can read such ending
comments and reconstruct the original Python indentations... (lines
splitted with \ and similar require some extra care).

Bye,
bearophile

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


  1   2   >