Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Michał Bartoszkiewicz
On 2006-08-09 at 08:02:03 (+0200), Stephan Kuhagen wrote:
> Don't yell at me for bringing in another language, but I really like the
> trick, Tcl does:
> 
> >#!/bin/sh
> ># The next line starts Tcl \
> >exec tclsh "$0" "$@"
> 
> This works by the somewhat weird feature of Tcl, that allows comments to be
> continued in the next line with "\" at the end of the comment-line. It
> looks unfamiliar, but has several advantages, I think. First it's really
> VERY unlikely, that there is no /bin/sh (while I found systems with
> different places for env), and you can add some other features at or before
> the actual call of the interpreter, i.e. finding the right or preferred
> version... - This way I coded a complete software-installer, that runs
> either as a Tcl/Tk-Script with GUI, or as bash-script, when no Tcl is
> available. - I really would like to have something like that for python,
> but I did not find a way to achieve that, yet.

You could use:
  #!/bin/sh
  """exec" python "$0" "$@"""
:)

-- 
 __  
|  \/  |  Michał Bartoszkiewicz <[EMAIL PROTECTED]>  | _ )
| |\/| |  GG:2298240 | _ \
|_|  |_|_For all resources, whatever it is, you need more. [RFC1925]_|___/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Stephan Kuhagen
Michał Bartoszkiewicz wrote:

> #!/bin/sh
> """exec" python "$0" "$@"""

Wow, cool... I like that!

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

Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Erik Max Francis
Stephan Kuhagen wrote:

> Michał Bartoszkiewicz wrote:
> 
>> #!/bin/sh
>> """exec" python "$0" "$@"""
> 
> Wow, cool... I like that!

Only someone genuinely fond of the Tcl hack could ...

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   No man who needs a monument ever ought to have one.
-- Nathaniel Hawthorne
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Unicode/utf-8 data in SQL Server

2006-08-09 Thread Laurent Pointal
John Machin a écrit :
> The customer should be very happy if you do
> text.decode('utf-8').encode('cp1252') -- not only should the file
> import into Excel OK, he should be able to view it in
> Word/Notepad/whatever.

+
text.decode('utf-8').encode('cp1252',errors='replace')

As cp1252 may not cover all utf8 chars.

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Stephan Kuhagen
Erik Max Francis wrote:

>>> #!/bin/sh
>>> """exec" python "$0" "$@"""
>> 
>> Wow, cool... I like that!
> 
> Only someone genuinely fond of the Tcl hack could ...

True, I admit, I'm a Tcl-Addict... But I really love Python too for many
reasons. But I miss features and tricks in both languages that I have in
the other...

Interleaving the script-language with shell-scripting was one of them. So
I'm a little bit happier with Python now... ;-)

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread ZeD
Stephan Kuhagen wrote:

>> #!/bin/sh
>> """exec" python "$0" "$@"""
> 
> Wow, cool... I like that!

yeah, but...

$ cat test.py
#!/bin/sh
"""exec" python "$0" "$@"""

print "Hello, world"
$ file test.py
test.py: Bourne shell script text executable

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


Re: import logging fails on MacPython 2.4.3

2006-08-09 Thread Diez B. Roggisch
Tod Olson schrieb:
> Anyone have advice for importing the logging module using MacPython 2.4.3?
> 
> MacPython installs the logging module in:
> 
> /Library/Frameworks/Python.framework/Versions/2.4/lib/logging/

On my machine, that is 
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/logging

> There's an __init__.py there and everything, but this directory is not
> in sys.path. I add it to sys.path as follows:
> 
>  >>> sys.path.append(os.path.join(sys.prefix, 'lib', 'logging'))
>  >>> print sys.path[-1]
> /Library/Frameworks/Python.framework/Versions/2.4/lib/logging


Which is wrong - you'd have to add the path without the logging part!

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Stephan Kuhagen
ZeD wrote:

> print "Hello, world"
> $ file test.py
> test.py: Bourne shell script text executable

Yes, the same happens with all Tcl-Scripts. I like to see this as a bug in
"file", not in the scripting...

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Erik Max Francis
Stephan Kuhagen wrote:

> Yes, the same happens with all Tcl-Scripts. I like to see this as a bug in
> "file", not in the scripting...

How does that make sense?  `file` cannot possibly understand the 
semantics of files at that level, at least not without executing them. 
And that's exactly what you _don't_ want to do when you're using `file` ...

