Re: Random passwords generation (Python vs Perl) =)

2007-01-31 Thread Gabriel Genellina
En Wed, 31 Jan 2007 01:08:28 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribió:

> raw_input can do the job of print
> while 1: raw_input(__import__('os').urandom(6).encode('base64'))
>
> And can anyone explain why this is so?
 while 1: input(__import__('os').urandom(6).encode('base64'))
> ^
> SyntaxError: unexpected EOF while parsing

input and raw_input are not the same, see the docs.

-- 
Gabriel Genellina

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


Re: Unicode error handler

2007-01-31 Thread Gabriel Genellina
En Wed, 31 Jan 2007 01:21:49 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribió:

> I don't understand what %r and r are and where they are from. The man
> 3 printf page doesn't have %r formatting.

Perhaps you should look into the Python docs instead?

-- 
Gabriel Genellina

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


Can't install Turbogears (with pysqlite) on Windows

2007-01-31 Thread Thomas
Hi there!

Installing TurboGears out-of-the-box (egg-based) on Windows doesn't
work because I can't
compile the extensions needed for the required pysqlite (also egg-
based):

Installed c:\programme\python24\lib\site-packages\turbogears-1.0.1-
py2.4.egg
Processing dependencies for TurboGears[standard,testtools]>=1.0
Searching for pysqlite
Reading http://www.python.org/pypi/pysqlite/
Reading http://pysqlite.org/
Reading http://www.python.org/pypi/pysqlite/2.3.3
Best match: pysqlite 2.3.3
Downloading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/
pysqlite-2.3.3.tar.gz
Processing pysqlite-2.3.3.tar.gz
Running pysqlite-2.3.3\setup.py -q bdist_egg --dist-dir c:\temp
\easy_install-ovrxv0\pysqlite-2.3.3\egg-dist-tmp-0ynhfx
warning: no files found matching 'doc\*.html'
error: Setup script exited with error: Python was built with version
7.1 of Visual Studio, and extensions need to be built with the same
version of the compiler, but it isn't installed.

To get away without the need to compile the pysqltite extensions I
tried  to install the Windows-binary package of pysqlite manually
before installing TG this also doesn't work, because easy_install
doesn't know anything of my fresh installed pysqlite and tries to
install the egg from cheeseshop (with the above error . . .).

Any suggestions to get beyond this?
Is it possible to "tweak" the TG egg-installation so that it won't try
to "easy_install pysqlite"?
For the application I'm intending to build with TurboGears I don't
even need pysqlite :(

Thomas

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


Re: Random passwords generation (Python vs Perl) =)

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

> And can anyone explain why this is so?
 while 1: input(__import__('os').urandom(6).encode('base64'))
> ...
> BgiWdv//
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 0
> 
> ^
> SyntaxError: unexpected EOF while parsing

It's `input()` that expects a valid Python expression.  An empty one
doesn't work, it has to evaluate to something.

In [2]: input()


   File "", line 0

 ^
SyntaxError: unexpected EOF while parsing

Ciao,
Marc 'BlackJack' Rintsch

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


Re: Resizing widgets in text windows

2007-01-31 Thread Eric Brunel
On Tue, 30 Jan 2007 23:13:07 +0100, <[EMAIL PROTECTED]> wrote:
> I'm using a text widget to hold a set of plots, one plot per line,
> such that the scrolling capability of the text widget can be taken
> advantage of to display only a subset of the plots at any given time.
> In the analyses my program automates, there are at least several plots
> are typically loaded into the text widget. This works out splendidly,
> but the width of the plots has thus far been a static thing. Now, I'll
> be able to adjust the plots widths so that when the owner window is
> resized, the width of each plot in the text widget is adjusted and the
> plot continues to occupy the entire text widget but no more, making
> for a much more professional looking product.

IMHO, "abusing" the text widget to do that is quite likely to cause  
problems in the future. For this use case, I would have used a Canvas with  
scrollbars containing a Frame where the plots are packed or gridded  
vertically. The Canvas's scrollregion should then be adjusted each time a  
plot is added, removed or resized, and you'd still have to use the  
 event to resize the Frame to the Canvas's width. But at least,  
that's what Canvases and Frames are for; the Text widget is for... well,  
displaying text. Also note that Pmw (http://pmw.sourceforge.net/) has a  
ScrolledFrame megawidget that just does what you want.

> Muchas gracias.

You're welcome.

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


Re: thread and processes with python/GTK

2007-01-31 Thread awalter1
HI,

I launch my application by 'python script.py'
I've already add a sys.stdout.flush with no effect.

if the idle_add is an alternative to thread, where to get details
about its use (no reference in http://www.pygtk.org/docs/pygtk/
index.html, but very brief information in GTK+ documentation)
In my case how to implement the system call 'ps -def' through idle_add

Thanks

On 30 jan, 16:44, Thomas Guettler <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> how do you start the python app? Goes stdout
> to a terminal or a pipe?
>
> "python script.py"
> and "python script.py | cat" behave different.
>
> Maybe "sys.stdout.flush()" helps you.
>
> BTW, I switched from threads to idle_add for pygtk
> applications.
>
>
>
>
>
> awalter1 wrote:
> > Hello,
>
> > I'm developping an application with python, pyGTK and GTK+.
> > I've performed many tests by using methods as Popen, popen2,
> > os.system ... to communicate with Unix (HPUX),
> > The last attempt is this code written in a thread :
> >fin,fout = popen2.popen2('ps -def')
> >line = fin.readline()
> >while 1 :
> >if not line : break
> >print "line=",line
> >line = fin.readline()
> >fin.close()
> > In that case, lines are printed only when I exit my application.
> > Usually the behavior is not as expected and I cannot understand why. I
> > am wondering that it could be a constraint from the use of GTK
> > (mainloop() existence ???).
> > Is somebody aware about conflict between GTK use and unix mechanism.
>
> > Thanks for you help
>
> --
> Thomas Güttler,http://www.thomas-guettler.de/http://www.tbz-pariv.de/
> E-Mail: guettli (*) thomas-guettler + de
> Spam Catcher: [EMAIL PROTECTED] Masquer le texte des messages précédents -
>
> - Afficher le texte des messages précédents -


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


Re: Find and replace in a file with regular expression

2007-01-31 Thread Wolfgang Grafen
Just in case you didn't think about it there is a plain replace method for 
strings

How to quick-search this method with 'dir'
 >>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', 
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 
'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 
'title', 'translate', 'upper', 'zfill']

 >>> help("".replace)
Help on built-in function replace:

replace(...)
 S.replace (old, new[, maxsplit]) -> string

 Return a copy of string S with all occurrences of substring
 old replaced by new.  If the optional argument maxsplit is
 given, only the first maxsplit occurrences are replaced.

and now how to apply it:
new_text = open(fileName).read().replace("SOURCE", "REPLACE")

which is the preferred method for a simple task like this.

TOXiC wrote:
> Hi everyone,
> First I say that I serched and tryed everything but I cannot figure 
> out how I can do it.
> I want to open a a file (not necessary a txt) and find and replace a 
> string.
> I can do it with:
> 
> import fileinput, string, sys
> fileQuery = "Text.txt"
> sourceText = '''SOURCE'''
> replaceText = '''REPLACE'''
> def replace(fileName, sourceText, replaceText):

Now how to solve it with a simple regular expression:

 >>> import re
 >>> re_replace = re.compile("SOURCE").sub
 >>>
 >>> txt = "   SOURCE   SOURCE \n   SOURCE  "
 >>>
 >>> print re_replace("REPLACE", txt)
'   REPLACE   REPLACE \n   REPLACE  '
 >>> new_text = re_replace("REPLACE", open(fileName).read())

A regular expression for this task is kind of overkill. Mastering
regular expression is the efford very worth.

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


Retrieve keywords a internet domain name

2007-01-31 Thread Andy Wu
Hi All,

I've been working on a domain parking project where we need to analyze
a domain name, say "bookhotel", and get keywords(book, hotel) out of
it, then use these keywords to do some search.

There are two ways to do this as far as I can see, longest match and
quickest match.
Longest match:
bookhotel -> check with a dictionary -> False
bookhote -> dictionary -> False
...
book -> dictionary -> True, kw1 = book
then try the rest of the domain name
hotel -> dictionary -> True, kw2 = hotel

While quickest match starts with 'b'.

The keywords sure will not be perfect, but I think these two will work
for us at the moment.

Any comments/suggestions on this?

Also, does anyone know where I can find a decent dictionary that I can
use to verify if a word is a valid English word?

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


Re: Unicode error handler

2007-01-31 Thread Walter Dörwald
Martin v. Löwis wrote:

> Walter Dörwald schrieb:
>> You might try the following:
>>
>> # -*- coding: iso-8859-1 -*-
>>
>> import unicodedata, codecs
>>
>> def transliterate(exc):
>>  if not isinstance(exc, UnicodeEncodeError):
>>  raise TypeError("don'ty know how to handle %r" % r)
>>  return (unicodedata.normalize("NFD", exc.object[exc.start])[:1],
>> exc.start+1)
> 
> I think a number of special cases need to be studied here.
> I would expect that this is "semantically correct" if the characters
> being dropped are combining characters (at least in the languages I'm
> familiar with, it is common to drop them for transliteration).

True, it might make sense to limit the error handler to handling latin 
characters.

> However, if you do
> 
> py> for i in range(65536):
> ...   c = unicodedata.normalize("NFD", unichr(i))
> ...   for c2 in c[1:]:
> ... if not unicodedata.combining(c2): print hex(i),;break
> 
> you'll see that there are many characters which don't decompose
> into a base character + sequence of combining characters. In
> particular, this involves all hangul syllables (U+AC00..U+D7A3),
> for which it is just incorrect to drop the "jungseongs"
> (is that proper wording?).

Of course the above error handler only makes sense, when the decomposed 
codepoints are encodable in the target encoding. For your hangul example 
neither u"\ac00" nor the decomposed version u"\u1100\u1161" er encodable.

> There are also some cases which I'm completely uncertain about,
> e.g. ORIYA VOWEL SIGN AI decomposes to ORIYA VOWEL SIGN E +
> ORIYA AI LENGTH MARK. Is it correct to drop the length mark?
> It's not listed as a combining character. Likewise,
> MYANMAR LETTER UU decomposes to MYANMAR LETTER U +
> MYANMAR VOWEL SIGN II; same question here.

Servus,
Walter

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


Re: parent-child object design question

2007-01-31 Thread Ben Finney
"Steven D'Aprano" <[EMAIL PROTECTED]> writes:

> > def _accumulate_properties(self, properties):
> > self.properties = []
>
> Probably better to put that in the __init__ method, otherwise if
> somebody runs instance._accumulate_properties(...) again, it will
> have the side-effect of throwing away whatever was already in
> instance.properties.

That's the point of naming it with a leading underscore. You've
already explained that this is convention for "Private, don't use".

> Some people might argue that if someone runs a private method like
> _accumulate_properties, they deserve whatever bad things happen to
> them.  But I say, well, sure, but why *design* your method to break
> things when called twice?