The file _is_ a /bin/sh executable.  You're just having that /bin/sh 
executable run something else -- how could `file` figure that out 
without a ridiculously complicated set of rules that rise to the level 
of a sh interpreter -- thereby, defeating the purpose?

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Only those who dare to fail greatly can ever achieve greatly.
-- Robert F. Kennedy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Tobias Brox
[Erik Max Francis
> How does that make sense?  `file` cannot possibly understand the 
> semantics of files at that level, at least not without executing them. 
> And that's exactly what you _don't_ want to do when you're using `file` ...

This is very off-topic, but if it's fairly common to begin tcl-scripts
as a /bin/sh-file with "exec tcl" at one of the first lines, I think
"file" ought to be able to recognize it. 

"""exec" python is clearly an obscure hack not used by many, so I
don't see why "file" should ever recognize that :-)

-- 
Tobias Brox, 69°42'N, 18°57'E
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Erik Max Francis
Tobias Brox wrote:

> This is very off-topic, but if it's fairly common to begin tcl-scripts
> as a /bin/sh-file with "exec tcl" at one of the first lines, I think
> "file" ought to be able to recognize it. 
> 
> """exec" python is clearly an obscure hack not used by many, so I
> don't see why "file" should ever recognize that :-)

The point is, they're all part of the same tactic -- the particulars of 
sh.  Special casing each one is a task without an end.  People will come 
up with variants that will do the right thing but foil `file`, 
intentionally or unintentionally -- just as we've seen in this thread.

The right way to approach this with `file` is to acknowledge that such 
tricks are inherently sh-specific and leave it identified as a sh file. 
  Because that is, of course, exactly what it is.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Only those who dare to fail greatly can ever achieve greatly.
-- Robert F. Kennedy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Stephan Kuhagen
Tobias Brox wrote:

> This is very off-topic,

Sorry for starting that...

> but if it's fairly common to begin tcl-scripts 
> as a /bin/sh-file with "exec tcl" at one of the first lines, I think
> "file" ought to be able to recognize it.
> 
> """exec" python is clearly an obscure hack not used by many, so I
> don't see why "file" should ever recognize that :-)

That's what I meant. It is okay for a Python-script not to be recognized by
"file" that way, it is enough that I can do it, if I need to. But file
should recognize this for Tcl, because it is common there. And if it needs
to work for Tcl only, one can construct a simple mechanism for "file" to
check this.

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


Re: Unicode/utf-8 data in SQL Server

2006-08-09 Thread John Machin
Laurent Pointal wrote:
> John Machin a écrit :
> > The customer should be very happy if you do
> > text.decode('utf-8').encode('cp1252') -- not only should the file
> > import into Excel OK, he should be able to view it in
> > Word/Notepad/whatever.
>
> +
> text.decode('utf-8').encode('cp1252',errors='replace')
>
> As cp1252 may not cover all utf8 chars.

In that case, the OP may well want to use 'xmlcharrefreplace' or
'backslashreplace' as they stand out more than '?' *and* the original
Unicode is recoverable if necessary e.g.:

#>>> msg = u'\u0124\u0114\u0139\u013B\u0150'
>>> print msg
HELLO
#>>> msg.encode('cp1252', 'replace')
'?'
#>>> msg.encode('cp1252', 'xmlcharrefreplace')
'ĤĔĹĻŐ'
#>>> msg.encode('cp1252', 'backslashreplace')
'\\u0124\\u0114\\u0139\\u013b\\u0150'
#>>> 

Cheers,
John

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread ZeD
Erik Max Francis wrote:

> The file _is_ a /bin/sh executable.  You're just having that /bin/sh
> executable run something else -- how could `file` figure that out
> without a ridiculously complicated set of rules that rise to the level
> of a sh interpreter -- thereby, defeating the purpose?

but...

$ cat test.py
#!/usr/bin/env python

print "Hello, world"
$ file test.py
file.py: a python script text executable

following what you said, test.py is a /usr/bin/env script, not a python one.

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Tobias Brox
[Erik Max Francis]
> The point is, they're all part of the same tactic -- the particulars of 
> sh.  Special casing each one is a task without an end.  People will come 
> up with variants that will do the right thing but foil `file`, 
> intentionally or unintentionally -- just as we've seen in this thread.

I have no clue about Tcl, but it was said some postings ago that "all
Tcl-scripts are recognized as sh".  If this is true, I think it ought
to be fixed.  Searching for one of the very first lines to begin with
#, end with \, and followed by "exec tcl" doesn't sound like
rocket-science to me, though I've neither studied magic(4) or Tcl
scripting conventions.

I do understand that it would still be many ways to start a Tcl-script
without getting recognized by the above logic, as well as ways to
trick file into reporting a real shell script to be a Tcl-script.
IMHO a 90% hit rate is far better than 0% hit rate.

> The right way to approach this with `file` is to acknowledge that such 
> tricks are inherently sh-specific and leave it identified as a sh file. 
>   Because that is, of course, exactly what it is.

A shell script containing some inline tcl is a shell script, though
when the only shell-command is "start up tcl" and the rest of the file
is tcl-code, I really don't think it can be defined as a "shell
script" anymore.  Particularly not if almost all tcl-scripts are
started that way.

-- 
Tobias Brox, 69°42'N, 18°57'E
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie - How to iterate list or scalar ?

2006-08-09 Thread Bruno Desthuilliers
Terry Reedy wrote:
> "Bruno Desthuilliers" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> FWIW, the iterator protocol appeared with Python 2.2. Before this
>> version, the above solution was the only one that allowed iteration over
>> a container type.
>>
>> Now  if you wonder why string, unicode and buffer don't have __iter__
>> while other sequence types have it, ask your favourite Python guru (and
>> please keep me informed !-).
> 
> Giving that Python still has to support the old __getitem__ protocol in for 
> statements, there was no need to rewrite stuff that worked and no one did 
> so for those types. 

What I wonder here is why __iter__ has been added to lists and tuples
but not to strings (not that I'm complaining, it's just curiousity...)

> The emergent problem of identifying an 'iterable' had 
> been noted and Guido has, I believe, approved the addition of '__iter__' to 
> those types for 2.6.  (But someone still has to write the patches ;-)

Which is a GoodThing(tm) wrt/ consistency - and makes clear I should not
have talked about the hasattr(obj, '__iter__') hack.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class data being zapped by method

2006-08-09 Thread Bruno Desthuilliers
Simon Forman wrote:
(snip)
> Not that this has anything to do with your actual question, but there
> are a number of small details that I noticed while reading your code:
> 
> 
> 2.) Reading lines from a file is better done like so:
> 
> arrLines = open('datafiles/'+filename+'.tabdata').readlines()

Actually, it's better done like so:

fpath = os.path.join('datafiles', filename + ".tabdata")
f = open(fpath)
try:
  process_opened_file(f)
finally:
  f.close()

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


ALLAH

2006-08-09 Thread faruk . nur
Kader;

soru:madem,herşey bir kader defterinde yazılı ve herşey ona göre
oluyor.o halde insanlar niçin cehenneme gidiyor?
cevap:evet herşey bir kader defterinde yazılı ve herşey ona göre
oluyor.ama,defterde yazılı olduğu için o şey olmuyor.

mesela;meteroloji uzmanı,uydudan gelen fotoğraflara bakarak geleceği
görebilmektedir.bir insan ne kadar yükseğe çıkarsa hem görüş
alanı genişler hemde geleceği görebilir. uzman, uydudan görüyor
ki,Türkiye"nin batısından yağmur bulutları geliyor.bulutların
hızını ve yönünü hesaplıyarak,hemen defterine şunları
yazıyor,"yarın türkiye bulutlu ve yağışlı
olacak".bulutların gelmesine bir gün var.bir gün sonra türkiye
bulutlu ve yağışlı olsa;acaba meteroloji uzmanı bir gün önceden
deftere,bu olayı yazdığı içinmi olaylar oluyor?yoksa uzman
olayları uydudan önceden gördüdemi yazdı.

doğru cevap;gördüde yazdı.yazdığı için olaylar olmamakta,fakat
olayın öyle olacağını önceden görüp yazmıştır.

Mesela;aklı başında bir kişiyi, siz sırtınıza alsanız,nereye
gitmek istersen seni oraya götüreceğim deseniz,diyelim ki iki yol
var biri,tehlikeli yol, öteki tehlikesiz yol.siz baştan o kişiye
uyarıda bulunarak her iki yolun durumunu anlatsanız buna rağmen,o
kişi beni tehlikeli yoldan götür dese,o tehlikeli yolda başına bir
kaza gelse ,size diyebilirmi ki,bak senin yüzünden başıma bu kaza
geldi diyemez.çünkü kendi iradesiyle tehlikeli yolu
seçmiştir.götüren değil,isteyen suçludur.Güç ve kuvvet yalnız
Allah"tandır.bunu felçli hastalar daha iyi bilir.Götüren
Allah"tır, fakat tehlikeli yolda gitmek isteyen,insan suçludur. Hem
insan başıboş bırakılmış da değildir. Cüz-i iradesinden başka
kendisine ait  günahları ve borçları vardır.sevaptaki hissesi ise
pek azdır.Kimin ve neyin sayesinde  sevap işlemiştir düşünmesi
gerekir.




Allah;
birzaman gayet zengin bir ressam,sergi açmak istemiş,fakat sahnenin
gerisinde durmuş kendisini konuklara göstermemiş.konuklara
hertürlü ikramı yapmış.sergiyi gezen misafirler,harika resimlere
bakmışlar,ne kadar güzel resimler diyerek aralarında konuşurlarken
birisi, ressamı göremediği için, acaba bu resimler nasıl olmuştur
diye bir soru ortaya atmış.bir kısım insanlar,bu resimler kendi
kendine olmuştur demişler.bir kısım insanlar resimleri tabiiyyat
kanunlarının yaptığını iddia etmişler.bir kısım insanlar ise
resimleri,resmi meydana getiren,boya,fırça, tablo birlikte bu resmi
kafa kafaya vermişler  meydana getirmiştir demişler.bir kısım
insanlar ise,harika resimleri ancak bir ressam tarafından
yapılabileceğini söyleyerek,kendilerine ikramda bulunan ressamı
içeriden,alkışlar ile davet edip,kendisiyle tanışmış ve
teşekkür etmişler.işte biz,kainatın tek yaratıcısı olan, o
ressama Allah diyoruz. ressamdan farkı, gerçek ve canlı resimler
yaratmasıdır.

Resim,ressamın bir parçası olmadığı gibi; ressam da, resmin bir
parçası değildir.

Soru:Peki,Allah"ı kim yaratmıştır?sorusu(şeytanın insanları
kandırmak için sorduğu sorudur) genellikle insanların kafasının
karışmasına yol açmış,bu soruda takılıp kalmışlardır.
İnsanların bu sorunun cevabını bulmaya çalışması,nafiledir.

Mesela; diyelimki bir saraya girmek için yüz kapı var,ama bir kapı
kapalı ve sarayın sahibi ancak o kapıyı açabilir ve anahtarda
sadece ondadır.Dışarıdan saraya girmeye çalışan biri,açık
doksandokuz kapının herhangi birinden içeri girebilir.Fakat kapalı
kapının önünde durup o kapıyı açamayınca,bu saraya girilemez
diyemez,Çünkü diğer doksandokuz kapı açıktır.Aynen
öylede,Allah"ı kim yaratmıştır, sorusu farzedelim ki kapalı bir
kapıdır.O kapının anahtarı sadece Allah"tadır.Allah"a inanmak
için doksandokuz kapı açıktır.Ama inat edip,kapalı kapının
önünde durmak ve saray sahibini inkar etmek ve açık kapıdan saraya
girmemek akıl karı değildir.

Peki Allah yoksa,bu kainatı kim yaratmıştır? bu kainat nasıl
olmuştur?yani yukarıdaki harika resimler nasıl olmuştur? sorusunun
cevabını inat edenlerin vermesi gerekir.

İlmin kapısı Hz.Ali şöyle der,"Varsayalım ki inanmayan inat
edenlerin dediği gibi Allah,ahiret,cennet,hesap kitap, vs.yok.Ne
inanana bir şey olur,nede inanmamakta inat edene.Ama ya
varsa,"inanana yine bir şey olmaz ama inanmamakta inat eden; işini
şansa bırakmış olur ki buda akıl karı değildir.

Tevekkül ve dua;

bir çifçi,evvela(önşart);ürün almak için,1-toprağını nadasa
koyacak,2-toprağını sürecek,tohumu dikecek,3-sulayacak.vb.fiili dua
edecek.

Sonra; Allah"a ,ürün vermesi için kavli(sözlü) dua
edecek.Çünkü bir afet gelir ürünü alıp
götürebilir.Mesela;Çekirge ve sel afeti gibi.Şartlardan birinin
eksik olması,neticeye engeldir.
Dua eden kişi için o istediği, kendisi hakkında hayırlı olup
olmadığını dua eden bilemez.O halde duam niye,niçin kabül
edilmedi diye,üzülmemelidir.

Mesela;Bir anne ve baba hiçbir zaman çocuğunun kötülüğünü
istemediği için ,terbiyeye muhtaç çocuğunun her istediğini de
yapmaz .Bu imtihan dünyasında,sınırlı ve kayıtlı olduğumuz
için her istediğimizi elde edemeyiz,her istediğimizi
yapamayız.Fakat her istediğimizi elde edecek ve her istediğimizi
yapabileceğimiz bir yer vardır ki o ye

Best way to construct an email - attach a html file and send

2006-08-09 Thread a
What is the best way to construct an email in python and also attach a
html file

the html file to be attached is not on disk, but should be dynamically
constructed in the python script

I want to attach the django debug error to an email and mail it to
myself whenever there is an error in the application

thanks a lot
py

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


Re: Looking for an intellisense with good help IDE for Python

2006-08-09 Thread Marco Aschwanden
The best code completion you can get for Python is delivered by WingIDE:

http://wingware.com/

I have seen, PyDev, Kommodo, Spe and when it comes to code completion for  
Python than nothing beats WingIDE. Maybe anyone can proof the contrary.

WingIDE is not for free though (Personal: 35 USD upto Profession: 180 USD)  
- you can download a fully fuctional version and prolong it a few times...  
try it out, if you are willing to pay a few bucks.

Cheers,
Marco

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Slawomir Nowaczyk
On Mon, 07 Aug 2006 16:47:57 -0700
Jason <[EMAIL PROTECTED]> wrote:

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

I must admit I do not get this "indicate intentions twice" argument,
even though I heard it a number of times now... It's not that braces
require more work or more typing or something, after all -- at least
not if one is using a decent editor.

Really, typing brace after function/if/etc should add newlines and
indent code as required -- automatically. Actually, for me, it is even
*less* typing in C and similar languages... I probably should teach my
Emacs to automatically add newline after colon in Python, just as it
does after a brace in C... As soon as I figure out how to deal with
dictionary literals. Hmmm.

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

"Be strict when sending and tolerant when receiving."
 RFC 1958 - Architectural Principles of the Internet - section 3.9

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


Re: Nested function scope problem

2006-08-09 Thread Slawomir Nowaczyk
On Fri, 04 Aug 2006 14:09:15 -0300
Gerhard Fiedler <[EMAIL PROTECTED]> wrote:

#> > #> > I disagree. At least in my understanding, which, up to now, was
#> > #> > perfectly enough to explain everything about how Python variables
#> > #> > behave:
#> > #> > 
#> > #> > The address operator in C is what textual representation (i.e. what
#> > #> > you type, like "a") is in Python. Equivalent of id() is a dereference
#> > #> > operator.
#> > #> 
#> > #> But then you are not talking about C variables.
#> > 
#> > I am. The fact that Python variables behave like C pointers isn't
#> > overly relevant. A pointer is perfectly good C variable to me.
#> 
#> Let me try to make myself clear... Using your example, we have int*a. a is
#> a pointer to int. a is a C variable. *a is treated as an int; it may be a C
#> variable (of type int or not), but it often (maybe even more often than
#> not) is /not/ a C variable. When you request memory from the heap, you
#> don't get a C variable from the heap, you get a requested number of bytes.
#> This is not a C variable, it's only memory that gets written to using a
#> pointer.

I agree.

#> You can say that in the context of your application logic, that is an
#> application variable. But it is not a C language variable.

I am not saying that. All the time I am talking about "C variable" I
mean "a", not "*a".

#> The pointer itself (a) is of course a C variable. But you're not basing
#> your analogy on C pointer variables (a), you are basing it on whatever C
#> pointer variables point to (*a), which is in the general case not a C
#> variable (even though it can be one).

I beg to differ. I *am* basing my analogy on the fact that "a" is a
variable.

#> To better understand what I'm talking about, try to make a consistent
#> analogy. One side Python terms, on the other side the analogous C terms. 
#> 
#> You said previously:
#> >>> The address operator in C is what textual representation (i.e. what you
#> >>> type, like "a") is in Python. Equivalent of id() is a dereference
#> >>> operator.
#> 
#> Python === C
#> Textual representation a === Address operator (&a)
#> id(a) === Dereference operator (*a)

Nope. Equivalence table can look like this:

   Python C
variable:a  variable:  a
textual representation: "a" address operator: &a
id of object:   id(a)   dereference operator: *a

Also, notice, that "id(a)" does not really "identify" a variable. It
only identifies *object* which is bound to this variable. Both in
Python and in C.

#> I think I didn't quite translate what you meant, but you get the idea. I
#> don't think you can come up with a working analogy. The differences are
#> just too many -- if you consider the C language on the right side, not a
#> custom application you developed in C.

I do think this is a working analogy.

#> > #> Using a normal C variable, this doesn't work:
#> > #> 
#> > #>   int c = 5;
#> > #>   printf( "id(c)=%x", *c );
#> > 
#> > Depends on what do you expect. The above is kind of equivalent to,
#> > say:
#> > 
#> > locals()[5]
#> 
#> No. You said that in your analogy, the "Equivalent of id() is a dereference
#> operator." I took a C variable (c) and applied to it what you say is the
#> equivalent of id() in C: the dereference operator.

OK, I was sloppy... id( locals()[5] ) doesn't work either.

You take a C variable which doesn't point at any object. This can be
seen as taking id() of an unbound variable in Python. Of course, there
*is* a difference: you get an exception in Python, a segfault in C.
But I do not see how that justifies to claim that Python has no
variables.

#> Python:
#>   c = 5
#>   id(c)
#> C:
#>   int c = 5;
#>   printf( "id(c)=%x",*c);
#> 
#> If that is not correct according to your analogy, 

It is not. "int c=5" is not equivalent, in my analogy, to "c=5". In
fact, "int c=5" has no real equivalent in Python: you cannot have a
Python name (i.e. variable) have a *direct value* of 5: it has to be
bound to some object.

#> your analogy doesn't seem to be worded in the way you mean it.

Possibly. Does the table above explain my idea better?

#> > That's possible. I wouldn't expect too many C programmers to have any
#> > notion of "id of a variable". I, for example, never thought about such
#> > thing before this thread.
#> 
#> I'm not sure how much C you did. But the address of a variable is a quite
#> important concept in C; something that "identifies" the variable. For
#> example, it is important to distinguish between static, heap and stack
#> variables, and one of the main differences is their address space and the
#> different ways these address spaces get managed.

Sure. I do not know how is this relevant to current discussion,
though. Of course "address of variable" is important in C. Just as
textual representation is important in Python (allowing you to do
stuff like "eval('a+1')".

Obviously, *if* you consider address of a C variable 

Re: Nested function scope problem

2006-08-09 Thread Slawomir Nowaczyk
On Sun, 06 Aug 2006 11:37:46 -0300
Gerhard Fiedler <[EMAIL PROTECTED]> wrote:

#> On 2006-08-06 06:41:27, Slawomir Nowaczyk wrote:
#> 
#> > Since Python doesn't (supposedly) have variables, it couldn't have come
#> > from Python. 
#> 
#> The idea (of this part of the thread) was to find the analogy between C
#> variables and Python variables, at least that's what you said a few
#> messages ago.

Yes. *I* believe Python has variables. I was under an impression that
you do not. But I do not believe there is any "identity of a variable"
which corresponds to "id()". Still, you used such term -- repeatedly.

I do not know what do you mean by it.

#> You claimed that there exists such an analogy between C variables
#> and Python variables. 

Yes.

#> (We never disputed the existence of Python variables; not sure why
#> you come up with that now. That was so far back in this thread.)

Well, I *only* came out with C/Python analogy in order to show that it
actually *does* make sense to talk about variables in Python -- since
some people claimed Python variables are a completely different kind
of beast than C variables, thus we should not be using the same name.

It was never my goal to show that Python and C variables behave the
same way or anything.

So it seems like we misunderstood each others intents.

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

I don't care if I AM a lemming. I'm NOT going!

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


setup.py when you can't write to site-packages?

2006-08-09 Thread andybak
There are several gaps in my Python knowledge, one of which is the what
exactly setuptools does and how it works.

I'm on a shared host so can't write to site-packages therefore most
setup.py's fail.

My strategy for pure python packages is to run setup.py locally and
copy anything that gets put in site-packages across to the shared host
somewhere in my Python path. I'm sure there is a better solution!

What's the best approach for situations when you can't tamper with the
Python install?

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


Re: setup.py when you can't write to site-packages?

2006-08-09 Thread Diez B. Roggisch
andybak wrote:

> There are several gaps in my Python knowledge, one of which is the what
> exactly setuptools does and how it works.
> 
> I'm on a shared host so can't write to site-packages therefore most
> setup.py's fail.
> 
> My strategy for pure python packages is to run setup.py locally and
> copy anything that gets put in site-packages across to the shared host
> somewhere in my Python path. I'm sure there is a better solution!
> 
> What's the best approach for situations when you can't tamper with the
> Python install?

If you've got setuptools installed, you can use the development mode + a
staging dir that you put in your PYTHONPATH. Then the copying is done for
you.

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


Session implementation for Python

2006-08-09 Thread Vlad Dogaru
Hello,

is there any PHP-like implementation for sessions in Python? I fear 
that writing my own would be seriously insecure, besides I could 
actually learn a lot by inspecting the code.

The reason I am asking is that I would like to implement simple scripts 
which require login with CGI (no mod_python or Django -- I want to 
learn CGI first).

Thanks in advance,
Vlad

-- 
There is nothing more dangerous than an idea when it is the only one 
you have.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for an intellisense with good help IDE for Python

2006-08-09 Thread taleinat
Miki  gmail.com> writes:

> The IDLE that will come (soon) with Python 2.5 with have some
> intellisense. Not all that you requested but some of it.
> 

On the same note, IDLE's completion module has received some serious upgrades
recently (such as dictionary key completion and case-insensitive completion),
but these haven't made it into the main Python trunk yet. I maintain a stable
version of IDLE with many new features, including the much-improved completion,
which can be found at:

http://www.mashebali.com/?Tal_Einat%27s_IDLE

Feel free to download, comment, and report bugs :)

- Tal
reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))],
   [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3]

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


Re: Session implementation for Python

2006-08-09 Thread _max
Flup does sessions, in the form of a WSGI middleware:

http://www.saddi.com/software/flup/

Vlad Dogaru wrote:
> Hello,
>
> is there any PHP-like implementation for sessions in Python? I fear
> that writing my own would be seriously insecure, besides I could
> actually learn a lot by inspecting the code.
>
> The reason I am asking is that I would like to implement simple scripts
> which require login with CGI (no mod_python or Django -- I want to
> learn CGI first).
>
> Thanks in advance,
> Vlad
>
> --
> There is nothing more dangerous than an idea when it is the only one
> you have.

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


Re: import logging fails on MacPython 2.4.3

2006-08-09 Thread Tod Olson
Diez B. Roggisch wrote:
> Tod Olson schrieb:
>> Anyone have advice for importing the logging module using MacPython 
>> 2.4.3?
>>
>> MacPython installs the logging module in:
>>
>> /Library/Frameworks/Python.framework/Versions/2.4/lib/logging/
> 
> On my machine, that is 
> /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/logging

That's good to hear, as it agrees with the other Python installations 
I've examined. That locations makes much more sense than where it landed 
on my machine.

>> There's an __init__.py there and everything, but this directory is not
>> in sys.path. I add it to sys.path as follows:
>>
>>  >>> sys.path.append(os.path.join(sys.prefix, 'lib', 'logging'))
>>  >>> print sys.path[-1]
>> /Library/Frameworks/Python.framework/Versions/2.4/lib/logging
> 
> 
> Which is wrong - you'd have to add the path without the logging part!

Great, thanks!

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


Re: Session implementation for Python

2006-08-09 Thread Bruno Desthuilliers
Vlad Dogaru wrote:
> Hello,
> 
> is there any PHP-like implementation for sessions in Python? I fear 
> that writing my own would be seriously insecure, besides I could 
> actually learn a lot by inspecting the code.
> 
> The reason I am asking is that I would like to implement simple scripts 
> which require login with CGI (no mod_python or Django -- I want to 
> learn CGI first).

http://jonpy.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setup.py when you can't write to site-packages?

2006-08-09 Thread andybak
Thanks Diez.

For one thing I was getting setuptools mixed up with distutils. Then it
occurred to me that this might be covered in the standard distutils
docs (obvious I know but before I was thinking of it as a general
Python problem and therefore wasn't sure where it might be documented)

The solution was therefore right in plain view:
http://docs.python.org/inst/alt-install-windows.html (despite the
misleading url this page applies to Unix)

(Must. Check. Docs. Before. Posting.)

Diez B. Roggisch wrote:
> andybak wrote:
>
> > There are several gaps in my Python knowledge, one of which is the what
> > exactly setuptools does and how it works.
> >
> > I'm on a shared host so can't write to site-packages therefore most
> > setup.py's fail.
> >
> > My strategy for pure python packages is to run setup.py locally and
> > copy anything that gets put in site-packages across to the shared host
> > somewhere in my Python path. I'm sure there is a better solution!
> >
> > What's the best approach for situations when you can't tamper with the
> > Python install?
>
> If you've got setuptools installed, you can use the development mode + a
> staging dir that you put in your PYTHONPATH. Then the copying is done for
> you.
> 
> Diez

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread [EMAIL PROTECTED]
Slawomir Nowaczyk wrote:
>
> I must admit I do not get this "indicate intentions twice" argument,
> even though I heard it a number of times now... It's not that braces
> require more work or more typing or something, after all -- at least
> not if one is using a decent editor.

Its not the typing, its the fact that when you say the same thing
twice, there is the potential for them to get out of sync.  If the
method the compiler uses (braces) and the method the human uses
(indentation) to determine what the code does don't agree, then a
reader will be likely to misunderstand what it will actually do.  One
of the driving principles behind Python is that, because code will be
read more often than written, readability is more important.

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


Re: Question about using python as a scripting language

2006-08-09 Thread Wildemar Wildenburger
Steve Lianoglou wrote:
> Delaney, Timothy (Tim) wrote:
>> This is just asking for trouble.
>>
>> my_list = eval('import shutil; shutil.rmtree('/')')
> 
> Hah .. wow.
> 
> And in related news: you still shouldn't be taking candy from
> strangers.
> 
> Point well taken. Thanks for flagging that one.

Heck, whenever *is* it OK to use eval() then?

?-\
wildemar


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


Re: singleton decorator

2006-08-09 Thread Wildemar Wildenburger
Pedro Werneck wrote:
 class Singleton(object):
> ... def __new__(cls, *args, **kwds):
> ... try:
> ... return cls._it
> ... except AttributeError:
> ... cls._it = object.__new__(cls, *args, **kwds)
> ... return cls._it
> 
> But __init__ will be called once for each time you call A, even if it's
> always the same instance returned. If this is a problem, you'll need
> another method to use for initialization and call it only once.
> 

Or you could always just use the __new__() method instead of __init__(), 
putting all your initialization into the above except-block. If you 
replace 'cls._it = ...' with 'self = cls_it = ...' you'll feel right at 
home too :).

Anything 'unpythonic' (gosh how I hate that word ;)) about that, BTW?

c.u.
wildemar

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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread msoulier
John Salerno wrote:
> I understand the difference, but I'm just curious if anyone has any
> strong feelings toward using one over the other?

I personally prefer being explicit over implicit, but then, that is in
the Zen of Python.

I work on machines with multiple interpreters installed. I find picking
the first one in the path to be very annoying. That means that it's
going to work differently for different people based on their PATH.

Mike

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


Re: singleton decorator

2006-08-09 Thread Pedro Werneck
On Tue, 08 Aug 2006 14:50:39 +0200
Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:

> Or you could always just use the __new__() method instead of
> __init__(),  putting all your initialization into the above
> except-block. If you  replace 'cls._it = ...' with 'self = cls_it =
> ...' you'll feel right at  home too :).
> 
> Anything 'unpythonic' (gosh how I hate that word ;)) about that, BTW?

Yes. :)

You'll have to make a custom Singleton class for each subclass you want
to make a singleton, instead of just creating a custom _init method for
each one of them.

You can use the subclass __new__, but that's definitely 'unpythonic'. 

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Pierre Barbier de Reuille
Carl Banks wrote:
> Michiel Sikma wrote:
>> Op 8-aug-2006, om 1:49 heeft Ben Finney het volgende geschreven:
>>
>>> As others have pointed out, these people really do exist, and they
>>> each believe their preconception -- that significant whitespace is
>>> intrinsically wrong -- is valid, and automatically makes Python a
>>> lesser language.
>> Well, I most certainly disagree with that, of course, but you gotta
>> admit that there's something really charming about running an auto-
>> formatting script on a large piece of C code, turning it from an
>> unreadable mess into a beautifully indented and organized document.
> 
> The only time I get that satisfaction is when I run the formatter to
> format some C code I'm asked to debug.  Quite often the problem was
> something that could have been easily spotted if the coder had used
> good indentation in the first place.  Though they probably wouldn't
> have seen it anyways, considering the poor programming skills of most
> engineers (the classical definition, not computer engineers).
> 
> The very fact the code formatters exist should tell you that grouping
> by indentation is superior.
> 
> 
> Carl Banks
> 

Problem being : grouping by indentation do *not* imply good indentation.
For example, I had to read a piece of (almost working) code which looked
like that :


  if cond1 : stmt1
 stmt2
 stmt3
  if cond2:  stmt4
 stmt5
  elif cond3:stmt6
 stmt7
  else:  stmt8
 stmt9
 stmt10
 stmt11



So you can tell what you want, but this code is valid but impossible to
read and impossible to reindent correctly. So although I personnaly like
Python, I still don't think meaningful indentation is good.

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Jean-Paul Calderone
On Wed, 09 Aug 2006 13:47:03 +0100, Pierre Barbier de Reuille <[EMAIL 
PROTECTED]> wrote:
>Carl Banks wrote:
>> Michiel Sikma wrote:
>>> Op 8-aug-2006, om 1:49 heeft Ben Finney het volgende geschreven:
>>>
 As others have pointed out, these people really do exist, and they
 each believe their preconception -- that significant whitespace is
 intrinsically wrong -- is valid, and automatically makes Python a
 lesser language.
>>> Well, I most certainly disagree with that, of course, but you gotta
>>> admit that there's something really charming about running an auto-
>>> formatting script on a large piece of C code, turning it from an
>>> unreadable mess into a beautifully indented and organized document.
>>
>> The only time I get that satisfaction is when I run the formatter to
>> format some C code I'm asked to debug.  Quite often the problem was
>> something that could have been easily spotted if the coder had used
>> good indentation in the first place.  Though they probably wouldn't
>> have seen it anyways, considering the poor programming skills of most
>> engineers (the classical definition, not computer engineers).
>>
>> The very fact the code formatters exist should tell you that grouping
>> by indentation is superior.
>>
>>
>> Carl Banks
>>
>
>Problem being : grouping by indentation do *not* imply good indentation.
>For example, I had to read a piece of (almost working) code which looked
>like that :
>
>
>  if cond1 : stmt1
> stmt2
> stmt3
>  if cond2:  stmt4
> stmt5
>  elif cond3:stmt6
> stmt7
>  else:  stmt8
> stmt9
> stmt10
> stmt11
>

This isn't actually legal Python.  Each branch starts with a simple suite and 
then proceeds to try to have a full suite as well.  A block can consist of one 
or the other, but not both.  Additionally, the nested if/elif has the wrong 
indentation and fits into no suite.

The closest legal example I can think of is:

  if cond1 :
 stmt2
 stmt3
 if cond2:
stmt5
 elif cond3:
stmt7
  else:
 stmt9
 stmt10
 stmt11

Which, while ugly, actually makes it much clearer what is going on.

>
>So you can tell what you want, but this code is valid but impossible to
>read and impossible to reindent correctly. So although I personnaly like
>Python, I still don't think meaningful indentation is good.

If your example were actually valid (which it isn't), all it would
demonstrate is that Python should be even stricter about indentation,
since it would have meant that there is still some whitespace which
has no meaning and therefore can be adjusted in meaingless ways by
each programmer, resulting in unreadable junk.

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


need hint for refactoring

2006-08-09 Thread GHUM
I have a bunch of function like:

def p2neufrage(_):
""" create new element"""
anfrage,ergebnis=getanfrage()
if ergebnis.get("status","ok") == "ok":
wert=anfrage["feld"]
# do something
# unique here


ergebnis["innerHTML"]=. something 

#
return simplejson.dumps(ergebnis, skipkeys=False,
ensure_ascii=False, check_circular=True, allow_nan=True)


so, everywhere there is the same beginning:

anfrage,ergebnis=getanfrage()

I analyze some transmitted jason-document; check for errors

then I take the values out of the request, process it and fill the
slots of a result ("ergebnis") dictionary, which is returned.


So the beginning and the end of the function is allways repeated. It
would be great to factor it out ... i startet with that ...getanfrage()
call. 

Is there anything more possible?

Thanks for any hint

Harald

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


Re: need hint for refactoring

2006-08-09 Thread Diez B. Roggisch
GHUM wrote:

> I have a bunch of function like:
> 
> def p2neufrage(_):
> """ create new element"""
> anfrage,ergebnis=getanfrage()
> if ergebnis.get("status","ok") == "ok":
> wert=anfrage["feld"]
> # do something
> # unique here
> 
> 
> ergebnis["innerHTML"]=. something 
> 
> #
> return simplejson.dumps(ergebnis, skipkeys=False,
> ensure_ascii=False, check_circular=True, allow_nan=True)
> 
> 
> so, everywhere there is the same beginning:
> 
> anfrage,ergebnis=getanfrage()
> 
> I analyze some transmitted jason-document; check for errors
> 
> then I take the values out of the request, process it and fill the
> slots of a result ("ergebnis") dictionary, which is returned.
> 
> 
> So the beginning and the end of the function is allways repeated. It
> would be great to factor it out ... i startet with that ...getanfrage()
> call.
> 
> Is there anything more possible?

Use a decorator, out of my head:

def foo(f):
def _w(*args, **kwargs):
anfrage,ergebnis=getanfrage()
new_args = (args[0],) + (anfrage, ergebnis) + args[1:]
f(*new_args, **kwargs)
return simplejson.dumps(ergebnis, skipkeys=False,
ensure_ascii=False, check_circular=True, allow_nan=True)

return _w

Then do

@foo
def p2neufrage(_, anfrage, ergebnis):
""" create new element"""
if ergebnis.get("status","ok") == "ok":
wert=anfrage["feld"]
# do something
# unique here
ergebnis["innerHTML"]=. something 


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


Re: Regd:Video Converter Programming

2006-08-09 Thread Grant Edwards
On 2006-08-09, placid <[EMAIL PROTECTED]> wrote:

>> I want to write an avi to flv converter in php but i am a complete
>> newbie to it.

> via a Google search for "python video convert" i found the following
>
> http://pymedia.org/

Except he wants to write it in PHP.

Not sure why he's asking us about it here in c.l.python.

-- 
Grant Edwards   grante Yow!  Like I always
  at   say -- nothing can beat
   visi.comthe BRATWURST here in
   DUSSELDORF!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about using python as a scripting language

2006-08-09 Thread Slawomir Nowaczyk
On Tue, 08 Aug 2006 14:32:32 +0200
Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:

#> Steve Lianoglou wrote:
#> > Delaney, Timothy (Tim) wrote:
#> >> This is just asking for trouble.
#> >>
#> >> my_list = eval('import shutil; shutil.rmtree('/')')
#> > 
#> > Hah .. wow.
#> > 
#> > And in related news: you still shouldn't be taking candy from
#> > strangers.
#> > 
#> > Point well taken. Thanks for flagging that one.
#> 
#> Heck, whenever *is* it OK to use eval() then?

eval is like optimisation. There are two rules:

Rule 1: Do not use it.
Rule 2 (for experts only): Do not use it (yet).

:)

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

The good people sleep much better at night than the bad people. Of course,
the bad people enjoy the waking hours much more.

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


Re: Best way to construct an email - attach a html file and send

2006-08-09 Thread Larry Bates
a wrote:
> What is the best way to construct an email in python and also attach a
> html file
> 
> the html file to be attached is not on disk, but should be dynamically
> constructed in the python script
> 
> I want to attach the django debug error to an email and mail it to
> myself whenever there is an error in the application
> 
> thanks a lot
> py
> 
Here is a link to a class that will allow you to attach files.  You
can either write the HTML to a tempfile and attach or modify a
little to accept a string or cstringIO object instead.  Hope it
helps.

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


Re: How to reverse tuples in a list?

2006-08-09 Thread Boris Borcic
Applying the perl motto (there is more than one way to do it) sure enough leads 
to a perlish solution... as measured by line noise.

 >>> t = [('a', 11,1.0), ('b',22,2.0),('c',33,3.0)]
 >>> zip(*zip(*t)[::-1])
[(1.0, 11, 'a'), (2.0, 22, 'b'), (3.0, 33, 'c')]

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Brett g Porter
[EMAIL PROTECTED] wrote:
> Its not the typing, its the fact that when you say the same thing
> twice, there is the potential for them to get out of sync.  If the
> method the compiler uses (braces) and the method the human uses
> (indentation) to determine what the code does don't agree, then a
> reader will be likely to misunderstand what it will actually do.  One
> of the driving principles behind Python is that, because code will be
> read more often than written, readability is more important.

Not to mention the errors that creep in when code is maintained, like 
when C code starting out as

if (i < SOME_CONSTANT)
doSomething();

gets "maintained" to

if (i < SOME_CONSTANT)
doSomething();
doSomethingDangerous();

without the programmer adding the surrounding braces. The programmer's 
intent is clear to me as a human, but the C compiler will disagree with 
me, and in this case, the compiler will be right and I'm wrong.

You can (and we do, at my company) have coding standards that mandate 
braces around single line if()s in C/C++, but that's really just 
patching around the problem (and it counts on humans being consistent).

Pushing the scutwork down onto tools is not as good a solution as 
eliminating the scutwork, especially when it shouldn't be necessary at 
all...




-- 
// Brett g Porter * [EMAIL PROTECTED]
// http://www.bgporter.net/blog
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to construct an email - attach a html file and send

2006-08-09 Thread skip

py> What is the best way to construct an email in python and also attach
py> a html file
...

Check out the email package.

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


Re: setup.py when you can't write to site-packages?

2006-08-09 Thread skip

andy> What's the best approach for situations when you can't tamper with
andy> the Python install?

python setup.py install --prefix=/some/where/else

The arg to --prefix is analogous to /usr or /usr/local.  For example, if you
are running Python 2.4, your files will wind up in

/some/where/else/lib/python2.4/site-packages

Just add that directory to PYTHONPATH and you should be good to go.

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


Re: Question about using python as a scripting language

2006-08-09 Thread skip

Wildemar> Heck, whenever *is* it OK to use eval() then?

When you're sure of the validity of the string you are feeding it.
Unfortunately, the more you know about the string (and thus how valid it is
in your current context), the less you need eval.  For example, if I know a
string s only contains digits and I want an integer out of the result, I can
avoid eval() by calling int(s).  Even if I don't know for sure that it's a
string of digits I'm still better off calling int() and trapping any
exceptions:

try:
n = int(s)
except ValueError:
print "hmmm...", repr(s), "doesn't look like an integer to me."

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, 
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes
>of the driving principles behind Python is that, because code will be
>read more often than written, readability is more important.

In which case, for long functions with multiple levels of indentation 
Python fails compared to languages that use braces or END or end; etc.

Stephen
-- 
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk/software.html
Computer Consultancy, Software Development
Windows C++, Java, Assembler, Performance Analysis, Troubleshooting
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do people really complain about significant whitespace?

2006-08-09 Thread skip

>> of the driving principles behind Python is that, because code will be
>> read more often than written, readability is more important.

Stephen> In which case, for long functions with multiple levels of
Stephen> indentation Python fails compared to languages that use braces
Stephen> or END or end; etc.

No.  In that case Python makes it more readily apparent that your code is
too complex.  With C, Java, C++, Perl or FORTRAN you just smush everything
over to the left and pretend it's not. ;-)

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


Re: How to reverse tuples in a list?

2006-08-09 Thread Sion Arrowsmith
Robert Kern  <[EMAIL PROTECTED]> wrote:
>Python 2.4+:
>
>   y = [tuple(reversed(t)) for t in y]
>

Python 2.3:

   y = [ t[::-1] for t in y ]

Obviously works in 2.4 as well, where I make it faster than using
tuple(reversed(t)). Which isn't surprising, as it's not constructing
the intermediate list.

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

Re: do people really complain about significant whitespace?

2006-08-09 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, 
Gerhard Fiedler <[EMAIL PROTECTED]> writes
>But there is well-written code that is as much as reasonably possible
>self-documenting, meaning easy to read and understand, with a clear
>structure, helpful names, appropriate types (where applicable) etc etc.

But that code is documenting what is does, not what it should do.
That is the fallacy of self-documenting. It is simply a bogus concept. 
If you have the two together then if they match, most likely the program 
is written correctly. If you have only the one you can't make the 
comparison.

I don't think you should have a line of comment per line of code. I once 
worked in a place where they insisted on 1 comment per 5 lines of code. 
I was the #1 troublemaker there after they created that rule - I hated 
it. It resulted in a lot of bogus comments that added nothing. Its what 
you write and where. The problem with the self-documenting crowd is they 
don't write anything so you can't follow their assumptions in the 
comments.

It should be as sparse as you can get but enough so that each 
block/chunk of code can be validated by comparing it with the comment 
that describes what you are doing.

My first code was basic on a VIC-20, then assembly on a variety of 
different 6502/6510 based machines (C64, C16, Atari...). I didn't bother 
much with comments back then. I was writing games and once they are done 
you never revisit them so you didn't care too much as long as you got 
the job done. I thought it was reasonably obvious what each function did 
etc. Ding! I went back some years later and looked at some of my own 
code. I had little idea what a lot of it did. I started commenting my 
code after that. So when it came time to port a game written for the 
6510/6516/6502 to the 68000 (Atari ST) and IBM PC-AT (80286) the 
comments came in handy. Sadly the game never saw the light of day for 
legal reasons outside of my control. The game was a copy of the 
wonderful arcade game "Dingo" written by Ashbury Computers and Graphics 
(the team that later became Ultimate Play the Game who wrote for the 
Sinclair ZX Spectrum very successfully in the 1980s). A bit of history 
for you :-)

Since someone mentioned assemblers and significant whitespace and I'm 
rambling about assembly: I don't every remember whitespace being 
significant for any of the assemblers I used (650x, 630x, 680x, 8085, 
80286, 68000). There was a convention though - you indented to column 8 
to write the mnemonics and used the first 6 or 7 chars for labels for 
branch/jmp instructions.

>Come on, if you have been in the business for 23 years you know what I
>mean.

If you mean, should code be well written, thought about, well formatted, 
sensible class/variable names, redesigned if you find a better way, sure 
no problem with that.

Stephen
-- 
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk/software.html
Computer Consultancy, Software Development
Windows C++, Java, Assembler, Performance Analysis, Troubleshooting
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do people really complain about significant whitespace?

2006-08-09 Thread Slawomir Nowaczyk
On Wed, 09 Aug 2006 05:00:20 -0700
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

#> Slawomir Nowaczyk wrote:
#> >
#> > I must admit I do not get this "indicate intentions twice" argument,
#> > even though I heard it a number of times now... It's not that braces
#> > require more work or more typing or something, after all -- at least
#> > not if one is using a decent editor.
#> 
#> Its not the typing, its the fact that when you say the same thing
#> twice, there is the potential for them to get out of sync.  

Which, in my book, is the *right* thing... if I see a wrongly indented
piece of code, that's a good sign that it needs to be checked. It's
the same principle as in "if documentation and code disagree, both are
probably wrong."

YMMV, of course.

#> If the method the compiler uses (braces) and the method the human
#> uses (indentation) to determine what the code does don't agree,
#> then a reader will be likely to misunderstand what it will actually
#> do.

Well, not in my experience. In my experience, such discrepancies
usually only show up in places where something bad happens anyway.

#> One of the driving principles behind Python is that, because code
#> will be read more often than written, readability is more
#> important.

That's exactly my point :)

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

Today advance is so rapid that even the astronauts who set foot on the
moon in 1969 had never seen a digital watch

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Slawomir Nowaczyk
On Wed, 09 Aug 2006 09:13:21 -0500
[EMAIL PROTECTED] wrote:

#> 
#> >> of the driving principles behind Python is that, because code will be
#> >> read more often than written, readability is more important.
#> 
#> Stephen> In which case, for long functions with multiple levels of
#> Stephen> indentation Python fails compared to languages that use braces
#> Stephen> or END or end; etc.
#> 
#> No.  In that case Python makes it more readily apparent that your code is
#> too complex.  With C, Java, C++, Perl or FORTRAN you just smush everything
#> over to the left and pretend it's not. ;-)

Well, one space is sufficient indentations for Python, right? So even
on 80 column screen, you can easily fit about 40 levels of nesting
before it becomes a real problem :D

In other words, it is possible to write bad code in any language. We
should focus on making it easier to write good code, not to make
writing bad code difficult.

-- 
 Best wishes,
   Slawomir Nowaczyk
 ( [EMAIL PROTECTED] )

The nice thing about standards is that there are so
many of them to choose from.

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


Re: Best way to construct an email - attach a html file and send

2006-08-09 Thread Grant Edwards
On 2006-08-09, a <[EMAIL PROTECTED]> wrote:

> What is the best way to construct an email in python and also
> attach a html file
>
> the html file to be attached is not on disk, but should be
> dynamically constructed in the python script

Sounds like a job for MimeWriter to me.

-- 
Grant Edwards   grante Yow!  BEEP-BEEP!! I'm a
  at   '49 STUDEBAKER!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class data being zapped by method

2006-08-09 Thread Sion Arrowsmith
Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>fpath = os.path.join('datafiles', filename + ".tabdata")

fpath = os.path.join('datafiles', filename + os.path.extsep + "tabdata")

8-) I'm a bit bemused by extsep -- it didn't appear until 2.2, by
which time there can't have been many people with an OS where it was
anything other than '.'.

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

Re: do people really complain about significant whitespace?

2006-08-09 Thread Carl Banks
Stephen Kellett wrote:
> In message <[EMAIL PROTECTED]>,
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes
> >of the driving principles behind Python is that, because code will be
> >read more often than written, readability is more important.
>
> In which case, for long functions with multiple levels of indentation
> Python fails compared to languages that use braces or END or end; etc.

I don't really understand how a closing brace helps here.  Care to
explain why it helps you?

(Deeply nested long functions are evil anyways.  If you have such a
function then you have bigger problems than minor defects in
readability. :)


Carl Banks

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread skip

Slawomir> #> No.  In that case Python makes it more readily apparent
Slawomir> #> that your code is too complex.  With C, Java, C++, Perl or
Slawomir> #> FORTRAN you just smush everything over to the left and
Slawomir> #> pretend it's not. ;-)

Slawomir> Well, one space is sufficient indentations for Python, right? So 
even
Slawomir> on 80 column screen, you can easily fit about 40 levels of nesting
Slawomir> before it becomes a real problem :D

Oh, sure.  Hence the smiley in my post...

Smileys all around.  I'm happy.

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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Rob Wolfe

Slawomir Nowaczyk wrote:

> Really, typing brace after function/if/etc should add newlines and
> indent code as required -- automatically. Actually, for me, it is even
> *less* typing in C and similar languages... I probably should teach my
> Emacs to automatically add newline after colon in Python, just as it
> does after a brace in C... As soon as I figure out how to deal with
> dictionary literals. Hmmm.

Are you sure? My Emacs already know how to do it with the help
of python-mode and magic function py-newline-and-indent.

emacs-version "21.3.1"
py-version "$Revision: 4.63 $"

Regards,
Rob

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


Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread Brendon Towle
Slawomir Nowaczyk noted:#> Heck, whenever *is* it OK to use eval() then?eval is like optimisation. There are two rules:Rule 1: Do not use it.Rule 2 (for experts only): Do not use it (yet).So, that brings up a question I have. I have some code that goes out to a website, grabs stock data, and sends out some reports based on the data.Turns out that the website in question stores its data in the format of a Python list (http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search the source for "var table_body"). So, the part of my code that extracts the data looks something like this:    START_MARKER = 'var table_body = '    END_MARKER = '];'    def extractStockData(data):    pos1 = data.find(START_MARKER)    pos2 = data.find(END_MARKER, pos1)    return eval(data[pos1+len(START_MARKER):END_MARKER])(I may have an off-by-one error in there somewhere -- this is from memory, and the code actually works.)My question is: what's the safe way to do this?B. -- Brendon Towle, PhDCognitive Scientist+1-412-690-2442x127Carnegie Learning, Inc.The Cognitive Tutor Company ®Helping over 375,000 students in 1000 school districts succeed in math. -- 
http://mail.python.org/mailman/listinfo/python-list

Re: ALLAH

2006-08-09 Thread Skip Montanaro
Sybren Stuvel  YOURthirdtower.com.imagination> writes:

> You might want to try in English.

Given the subject of the message, I suspect he wasn't trying to reach an
English-speaking audience... ;-)

Skip



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


Re: do people really complain about significant whitespace?

2006-08-09 Thread Carl Banks
Pierre Barbier de Reuille wrote:
> Problem being : grouping by indentation do *not* imply good indentation.

By itself, it doesn't.  But with grouping by indentation, bad
indentation no longer results from mere carelessness, which is no small
thing.

Although Python doesn't do this, it is possible to mandate a specific
indent (4 spaces, say), or at least a reasonable consistent indent,
which would indeed all but guarantee good indenting.  (I say "all but"
only to account for deliberately misleading code, perhaps using clever
line breaks and comments.)


> For example, I had to read a piece of (almost working) code which looked
> like that :
>
>   if cond1 : stmt1
>  stmt2
>  stmt3
>   if cond2:  stmt4
>  stmt5
>   elif cond3:stmt6
>  stmt7
>   else:  stmt8
>  stmt9
>  stmt10
>  stmt11
>
> So you can tell what you want, but this code is valid but impossible to
> read and impossible to reindent correctly. So although I personnaly like
> Python, I still don't think meaningful indentation is good.

Even if this were legal code (it isn't), it's still more transparent
than some of the C code I've seen.


Carl Banks

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


Re: beginner questions on embedding/extending python with C++

2006-08-09 Thread Hoop
Hi All,
I am in the process also of trying to call Python script from a C++
windows app.
I have looked at the Boost site and am currently reading over the
Embedding portion of the tutorial. A question I have is that there
appear to be about 4 or 5 Boost items avaiable for download. Which one
should be downloaded to do the embedding?
Thanks
Jeff
Qun Cao wrote:
> Thanks for all the good pointers!
> I am still reading throught them, but Boost seems to be the way to go!
>
> Roman Yakovenko wrote:
> > On 8 Aug 2006 02:28:31 -0700, Qun Cao <[EMAIL PROTECTED]> wrote:
> > > Hi Everyone,
> > >
> > > I am a beginner on cross language development. My problem at hand is to
> > > build a python interface for a C++ application built on top of a 3D
> > > game engine.  The purpose of this python interface is providing a
> > > convenient scripting toolkit for the application.
> >
> > As for me, Boost.Python is the way to go.
> >
> > Fortunately you are not the first one, and I hope not the last one :-) :
> >
> > http://language-binding.net/pyplusplus/quotes.html#who-is-using-pyplusplus
> > 1. Python-OGRE
> >   * http://lakin.weckers.net/index_ogre_python.html
> >   * http://tinyurl.com/mvj8d
> >
> > 2. http://cgkit.sourceforge.net/ - contains Python bindings for Maya C++ SDK
> >
> > 3. PyOpenSG - https://realityforge.vrsource.org/view/PyOpenSG/WebHome
> >The goal of PyOpenSG is to provide python bindings for the OpenSG
> >scene graph.
> >
> > > Since the main program is still going to be the C++ application, I
> > > guess we need to embedding the python scripts in the C++ code.
> >
> > Boost.Python is the only tool that provides complete functionality(
> > extending and
> >   embedding ). Also I think cgkit is dealing with the problem too.
> >
> > > But for this to work, the python code needs to know the Player class,
> > > is it right?
> >
> > Right.
> >
> > Does that mean I need to build a python wrapper class for
> > > Player and "import Player" in the python code?  But because this
> > > application is built on top of a game engine, Player class inherits
> > > many classes from there, I cannot possibly wrapping them all, right?
> >
> > It depends on how much functionality you want to export.
> >
> > > Also, some global objects are probably needed in this code of adding
> > > players, how can the python code access them?
> >
> > Boost.Python provides the functionality you need.
> >
> > > Btw, if you can point me to any source code of non-trivial projects
> > > utilizing SWIG/Boost.Python, that would be very helpful.  I found the
> > > examples on the tutorials are far too simple.
> >
> > Those are tutorials, they should be simple, right :-) ?
> >
> > --
> > Roman Yakovenko
> > C++ Python language binding
> > http://www.language-binding.net/

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


using python with tar files and compressed files

2006-08-09 Thread John Salerno
Here's the name of a file I have: wxPython-newdocs-2.6.3.3.tar.bz2

Now, I tried this:

import tarfile
tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2')

but got this:

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2')
   File "C:\Python24\lib\tarfile.py", line 901, in open
 return func(name, filemode, fileobj)
   File "C:\Python24\lib\tarfile.py", line 1006, in bz2open
 raise ReadError, "not a bzip2 file"
ReadError: not a bzip2 file

So I'm a little confused. When dealing with a tar.gz or tar.bz2 file, do 
you need to uncompress it first with the proper module (gzip or bz2)? Or 
does tarfile take care of this? If so, why doesn't it recognize the 
above file? Or am I just doing it the wrong way? (I'm following an 
example in the docs)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do people really complain about significant whitespace?

2006-08-09 Thread Michiel Sikma

Op 9-aug-2006, om 16:48 heeft Carl Banks het volgende geschreven:

> Even if this were legal code (it isn't), it's still more transparent
> than some of the C code I've seen.
>
>
> Carl Banks

Still kind of too bad that means there won't ever be an International  
Obfuscated Python Code Contest.

#define _ -F<00||--F-OO--;
int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO()
{
 _-_-_-_
_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_
   _-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
   _-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_
 _-_-_-_
}

:)

Michiel

(source: http://www0.us.ioccc.org/years.html#1988)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread skip

Brendon> Turns out that the website in question stores its data in the
Brendon> format of a Python list
Brendon> (http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search the
Brendon> source for "var table_body"). So, the part of my code that
Brendon> extracts the data looks something like this:

...
Brendon>  return eval(data[pos1+len(START_MARKER):END_MARKER])

Brendon> My question is: what's the safe way to do this?

At the top level the lines look like a Python list.  On a line-by-line basis
they also have consistent structure.  Read it line-by-line, parse the lines
(using regular expressions or whatever), then append the parsed values to a
list, something like (untested):

import re
symbolinfo = []
sympat = re.compile(
r'\[',
r'"(?P[^"]+)",'
r' *"(?P[^"]+)",'
r' *(?[^,]+,'
r' *(?[^,]+,'
r' *(?[^,]+,'
r' *(?[^,]+,'
r' *(?[^,]+,'
r' *"(?P[^"]*)"
r' *"(?P[^"]*)"
r'\]')
for line in urllib.urlopen("http://...";):
mat = sympat.match(line)
if mat is not None:
symbolinfo.append(mat.groupdict())

The regular expression is fairly fragile, but that's okay.  If their format
changed from a list of ten elements to a list of eight or twelve elements,
you'd probably be interested in knowing about that asap.  eval() probably
wouldn't fail unless they completely butchered the table syntax.

With a small amount of input massaging, you could do this more cleanly with
the csv module.  That's left as an exercise for the reader.

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


Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread Chris Lambacher
How is your data stored? (site was not loading for me).

test = 'blah = [1,2,3,4,5]'
>>> var,val = test.split('=')
>>> print var,val
blah   [1,2,3,4,5]
>>> val = val.strip('[] ')
>>> print val
1,2,3,4,5
>>> vals = [int(x) for x in val.split(',')]
>>> print vals
[1, 2, 3, 4, 5]


More sophisiticated situations (like nested lists) may require something like 
pyparsing.

from pyparsing import Suppress, Regex, delimitedList, Forward, QuotedString

stringValue = QuotedString('"', '\\', multiline=True)

intValue = Regex(r'[+-]?0|([1-9][0-9]*)')
intValue.setParseAction(lambda s,l,toks: int(toks[0]))

floatValue = Regex(r'[+-]?[0-9]+\.[0-9]+([eE][+-]?[0-9]+)?')
floatValue.setParseAction(lambda s,l,toks: ('real', float(toks[0])))
constantValue = stringValue ^ intValue ^ floatValue
arrayInitializer = Forward()
arrayInitializer << (Suppress("[") + delimitedList(constantValue ^ 
arrayInitializer) \
+ Suppress("]"))
arrayInitializer.setParseAction(lambda s,l,toks: toks.asList())

test_data = '["a", 1, 5.6, ["b","c",6, 10.0e-19]]'
print arrayInitializer.parseString(test_data)

results in:
['a', 1, ('real', 5.5996), 'b', 'c', 6, ('real', 
1.0001e-18)]

-Chris
On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote:
>Slawomir Nowaczyk noted:
> 
>  #> Heck, whenever *is* it OK to use eval() then?
>  eval is like optimisation. There are two rules:
>  Rule 1: Do not use it.
>  Rule 2 (for experts only): Do not use it (yet).
> 
>So, that brings up a question I have. I have some code that goes out to a
>website, grabs stock data, and sends out some reports based on the data.
>Turns out that the website in question stores its data in the format of a
>Python list ([1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search
>the source for "var table_body"). So, the part of my code that extracts
>the data looks something like this:
>START_MARKER = 'var table_body = '
>END_MARKER = '];'
>def extractStockData(data):
>pos1 = data.find(START_MARKER)
>pos2 = data.find(END_MARKER, pos1)
>return eval(data[pos1+len(START_MARKER):END_MARKER])
>(I may have an off-by-one error in there somewhere -- this is from memory,
>and the code actually works.)
>My question is: what's the safe way to do this?
>B.
>--
>Brendon Towle, PhD
>Cognitive Scientist
>+1-412-690-2442x127
>Carnegie Learning, Inc.
>The Cognitive Tutor Company ?
>Helping over 375,000 students in 1000 school districts succeed in math.
> 
> References
> 
>Visible links
>1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100

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

Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread skip

skip> import re
skip> symbolinfo = []
skip> sympat = re.compile(
skip> r'\[',

Make that

r',?\['

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


Re: Open file handles?

2006-08-09 Thread Thomas Bartkus

"Jon" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Perhaps using os you could work with lsof
> [http://www.linuxcommand.org/man_pages/lsof8.html]
>
> Jon
>

Of course! That's perfect.
Thank you!

How silly of me not to have noticed that "lsof" means "ListOpenFiles" ;-)
Thomas Bartkus



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


Re: Question about using python as a scripting language

2006-08-09 Thread Carl Banks
Wildemar Wildenburger wrote:
> Steve Lianoglou wrote:
> > Delaney, Timothy (Tim) wrote:
> >> This is just asking for trouble.
> >>
> >> my_list = eval('import shutil; shutil.rmtree('/')')
> >
> > Hah .. wow.
> >
> > And in related news: you still shouldn't be taking candy from
> > strangers.
> >
> > Point well taken. Thanks for flagging that one.
>
> Heck, whenever *is* it OK to use eval() then?

1. When you deliberately want to give the user power to run Python
code.  (For example, I've written an HTML generator--who hasn't--that
uses eval and exec to expand in-line Python code.  Perfectly ok as long
as you don't let untrusted users run the program.)

2. When you construct Python code within your program using no
untrusted data


Carl Banks

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


Re: Question about using python as a scripting language

2006-08-09 Thread Carl Banks

Delaney, Timothy (Tim) wrote:
> Steve Lianoglou wrote:
>
> > One thing you could do is use the eval or compile methods. These
> > functions let you run arbitray code passed into them as a string.
> >
> > So, for instance, you can write:
> > my_list = eval('[1,2,3,4]')
>
> This is just asking for trouble.
>
> my_list = eval('import shutil; shutil.rmtree('/')')

Fortunately, that won't work because eval expects an expression.
Unfortunately, this will:

my_list = eval('__import__("shutil").rmtree("/")')


Carl Banks

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


Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread Chris Lambacher
There were some mistakes in here.  Thats what I get for repurposing existing
code for an example.  The uncommented lines are changed.

On Wed, Aug 09, 2006 at 11:04:32AM -0400, Chris Lambacher wrote:
from pyparsing import Suppress, Regex, delimitedList, Forward, QuotedString, 
Group
> 
> stringValue = QuotedString('"', '\\', multiline=True)
> 
> intValue = Regex(r'[+-]?0|([1-9][0-9]*)')
> intValue.setParseAction(lambda s,l,toks: int(toks[0]))
> 
> floatValue = Regex(r'[+-]?[0-9]+\.[0-9]+([eE][+-]?[0-9]+)?')
floatValue.setParseAction(lambda s,l,toks: float(toks[0]))
> constantValue = stringValue ^ intValue ^ floatValue
> arrayInitializer = Forward()
arrayInitializer << (Suppress("[") + delimitedList(constantValue ^ 
Group(arrayInitializer)) \
 + Suppress("]"))
> arrayInitializer.setParseAction(lambda s,l,toks: toks.asList())
> 
> test_data = '["a", 1, 5.6, ["b","c",6, 10.0e-19]]'
> print arrayInitializer.parseString(test_data)
> 
> results in:
['a', 1, 5.5996, ['b', 'c', 6, 1.0001e-18]]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: timeout calling local sendmail

2006-08-09 Thread [EMAIL PROTECTED]
that's
 "timeout calling local sendmail"
not
"timeout calling local se"


[EMAIL PROTECTED] wrote:
> (Environment: RedHat Linux recent, Python 2.3.5)
>
> We have a batch processing script that on occasion needs to send out an
> email. We have a sendmail running locally.
>
> Sometimes we get a socket timeout on sending that email. Increasing the
> timeout to 30sec reduced but did not eliminate it.
>
> It seems to happen more often when sending to some addresses in the UK,
> but it's definitely not limited to that.
>
> And, while we sometimes send a number of messages in a short period of
> time, (a) it's all single-threaded, and (b) the failure is often but
> not always the 1st message in the batch.
>
> Any ideas on what's going on? I don't know much about the
> thread/process model of sendmail to have any clue why this is
> happening.

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


Embedding Python in C/C++

2006-08-09 Thread kingcrustybun
Not a Python newb but a bit out of my depth here...

We are trying to use the Python interpreter from within a C/C++
aplication to execute Python code which is in an external file. The
idea is to share a dictionary between the C app and the python script.
After Py_Initialize()

we do something like (ignoring checks)
p_module = PyImport_ImportModule("moduleX");
p_dict = PyDict_New();

Then, to add the dictionary we use
PyModule_AddObject(p_module, "dictName", p_dict);
Which fails.

I was expecting to see an empty dictionary called "dictName" in the
list of variables when i execute vars() in the imported python script.

Is the approach at least correct?

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


ChiPy Chicago Python User Group Meeting Tomorrow

2006-08-09 Thread bray
This will be our best meeting yet! ChiPy's Monthly meeting this Thurs.
August 10, 2006. 7pm. (except for folks who want to help setup at 6:30
and get first dibs on
pizza-compliments of Uncle Roy (Singham))

Topics
--

* Adrian Holovaty's new Django Add-on for quickly publishing websites.
* John Melesky on AppScript
* Sir Galahad on Python 2.5 (beta 3) in a nutshell
* BarCamp review and hangovers
* Lighting talks: MD5, ...

Location


ThoughtWorks' Chicago office
651 West Washington Blvd., 6th floor
Chicago, IL 60661

Location description:
"6 story, brick building on the Southwest corner of Washington Blvd. and
Desplaines St."
"Right next to the 90/94 freeway"
"Across the street from the Social Security building"

* Map 
* "Official" info 

Call jason at 3 1 2 - 3 7 3 . 8 5 5 6 if you get locked out or lost.
(The external doors should be open, but be sure to enter on the "east"
side (Desplaines)

Street (meter) parking is available in the area. Shoot for "free" (no
meters) parking on the South side of the building if you're lucky. And
be sure to feed those meters; Brother Leader Daley collects tons of cash
from meter fines in this area. Garage parking is also available across
the street (technically across the interstate) at the very tall
SkyBridge condo building.

1) The closest "L" stop is Clinton on the "Green Line". (About an 8
minute walk from TW.)
2) The closest Metra station is the Ogilvie Transportation Center (in
the Citibank Building) 2 blocks east of TW. (a 4 minute walk)
3) The closest water taxi stop is at Madison Street Bridge at 2 North
Riverside Plaza. () ;-)
4) I can't find good info on the nearest helipad. Sorry, Mr. Trump.
5) Besides garage parking at SkyBridge across the freeway and meter
parking around the building, there is additional garage parking at the
Presidential Towers at Jefferson & Madison. There are 2 non-garage
parking lots adjacent to our building. (I don't know the lots' "after
5pm" parking rules, though).  Theme: If you're addicted to oil, there
are lots of parking options within a short walk.


About ChiPy
---

ChiPy is a group of Chicago Python Programmers, l33t, and n00bs.
Meetings are held monthly at various locations around Chicago.
Also, ChiPy is a proud sponsor of many Open Source and Educational
efforts in Chicago. Stay tuned to the mailing list for more info.

ChiPy website: 
ChiPy Mailing List: 
Python website: 



Forward this on. 


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


Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread Brendon Towle
On 9 Aug 2006, at 11:04 AM, Chris Lambacher wrote:How is your data stored? (site was not loading for me).In the original source HTML, it's like this (I've deleted all but the beginning and the end of the list for clarity):var table_body = [["ATVI", "Activision, Inc.",12.75,0.15,1.19,2013762,0.04,"N","N"],["YHOO", "Yahoo! Inc.",27.7,0.26,0.95,6348884,0.21,"N","N"]];More sophisiticated situations (like nested lists) may require something like pyparsing.I could do that, or I could do something like the re.* trick mentioned by another poster. But, doesn't it offend anyone else that the only clean way to access functionality that's already in Python is to write long complicated Python code? Python already knows how to extract a list object from a string; why should I have to rewrite that?B.On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote:    Slawomir Nowaczyk noted:     #> Heck, whenever *is* it OK to use eval() then?     eval is like optimisation. There are two rules:     Rule 1: Do not use it.     Rule 2 (for experts only): Do not use it (yet).   So, that brings up a question I have. I have some code that goes out to a   website, grabs stock data, and sends out some reports based on the data.   Turns out that the website in question stores its data in the format of a   Python list ([1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search   the source for "var table_body"). So, the part of my code that extracts   the data looks something like this:       START_MARKER = 'var table_body = '       END_MARKER = '];'   def extractStockData(data):       pos1 = data.find(START_MARKER)       pos2 = data.find(END_MARKER, pos1)       return eval(data[pos1+len(START_MARKER):END_MARKER])   (I may have an off-by-one error in there somewhere -- this is from memory,   and the code actually works.)   My question is: what's the safe way to do this?   B.   --   Brendon Towle, PhD   Cognitive Scientist   +1-412-690-2442x127   Carnegie Learning, Inc.   The Cognitive Tutor Company ®   Helping over 375,000 students in 1000 school districts succeed in math.References   Visible links   1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100  -- http://mail.python.org/mailman/listinfo/python-list  -- Brendon Towle, PhDCognitive Scientist+1-412-690-2442x127Carnegie Learning, Inc.The Cognitive Tutor Company ®Helping over 375,000 students in 1000 school districts succeed in math. -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread skip

Brendon> I could do that, or I could do something like the re.* trick
Brendon> mentioned by another poster. But, doesn't it offend anyone else
Brendon> that the only clean way to access functionality that's already
Brendon> in Python is to write long complicated Python code? Python
Brendon> already knows how to extract a list object from a string; why
Brendon> should I have to rewrite that?

Doesn't bother me at all.  One, it's not actually Python code, it's
JavaScript.  It's just serendipity that the table can be parsed as a Python
list.  Two, there's nothing to prevent the authors from changing the
formatting in an incompatible way in the future.  Three, it's completely
untrusted input and shouldn't be fed to eval().  Four, it's not actually
complicated code (using the csv module would probably be simpler).  Had the
NASD had a requirement that their HTML pages be easily assimilated into
Python I might agree with you.  I suspect that wasn't high up on their
priority list though.  Five, you have to stop thinking of it a "list
object".  It's just a string of bytes which happens at this point in time to
intersect with the definition of a Python list.  You're trying to wish it
was something that it's not.

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


Re: Class data being zapped by method

2006-08-09 Thread Bruno Desthuilliers
Sion Arrowsmith wrote:
> Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>> fpath = os.path.join('datafiles', filename + ".tabdata")
> 
> fpath = os.path.join('datafiles', filename + os.path.extsep + "tabdata")

> 8-) I'm a bit bemused by extsep -- it didn't appear until 2.2, by
> which time there can't have been many people with an OS where it was
> anything other than '.'.

FWIW, I know of only one family of OSes that relies on the name-dot-ext
scheme for anything else than informative purpose...

Now Python runs on a lot of platforms, so some of them may possibly be
somewhat exotic wrt/ this kind of stuff ?
-- 
http://mail.python.org/mailman/listinfo/python-list


knowing when file is flushed to disk

2006-08-09 Thread John Pote
Hello,

I'm using a Python CGI script on a web server to log data from a remote site 
every few minutes. I do not want to lose any data for whatever rare reason - 
power outage/os crash just at the wrong moment etc. So I would like to know 
when the data is actually written to disk and the file closed. At that point 
I can signal deleting of the data at the remote site which has very limited 
storage.

Is there some way from my Python script to know when the data is actually on 
the disk. BTW server OS is Linux. Presumably calling flush() and close() on 
the output file will initiate the disk write, but do they wait for the 
actual disk write or immediately return leaving the OS to do the write when 
it sees fit?

Any thoughts appreciated,

John 


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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Christophe
Stephan Kuhagen a écrit :
>> Always prefer to use env over a hardcoded path, because that hardcoded
>> path will invariably be wrong.  (Yes, for those about to nitpick, it's
>> conceivable that env might be somewhere other than /usr/bin.  However,
>> that is very rare and results in a no-win situations regardless of the
>> issue of where Python is installed.)
> 
> Don't yell at me for bringing in another language, but I really like the
> trick, Tcl does:
> 
>>#!/bin/sh
>># The next line starts Tcl \
>>exec tclsh "$0" "$@"
> 
> This works by the somewhat weird feature of Tcl, that allows comments to be
> continued in the next line with "\" at the end of the comment-line. It
> looks unfamiliar, but has several advantages, I think. First it's really
> VERY unlikely, that there is no /bin/sh (while I found systems with
> different places for env), and you can add some other features at or before
> the actual call of the interpreter, i.e. finding the right or preferred
> version... - This way I coded a complete software-installer, that runs
> either as a Tcl/Tk-Script with GUI, or as bash-script, when no Tcl is
> available. - I really would like to have something like that for python,
> but I did not find a way to achieve that, yet.
> 
> Regards
> Stephan
> 

What about that one ( windows .bat file ) :

@echo off
rem = """-*-Python-*- script
rem  DOS section 
rem You could set PYTHONPATH or TK environment variables here
python -x %~f0 %*
goto exit

"""
#  Python section 
import sys
print sys.argv


DosExitLabel = """
:exit
rem """


I'm sure it can be updated to work on Unix too :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading.Event usage causing intermitent exception

2006-08-09 Thread [EMAIL PROTECTED]

Tim Peters wrote:
> [EMAIL PROTECTED]
> > Admittedly this problem causes no actual functional issues aside from
> > an occasional error message when the program exits.  The error is:
> >
> > Unhandled exception in thread started by
> > Error in sys.excepthook:
> > Original exception was:
> >
> > Yes all that info is blank.
>
> That's typical when the interpreter has torn so much of itself down
> that there's not enough left in the `sys` module even to print
> exception info gracefully.  The easiest way to stop that is to stop
> /trying/ to run Python code while the interpreter is tearing itself
> down.
>
> > The application is a console application that is waiting for some
> > condition on the machine to happen.  However, I leave open the
> > possiblitiy to cancel by a single key press at which
> > point the program terminates.  Suffice it to say, I cannot perform both
> > checks without invoking threads as the key press gets "missed"
> > sometimes.  Below is a simplification of the code
> >
> > canceled = False
> > myEvent = threading.Event()
> >
> > def watchForCancel()
> > global canceled
> > # turn of terminal buffering and capture key presses here
> > canceled = True
> > myEvent.set()
>
> Presumably this is some kind of poll-and-sleep loop?  If so, add a
> check to get out of the loop if myEvent.isSet().  Or if not, make it
> some kind of poll-and-sleep loop ;-)

after setting up the terminal correctly, ie changing buffering settings
etc. (I want to cancel with a single key-press with no "return" hit.
This was suprisingly difficult to do.  The wait code is simply:

while keyPressed != 'q':
keyPressed = sys.stdin.read(1)

The really annoying thing here, is that I cannot put in any other steps
in the while loop without sometimes missing the key press.  I have to
unbuffer the terminal(otherwise the read doesn't return until the enter
key is pressed), and for whatever reason performing any action no
matter how trivial leads to missing the key stroke on occasion - that's
why I pursued the daemon route.
>
> > def watchForCondition()
> > # do a bunch of stuff checking the system
> > myEvent.set()
>
> Ditto.
>
> > cancelThread = threading.Thread(target = watchForCancel)
> > cancelThread.setDaemon(True)  # so I can exit the program when I want to
>
The conditional thread will never terminate without making the threads
aware of eachother.  Setting them daemon allows the interpreter to
shutdown with one of them running - and ocaisonally cuases the error.
What I find interesting, the behavior only happens when I cancel, not
when the condition is reached.

> And get rid of that.  The comment doesn't make sense to me, and
> forcing a thread to be a daemon is exactly what /allows/ the thread to
> keep running while the interpreter is tearing itself down.  That's why
> "daemonism" isn't the default:  it's at best delicate.  I don't see a
> real reason for wanting this here.
>
> > cancelThread.start()
> > conditionThread = threading.Thread(target = watchForCondition)
> > conditionThread.setDaemon(True)
>
> Ditto.
>
> > conditionThread.start()
> >
> > myEvent.wait()
> >
> > if cancelled:
> > sys.exit(2)
> >
> > # do more stuff if the condition returned instead of cancel and then
> > I'm done
> >
> >
> > I've left out most of the active code, just cuz I think it muddies the
> > water.  Now about 9 out of 10 times this works just fine.  However,
> > every once in a while I get the exceptions mentioned above, but only
> > when I cancel out of the operation.  I think the conditionThread is in
> > the process of shutting down and gets hosed up somehow and spits out an
> > exception, but the interpreter no longer has access to the info since
> > it is shutting down.
>
> At this point it's likely that even sys.stdout and sys.stderr no
> longer exist.  The "Unhandled exception" message is printed directly
> to the C-level `stderr` instead.
>

exactly - giving me no way to swallow it.

> > ...
> > I suppose I could make the threads aware of each other, but that just
> > seems stupid.  Any suggestions on how to eliminate this intermittent
> > error?
>
> Stop forcing them to be daemon threads.  The interpreter won't start
> to tear itself down then before both threads terminate on their own.
> To arrange for that, it's not necessary for the threads to become
> aware of each other, but it is necessary for the threads to become
> aware of another (shared) reason /for/ exiting.  The most natural way
> to do that, given what you said above, is to make both threads aware
> that their shared myEvent event may get set "externally", and to stop
> when they find it has been set.

Due to the oddities of capturing that keypress at the console, I
suspect I can un-daemonize the conditional thread and check for
cancelled=True and have it return.  Since the error only occurs when
the conditional thread is still running, undaemonizing it will prevent
that and allow the interpreter to shut down more gracef

Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread Chris Lambacher
On Wed, Aug 09, 2006 at 11:51:19AM -0400, Brendon Towle wrote:
>On 9 Aug 2006, at 11:04 AM, Chris Lambacher wrote:
> 
>  How is your data stored? (site was not loading for me).
> 
>In the original source HTML, it's like this (I've deleted all but the
>beginning and the end of the list for clarity):
>var table_body = [
>["ATVI", "Activision, Inc.",12.75,0.15,1.19,2013762,0.04,"N","N"]
>,["YHOO", "Yahoo! Inc.",27.7,0.26,0.95,6348884,0.21,"N","N"]
>];
I didn't realize it was javascript syntax, a json implimentation would
probably work for you: http://cheeseshop.python.org/pypi/simplejson

> 
>  More sophisiticated situations (like nested lists) may require something
>  like pyparsing.
> 
>I could do that, or I could do something like the re.* trick mentioned by
>another poster. But, doesn't it offend anyone else that the only clean way
>to access functionality that's already in Python is to write long
>complicated Python code? Python already knows how to extract a list object
>from a string; why should I have to rewrite that?
I don't disagree with you.  The problem is that the obvious way to do it
(eval) is a big security hole.  In this case you are trusting that no one
inserts themselves between you and the website providing you with code to 
EXECUTE.  I have heard of people attempting to use the parser provided with
python and examining the AST to do this, but I think that approach is even
more complicated.
>B.
> 
>  On Wed, Aug 09, 2006 at 10:23:49AM -0400, Brendon Towle wrote:
> 
>   Slawomir Nowaczyk noted:
> #> Heck, whenever *is* it OK to use eval() then?
> eval is like optimisation. There are two rules:
> Rule 1: Do not use it.
> Rule 2 (for experts only): Do not use it (yet).
>   So, that brings up a question I have. I have some code that goes
>out to a
>   website, grabs stock data, and sends out some reports based on the
>data.
>   Turns out that the website in question stores its data in the
>format of a
>   Python list
>([1][1]http://quotes.nasdaq.com/quote.dll?page=nasdaq100, search
>   the source for "var table_body"). So, the part of my code that
>extracts
>   the data looks something like this:
>   START_MARKER = 'var table_body = '
>   END_MARKER = '];'
>   def extractStockData(data):
>   pos1 = data.find(START_MARKER)
>   pos2 = data.find(END_MARKER, pos1)
>   return eval(data[pos1+len(START_MARKER):END_MARKER])
>   (I may have an off-by-one error in there somewhere -- this is from
>memory,
>   and the code actually works.)
>   My question is: what's the safe way to do this?
>   B.
>   --
>   Brendon Towle, PhD
>   Cognitive Scientist
>   +1-412-690-2442x127
>   Carnegie Learning, Inc.
>   The Cognitive Tutor Company ?
>   Helping over 375,000 students in 1000 school districts succeed in
>math.
>References
>   Visible links
>   1. [2]http://quotes.nasdaq.com/quote.dll?page=nasdaq100
> 
>--
>[3]http://mail.python.org/mailman/listinfo/python-list
> 
>--
>Brendon Towle, PhD
>Cognitive Scientist
>+1-412-690-2442x127
>Carnegie Learning, Inc.
>The Cognitive Tutor Company ?
>Helping over 375,000 students in 1000 school districts succeed in math.
> 
> References
> 
>Visible links
>1. http://quotes.nasdaq.com/quote.dll?page=nasdaq100
>2. http://quotes.nasdaq.com/quote.dll?page=nasdaq100
>3. http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Eval (was Re: Question about using python as a scripting language)

2006-08-09 Thread Brendon Towle
On 9 Aug 2006, at 12:03 PM, [EMAIL PROTECTED] wrote:    Brendon> I could do that, or I could do something like the re.* trick    Brendon> mentioned by another poster. But, doesn't it offend anyone else    Brendon> that the only clean way to access functionality that's already    Brendon> in Python is to write long complicated Python code? Python    Brendon> already knows how to extract a list object from a string; why    Brendon> should I have to rewrite that?Doesn't bother me at all.  One, it's not actually Python code, it's_javascript_.  It's just serendipity that the table can be parsed as a Pythonlist.  Two, there's nothing to prevent the authors from changing theformatting in an incompatible way in the future.I think that these are actually the same reason, and can be safely ignored, because item 2 is true no matter what method I use to parse the data. Sure, it's serendipity, but that happens to be the hand I'm dealt at the moment; why not exploit the serendipity?  Three, it's completelyuntrusted input and shouldn't be fed to eval().  This is the crucial point, and the reason I asked the question to begin with.Lisp (which I'm used to) has the read-eval-print loop; I think that my confusion was because:1. Python's eval(X) is essentially the same as Lisp's (eval (read-from-string X)), not Lisp's (eval X) or Lisp's (read-from-string X);2. The '[' character that begins a list should actually be read as a function call, not a data delimiter. (Which, in the context of list comprehensions, makes a lot of sense as I think about it.)Four, it's not actuallycomplicated code (using the csv module would probably be simpler).I'll look into the csv module.And, it may not be complicated on an absolute scale, but Chris' re.* method turned one line of code into about 15; that's certainly a non-trivial increase in complexity.Five, you have to stop thinking of it a "listobject".  It's just a string of bytes which happens at this point in time tointersect with the definition of a Python list.  You're trying to wish itwas something that it's not.I must be confused here. If I call the following function:  eval('[1, 2, 3]')what does that function call return, if not a list object?Sure, the string isn't a list object; it's a string of bytes that happens to be syntactically identical to the definition of a list in python code. I was hoping for a clean and safe way to exploit that identical-ness; apparently, all the clean ways are unsafe, and all the safe ways are unclean.B. -- Brendon Towle, PhDCognitive Scientist+1-412-690-2442x127Carnegie Learning, Inc.The Cognitive Tutor Company ®Helping over 375,000 students in 1000 school districts succeed in math. -- 
http://mail.python.org/mailman/listinfo/python-list

__contains__ vs. __getitem__

2006-08-09 Thread David Isaac
I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys.  (The why of that is not important for
this question.)

I was delighted to find that __contains__ still works as before
after overriding __getitem__.So even though instance['key']
does not raise KeyError, I still get (as desired)  'key' in instance ==
False.

Looking forward:
Can I count on this independence of __getitem__ and __contains__?
I would like to understand whether it will be safe to count on this
behavior.

Thank you,
Alan Isaac


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


Re: __contains__ vs. __getitem__

2006-08-09 Thread Bruno Desthuilliers
David Isaac wrote:
> I have a subclass of dict where __getitem__ returns None rather than
> raising KeyError for missing keys.  (The why of that is not important for
> this question.)

Well, actually it may be important... What's so wrong with d.get('key')
that you need this behaviour ?

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


Re: using python with tar files and compressed files

2006-08-09 Thread enigmadude
This syntax works on other bzipped tar files. But it's not unheard of
that large tarballs will get corrupted from a download mirror. Use a
download manager and try redownloading the file. Usually a mirror will
include an md5sum text file so that you can compare the checksum to
your downloaded file to verify its integrity. For some reason, the
wxPython site doesn't have them.

John Salerno wrote:
> Here's the name of a file I have: wxPython-newdocs-2.6.3.3.tar.bz2
>
> Now, I tried this:
>
> import tarfile
> tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2')
>
> but got this:
>
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  tar = tarfile.open('wxPython-newdocs-2.6.3.3.tar.bz2', 'r:bz2')
>File "C:\Python24\lib\tarfile.py", line 901, in open
>  return func(name, filemode, fileobj)
>File "C:\Python24\lib\tarfile.py", line 1006, in bz2open
>  raise ReadError, "not a bzip2 file"
> ReadError: not a bzip2 file
>
> So I'm a little confused. When dealing with a tar.gz or tar.bz2 file, do
> you need to uncompress it first with the proper module (gzip or bz2)? Or
> does tarfile take care of this? If so, why doesn't it recognize the
> above file? Or am I just doing it the wrong way? (I'm following an
> example in the docs)

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


Re: paramter passing question

2006-08-09 Thread diffuser78
It partly works but I get error printed out on the console.

Traceback (most recent call last):
  File "NewProject.py", line 87, in OnEdit
win = MyFrame4(self, -1, "",sim_name=sim_name)
  File "NewProject.py", line 1098, in __init__
wx.Frame.__init__(self, *args, **kwds)
  File
"/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode/wx/_windows.py",
line 476, in __init__
newobj = _windows_.new_Frame(*args, **kwargs)
TypeError: 'sim_name' is an invalid keyword argument for this function

Larry Bates wrote:
> [EMAIL PROTECTED] wrote:
> > I wrote a small app in wxPython using wxGlade as designer tool. wxGlade
> > brings and writes a lot of code by itself and thats where my confusion
> > started. Its about parameter passing. Here is my little confusion.
> >
> > ***CODE BEGINS
> > class MyFrame1(wx.Frame):
> > def __init__(self, *args, **kwds):
> >  .
> >  .
> > def OnEdit(self, event):
> >  sim_name = 'some_string'
> >  win = MyFrame2(self, -1, "")
> >  win.Show(True)
> > 
> >
> > class MyFrame2(wx.Frame):
> > def __init__(self, *args, **kwds):
> >  .
> >  .
> > def onLaunch(self, event):
> >  ## This function needs to use the parameter sim_name which is
> > in class MyFrame1-->OnEdit
> > ***CODE ENDS
> >
> > I want to pass sim_name parameter to MyFrame2 in def OnEdit function
> > but I don't know how to do it. I tried couple of things but always got
> > some error. I have done some parameter passing in normal Python code
> > but *args and **kwds is a little confusing.
> >
> > Could you please tell me how to send parameter "sim_name" from
> > MyFrame1(in OnEdit function) and how to recieve it in MyFrame2 so that
> > I can use that parameter in MyFrame2 namespace.
> >
> > Every help is appreciated.
> >
> > Thanks
> >
> How about using the keyword args to pass it:
>
> class MyFrame1(wx.Frame):
> def __init__(self, *args, **kwds):
>  .
>  .
> def OnEdit(self, event):
>  sim_name = 'some_string'
>  win = MyFrame2(self, -1, "", sim_name=sim_name)
>  win.Show(True)
> 
>
> class MyFrame2(wx.Frame):
> def __init__(self, *args, **kwds):
>  .
>  .
> self.sim_name=kwds.get('sim_name', 'default sim_name')
>
> def onLaunch(self, event):
>  ## This function needs to use the parameter sim_name which is
>  ## self.sim_name can be used here
> 
> -Larry Bates

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


Re: Class data being zapped by method

2006-08-09 Thread Kevin M
Good news. I've fixed it up and all seems to be well.

Thanks, all. I've learned a lot from this :)


John Machin wrote:
> Kevin M wrote:
> > Inline
> >
> > > 1.) Why are you removing the .pyc file?
> >
> > After I had run the script once and subsequently changed the class
> > file, I would run the script again, and it would use the pyc file from
> > the older revision of the script. I got frustrated with having to
> > manually delete the pyc file before rerunning the script after every
> > edit, so I built it in.
>
> Huh? Something funny is going on here. (1) You should never need to
> delete a pyc file (2) A script run from the command line doesn't create
> a pyc file, only imported modules get that. So: What platform are you
> running it on? What version of Python? Are you running the script from
> the command line, or in an IDE? Which IDE?
>
> >
> > > 2.) Reading lines from a file is better done like so:
> > >
> > > arrLines = open('datafiles/'+filename+'.tabdata').readlines()
> > >
> > > and the 'r' flag is the default, you can omit it.
> >
> > I know. In fact, this was the original code. However, I have read in
> > many places that if the file is *massive*, which is true in my case, it
> > is far more efficient to use the line-by-line implicit method I used.
> > On a decent machine it doesn't really make a noticeable difference, but
> > some of the ".tabdata" files I'm parsing are > 20MB plain text, so I
> > figured that warranted the alternative approach.
>
> Firstly, 20MB is not massive.
> Secondly, the problem with large files is keeping a list like arrLines
> hanging about when you only need one line at a time.
> If you insist on keeping the list, get it in one hit using readlines(),
> instead of assembling it yourself manually.
>
> >
> >
> > John M, I realized what you meant about splitting the code between the
> > class and the processing file. At first it seemed intuitive, but
> > stepping back, it doesn't really make sense that a test would be able
> > to analyze and take an inventory of *itself*. I think I'm going to
> > reorganize the code such that the Test class does nothing but provide a
> > barebones data structure with which to work.
> >
> > And regarding the file separation, it's totally personal preference. It
> > scales well, at least.
>
> One class per file does *not* scale well, even when you're not being
> driven silly by having to flick backwards & forwards furiously between
> files :-)
>
> >
> > Another Aside --
> >
> > Does anybody see any major bottlenecks in the code? I'd like to be able
> > to speed up the program considerably. Psyco was really no help.
> >
>
> 1. Get it refactored and working correctly first. "except IndexError:
> pass" certainly won't help you win the Grand Prix; how many of those
> were you doing per 20MB of data?
> 2. How long does it take to run ? How long would you prefer it to take?
> How many lines x how many tests == 20 MB?
> 
> Cheers,
> John

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


Escape sequences (colour) and padding with "%8s"%

2006-08-09 Thread Anton81
Hi all!

I used escape sequences to produce colour output, but a construct like

print "%8s" % str_with_escape

doesn't do the right thing. I suppose the padding counts the escape
characters, too.

What could be a solution?

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


Status of Epydoc

2006-08-09 Thread Kent Tenney
Howdy,

I would very like to use Epydoc 3.0,
however I've found a couple bugs and the
mailing list;
http://sourceforge.net/mailarchive/forum.php?forum_id=39919
doesn't seem to be working, the last couple
messages I've posted haven't shown up.

Does anyone know the status of 
Epydoc 3.0 development?

Thanks,
Kent


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


Re: #!/usr/bin/python or #!/usr/bin/env python?

2006-08-09 Thread Aahz
In article <[EMAIL PROTECTED]>,
John Salerno  <[EMAIL PROTECTED]> wrote:
>
>I understand the difference, but I'm just curious if anyone has any 
>strong feelings toward using one over the other? I was reading that a 
>disadvantage to the more general usage (i.e. env) is that it finds the 
>first python on the path, and that might not be the proper one to use. I 
>don't know if that's a real issue most of the time, but it's at least 
>something to consider.

The main argument against the env method is that I've seen a fair number
of sysadmins claim that it's less secure.  I'm not competent to judget
that claim myself, but I prefer to play safe and stay away from env.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


Python share CPU time?

2006-08-09 Thread Yannick
Hi,

I would like to program a small game in Python, kind of like robocode
(http://robocode.sourceforge.net/).
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
Is Python just not adapted to this kind of things?

Thanks,
Yannick

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


Re: __contains__ vs. __getitem__

2006-08-09 Thread enigmadude
That's a vague question, so the obligatory "it depends" response
applies here.

If you want to guard against the unexpected, perhaps it's a good idea
to write unit tests rather than to take someone's word that it *should*
work okay every time, in every case, no matter what you're doing with
the data. Think of what behavior would be disasterous (whether it seems
possible or not), then write a test for that behavior. Also write tests
for things that "obviously" *should* hold true... just to make sure
they hold true.

Maybe you can't think of ways that this class could possibly screw
things up, but it's always nice to have reassurance anyway :-) The
closest thing to certainty about code is to test it.

David Isaac wrote:
> I have a subclass of dict where __getitem__ returns None rather than
> raising KeyError for missing keys.  (The why of that is not important for
> this question.)
>
> I was delighted to find that __contains__ still works as before
> after overriding __getitem__.So even though instance['key']
> does not raise KeyError, I still get (as desired)  'key' in instance ==
> False.
>
> Looking forward:
> Can I count on this independence of __getitem__ and __contains__?
> I would like to understand whether it will be safe to count on this
> behavior.
> 
> Thank you,
> Alan Isaac

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


Re: Nested function scope problem

2006-08-09 Thread Gerhard Fiedler
On 2006-08-09 07:54:21, Slawomir Nowaczyk wrote:

> Nope. Equivalence table can look like this:
> 
>Python C
> variable:a  variable:  a
> textual representation: "a" address operator: &a
> id of object:   id(a)   dereference operator: *a
> 
> Also, notice, that "id(a)" does not really "identify" a variable. It
> only identifies *object* which is bound to this variable. Both in
> Python and in C.

Rests one question: what is the value of the variable? In Python, it would
be the result of "a". In C, it would be the result of ...? 

Gerhard

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


Re: Info on continuations?

2006-08-09 Thread vasudevram

Michael wrote:
> vasudevram wrote:
>
> >
> > Hi,
> >
> > I am Googling and will do more, found some stuff, but interested to get
> > viewpoints of list members on:
> >
> > Continuations in Python.
> >
> > Saw a few URLs which had some info, some of which I understood. But
> > like I said, personal viewpoints are good to have.
>
> Python doesn't really support continuations. Generators (and co-routines in
> general) have similar properties to continuations, however they're not
> continuations. Closures are also sometimes considered cousins to
> continuations, and python's support for those is pretty good IMO. (again
> however, closures are not continuations).
>
> Since it looks like you're also looking for what continuations are, I think
> the following is the simplest way of explaining them. If you've ever
> programmed in BASIC, *in a way* if you think of methods/functions as a
> named GOSUB, then continuation (in a way) are a way of giving a name to a
> goto (it's more subtle than that though since a continuation os often
> defined to "remember" state in a similar way to a closure). Like a function
> you can pass them round as objects. Like a generator/closure they remember
> the state they were in.
>
> *Personally* , I think python NOT supporting full continuations is a GOOD
> thing, since full continuations, whilst powerful, are also a great source
> of confusion for people. (That said, I have a usecase I'd find them useful
> for - I think they'd be useful for plugin architectures - but IMO that
> doesn't outweigh the risk of code obfuscation :-)
>
> One particular usecase that people seem to like continuations for,
> specifically how they're used in seaside, is actually a subset of
> functionality that python *can* support (to a large extent).
>
> Essentially the idea is to be able to take a web application and make it
> look linear. CherryFlow allows you for example to write this:
>
> @expose
> @flow
> def example_flow():
> yield view.first_page()
> if request.args["choice"] == "a":
> yield view.choice_a_page()
> else:
> yield view.choice_b_page()
> yield view.last_page()
>
> (example from: http://tinyurl.com/qzpqu )
>
> This causes the user's browser to show a page where they have a choice of
> "a" or "b". Depending on what they choose, they then either are presented
> with choice_a_page or choice_b_page. Finally, no matter which option they
> chose, you are presented with the last page.
>
> Something similar can be done using Kamaelia, though at present only the
> mechanism exists there, without any sugar (http://tinyurl.com/n3bh7 -
> specifically websiteSessionExampleComponent). The reason I mention it is to
> say that it's relatively simple to do using python :-)
>
> I have to stress though, this usage of continuations in Seaside, as
> emulate-able in python is a subset of the full power of continuations,
> which isn't available in python at present. (Though it's possible hacking
> greenlets could result in something). (In fact the way seaside uses them as
> far as I can tell is more to implement co-routine like behaviour than
> anything else (!))
>
> Anyway, hope that's interesting/useful - looking at your other comments,
> you're just looking for information and usecases at the moment :-)
>
> Regards,
>
>
> Michael.

Yes, that's quite right - only looking for info and use cases at
present - and thanks for the info, it was interesting and useful :-)
Need to check all the inputs out ...

Vasudev

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


What's the cleanest way to compare 2 dictionary?

2006-08-09 Thread John Henry
Hi list,

I am sure there are many ways of doing comparision but I like to see
what you would do if you have 2 dictionary sets (containing lots of
data - like 2 keys and each key contains a dozen or so of records)
and you want to build a list of differences about these two sets.

I like to end up with 3 lists: what's in A and not in B, what's in B
and not in A, and of course, what's in both A and B.

What do you think is the cleanest way to do it?  (I am sure you will
come up with ways that astonishes me  :=) )

Thanks,

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


Re: Nested function scope problem

2006-08-09 Thread Gerhard Fiedler
On 2006-08-09 07:54:22, Slawomir Nowaczyk wrote:

> It was never my goal to show that Python and C variables behave the
> same way or anything.
> 
> So it seems like we misunderstood each others intents.

That seems to be the case :)

I never really meant to say that I think that Python does not have
variables. If anything, I meant that Bruno's explanation that they behave
fundamentally different from C variables (and that therefore it may be
confusing to call them both "variables") helped me to understand better
some of the differences. For me, that was mainly regarding the concepts of
immutability -- which is something that in this form doesn't exist in C.
(It can of course be implemented in C -- after all, I think original Python
is implemented in C.)

Gerhard

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


Re: Python share CPU time?

2006-08-09 Thread Grant Edwards
On 2006-08-09, Yannick <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would like to program a small game in Python, kind of like robocode
> (http://robocode.sourceforge.net/).
> Problem is that I would have to share the CPU between all the robots,
> and thus allocate a time period to each robot. However I couldn't find
> any way to start a thread (robot), and interrupt it after a given time
> period.

The robot code thread needs to block when it runs out of things
to do.

> Any suggestions on how to proceed?

Just start a thread for each robot, and put a call to
time.sleep(0.010) in the main loop for the robot code.  Adjust
the 0.010 value to taste.

As an alternative to sleeping, you could wait for some sort of
event each time through the loop.

> Is Python just not adapted to this kind of things?

It's quite well adapted to this sort of thing.

-- 
Grant Edwards   grante Yow!  Why don't you
  at   ever enter and CONTESTS,
   visi.comMarvin?? Don't you know
   your own ZIPCODE?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-08-09 Thread Gerhard Fiedler
On 2006-08-09 07:54:22, Slawomir Nowaczyk wrote:

> But I do not believe there is any "identity of a variable"
> which corresponds to "id()". Still, you used such term -- repeatedly.
> 
> I do not know what do you mean by it.

In C, the "identity" of anything is usually the memory location. Same 
location means "same thing", different location means "different thing". 
Python is a few levels above this almost hardware level. So while the 
memory thing in the end still holds for Python also, it has other means 
above that (and I'm not sure it even allows native access to the raw memory 
access). 

So if you want to know whether two Python variables refer to the same 
object, you get the id() of them; same id() means they refer to the same 
object. If you want to know whether two C variables (not necessarily 
pointers, I mean variables) refer to the same memory location, you get 
their addresses. Same address means they refer to the same memory location.

Since the identity of a variable is not a defined concept in C, it can only 
be a (subjective) approximation. I feel that the address of a variable 
reflects most closely what I would see as its identity in C. But that's 
subjective, of course.

Gerhard

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


Re: Python share CPU time?

2006-08-09 Thread enigmadude
There's several ways of doing concurrency in Python. Other than the
threading module, have you tried FibraNet? It's designed with simple
games in mind.
You can download it at http://cheeseshop.python.org/pypi/FibraNet.
Specifically the nanothreads module from FibraNet uses generators to
simulate light-weight cooperative threads.

Generator-based approaches are fast and *deterministic*, unlike true
threads where you have to account for race conditions, etc. You can
pause, resume, kill, or end a "thread". In Python 2.5 (soon to be
released), generators will be consumers rather than just producers, so
you can pass things into generators (without needing global variables
as a workaround) rather than only being able to spit out data
on-the-fly. They'll also have a more graceful way to handle exceptions.

For a good overview of the concept, especially if you want to implement
this yourself instead of using Fibranet (although re-use is often the
better choice), take a look at this link from the Charming Python
column:
http://gnosis.cx/publish/programming/charming_python_b7.html.

If this all seems too exotic, then you can also just go with the
traditional threading approach with the threading module. Normally
you'll want to use the "threading" module rather than the lower-level
"thread" module. But be warned, threads are a big can of worms.

I hope you find this useful.

Yannick wrote:
> Hi,
>
> I would like to program a small game in Python, kind of like robocode
> (http://robocode.sourceforge.net/).
> Problem is that I would have to share the CPU between all the robots,
> and thus allocate a time period to each robot. However I couldn't find
> any way to start a thread (robot), and interrupt it after a given time
> period.
> Any suggestions on how to proceed?
> Is Python just not adapted to this kind of things?
> 
> Thanks,
> Yannick

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


  1   2   >