Exactly the same could be said for calling the __init__ method twice.

> Who knows, maybe you'll decide you want to call it twice yourself.

Right. In which case, it's good that it's already in a separate,
clearly-named, single-purpose method.

Make the code easy to understand, not idiot-proof.

-- 
 \  "One time a cop pulled me over for running a stop sign. He |
  `\said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__) don't believe everything I read.'"  -- Steven Wright |
Ben Finney

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


Re: data design

2007-01-31 Thread skam
On Jan 30, 8:06 pm, "Paddy" <[EMAIL PROTECTED]> wrote:
>
> Google for YAML and JSON formats too
>

YAML and JSON are good when used as data-interchange format, not as
configuration files.
These formats are too complex for non-programmers, so they will ask
aid for every editing ;)

I suggest ini-like files, parsed using ConfigParser, but you should
have a look to ConfigObj that has got automatic type conversion and
other interesting features

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


Re: BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job

2007-01-31 Thread bryan rasmussen
I think he meant that the body of Thermate was found among WTC
physical samples, the conclusion is that Thermate was responsible for
collapsing the WTC. The further conclusion is that Thermate is or was
in possession of time travel technology, he has obviously recently
gone back in time to attack the WTC and been killed. This would
explain why trolling duties have been recently taken up by
[EMAIL PROTECTED] on this list.

Cheers,
Bryan Rasmussen

On 1/31/07, soutjhyDin <[EMAIL PROTECTED]> wrote:
>
> <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > http://portland.indymedia.org/en/2006/06/341238.shtml
> >
> > BYU Physics Prof Finds Thermate in WTC Physical Samples, Building
> > Collapses an Inside Job
> > author: Jacob Hamblin
> > Based on chemical analysis of WTC structural steel residue, a Brigham
> > Young University physics professor has identified the material as
> > Thermate. Thermate is the controlled demolition explosive thermite
> > plus sulfur.
>
> WRONG!  you must make this stuff up as you go along.
>
> Thermate and thermite have nothing to do with "controlled demolition",
> moron.
>
> What is the prime ingredient of both?  Rust.
>
> The Iron Oxide(s), dummy.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieve keywords a internet domain name

2007-01-31 Thread Létező
> Also, does anyone know where I can find a decent dictionary that I can
> use to verify if a word is a valid English word?

Debian packages such as openoffice, ispell, aspell may contain a word list. 
You can search google for +english +"word list" or something similar.

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


Re: Web File System

2007-01-31 Thread Toby A Inkster
anthony.cutrone wrote:

> Files and folders have to be in an SQL database, mounted in ext3-like 
> system. File would be identified by a single ID, and links with names 
> should be connected on these IDs.

Take a look at FUSE.

Also, have you considered subversion?

-- 
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data design

2007-01-31 Thread Imbaud Pierre
James Stroud a écrit :
> Szabolcs Nagy wrote:
> 
>>> Hurray for yaml! A perfect fit for my need! And a swell tool!
>>> Thanks a lot!
>>
>>
>>
>> i warn you against yaml
I feel both thanful, and sorry, for your warning. And not convinced
yet, but Ill be cautious.
>> it looks nice, but the underlying format is imho too complex (just 
>> look at their spec.)
complex indeed, but real powerful.
Is it not true that: if I used yaml, sticking to what .ini allows,
yaml files would be simple?
>>
>> you said you don't want python source because that's too complex for 
>> the users.
>> i must say that yaml is not easier to use than python data structures.

Easier to read and write, U must agree.
Surround strings with quotes is a python requirement, to distinguish
them from identifiers. This only makes data input for python somewhat
clumsy.
Granted, its a new format to learn. But sharing this format with a
much wider community than python, aint this worth the effort?
(well, if yaml succeeds and spreads...)
>>
>> if you want userfriedly config files then ConfigParser is the way to go.
Granted. for END users. I rather target administrators, programmers,
integrators: make customization an easy process, and allowing this
customization to go much farther than changing simple values, aint
this the REAL challenge for new applications?
>>
>> if you want somthing really simple and fast then i'd recommend s-
>> expressions of lisp
lisp is more powerful than python. its syntax deterred many
programmers, who adopted python, it will deter my targeted
"customizers". And the process to translate to python structure, I
have no idea. involves a python or lisp translater...
>>
>> also here is an identation based xml-like tree/hierarchical data 
>> structure syntax:
>> http://www.scottsweeney.com/projects/slip/
Pretty nice, too! James, have a look at this!
>>
> 
> I've been spending the last 2 days weighing ConfigParser and yaml, with 
> much thought and re-organizing of each file type. The underlying 
> difference is that, conceptually, ini files are an absurdly limited 
> subset of yaml in that ini files are basically limited to a map of a map.
U have a point here.
> 
> For instance, I have a copy_files section of a configuration. In order 
> to know what goes with what you have to resort to gymnastics with the 
> option names
> 
> [copy_files]
> files_dir1 = this.file that.file
> path_dir1 = /some/path
> 
> files_dir2 = the_other.file yet_another.file
> path_dir2 = /some/other/path
> 
> In yaml, it might look thus.
> 
> copy_files :
>  - files : [this.file, that.file]
>path  : /some/path
>  - files : [the_other.file, yet_another.file]
>path  : /some/other/path
> 
> Both are readable (though I like equals signs in appearance over 
> colons), but yaml doesn't require a lot of string processing to group 
> the files with the paths. I don't even want to think the coding 
> gymnastics required to split all of the option names and then group 
> those with common suffixes.
> 
> Now if the config file were for copying only, ini would be okay, because 
> one could just have sections that group paths and dirs:
> 
> [dir1]
> files = this.file, that.file
> path = /some/path
> 
> [dir2]
> ...
> 
> But if you need different kinds of sections, you have outgrown ini.
> 
> In essence, ini is limited to a single dictionary of dictionaries while 
> yama can express pretty much arbitrary complexity.
James, this single formula makes things real clear.
As we both work on the subject, maybe we could continue to exchange
ideas, and information?
Have a look at the link Szabolcs Nagy <[EMAIL PROTECTED]> gives:
http://www.scottsweeney.com/projects/slip/
Ill further dig yaml, with 2 questions:
- how do I translate to python?
- how do I express and/or enforce rules the data should follow?
   (avoid the classic: configuration data error raise some obscure
   exception).

Big thanks to Szabolcs Nagy (hungarian, my friend? I love this
country), although I seem to disagree, your statements are pretty
clear and helpful, and... maybe U are right, and I am a fool...
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


Help needed on config files

2007-01-31 Thread jvdb
Hi there,

I am quite new on python programming and need some help on solving my
problem..

I have to make a (python) program which deletes files from
directories. I don't think deleting, etc. is the problem. The problem
is that the directories where i have to delete them are 'dynamic'/
subject to change. So what i thought is to make a config file
containing an identifier (useful for myself) and there the directory.
something like:
[PROJECTx]

[PROJECTy]


I have already seen that there are sorts of modules where you can read
a config file, but only when you know the key.. Can someone help me
out on this? The configfile can be altered in time (as there are more
projects coming where i have to delete files on a scheduled basis).

This is a good learning project for me, but i really don't see how to
solve this.

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


Re: Help me understand this

2007-01-31 Thread Christophe
James Stroud a écrit :
> Beej wrote:
> (2).__add__(1)
> 
> Nice. I would have never thought to put parentheses around an integer to 
> get at its attributes.
> 
> James

You can also do it like that :

 >>> 2 .__add__(1)
3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: data design

2007-01-31 Thread BJörn Lindqvist
On 1/31/07, James Stroud <[EMAIL PROTECTED]> wrote:
> [copy_files]
> files_dir1 = this.file that.file
> path_dir1 = /some/path
>
> files_dir2 = the_other.file yet_another.file
> path_dir2 = /some/other/path
>
> In yaml, it might look thus.
>
> copy_files :
>   - files : [this.file, that.file]
> path  : /some/path
>   - files : [the_other.file, yet_another.file]
> path  : /some/other/path
>
> Both are readable (though I like equals signs in appearance over
> colons), but yaml doesn't require a lot of string processing to group
> the files with the paths. I don't even want to think the coding
> gymnastics required to split all of the option names and then group
> those with common suffixes.

But is not that a perfect world example? Consider:

[copy_files]
files_dir1=this.file that.file
path_dir1=/some/path
files_dir2=the_other.file yet_another.file
path_dir2=/some/other/path

versus:

copy_files:
-files:[this.file,that.file]
path:/some/path
-files:[the_other.file,yet_another.file]
path:/some/other/path

Mandatory indentation is good in programming languages, but does it
really belong in configuration files? With tabs verboten to boot.

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


Re: Executing Javascript, then reading value

2007-01-31 Thread skip

Melih> In fact what you're describing is exactly what I needed. I ended
Melih> up finding a way to execute the javascript using Rhino and then
Melih> capturing the result. Not exactly what I wanted to do, but once I
Melih> found it out, it works.

There is an embeddable C implementation as well: SpiderMonkey.  It has both
a core engine and a standalone app.  There also appears to a an unmaintained
Python interface: python-spidermonkey.  Relevant URLs:

http://www.mozilla.org/js/spidermonkey/
http://cheeseshop.python.org/pypi/python-spidermonkey/

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


Re: data design

2007-01-31 Thread James Stroud
BJörn Lindqvist wrote:
> On 1/31/07, James Stroud <[EMAIL PROTECTED]> wrote:
>> [copy_files]
>> files_dir1 = this.file that.file
>> path_dir1 = /some/path
>>
>> files_dir2 = the_other.file yet_another.file
>> path_dir2 = /some/other/path
>>
>> In yaml, it might look thus.
>>
>> copy_files :
>>   - files : [this.file, that.file]
>> path  : /some/path
>>   - files : [the_other.file, yet_another.file]
>> path  : /some/other/path
>>
>> Both are readable (though I like equals signs in appearance over
>> colons), but yaml doesn't require a lot of string processing to group
>> the files with the paths. I don't even want to think the coding
>> gymnastics required to split all of the option names and then group
>> those with common suffixes.
> 
> But is not that a perfect world example? Consider:
> 
> [copy_files]
> files_dir1=this.file that.file
> path_dir1=/some/path
> files_dir2=the_other.file yet_another.file
> path_dir2=/some/other/path
> 
> versus:
> 
> copy_files:
> -files:[this.file,that.file]
> path:/some/path
> -files:[the_other.file,yet_another.file]
> path:/some/other/path
> 
> Mandatory indentation is good in programming languages, but does it
> really belong in configuration files? With tabs verboten to boot.
> 

I'm not sure whether to agree with you or disagree with you. My 
conclusion is that if it is at all possible, try to use an ini file, 
even if you have to stretch your imagination a bit. More complex formats 
are prone to one's assigning some imperative meaning to the structure 
(as I am doing with my example, which might make it a bad one). However, 
these more complex formats can intensely useful for (1) knowledgeable 
people with (2) complicated data.
-- 
http://mail.python.org/mailman/listinfo/python-list


another newbie question: why should you use "*args" ?

2007-01-31 Thread stef

why should I use *args,
as in my ignorance,
making use of a list (or tupple) works just as well,
and is more flexible in it's calling.
So the simple conclusion might be: never use "*args",
or am I overlooking something ?

# method 1
def execute (self, *args):
for i in range ( len(args) ):
... do something

# method 2
def chunk_plot(self, list):
for i in range ( len(list) ):
  do something


# calling method 1:
execute (S[0], S[4] )

# calling method 2:
execute ( ( S[0], S[4] ) )

# or *the extra flexibility)
mylist = ( S[0], S[4] )
execute ( mylist )


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


Regex with ASCII and non-ASCII chars

2007-01-31 Thread TOXiC
Hello everybody.
How I can do a regex match in a string with ascii and non ascii chars
for example:

regex = re.compile(r"(ÿÿ‹ð…öÂty)", re.IGNORECASE)
match = regex.search("ÿÿ‹ð…öÂty")
if match:
result = match.group()
print result
else:
result = "No match found"
print result

it return "no match found" even if the two string are equal.
Help me please!
Thx in advance :)

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

Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread Diez B. Roggisch
stef wrote:

> 
> why should I use *args,
> as in my ignorance,
> making use of a list (or tupple) works just as well,
> and is more flexible in it's calling.
> So the simple conclusion might be: never use "*args",
> or am I overlooking something ?

Yup. For example decorators, that wrap functions. If you do that, you want
to return a function that captures all passed arguments, does something,
and then invokes the original function with the original arguments. Like
this:


def logging_decorator(f):
def _f(*args, **kwargs):
print "calling %r with (%r, %r)", % (f, args, kwargs)
return f(*args, **kwargs)

return _f


@logging_decorator
def im_just_a_function(some, argument, and, other=None):
pass




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


Re: BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job

2007-01-31 Thread John McCallum
On Tue, 30 Jan 2007 19:48:45 -0600, soutjhyDin wrote:

> <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> http://portland.indymedia.org/en/2006/06/341238.shtml
>>
>> BYU Physics Prof Finds Thermate in WTC Physical Samples, Building
>> Collapses an Inside Job
> 
> [...]
> 
> The Iron Oxide(s), dummy.

This is way off topic in most of the groups it has been posted to.
Please restrict replies to the only one that seems remotely relevant:

soc.culture.usa

We can just plonk the original author, and I'm sure most have, but when
others reply we need to plonk them too. It's just more effort. ;)

Cheers,
John McCallum
Edinburgh

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


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread Bruno Desthuilliers
stef a écrit :
> 
> why should I use *args,
> as in my ignorance,
> making use of a list (or tupple) works just as well,
> and is more flexible in it's calling.

Err... How so ?

> So the simple conclusion might be: never use "*args",
> or am I overlooking something ?

Try writing generic higher order functions without it, and let us know.

dummy example:

def trace(func, *args, **kw):
   print "calling %s with %s %s" % (func.__name__, str(args), kw)
   try:
 result = func(*args, **kw)
 print "got %s" % str(result)
 return result
   except Exception, e:
 print "raised : %s" % e
 raise

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


Re: Sorting a List of Lists

2007-01-31 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> I can't seem to get this nailed down and I thought I'd toss it out 
> there as, by gosh, its got to be something simple I'm missing.
> 
> I have two different database tables of events that use different 
> schemas. I am using python to collate these records for display. I do 
> this by creating a list of lists that look roughly like this:
> 
> events = [['Event URL as String', 'Event Title as String ', Event Date 
> as Datetime], ...]

Then you should not use a list of lists, but a list of tuples.

> I then thought I'd just go events.sort(lambda x,y: x[2] it a day. That didn't work. But then lamda functions like to be very 
> simple, maybe object subscripts aren't allowed (even though I didn't 
> get an error). So I wrote a comparison function that looks much as you 
> would expect:
> 
> def date_compare(list1, 
> list2):
> x = list1[2]
> y = list2[2]
> if 
> x>y:
> return 
> 1
> elif 
> x==y:
> return 
> 0
> else: # 
> x return -1
> 
> But as before sorting with this function returns None.
> 
> What have I overlooked?

Lol.

I guess this is a FAQ. list.sort() performs a destructive in-place sort, 
and always return None. This is in the FineManual:

[EMAIL PROTECTED]:~$ python
Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> help(list.sort)
Help on method_descriptor:

sort(...)
 L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 cmp(x, y) -> -1, 0, 1

You may want to use sorted(iterable, cmp=None, key=None, reverse=False) 
if you don't want to sort in-place.

Also, using comparison functions is usually not the most efficient way 
to do such a sort. In your case, I'd go for a good old 
Decorate/sort/undecorate (AKA schwarzian transform):

events = [evt for date, evt in
   sorted([(evt[2], evt) for evt in events])]


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


marshal.loads ValueError

2007-01-31 Thread abcd
I have the following code which is sent over the wire as a string...

from time import time
class Foo:
def go(self):
print "Time:", time()


I get this code and store it as, "data"

data = receivePythonSource()

Then I try...

exec marshal.loads(data) in my_module.__dict__

However I get an error saying:
ValueError: invalid literal for __float__: om time import time
class Foo:
def go(self):

almost like when I try to marshal and exec it misses the first two
characters, "fr" ...any ideas?

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


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread Dustan
On Jan 31, 5:41 am, stef <[EMAIL PROTECTED]> wrote:
> why should I use *args,
> as in my ignorance,
> making use of a list (or tupple) works just as well,
> and is more flexible in it's calling.

Others have mentioned the instances in which it's actually useful -
for catch-all arguments. But you also should take into consideration
the aesthetics, since python is supposed to be an aesthetically nice
language.

> So the simple conclusion might be: never use "*args",
> or am I overlooking something ?
>
> # method 1
> def execute (self, *args):
> for i in range ( len(args) ):
> ... do something
>
> # method 2
> def chunk_plot(self, list):
> for i in range ( len(list) ):
>   do something

It's bad practice to use built-ins like 'list' as a regular variable
name.

> # calling method 1:
> execute (S[0], S[4] )
>
> # calling method 2:
> execute ( ( S[0], S[4] ) )

Let's take a look at those side-by-side:
execute (S[0], S[4] )
execute ( ( S[0], S[4] ) )

Now, which one *looks* better?

> # or *the extra flexibility)
> mylist = ( S[0], S[4] )
> execute ( mylist )

Also, take into consideration the opposite end of the pole; you have
your list of arguments (args), and your about to call a function that
was declared something like this:
def someFunction(arg1, arg2, arg3):
  # etc.
Which is clearer?
someFunction(*args)
someFunction(args[0], args[1], args[2])

And if you've got a variable number of arguments, it becomes virtually
impossible to avoid using the *args syntax.

And that doesn't even begin to cover the need for **kargs! (which, if
you haven't noticed, is generally used next to *args)

It turns out that it's not really necessary in a static-typed language
like java (although java 5.0 introduced it); it's the dynamic nature
of python that makes these syntactic sugars necessary. And without
them, function calls can get really ugly.

> thanks,
> Stef Mientki

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


'First class' Relationships

2007-01-31 Thread bearophileHUGS
Currently reading an article, "First Class Relationships in an Object-
oriented Language", by Gavin Bierman and Alisdair Wren:
http://homepages.inf.ed.ac.uk/wadler/fool/program/final/4/4_Paper.pdf

Found in the "Lambda the Ultimate" blog:
http://lambda-the-ultimate.org/node/2013

Maybe it can be done in Python too, with a metaclass "Relationship".
The relation can probably be added dynamically to an object/class.
Some typecheek can be added too, if necessary.

Bye,
bearophile

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


Re: error messages containing unicode

2007-01-31 Thread Jim
Thanks Steve, I appreciate your patience.

On Jan 31, 1:39 am, Steven D'Aprano <[EMAIL PROTECTED]>
wrote:
> If the built-in isn't Unicode aware, subclassing it won't magically make
> it so :-)
Oh, I agree.  If I have a string mesg that is unicode-not-ascii and I
say
  try:
  raise Exception mesg
  except Exception, err:
  print "Trouble"+mesg
then I have problems.   I  however am under the impression, perhaps
mistaken, that the built-in exceptions in the library will return as
error strings only ascii.  (I take as evidence of my understanding
that the built-in exceptions have a __str__() method but do not have
an explicit __unicode__() and so rely on a unicode(err) call being
passed on to __str__().  But as I've said above, I've been wrong so
many times before.  ;-)

My main point about the built-ins is that I want to catch them along
with my own exceptions.  That's what I meant by the next paragraph.
My class myException is a subclass of Exception so I can catch my
stuff and the standard stuff with an all-in-one panic button.
>
> > For instance, I write a lot of CGI and I want to wrap everything in a
> > try .. except.
> >   try:
> >   main()
> >   except Exception, err:
> >   print "Terrible blunder: ",str(err)
> > so that the err can be one of my exceptions, or can be one that came
> > with Python.
> > (And, that I can see, err.args can be either the relevant
> > string or a tuple containing the relevant string and the documentation
> > is silent on whether in the built-in exceptions if err.args is a tuple
> > then the string is guaranteed to be first in the tuple.)
>
> Does it matter? Just print the tuple.
In truth, it does matter.  In that example, for instance, some error
message is passed on to the user and I don't want it to be too bad.
"Database cannot be opened" is better than a "(u'Database cannot be
opened,1)"-type thing.  Besides which, Python is a nice language, and
I'm certain there is a nice way to do this; it is just that I'm having
trouble making it out.

> >> (2) convert the file name to ASCII before you store it; or
>
> > I need the non-ascii information, though, which is why I included it
> > in the error message.
>
> If you have the exception captured in "err", then you can grab it with
> err.where_i_put_the_unicode.
I want a method of grabbing it that is the same as the method used by
the built-ins, for the uniformity reasons that I gave above.   That I
could make out, the documentation was silent on what is the approved
way to grab the string.

> >> (3) add a __str__ method to your exception that is Unicode aware.
>
> > I have two difficulties with this: (1) as above I often raise Python's
> > built-in exceptions and for those __str__() is what it is, and
>
> Then don't use the built-in exception. If it won't do what you want it do
> do, use something else.
I use my exceptions for errors in my logic, etc.  But not being
perfect, sometimes I raise exceptions that I had not anticipated;
these are built-ins.

> > (2) this
> > goes against the meaning of __str__() that I find in the documentation
> > in ref/customization.html which says that the return value must be a
> > string object.
>
> I didn't mean return a unicode object :)
>
> You're absolutely correct. Your __str__ would need to return a string
> object, which means encoding the Unicode correctly to get a string object
> without raising an exception.
>
> e.g. something like this maybe (untested, not thought-through, probably
> won't work correctly, blah blah blah):
>
> def __str__(self):
> s = self.args.encode('ascii', 'replace')
> return "Unicode error converted to plain ASCII:\n" + s
>
> or whatever encoding scheme works for your application.
I did discuss this suggestion from another person above.  That would
mean either (a) throwing away the unicode-not-ascii parts of the error
message (but I want those parts, which is why I put them in there) or
(b) hard-coding the output encoding for error strings in hundreds of
error cases (yes, I have hundreds) or (c) passing as a parameter the
errorEncoding to each function that I write.  That last case doesn't
seem to be to be a likely best practice for such a nice language as
Python; I want a way to get the unicode object and go forward in the
program with that.

> It can take whatever you want it to take:
>
> class MyStupidException(Exception):
> def __init__(self, dayofweek, breakfast="spam and baked beans",
> *everythingelse):
> self.day = dayofweek
> self.breakfast = breakfast
> self.args = everythingelse
> def __str__(self):
> s = "On %s I ate %s and then an error '%s' occurred." % \
> (self.day.title(), self.breakfast, self.args)
> return s
>
> >>> raise MyStupidException('monday', 'cheese', 'bad things', 'happened', 2)
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> __main__.MyStupidException: On Monday I ate cheese and then an error
> '('bad things', 'happened', 2)' occu

Re: Help needed on config files

2007-01-31 Thread Rob Wolfe

jvdb wrote:
> Hi there,
>
> I am quite new on python programming and need some help on solving my
> problem..
>
> I have to make a (python) program which deletes files from
> directories. I don't think deleting, etc. is the problem. The problem
> is that the directories where i have to delete them are 'dynamic'/
> subject to change. So what i thought is to make a config file
> containing an identifier (useful for myself) and there the directory.
> something like:
> [PROJECTx]
> 
> [PROJECTy]
> 

What about this?

# proj.cfg
[PROJECTx]
path=/path/to/dir1
[PROJECTy]
path=/path/to/dir2

# cfg.py
from ConfigParser import ConfigParser
cfg = ConfigParser()
cfg.read("proj.cfg")
for proj in cfg.sections():
path = cfg.items(proj)[0][1]
print "proj: %s, path: %s" % (proj, path)

Is that not enough?

--
HTH,
Rob

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


Re: marshal.loads ValueError

2007-01-31 Thread Benjamin Niemann
Hello,

abcd wrote:

> I have the following code which is sent over the wire as a string...
> 
> from time import time
> class Foo:
> def go(self):
> print "Time:", time()
> 
> 
> I get this code and store it as, "data"
> 
> data = receivePythonSource()
> 
> Then I try...
> 
> exec marshal.loads(data) in my_module.__dict__
> 
> However I get an error saying:
> ValueError: invalid literal for __float__: om time import time
> class Foo:
> def go(self):
> 
> almost like when I try to marshal and exec it misses the first two
> characters, "fr" ...any ideas?

marshal is used to (de)serialize python objects from/to strings.
marshal.loads() tries to deserialize an encoded string back into a python
object - which does not make sense here.
What you probably want is:

exec data in my_module.__dict__


HTH

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


Re: marshal.loads ValueError

2007-01-31 Thread abcd
On Jan 31, 8:02 am, Benjamin Niemann <[EMAIL PROTECTED]> wrote:
> marshal is used to (de)serialize python objects from/to strings.
> marshal.loads() tries to deserialize an encoded string back into a python
> object - which does not make sense here.
> What you probably want is:
>
> exec data in my_module.__dict__

thanks that took care of it.

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


Re: Help needed on config files

2007-01-31 Thread Daniele Varrazzo
On Jan 31, 11:04 am, "jvdb" <[EMAIL PROTECTED]> wrote:
> Hi there,
>
> I am quite new on python programming and need some help on solving my
> problem..
>
> I have to make a (python) program which deletes files from
> directories. I don't think deleting, etc. is the problem. The problem
> is that the directories where i have to delete them are 'dynamic'/
> subject to change. So what i thought is to make a config file
> containing an identifier (useful for myself) and there the directory.
> something like:
> [PROJECTx]
> 
> [PROJECTy]
> 
>
> I have already seen that there are sorts of modules where you can read
> a config file, but only when you know the key.. Can someone help me
> out on this? The configfile can be altered in time (as there are more
> projects coming where i have to delete files on a scheduled basis).

The classes defined in the ConfigParser module contain a 'sections()'
method that do what you need.

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

Daniele

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


Re: Regex with ASCII and non-ASCII chars

2007-01-31 Thread Peter Otten
TOXiC wrote:

> How I can do a regex match in a string with ascii and non ascii chars
> for example:
> 
> regex = re.compile(r"(ÿÿ?ð?öÂty)", re.IGNORECASE)
> match = regex.search("ÿÿ?ð?öÂty")
> if match:
> result = match.group()
> print result
> else:
> result = "No match found"
> print result
> 
> it return "no match found" even if the two string are equal.

For equal strings you should get a match:

>>> re.compile("Zäöü", re.IGNORECASE).search("yadda zäöü yadda")
<_sre.SRE_Match object at 0x401e0a68>
>>> print _.group()
zäöü

For case ignorance your best bet is unicode:

>>> re.compile(u"äöü", re.IGNORECASE|re.UNICODE).search(u"ÄÖÜ")
<_sre.SRE_Match object at 0x401e09f8>

Peter

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


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread stef



It's bad practice to use built-ins like 'list' as a regular variable
name.
  
ok, but it was just an example (in practice, I always use very long 
names ;-)
  

# calling method 1:
execute (S[0], S[4] )

# calling method 2:
execute ( ( S[0], S[4] ) )



Let's take a look at those side-by-side:
execute (S[0], S[4] )
execute ( ( S[0], S[4] ) )

Now, which one *looks* better?

  

# or *the extra flexibility)
mylist = ( S[0], S[4] )
execute ( mylist )



Also, take into consideration the opposite end of the pole; you have
your list of arguments (args), and your about to call a function that
was declared something like this:
def someFunction(arg1, arg2, arg3):
  # etc.
Which is clearer?
someFunction(*args)
someFunction(args[0], args[1], args[2])

And if you've got a variable number of arguments, it becomes virtually
impossible to avoid using the *args syntax.

  

# So with this construct, I have all flavours:

def chunk_plot(*args):
   if len(args)==1: my_example_var = args[0]
   else: my_example_var = args
   for i in range  ( len ( my_example_var ) ):
   ... do something with  my_example_var [i]

# calling the procedure
chunk_plot (S[1], S[4])
chunk_plot ( ( S[1], S[4] ) )
my_action_list = ( S[1], S[2] )
chunk_plot ( my_action_list )


And sorry, no need for kwargs for now ;-)

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

Re: Help needed on config files

2007-01-31 Thread jvdb
Yes! That does the trick, thanks, both of you!

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


"Correct" db adapter

2007-01-31 Thread king kikapu
Hi to all,

i have started a month ago to seriously studying Python. I am now
looking at the databases stuff
and i want the opinion of more experienced Python programmers (than
me) at the following :

I see that there are a lot of databases adapters on the net, some
following the DB-API 2.0 and some others do not. I want to use a db-
module that do not tie me down to a specific database and that fully
supports DB-API 2.0
Now i am using Sql Server but who knows about tomorrow.

I started using pyodbc and looking how i can e.x. call stored
procedure with arguments and all that stuff.
This is using ODBC syntac and i found enough info on the net.

Is the approach i took the "correct" one or is there a better db-
module so i can use ?

Thanks in advance

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


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread Eugene Antimirov
stef wrote:

> # method 2
> def chunk_plot(self, list):
> for i in range ( len(list) ):
>   do something


And one note more. Just to be more pythonic you shouldn't use form 
range(len(blabla)). Instead use:

for i in list:
blabla...


-- 
Sincerely,
Eugene Antimirov
PortaOne, Inc., SIP Support Engineer
[EMAIL PROTECTED]

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


Re: Synchronous shutil.copyfile()

2007-01-31 Thread Hugo Ferreira

I'm banging my head over this one... sometimes it just works... *argh*

Here's a snip of my problem:

import win32com.client
import shutil
import time

engine = win32com.client.Dispatch("DAO.DBEngine.36")
table = 'STUFFTODELETE'
dstFilename = 'in.mdb'
workingfile = 'work.mdb'

shutil.copyfile(dstFilename, workingfile)

print 'Sleeping 5 after copy...'
time.sleep(5)

dstDb = engine.OpenDatabase(workingfile)

print 'Sleeping 5 after open...'
time.sleep(5)

dstDb.Execute('DELETE FROM ' + table)

At at *exactly* this line, I get the error:

C:\Python24\lib\site-packages\win32com\gen_py\00025E01-
--C000-0046x0x5x0.py510
com_error: (-2147352567, 'Exception occurred.', (0, 'DAO.Database', 'Not a
valid bookmark.', 'jeterr40.chm', 5003159, -2146825129), None)

Sometimes... Yes, the database is a %"#$"# MSAccess. This script is running
under windows.

Any ideas?

On 1/31/07, Hugo Ferreira <[EMAIL PROTECTED]> wrote:


Well.. Thx for the answers.

The only way I had to make it work was to use a time.sleep(10) after the
shutil.copyfile(). Since this is a night-run script, I can waste 10
seconds, but it still knocks me out "why" it happens...

Cheers!

Hugo Ferreira

On 30 Jan 2007 18:06:15 + (GMT), Matthew Woodcraft <[EMAIL PROTECTED]>
wrote:
>
> Hugo Ferreira < [EMAIL PROTECTED]> wrote:
> > I have a problem. I'm using calling shutil.copyfile() followed by
> > open(). The thing is that most of the times open() is called before
> > the actual file is copied. I don't have this problem when doing a
> > step-by-step debug, since I give enough time for the OS to copy the
> > file, but at run-time, it throws an exception.
> >
> > Is there anyway to force a sync copy of the file (make python wait for
> > the completion)?
>
> shutil.copyfile() closes both files before it returns, so I suspect
> this is an OS-level bug.
>
> The most likely culprits are buggy network filesystems and buggy
> on-access virus scanners.
>
> -M-
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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

Re: Can't install Turbogears (with pysqlite) on Windows

2007-01-31 Thread Thomas
The solution can be found here:
http://groups.google.com/group/turbogears/browse_thread/thread/2dc72464a48fde94

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


Re: Help needed on config files

2007-01-31 Thread Larry Bates
jvdb wrote:
> Hi there,
> 
> I am quite new on python programming and need some help on solving my
> problem..
> 
> I have to make a (python) program which deletes files from
> directories. I don't think deleting, etc. is the problem. The problem
> is that the directories where i have to delete them are 'dynamic'/
> subject to change. So what i thought is to make a config file
> containing an identifier (useful for myself) and there the directory.
> something like:
> [PROJECTx]
> 
> [PROJECTy]
> 
> 
> I have already seen that there are sorts of modules where you can read
> a config file, but only when you know the key.. Can someone help me
> out on this? The configfile can be altered in time (as there are more
> projects coming where i have to delete files on a scheduled basis).
> 
> This is a good learning project for me, but i really don't see how to
> solve this.
> 
Others have answered your specific question, I thought I'd add my
2 cents.  As the config file grows you will need to have other
sections that are not PROJECT# sections.  I use the pattern:

from ConfigParser import ConfigParser
cfg = ConfigParser()
cfg.read("proj.cfg")
projectSections=[section for section in cfg.sections()
 if x.startswith('PROJECT')]

#
# Note: sections are case sensitive
#
for project in projectSections:
#
# Do your work
#

-Larry



This seems to work quite well.  I hope information helps.

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


Re: Conditional expressions - PEP 308

2007-01-31 Thread Colin J. Williams
Paddy wrote:
> On Jan 30, 9:51 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:
>> It would be helpful if the rules of the game were spelled out more clearly.
>>
>> The conditional expression is defined as X if C else Y.
>> We don't know the precedence of the "if" operator.  From the little test
>> below, it seem to have a lower precedence than "or".
>>
>> Thus, it is desirable for the user to put the conditional expression in
>> parentheses.
>>
>> Colin W.
>>
>> # condExpr.py
>> # PEP 308 defines a conditional expression as X if C else Y
>> # but we don't know exactly what X is supposed to be.
>> # It doesn't seem to be spelled out in the syntax.
>>
>> def main():
>>names= ['abc', 'def', '_ghi', 'jkl', '_mno', 'pqrs']
>>res= ''
>>for w in names:
>> res= res + w if w[0] != '_' else ''
>> z= 1
>>print 'res1:', res
>>
>>res= ''
>>for w in names:
>> res= res + (w if w[0] != '_' else '')
>> z= 1
>>print 'res2:', res
>>
>> if __name__ == '__main__':
>>main()
>>
>> Result:
>> [Dbg]>>>
>> res1: pqrs
>> res2: abcdefjklpqrs
> 
> But to give them credit though, in Whats new in Python 2.5: PEP 308,
> they do mention that as a matter of style you should parenthesise the
> if-expression, and the example given consistes of just a simple
> assignment of the if-expr to a name.
> - Paddy.
> 
Yes, I agree.  The ternary operator is a step forward.

I was trying to make the point that the parentheses are necessary if X 
is more than a simple value.  It's a pity that one finds this out by 
experiment rather than definition.

Colin W.

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


Re: Regex with ASCII and non-ASCII chars

2007-01-31 Thread TOXiC
Thx it work perfectly.
If I want to query a file stream?

file = open(fileName, "r")
text = file.read()
file.close()

regex = re.compile(u"(ÿÿ‹ð…öÂ)", re.IGNORECASE)
match = regex.search(text)
if (match):
result = match.group()
print result
WritePatch(fileName,text,result)
else:
result = "No match found"
print result

It return "no match found" (the file contain the string "ÿÿ‹ð…öÂ"
but...).
Thanks in advance for the help!

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

Re: "Correct" db adapter

2007-01-31 Thread Laurent Rahuel
Maybe you should take a look at sqlalchemy

king kikapu wrote:

> Hi to all,
> 
> i have started a month ago to seriously studying Python. I am now
> looking at the databases stuff
> and i want the opinion of more experienced Python programmers (than
> me) at the following :
> 
> I see that there are a lot of databases adapters on the net, some
> following the DB-API 2.0 and some others do not. I want to use a db-
> module that do not tie me down to a specific database and that fully
> supports DB-API 2.0
> Now i am using Sql Server but who knows about tomorrow.
> 
> I started using pyodbc and looking how i can e.x. call stored
> procedure with arguments and all that stuff.
> This is using ODBC syntac and i found enough info on the net.
> 
> Is the approach i took the "correct" one or is there a better db-
> module so i can use ?
> 
> Thanks in advance

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


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread stef
Eugene Antimirov wrote:
> stef wrote:
>
>> # method 2
>> def chunk_plot(self, list):
>> for i in range ( len(list) ):
>>   do something
>
>
> And one note more. Just to be more pythonic you shouldn't use form 
> range(len(blabla)). Instead use:
>
> for i in list:
> blabla...
>
>
I would love that,
but please tell me how (I need an integer counter for something else too):

def chunk_plot(*args):
if len(args) == 1:  list = args[0]
else:   list = args
 
color = ['g','r','b','y','m']
plot ( list[0], color[0])
hold (True)
for i in range  (  1,  len(list)  ):
 plot  (  list[i],  color[i]  )



cheers,
Stef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Correct" db adapter

2007-01-31 Thread Daniel Nogradi
> Maybe you should take a look at sqlalchemy
>
> > Hi to all,
> >
> > i have started a month ago to seriously studying Python. I am now
> > looking at the databases stuff
> > and i want the opinion of more experienced Python programmers (than
> > me) at the following :
> >
> > I see that there are a lot of databases adapters on the net, some
> > following the DB-API 2.0 and some others do not. I want to use a db-
> > module that do not tie me down to a specific database and that fully
> > supports DB-API 2.0
> > Now i am using Sql Server but who knows about tomorrow.
> >
> > I started using pyodbc and looking how i can e.x. call stored
> > procedure with arguments and all that stuff.
> > This is using ODBC syntac and i found enough info on the net.
> >
> > Is the approach i took the "correct" one or is there a better db-
> > module so i can use ?
> >
> > Thanks in advance
>

SQLObject might be of interest to you:
http://sqlobject.org/ it is a DB-API 2.0 compliant ORM.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread Jeffrey Froman
stef wrote:

>> And one note more. Just to be more pythonic you shouldn't use form
>> range(len(blabla)). Instead use:
>>
>> for i in list:
>> blabla...
>>
>>
> I would love that,
> but please tell me how (I need an integer counter for something else too):

for index, item in enumerate(args):
...


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


Re: Help needed on config files

2007-01-31 Thread jvdb
Ok, with all your help and very useful hints, i managed to solve it!
thanks!
Now my program loops through the config file, and deletes the files
older than 7 days with a specified extension.
Here's my program:
#this project removes old log files

import os, time
from ConfigParser import ConfigParser
now=time.time()

cfg = ConfigParser()
cfg.read("projects.cfg")

#loop through the config file
for proj in cfg.sections():
print ""
#get the path where file files should be
path = cfg.items(proj)[1][1]
#get the filetype
ftype = cfg.items(proj)[0][1]
print "project: %s, path to old logfiles: %s" % (proj, path)
dirList=os.listdir(path)
# Now check if the file is not a dir and then check if the file is
older than 7 days
for fname in dirList:
if fname.endswith(ftype):
pad = path+"\\"+fname
if os.stat(pad).st_mtime < now - 7 * 86400:
if os.path.isfile(pad):
os.remove(pad)
print "The file %s is deleted" % (fname)



===
#projects.cfg
[ebiz_factuur]
dir=c:\customer\ebiz_factuur
type=.log
[test]
dir=c:\temp
type=.txt

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


subway

2007-01-31 Thread Daniel Nogradi
Does anyone know what has happened to the codebase of the subway
project? It seems the whole project has been shut down leaving no
trace of the code on net but I would be very happy to see it,
apparently it had some cool features that would be fun to look at.
Does anyone have access to the code and/or is willing to make it
publically available?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex with ASCII and non-ASCII chars

2007-01-31 Thread Peter Otten
TOXiC wrote:

> Thx it work perfectly.
> If I want to query a file stream?
> 
> file = open(fileName, "r")
> text = file.read()
> file.close()

Convert the bytes read from the file to unicode. For that you have to know
the encoding, e. g.

  file_encoding = "utf-8" # replace with the actual encoding
  text = text.decode(file_encoding)

> regex = re.compile(u"(ÿÿ‹ð…öÂ)", re.IGNORECASE)
> match = regex.search(text)
> if (match):
> result = match.group()
> print result
> WritePatch(fileName,text,result)
> else:
> result = "No match found"
> print result
> 
> It return "no match found" (the file contain the string "ÿÿ‹ð…öÂ"
> but...).
> Thanks in advance for the help!

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

Re: error messages containing unicode

2007-01-31 Thread Jim
Oops, there is a typo in what I wrote above.  Sorry.

On Jan 31, 7:57 am, "Jim" <[EMAIL PROTECTED]> wrote:
> Oh, I agree.  If I have a string mesg that is unicode-not-ascii and I
> say
>   try:
>   raise Exception mesg
>   except Exception, err:
>   print "Trouble"+mesg
> then I have problems.
should say:
   try:
   raise Exception mesg
   except Exception, err:
   print "Trouble"+str(err)

Jim

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


Re: another newbie question: why should you use "*args" ?

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

> Eugene Antimirov wrote:
>
>> And one note more. Just to be more pythonic you shouldn't use form 
>> range(len(blabla)). Instead use:
>>
>> for i in list:
>> blabla...
>>
>>
> I would love that,
> but please tell me how (I need an integer counter for something else too):
> 
> def chunk_plot(*args):
> if len(args) == 1:  list = args[0]
> else:   list = args
>  
> color = ['g','r','b','y','m']
> plot ( list[0], color[0])
> hold (True)
> for i in range  (  1,  len(list)  ):
>  plot  (  list[i],  color[i]  )

No need for the counter here.

for args in zip(list[1:], color[1:]):
plot(*args)

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


Python tools to manipulate JARs ?

2007-01-31 Thread Andy Dingley
I run build processes for a Java shop using Python (and some Ant).

Would anyone care to suggest favoured tools for manipulating the
innards of JARs? Or do I just treat them as plain zipfiles and get
stuck right in there?

Mainly I'm trying to query lists of classes and their embedded
versions and do some library dependency reporting. Performance speed
is starting to be an issue, as there's 1500+ classes in this bucket
and it's an interactive query.

Thanks for any suggestions

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


Re: another newbie question: why should you use "*args" ?

2007-01-31 Thread stef



I would love that,
but please tell me how (I need an integer counter for something else too):

def chunk_plot(*args):
if len(args) == 1:  list = args[0]
else:   list = args
 
color = ['g','r','b','y','m']

plot ( list[0], color[0])
hold (True)
for i in range  (  1,  len(list)  ):
 plot  (  list[i],  color[i]  )



No need for the counter here.

for args in zip(list[1:], color[1:]):
plot(*args)

  

that looks nice, thanks!
All the other people also thanks, "enumerate" looks also better than 
range(len(  nice !

Ciao,
Marc 'BlackJack' Rintsch
  


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

Any python scripts to do parallel downloading?

2007-01-31 Thread Frank Potter
I want to find a multithreaded downloading lib in python,
can someone recommend one for me, please?
Thanks~

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


Re: Conditional expressions - PEP 308

2007-01-31 Thread Steven Bethard
Colin J. Williams wrote:
> It would be helpful if the rules of the game were spelled out more clearly.
> 
> The conditional expression is defined as X if C else Y.
> We don't know the precedence of the "if" operator.  From the little test 
> below, it seem to have a lower precedence than "or".
> 
> Thus, it is desirable for the user to put the conditional expression in 
> parentheses.

Could you submit a documentation patch?

  http://sourceforge.net/tracker/?group_id=5470&atid=105470

It doesn't need to be in LaTeX.  Plain text is fine.  Just indicate in 
what document you think text should be added.

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


Re: Regex with ASCII and non-ASCII chars

2007-01-31 Thread TOXiC
It wont work with utf-8,iso or ascii...

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


Re: Any python scripts to do parallel downloading?

2007-01-31 Thread Jean-Paul Calderone
On 31 Jan 2007 08:23:57 -0800, Frank Potter <[EMAIL PROTECTED]> wrote:
>I want to find a multithreaded downloading lib in python,
>can someone recommend one for me, please?
>Thanks~

There are no threads, but perhaps http://jcalderone.livejournal.com/24285.html
would be interesting to you.

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


Re: subway

2007-01-31 Thread skip

Daniel> Does anyone know what has happened to the codebase of the subway
Daniel> project? It seems the whole project has been shut down leaving
Daniel> no trace of the code on net but I would be very happy to see it,
Daniel> apparently it had some cool features that would be fun to look
Daniel> at.  Does anyone have access to the code and/or is willing to
Daniel> make it publically available?

No guarantee that it will have any remnants of the subway project, but the
Wayback Machine might be a good place to start:

http://web.archive.org/web/*/http://subway.python-hosting.com

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


Re: Regex with ASCII and non-ASCII chars

2007-01-31 Thread TOXiC
On 31 Gen, 17:30, "TOXiC" <[EMAIL PROTECTED]> wrote:
> It wont work with utf-8,iso or ascii...

I think the best way is to search hex value in the file stream but I
tryed (in the regex) \hxx but it don't work...

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


Re: Unicode error handler

2007-01-31 Thread Walter Dörwald
[EMAIL PROTECTED] wrote:
> On Jan 30, 11:28 pm, Walter Dörwald <[EMAIL PROTECTED]> wrote:
> 
>> codecs.register_error("transliterate", transliterate)
>>
>>Walter
> 
> Really, really slick solution.
> Though, why was it [:1], not [0]? ;-)

No particular reason, unicodedata.normalize("NFD", ...) should never
return an empty string.

> And one more thing:
>> def transliterate(exc):
>> if not isinstance(exc, UnicodeEncodeError):
>> raise TypeError("don'ty know how to handle %r" % r)
> I don't understand what %r and r are and where they are from. The man
> 3 printf page doesn't have %r formatting.

%r means format the repr() result, and r was supposed to be exc. ;)

Servus,
   Walter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional expressions - PEP 308

2007-01-31 Thread Ziga Seilnacht
Colin J. Williams wrote:
> It would be helpful if the rules of the game were spelled out more clearly.
>
> The conditional expression is defined as X if C else Y.
> We don't know the precedence of the "if" operator.  From the little test
> below, it seem to have a lower precedence than "or".

The rules are specified in the Python Reference Manual:
http://docs.python.org/ref/Booleans.html

Ziga

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


Re: "Correct" db adapter

2007-01-31 Thread king kikapu
Thanks for the replies.

I think i do not need something like ORM, but just a db-module that i
can "work" the database with it.
I just want to know if pyodbc is the "correct" solution to do so or if
it is another db-module that is more
usefull for this job.

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


What is the dummy statement that do nothing in Python?

2007-01-31 Thread Dongsheng Ruan
I remember that in python there is some kind of dummy statement that just 
holds space and does nothing.

I want it to hold the place after a something like if a>b: do nothing

I can't just leave the space blank after if statement because there will be 
error message.

Does anybody know what to insert there?

Thanks! 


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


Python module for the IPod shuffle ...

2007-01-31 Thread Analog Kid

Hi all:
Im looking for a python module thatll let me do simple reads/writes from and
to an iPod shuffle similar to iTunes ... I read about the gPod module ...
but Im not sure whether it will work in Windows ...

Any help is greatly appreciated.

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

Re: What is the dummy statement that do nothing in Python?

2007-01-31 Thread Jean-Paul Calderone
On Wed, 31 Jan 2007 11:49:53 -0500, Dongsheng Ruan <[EMAIL PROTECTED]> wrote:
>I remember that in python there is some kind of dummy statement that just
>holds space and does nothing.
>
>I want it to hold the place after a something like if a>b: do nothing
>
>I can't just leave the space blank after if statement because there will be
>error message.
>
>Does anybody know what to insert there?

http://python.org/doc/tut/node6.html#SECTION00650

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


Re: What is the dummy statement that do nothing in Python?

2007-01-31 Thread Analog Kid

hey dongsheng:
not too sure what you are looking for ... but i guess a simple "pass"
statement should do it ...

if a > b: pass


hth,
-ajay


On 1/31/07, Dongsheng Ruan <[EMAIL PROTECTED]> wrote:


I remember that in python there is some kind of dummy statement that just
holds space and does nothing.

I want it to hold the place after a something like if a>b: do nothing

I can't just leave the space blank after if statement because there will
be
error message.

Does anybody know what to insert there?

Thanks!


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





--
BBQ - "Spare (My) Ribs" being contemplated
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: What is the dummy statement that do nothing in Python?

2007-01-31 Thread Stew Pid
On Wed, 31 Jan 2007 11:49:53 -0500, Dongsheng Ruan wrote:

> I remember that in python there is some kind of dummy statement that just 
> holds space and does nothing.
> 
> I want it to hold the place after a something like if a>b: do nothing
> 
> I can't just leave the space blank after if statement because there will be 
> error message.
> 
> Does anybody know what to insert there?
> 
> Thanks!

pass

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


RE: What is the dummy statement that do nothing in Python?

2007-01-31 Thread Carroll, Barry

> -Original Message-
> From: Dongsheng Ruan [mailto:[EMAIL PROTECTED]
> Sent: Wednesday, January 31, 2007 8:50 AM
> To: [email protected]
> Subject: What is the dummy statement that do nothing in Python?
> 
> I remember that in python there is some kind of dummy statement that
just
> holds space and does nothing.
> 
> I want it to hold the place after a something like if a>b: do nothing
> 
> I can't just leave the space blank after if statement because there
will
> be
> error message.
> 
> Does anybody know what to insert there?
> 
> Thanks!
> 
> 
Greetings:

Try 'pass':


if a>b:
pass
else:
dosomething()


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

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: subway

2007-01-31 Thread deelan
Daniel Nogradi wrote:
> Does anyone know what has happened to the codebase of the subway
> project? It seems the whole project has been shut down leaving no
> trace of the code on net but I would be very happy to see it,
> apparently it had some cool features that would be fun to look at.
> Does anyone have access to the code and/or is willing to make it
> publically available?

Try:



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


Re: What is the dummy statement that do nothing in Python?

2007-01-31 Thread Tim Daneliuk
Dongsheng Ruan wrote:
> I remember that in python there is some kind of dummy statement that just 
> holds space and does nothing.
> 
> I want it to hold the place after a something like if a>b: do nothing
> 
> I can't just leave the space blank after if statement because there will be 
> error message.
> 
> Does anybody know what to insert there?
> 
> Thanks! 
> 
> 

if a > b:
pass


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


Python **kwargs ?

2007-01-31 Thread johnny
What is **kwargs mean in python?  When you put double **, does it mean
passing by reference?

For example:
def redirect_to(request, url, **kwargs):

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


where has Stani's Py Editor gone?

2007-01-31 Thread John Pote
Hi everyone,

Been trying to get the latest version of Stani's Python Editor the last few 
days. But I cannot get any response out of 'pythonide.stani.be'. Anyone know 
what's happened?

Ta much,

John Pote 


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


Re: What is the dummy statement that do nothing in Python?

2007-01-31 Thread Dongsheng Ruan
Yes, that's just what I want.

Thanks!
  - Original Message - 
  From: Analog Kid 
  To: Dongsheng Ruan 
  Cc: [email protected] 
  Sent: Wednesday, January 31, 2007 12:04 PM
  Subject: Re: What is the dummy statement that do nothing in Python?


  hey dongsheng:
  not too sure what you are looking for ... but i guess a simple "pass" 
statement should do it ...

  if a > b: pass


  hth,
  -ajay

   
  On 1/31/07, Dongsheng Ruan <[EMAIL PROTECTED]> wrote: 
I remember that in python there is some kind of dummy statement that just
holds space and does nothing. 

I want it to hold the place after a something like if a>b: do nothing

I can't just leave the space blank after if statement because there will be
error message.

Does anybody know what to insert there? 

Thanks!


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




  -- 
  BBQ - "Spare (My) Ribs" being contemplated -- 
http://mail.python.org/mailman/listinfo/python-list

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

2007-01-31 Thread Chris Curvey
Hi all,

I have used the win32com libraries to set up a service called
MyService under Windows.  So far, so good.  Now I need to run multiple
copies of the service on the same machine.  I also have that working.
For monitoring and logging, I'd like each instance of the service to
know it's own identity (MyService1, MyService2, etc.)

But I can't quite seem to grasp how to do this.  In the code below,
the command line parameter "-i" gives the service an identity, but how
do I get the service to understand it's identity when it is started?

Many thanks!


class MyService(win32serviceutil.ServiceFramework):
"""NT Service."""

_svc_name_ = "MyService"
_svc_display_name_ = "My Service"

_id_ = ''

def SvcDoRun(self):
provider = MyServiceClass(identifier=self._id_)
provider.start()

# now, block until our event is set...
win32event.WaitForSingleObject(self.stop_event,
win32event.INFINITE)

   # __init__ and SvcStop snipped


###
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option("-i", "--identifier", dest="identifier")
(opts, args) = parser.parse_args()
if opts.number is not None:
MyService._svc_name_ += opts.identifier
MyService._svc_display_name_ += opts.identifier
MyService._provider_id_ = opts.identifier

win32serviceutil.HandleCommandLine(MyService,
customInstallOptions="i:")

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


Re: "Correct" db adapter

2007-01-31 Thread Bruno Desthuilliers
king kikapu a écrit :
> Thanks for the replies.
> 
> I think i do not need something like ORM, but just a db-module that i
> can "work" the database with it.

FWIW, SQLAlchemy is not an ORM, but an higher-level API for SQL 
integration. The ORM part is an optional feature built on top of this 
API. But I'm not sure SQLAlchemy supports SQL Server anyway !-)

> I just want to know if pyodbc is the "correct" solution to do so or if
> it is another db-module that is more
> usefull for this job.

AFAICT:

* there's an experimental MS SQL Server db-module:
http://www.object-craft.com.au/projects/mssql/

* the Win32 extensions offers support for ADO, but then it's not db-api 
compliant

* unless you use adodbapi, but I don't know if it's still supported 
(last release is 3+ years old):
http://adodbapi.sourceforge.net/

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


Re: how to "free" an object/var ?

2007-01-31 Thread Paddy
On Jan 31, 7:34 am, Steven D'Aprano <[EMAIL PROTECTED]>
wrote:
> On Tue, 30 Jan 2007 23:22:52 -0800, Paddy wrote:
> >> As far as I know there is no way to force the deletion of an object
> >> even if it is in use. This is a Good Thing.
>
> >> --
> >> Steven D'Aprano
>
> > The folowing will make the data available for garbage collection no
> > matter what references it:
>
>  l = ["data"] *10
>  l
> > ['data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data',
> > 'data']
>  l2 = l
>  l[:] = []
>  l2
> > []
>
> Sort of.
>
> What happens is that both l and l2 are names referring to the same list.
> After executing l[:] the *contents* of the list change, from lots of
> "data" to nothing. Naturally both l and l2 see the change, because they
> both point to the same list. But the original contents of the list still
> exist until the garbage collector sees that they are no longer in use,
> and then frees them.
>
> You can prove this by doing something like this:
>
> data = "\0"*100 # one (decimal) megabyte of data
> L = [data] # put it in a list
> L[:] = []  # "free" the contents of the list
> assert len(data) == 100
> # but the megabyte of data still there
>
> Again, you can't force Python to free up memory that is still in use.
> If you could, that would be a bug.
>
> --
> Steven D'Aprano

Thanks Stephen for explaining my answer a bit more.

The [:] = [] trick should be of most use when you go on to allocate
large amounts of data in your program once again, when the gc coud
then make some of the same memory available for the new objects.
As others have said, getting Python to give back memory to the
underlying OS is murder - The best way I have of doing that is to
split your program into two and chain their execution, which allows
the OS to reclaim the memory used by the first Python process when it
finishes.

- Paddy.

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


Re: Python **kwargs ?

2007-01-31 Thread Bruno Desthuilliers
johnny a écrit :
> What is **kwargs mean in python?  When you put double **, does it mean
> passing by reference?

Nope.

Python as support for both positional (*args) and named (**kwargs) varargs.

> For example:
> def redirect_to(request, url, **kwargs):

means that redirect_to expect a positional 'request' arg, a positional 
'url' argument, and any other arbitrary named arguments.

You'll find all relevant doc in the FineManual(tm):
http://www.python.org/doc/current/tut/node6.html#SECTION00672

HTH

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


Re: how to "free" an object/var ?

2007-01-31 Thread Aahz
In article <[EMAIL PROTECTED]>,
John Nagle  <[EMAIL PROTECTED]> wrote:
>Steven D'Aprano wrote:
>> On Tue, 30 Jan 2007 15:48:37 -0800, James Stroud wrote:
>> 
>> 
>>>Stef Mientki wrote:
>>>
If I create a large array of data or class,
how do I destroy it (when not needed anymore) ?
>
>If your data structure has no backlinks, it will go away
>as soon as the last reference to it disappears.  If your
>data structure has backlinks, it will hang around until
>garbage collection runs.  If your backlinks are
>weak references (see "weakref"), the data structure will
>be released much sooner.

Note that exceptions create links.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DCOP memory leak?

2007-01-31 Thread [EMAIL PROTECTED]
On 31 jan, 01:03, Larry Bates <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello,
>
> > I'm writing a python script for Amarok, I communicate with Amarok
> > using DCOP.
> > Now, I have to call DCOP very often and I noticed that every time I
> > make a DCOP call my program keeps growing in memory size.
>
> > To make sure it was DCOP i wrote the small program below:
>
> > from dcopext import DCOPClient, DCOPApp
>
> > while 0==0:
> > dcop=DCOPClient()
> > dcop.attach()
> > AmarokDcopRes = DCOPApp ("amarok", dcop)
> > ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs()
> > print Ms
>
> > If you run this script and monitor it's memory use you'll see that it
> > keeps growing.
>
> > Does anyone know how I can solve this problem?
>
> > Kind regards,
>
> > Tim
>
> I think you will find the objects are getting created so fast that
> garbage collection doesn't have time to clean them up as fast
> as you are creating new ones.  Since del dcop is not guaranteed
> to be "immediate" that won't help.
>
> Q: Can't you create dcop instance outside the loop and reuse it
> for every time through the loop?
>
> Q: Can you sleep or something after each loop or do you really
> want to peg the CPU checking forever?
>
> Q: How do you ever get out of this infinite loop?
> Note: while 0=0 is better written as while 1: and you need a
> break somewhere to get out of the loop.
>
> -Larry
Hi,

Thanks for the quick response.

The code I posted is not my actual program and was only to demonstrate
my problem. The complete program I'm writing uses QT and so the loop
is replaced by a Timer event.
I tried out the suggestion. I had already tried the del dcop
instruction, so I knew that wasn't it. I also placed the DCOP variable
outside my loop but that didn't help either.
What I did notice that my program only grew in memory use when the
'ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() ' code was
executed (or any other function using the AmarokDcopRes variable like
'ok, volume = AmarokDcopRes.player.getVolume()' )
Then I also tried to make my take a pause of a second in the loop but
this also didn't help, the program was still growing in memory use (a
lot slower though but I don't call that a solution)

So if you have any more ideas let me know. I'll keep on trying

Kind regards,

Tim

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


Re: subway

2007-01-31 Thread Daniel Nogradi
> Daniel> Does anyone know what has happened to the codebase of the subway
> Daniel> project? It seems the whole project has been shut down leaving
> Daniel> no trace of the code on net but I would be very happy to see it,
> Daniel> apparently it had some cool features that would be fun to look
> Daniel> at.  Does anyone have access to the code and/or is willing to
> Daniel> make it publically available?
>
> No guarantee that it will have any remnants of the subway project, but the
> Wayback Machine might be a good place to start:
>
> http://web.archive.org/web/*/http://subway.python-hosting.com

Thanks, that's a great idea, actually loads of stuff are on it, but
somehow from the link

http://web.archive.org/web/20060206044039/http://www.gosubway.org/install/Subway-0.2rc1-py2.4.egg

the egg file can not be downloaded completely, the connection is
closed at byte 138903 all the time and the file is bigger than that.
If anyone managed to grab the file please let me know so far I tried
wget and firefox.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where has Stani's Py Editor gone?

2007-01-31 Thread Stargaming
John Pote schrieb:
> Hi everyone,
> 
> Been trying to get the latest version of Stani's Python Editor the last few 
> days. But I cannot get any response out of 'pythonide.stani.be'. Anyone know 
> what's happened?
> 
> Ta much,
> 
> John Pote 
> 
> 

http://developer.berlios.de/project/showfiles.php?group_id=4161
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting a List of Lists

2007-01-31 Thread Paddy
On Jan 31, 12:35 pm, Bruno Desthuilliers  wrote:
> [EMAIL PROTECTED] a écrit :
>
> > I can't seem to get this nailed down and I thought I'd toss it out
> > there as, by gosh, its got to be something simple I'm missing.
>
> > I have two different database tables of events that use different
> > schemas. I am using python to collate these records for display. I do
> > this by creating a list of lists that look roughly like this:
>
> > events = [['Event URL as String', 'Event Title as String ', Event Date
> > as Datetime], ...]
>
> Then you should not use a list of lists, but a list of tuples.
>
>
>
> > I then thought I'd just go events.sort(lambda x,y: x[2] > it a day. That didn't work. But then lamda functions like to be very
> > simple, maybe object subscripts aren't allowed (even though I didn't
> > get an error). So I wrote a comparison function that looks much as you
> > would expect:
>
> > def date_compare(list1,
> > list2):
> > x = list1[2]
> > y = list2[2]
> > if
> > x>y:
> > return
> > 1
> > elif
> > x==y:
> > return
> > 0
> > else: #
> > x > return -1
>
> > But as before sorting with this function returns None.
>
> > What have I overlooked?
>
> Lol.
>
> I guess this is a FAQ. list.sort() performs a destructive in-place sort,
> and always return None. This is in the FineManual:
>
> [EMAIL PROTECTED]:~$ python
> Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
> [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> help(list.sort)
> Help on method_descriptor:
>
> sort(...)
>  L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
>  cmp(x, y) -> -1, 0, 1
>
> You may want to use sorted(iterable, cmp=None, key=None, reverse=False)
> if you don't want to sort in-place.
>
> Also, using comparison functions is usually not the most efficient way
> to do such a sort. In your case, I'd go for a good old
> Decorate/sort/undecorate (AKA schwarzian transform):
>
> events = [evt for date, evt in
>sorted([(evt[2], evt) for evt in events])]
>
> HTH

I agree with you B., but see the comments here:
  http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-
efficiency
for information on the relative speeds of rolling your own DSU versus
using itemgetter and key=...

- Paddy.


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


Re: "Correct" db adapter

2007-01-31 Thread Diez B. Roggisch
king kikapu wrote:

> Thanks for the replies.
> 
> I think i do not need something like ORM, but just a db-module that i
> can "work" the database with it.
> I just want to know if pyodbc is the "correct" solution to do so or if
> it is another db-module that is more
> usefull for this job.

I think you've got something wrong. There is no such thing as a generic
DB-Adapter, except maybe from the mxODBC which pushes the abstraction to
the ODBC-layer.

If your app is DB-API2.0-compatible, you should be able to more or less just
use your code with different adapters. There are several ways to accomplish
a configurable way, but in the end it boils down to someting like this:

if is_postgres:
  import psycopg2 as db
if is_mysql:
  import MySQLdb as db

Then db can be used to connect and query the db. A thin layer on top of that
should maybe be written to cover different parameter-styles, but that
shouldn't be too hard.

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


RE: Python tools to manipulate JARs ?

2007-01-31 Thread Sells, Fred
I have not tried this, but...
Assuming jython is out of the question
You might want to try a simple java command line program you could run from
popen

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
Behalf Of Andy Dingley
Sent: Wednesday, January 31, 2007 11:11 AM
To: [email protected]
Subject: Python tools to manipulate JARs ?


I run build processes for a Java shop using Python (and some Ant).

Would anyone care to suggest favoured tools for manipulating the
innards of JARs? Or do I just treat them as plain zipfiles and get
stuck right in there?

Mainly I'm trying to query lists of classes and their embedded
versions and do some library dependency reporting. Performance speed
is starting to be an issue, as there's 1500+ classes in this bucket
and it's an interactive query.

Thanks for any suggestions

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


Re: subway

2007-01-31 Thread deelan
Daniel Nogradi wrote:
(...)
> 
> the egg file can not be downloaded completely, the connection is
> closed at byte 138903 all the time and the file is bigger than that.
> If anyone managed to grab the file please let me know so far I tried
> wget and firefox.

I've checked on my hd and found a recent (Jun 2006) checkout
on the original SVN repos.

There's everything in it: Subway code, web site and examples:



HTH

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


Re: Python tools to manipulate JARs ?

2007-01-31 Thread Laszlo Nagy
Andy Dingley írta:
> I run build processes for a Java shop using Python (and some Ant).
>
> Would anyone care to suggest favoured tools for manipulating the
> innards of JARs? Or do I just treat them as plain zipfiles and get
> stuck right in there?
>
> Mainly I'm trying to query lists of classes and their embedded
> versions and do some library dependency reporting. Performance speed
> is starting to be an issue, as there's 1500+ classes in this bucket
> and it's an interactive query.
>   
I believe that you can rename any jar file to .zip and use zip tools to 
list its contents.

   Laszlo

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


Re: DCOP memory leak?

2007-01-31 Thread David Boddie
On Jan 31, 6:46 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> The code I posted is not my actual program and was only to demonstrate
> my problem. The complete program I'm writing uses QT and so the loop
> is replaced by a Timer event.
> I tried out the suggestion. I had already tried the del dcop
> instruction, so I knew that wasn't it. I also placed the DCOP variable
> outside my loop but that didn't help either.

You might get a precise answer to your question if you send a message
to the PyQt/PyKDE mailing list:

  http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

The original authors and contributors of various Python DCOP modules
read that list, so there's a chance they can either solve your problem
or offer some advice on how to work around it.

> What I did notice that my program only grew in memory use when the
> 'ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() ' code was
> executed (or any other function using the AmarokDcopRes variable like
> 'ok, volume = AmarokDcopRes.player.getVolume()' )

Do you find the same problem with other DCOP interfaces?

David

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


Re: Any python scripts to do parallel downloading?

2007-01-31 Thread Michele Simionato
On Jan 31, 5:23 pm, "Frank Potter" <[EMAIL PROTECTED]> wrote:
> I want to find a multithreaded downloading lib in python,
> can someone recommend one for me, please?
> Thanks~

Why do you want to use threads for that? Twisted is the
obvious solution for your problem, but you may use any
asynchronous framework, as for instance the good ol
Tkinter:

"""
Example of asynchronous programming with Tkinter. Download 10 times
the same URL.
"""

import sys, urllib, itertools, Tkinter

URL = 'http://docs.python.org/dev/lib/module-urllib.html'

class Downloader(object):
chunk = 1024

def __init__(self, urls, frame):
self.urls = urls
self.downloads = [self.download(i) for i in range(len(urls))]
self.tkvars = []
self.tklabels = []
for url in urls:
var = Tkinter.StringVar(frame)
lbl = Tkinter.Label(frame, textvar=var)
lbl.pack()
self.tkvars.append(var)
self.tklabels.append(lbl)
frame.pack()

def download(self, i):
src = urllib.urlopen(self.urls[i])
size = int(src.info()['Content-Length'])
for block in itertools.count():
chunk = src.read(self.chunk)
if not chunk: break
percent = block * self.chunk * 100/size
msg = '%s: downloaded %2d%% of %s K' % (
self.urls[i], percent, size/1024)
self.tkvars[i].set(msg)
yield None
self.tkvars[i].set('Downloaded %s' % self.urls[i])

if __name__ == '__main__':
root = Tkinter.Tk()
frame = Tkinter.Frame(root)
downloader = Downloader([URL] * 10, frame)
def next(cycle):
try:
cycle.next().next()
except StopIteration:
pass
root.after(50, next, cycle)
root.after(0, next, itertools.cycle(downloader.downloads))
root.mainloop()


Michele Simionato

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


Re: subway

2007-01-31 Thread Daniel Nogradi
> > the egg file can not be downloaded completely, the connection is
> > closed at byte 138903 all the time and the file is bigger than that.
> > If anyone managed to grab the file please let me know so far I tried
> > wget and firefox.
>
> I've checked on my hd and found a recent (Jun 2006) checkout
> on the original SVN repos.
>
> There's everything in it: Subway code, web site and examples:
>
> 
>
> HTH

Great! Thanks very much indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to "free" an object/var ?

2007-01-31 Thread Terry Reedy

"John Nagle" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|If your data structure has no backlinks, it will go away
| as soon as the last reference to it disappears.
|In Python, garbage collection is mostly a backup to
| the reference counting system.

These both are true of the CPython implementation (current and known 
future, at least) but not of other implementations and not of the language 
itself.

The same comment applies to some other posts in this thread.  GC, if any, 
is implementation defined.

tjr



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


Re: emulate a serial port in windows (create a virtual 'com' port)

2007-01-31 Thread Bas-i
On Jan 30, 7:34 am, Pom <[EMAIL PROTECTED]> wrote:

> how can I emulate a serial port in windows?

Google for ComEmulDrv3

This may do what you want.

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


Re: Any python scripts to do parallel downloading?

2007-01-31 Thread Carl J. Van Arsdall
Michele Simionato wrote:
> On Jan 31, 5:23 pm, "Frank Potter" <[EMAIL PROTECTED]> wrote:
>   
>> I want to find a multithreaded downloading lib in python,
>> can someone recommend one for me, please?
>> Thanks~
>> 
>
> Why do you want to use threads for that? Twisted is the
> obvious solution for your problem, but you may use any
> asynchronous framework, as for instance the good ol
>   
Well, since it will be io based, why not use threads?  They are easy to 
use and it would do the job just fine.  Then leverage some other 
technology on top of that.

You could go as far as using wget via os.system() in a thread, if the 
app is simple enough. 

def getSite(site):
  os.system('wget %s',site)
 
threadList =[]
for site in websiteList:
   threadList.append(threading.Thread( target=getSite,args=(site,)))

for thread in threadList:
   thread.start()

for thread in threadList:
   thread.join()

> Tkinter:
>
> """
> Example of asynchronous programming with Tkinter. Download 10 times
> the same URL.
> """
>
> import sys, urllib, itertools, Tkinter
>
> URL = 'http://docs.python.org/dev/lib/module-urllib.html'
>
> class Downloader(object):
> chunk = 1024
>
> def __init__(self, urls, frame):
> self.urls = urls
> self.downloads = [self.download(i) for i in range(len(urls))]
> self.tkvars = []
> self.tklabels = []
> for url in urls:
> var = Tkinter.StringVar(frame)
> lbl = Tkinter.Label(frame, textvar=var)
> lbl.pack()
> self.tkvars.append(var)
> self.tklabels.append(lbl)
> frame.pack()
>
> def download(self, i):
> src = urllib.urlopen(self.urls[i])
> size = int(src.info()['Content-Length'])
> for block in itertools.count():
> chunk = src.read(self.chunk)
> if not chunk: break
> percent = block * self.chunk * 100/size
> msg = '%s: downloaded %2d%% of %s K' % (
> self.urls[i], percent, size/1024)
> self.tkvars[i].set(msg)
> yield None
> self.tkvars[i].set('Downloaded %s' % self.urls[i])
>
> if __name__ == '__main__':
> root = Tkinter.Tk()
> frame = Tkinter.Frame(root)
> downloader = Downloader([URL] * 10, frame)
> def next(cycle):
> try:
> cycle.next().next()
> except StopIteration:
> pass
> root.after(50, next, cycle)
> root.after(0, next, itertools.cycle(downloader.downloads))
> root.mainloop()
>
>
> Michele Simionato
>
>   


-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Re: Sorting a List of Lists

2007-01-31 Thread Bruno Desthuilliers
Paddy a écrit :
> On Jan 31, 12:35 pm, Bruno Desthuilliers >Also, using comparison functions is usually not the most efficient way
>>to do such a sort. In your case, I'd go for a good old
>>Decorate/sort/undecorate (AKA schwarzian transform):
>>
>>events = [evt for date, evt in
>>   sorted([(evt[2], evt) for evt in events])]
>>
>>HTH
> 
> 
> I agree with you B., but see the comments here:
>   http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-
> efficiency
> for information on the relative speeds of rolling your own DSU versus
> using itemgetter and key=...

Yeps, looks like 2.5 got a real speedup wrt/ itemgetter. Nice to know, 
and thanks for the link (BTW, this profileit() decorator looks pretty 
nice too !-)

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


Re: DCOP memory leak?

2007-01-31 Thread [EMAIL PROTECTED]
On 31 jan, 19:51, "David Boddie" <[EMAIL PROTECTED]> wrote:
> On Jan 31, 6:46 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
> > The code I posted is not my actual program and was only to demonstrate
> > my problem. The complete program I'm writing uses QT and so the loop
> > is replaced by a Timer event.
> > I tried out the suggestion. I had already tried the del dcop
> > instruction, so I knew that wasn't it. I also placed the DCOP variable
> > outside my loop but that didn't help either.
>
> You might get a precise answer to your question if you send a message
> to the PyQt/PyKDE mailing list:
>
>  http://mats.imk.fraunhofer.de/mailman/listinfo/pykde
>
> The original authors and contributors of various Python DCOP modules
> read that list, so there's a chance they can either solve your problem
> or offer some advice on how to work around it.
>
> > What I did notice that my program only grew in memory use when the
> > 'ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() ' code was
> > executed (or any other function using the AmarokDcopRes variable like
> > 'ok, volume = AmarokDcopRes.player.getVolume()' )
>
> Do you find the same problem with other DCOP interfaces?
>
> David

Hi David,

I did tried out some other DCOP calls from other programs and I have
the same problem.

I followed your suggestion to subcribe and poste to the pyKDE mailing
list. I hope they can help me there.

Thanks,

Tim

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


Re: Any python scripts to do parallel downloading?

2007-01-31 Thread Carl Banks
Michele Simionato wrote:
> On Jan 31, 5:23 pm, "Frank Potter" <[EMAIL PROTECTED]> wrote:
> > I want to find a multithreaded downloading lib in python,
> > can someone recommend one for me, please?
> > Thanks~
>
> Why do you want to use threads for that? Twisted is the
> obvious solution for your problem,

Overkill?  Just to download a few web pages?  You've got to be
kidding.

> but you may use any
> asynchronous framework, as for instance the good ol
> Tkinter:

Well, of all the things you can use threads for, this is probably the
simplest, so I don't see any reason to prefer asynchronous method
unless you're used to it.  One Queue for dispatching should be enough
to synchronize everything; maybe a Queue or simple lock at end as well
depending on the need.

The OP might not even care whether it's threaded or asynchronous.


Carl Banks

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


Re: Python **kwargs ?

2007-01-31 Thread Szabolcs Nagy

johnny wrote:
> What is **kwargs mean in python?  When you put double **, does it mean
> passing by reference?

here's a little example:

>>> def f(a, *args, **kw):
... print 'a:',a
... print 'args:',args
... print 'kw:',kw
...
>>> f(1,2,3,x=4)
a: 1
args: (2, 3)
kw: {'x': 4}
>>> f(a=1,b=2,c=3)
a: 1
args: ()
kw: {'c': 3, 'b': 2}

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


Re: Any python scripts to do parallel downloading?

2007-01-31 Thread Jean-Paul Calderone
On 31 Jan 2007 12:24:21 -0800, Carl Banks <[EMAIL PROTECTED]> wrote:
>Michele Simionato wrote:
>> On Jan 31, 5:23 pm, "Frank Potter" <[EMAIL PROTECTED]> wrote:
>> > I want to find a multithreaded downloading lib in python,
>> > can someone recommend one for me, please?
>> > Thanks~
>>
>> Why do you want to use threads for that? Twisted is the
>> obvious solution for your problem,
>
>Overkill?  Just to download a few web pages?  You've got to be
>kidding.

Better "overkill" (whatever that is) than wasting time re-implementing
the same boring thing over and over for no reason.

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


Re: Python 2.5 Tkinter not configured

2007-01-31 Thread Jim
Diez B. Roggisch wrote:

> Jim schrieb:
>> I compiled Python 2.5 from python.org and I get an error message when I
>> try to import the Tkinter module. Python reports that there is no such
>> module. It says my Python isn't configured for Tkinter. How do I
>> configure it? I'm using GCC 4.1.1 to compile the tarball. Thanks for any
>> help with this.
> 
> You need to have tcl/tk together with it's development-headers
> installed. Python _should_ figure out where things are, and then be
> configured to include tkinter.
> 
> Diez

That was the problem, I got it working after recompiling. Thanks.

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


  1   2   >