wrapper classes question

2005-02-09 Thread vegetax
Hi i made a wrapper class for handling file and dir operations and i wonder,
 whats the performance penalty for making such wrapper classes? here it is:

##
import os

class File(object):

#access modes
F_OK = os.F_OK,
W_OK = os.W_OK,
R_OK = os.R_OK,
X_OK = os.X_OK
 

def __init__(s,pathToFile):

 s.path = pathToFile
 s.name = os.path.basename(s.path)
 s.dirName = os.path.dirname(s.path)
 #s.size = path.getsize(s.path)


def size(s):
 return os.path.getsize(s.path)

def open(s,mode='r'):
 return open(s.path,mode)

def openw(s):
 return open(s.path,'w')

def access(s,mode):
 return os.access(s.path,mode)

def abspath(s):
 return os.path.abspath(s.path)

def getatime(s):
 return os.path.getatime(s.path)

def getctime(s):
 return os.path.getctime(s.path)

def isabs(s):
 return os.path.isabs(s.path)

def isfile(s):
 return os.path.isfile(s.path)

def isdir(s):
 return os.path.isdir(s.path)

def ext(s):
 return os.path.splitext(s.path)[1]

def stat(s):
 return os.stat(s.path)

def access(s,mode):
 return os.access(s.path,mode)

def chdir(path) : os.chdir(path)

def cwd() : return os.getcwd()

def chmod(path,mode): return os.chmod(path,mode)

def chown(path,uid,gid): os.chown(path,uid,gid)

def ln(src,dest): os.symlink(src,dest)

def ls(path): return os.listdir(path)

def mkdir(path,rec=False,mode = 0777) : 
if not rec:
os.mkdir(path,mode)
else:
 os.makedirs(path,mode)

def rm(path):os.remove(path)

def rename(old,new): os.rename(old,new)

def rmdir(path): os.rmdir(path)

def xremove(path) : 
'just unix'
os.system('rm -rf %s' % path)

def utime(path,times=None):
'set times of a file\
times = tuple like (atime,ctime) '
os.utime(path,times)

if __name__ == '__main__':

f = File('/tmp')
print f.isfile()
print f.isdir()
print f.size()
print ls('/tmp')

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


Re: Confused with methods

2005-02-09 Thread Antoon Pardon
Op 2005-02-08, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
>> No python is not consistent and your continuous repetion doesn't
>> make it so. To illustrate, here the following code:
>> 
>> class A:
>>   l = []
>>   def f(): pass
>> 
>> a = A()
>> print a.l is A.l
>> print a.f is A.f
>> 
>> which produces:
>> 
>> True
>> False
>
> Thats only inconsistent from your POV because you refuse to accept that the
> scope of a function definition does matter.

It doesn't. As Alex has already explained, the above is equivallent to:

def h(): pass

class A:
  l = []
  f = h

a = A()
print a.l is A.l
print a.f is A.f


And such great error would surely brand you a Troll in his eyes.
Scope of definition has nothing to do with it. The only factor
that matters in this case is if the function is a class atribute
or not.

> And as usual its a topic of
> totally unrelevant practical impact and an expression of your strangely
> deeprooted desire to nitpick at such unrelevant details. 

If I told you that this detail, well not this particular one but
one that is close to it, will break one of my applications in
the transition from python 2.3 to 2.4, do you still think
it is irrelevant?

I would also argue that if a particular detail is a stumbling block
for someone to understand something it is not that irrelevant
and that claiming something is inconsistent while it is not,
is not a good way to remove such a stumbling block.


> Why don't you pick something that really bothers people and see if your
> skills (that I'm sure exist) can be of use there?

This did bother someone, it was a stumbling block for him understanding
what was going on.

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


Success using Python .NET with py2exe?

2005-02-09 Thread Harlin
Has anyone had any success using py2exe with anything you've written
using the Python .NET implementation? (This is the one from the Zope
website -- not ActiveState). I seem to be having trouble with py2exe
and anything I've written using the CLR modules. Has anyone encountered
this?

Thanks,

Harlin

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


Re: Name of type of object

2005-02-09 Thread Steven Bethard
Randall Smith wrote:
Jive Dadson wrote:
The traceback routine prints out stuff like,
NameError: global name 'foo' is not defined
NameError is a standard exception type.
What if I want to print out something like that?
I've determined that "global name 'foo' is not defined" comes from the 
__str__ member of the exception object.
Where does it find the string "NameError"?  In general, if I have an 
object, is there a way to obtain the name of the type of the object?

Thankee.
type(object) ?
Doesn't work for old-style classes like exceptions:
py> e = NameError("global name 'foo' is not defined")
py> type(e)

py> type(e).__name__
'instance'
For old-style classes, you'll need to go through __class__
py> e.__class__

py> e.__class__.__name__
'NameError'
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda

2005-02-09 Thread bruno modulix
e wrote:
here's what is probably an unusual question: 


A very open one at least !-)
--
bruno desthuilliers
ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| 
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
--
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda

2005-02-09 Thread bruno modulix
e wrote:
Question: WHAT IS LAMBDA? 
No need to scream, we here you quite well.
I can't figure out what it does from any 
documentation i've found anywhere. 
Then I doubt you really did search.
http://www.google.com/search?q=Python+%2B+lambda
i doubt i need it
Why ?
but i still want to 
know what the heck it is/does/fixes/whatever! 
lambda is a keyword that is used to create anonymous functions. This is 
pretty handy for simple callbacks.

--
bruno desthuilliers
ruby -e "print '[EMAIL PROTECTED]'.split('@').collect{|p| 
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
--
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused with methods

2005-02-09 Thread Diez B. Roggisch
> It doesn't. As Alex has already explained, the above is equivallent to:
> 
> def h(): pass
> 
> class A:
>   l = []
>   f = h
> 
> a = A()
> print a.l is A.l
> print a.f is A.f

So what - the difference is between bound and unbound method, which is what
were talking here about after all - so in the end, its a question of how a
bound method gets created. I'm pretty sure there are plenty of other ways
to create one - try the new module, metaclasses and what not. But that they
exist and are different from unbound methods or functions is not
inconsistent. In the same spirit you could call instance methods in
languages like java or c++ inconsistent - as the have an implicit first
argument, which "normal" functions don't have. So either way round - its a
bit of magic for having oo-style method dispatch. If you want to get rid of
it, don't use OO or at least don't use classes. Nobody prevents you from
doing that.

 
> If I told you that this detail, well not this particular one but
> one that is close to it, will break one of my applications in
> the transition from python 2.3 to 2.4, do you still think
> it is irrelevant?

If its not _this_ detail, its not relevant for _this_ thread. And a general
assertion that transitional changes between versions of python create
problems might be worth a discussion - but that's not what were talking
about here. Instead, we're talking about inconsistencies in _one_ certain
version of python - inconsistencies that no one except you seems to
perceive.

> 
> I would also argue that if a particular detail is a stumbling block
> for someone to understand something it is not that irrelevant
> and that claiming something is inconsistent while it is not,
> is not a good way to remove such a stumbling block.

The OP very well understood the difference between bound and unbound
methods. His confusion was that there was no general currying mechanism
behind it that would create subsequent argument bindings if he stuffed a
method into another class. He now understands better.
> This did bother someone, it was a stumbling block for him understanding
> what was going on.

It did bother him because he didn't understand it in the first place - and
he now does understand it.

Well, I'm well prepared to agree to disagree with you on this. If you feel
its inconsistent, I'm not trying to convince you otherwise. But as I said
before: Even if it _is_ - its still of no practical impact. Also the OP
didn't have any further problems after seeing whats getting on. So lets
move along.

-- 
Regards,

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


Re: Reportlab and Barcodes

2005-02-09 Thread Neil Benn
Josh wrote:
Hi All,
I need someone to explain to me how to output a Code39 barcode to a
Reportlab PDF. As far as I can tell, there is no means to do this with
the Canvas object, and the demo that is included with the libraries is
using the platypus Frame to place the barcode on the form. I do not
wish to use this method. I'm guessing that it needs to be placed on the
form as some type of graphic. It's obviously not going to work with the
drawText method. Any ideas? 

Thanks
Josh
 

Hello,
 Code39 isn't that complicated a barcode symbology to work 
with.  What you can do is to write some code which can encode a Code39 
barcode from a string into a simple graphic.  I used to have the 
official spec for the barcode but that was in an old job.  You can get 
the official spec from AIM - you'll have to pay for it but it's not 
much.  Although beware about the Narrow:Width ratio if you're gonna try 
and scan the barcode after printing it out - try and get hold of a 
crappy scanner (I got stung by using a good scanner before in the past).

Cheers,
Neil
--
Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 46
D-01307
Dresden
Germany
Tel : +49 (0)351 4173 154
e-mail : [EMAIL PROTECTED]
Cenix Website : http://www.cenix-bioscience.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python mail filter

2005-02-09 Thread Ulf Göransson
Mailer wrote:
The basic premise, as I understand is this:
Read mail from stdin
Parse headers etc using rfc822 or email module
Process
# Now I need to do one of the following:
# Discard mail
# Pass through
# Forward to another account, possibly modifying the mail
Now that I have coded up some stuff, the first looks easy - mails are
getting lost. So the question is (may not be entirely specific to Python),
how do I achieve the other two?
Currently, I have set up a .forward that pipes the mail to my script. I can
verify that this works by dumping the contents to a file. If I write to
stdout, however, the mail is not delivered. That doesn't quite look right
either - it's probably too late for the MTA to pick up. What I want to do is
to pass the processed mail back to Postfix so it can deliver it to the
correct local mail box.
I think something like this might work (snipped from a small script I 
use to email log files to myself):

smtp = smtplib.SMTP('localhost')
smtp.sendmail(sender, rcpt, msg.as_string())
smtp.close()
Regardless of MTA software, this should resend whatever is in msg (in my 
case a MIMEMultipart). If it should be forwarded, just change rcpt and 
the To: header.

Unless of course, the server is configured to block messages sent by 
localhost claiming to be from somewhere else...

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


Vectors in Visual Python

2005-02-09 Thread FLChamp
SOrry if this message is a little confused, it most probably reflects
the state of the author!

I have made a small program that plots the orbit of a planet in visual
python using visual.vector for all values. If i run the program it is
clear that the orbit is non-keplerian as the planets gradually moves
away from the sun. I am pretty sure the orbit should be keplerian so i
guess there must be some source of error in the program.

I am using "from __future__ import division" and the initial conditions
I have are from NASA's horizons system, all values are accuracte to
more than 10 decimal places.

I was wondering if there was a way to specify the type of number used
by visual.vector, for example, when using an array it is possible to
specify the type as float64. If visual.vector was using a smaller
amount of memory to store the number could this be the source of the
error I am finding? If not what else could be the culprit?

I have used a 4th order RK method which I have previously produced
Keplerian orbits with.

I hope I have made some sense here and look forward to any input

Many Thanks

Ben

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


strange behaviour with decorators.

2005-02-09 Thread Antoon Pardon

I tried the following program:

def positive(f):

  def call(self, u):

if u < 1:
  print 'Not Positive'
  raise ValueError
return f(self, u)

  return call

class Incrementor:

  def __init__(self, val=0):
self.value = val

  @positive
  def __call__(self, term = 1):
print 'incrementing'
self.value += term
return self.value

inc = Incrementor(0)
try:
  print inc(1)
  print inc()
  print inc(3)
  print inc(-2)
except:
  pass


And it gave me the following result:

incrementing
1


Now although this behaviour was surprising after somethought
I think I may understand why things go wrong, but I certainly
don't understand the result I got. I would think an error like:

TypeError: call() takes exactly 2 arguments (1 given)

would have been more appropiate.


Am I missing something?
Is it a bug?
Maybe both?

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


Re: python connect to server using SSH protocol

2005-02-09 Thread Toby Dickenson
On Tuesday 08 February 2005 13:26, Simon Anders wrote:

> This is what I was about to reply as well. But I did a short test 
> program and encountered a problem:
> 
> import os
> fi, foe = os.popen4 ('ssh dopey')
> print >>fi, 'ls'
> fi.close ()  # <-- this is annoying
> for line in foe:
> print line,
> foe.close ()
> 
> The above connects to a server, passes the command 'ls', which is 
> executed there, and prints the returned result.
> 
> However, reading from foe succeeds only if fin has been closed before. 
> An fi.flush() seems to be not sufficient. 

But this version below does work. Im not sure whats happening when using the 
file as an iterator to make a difference.

import os, sys
fi, foe = os.popen4 ('ssh x')
print >>fi, 'ls'
fi.flush ()  # <-- this is annoying
while 1:
b = foe.readline()
sys.stdout.write(b)


> But if one wants Python to  
> interactivly communicate with some shell on a remote machine, it is 
> inconvenient to have to close and reopen the connection all the time.

But this route carries a big deadlock risk. the rsync program can tunnel over 
ssh this way, but have first hand experience of
http://www.google.com/search?q=rsync+ssh+deadlock

In the script above, if 'ls' is replaced with a longer input then there is 
every chance that the fi stream will block before all of it is written, 
because this script hasnt started draining foe.

For a real python program using ssh (but not 'interactive'... data written to 
fi does not depend on data read from foe) see
http://dirstorage.sourceforge.net/replica.html
-- 
Toby Dickenson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python mail filter

2005-02-09 Thread Skip Montanaro

>> (P.S. I am very much aware of the existence of procmail, TMDA etc. My
>> requirements are very specific and requires integration with another
>> program, so I am only interested in getting a custom solution).

Tim> But are you aware that a procmail recipe can feed a message through
Tim> a filter, and then pass the results of that filter back in to the
Tim> e-mail system for further processing?

Should the OP need further evidence that this is possible, this is exactly
how I use SpamBayes [1].

Skip

[1] http://www.spambayes.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A ListComp that maintains its own state

2005-02-09 Thread Bernhard Herzog
Michael Spencer <[EMAIL PROTECTED]> writes:

> So, here's factorial in one line:
> # state refers to list of state history - it is initialized to [1]
> # on any iteration, the previous state is in state[-1]
> # the expression also uses the trick of list.append() => None
> # to both update the state, and return the last state
>
>  >>> [state.append(state[-1] * symbol) or state[-1]
> ... for symbol, state in it.izip(range(1,10),it.repeat([1]))
> ... ]
> [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>  >>>

There's no need for repeat:

>>> [state.append(state[-1] * symbol) or state[-1] 
for state in [[1]]
for symbol in range(1, 10)]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]


While we're at it, a while back I posted a list comprehension that
implements a 'recursive' flatten:

http://groups.google.de/groups?selm=s9zy8eyzcnl.fsf%40salmakis.intevation.de


   Bernhard

-- 
Intevation GmbH http://intevation.de/
Skencil   http://skencil.org/
Thuban  http://thuban.intevation.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java Integer.ParseInt translation to python

2005-02-09 Thread Nick Craig-Wood
jose isaias cabrera <[EMAIL PROTECTED]> wrote:
[java output]
>  StringLength = 40
>  c1 193 -63
>  7c 124 124
>  e1 225 -31
>  86 134 -122
>  ab 171 -85
>  94 148 -108
>  ee 238 -18
>  b0 176 -80
>  de 222 -34
>  8a 138 -118
>  e3 227 -29
>  b5 181 -75
>  b7 183 -73
>  51 81 81
>  a7 167 -89
>  c4 196 -60
>  d8 216 -40
>  e9 233 -23
>  ed 237 -19
>  eb 235 -21
>  [EMAIL PROTECTED]
> 
>  But, here is what I have for python,
> 
>  def PrepareHash(HashStr):
>while len(HashStr) > 0:
>  byte = HashStr[0:2]
>  print byte,int(byte,16),byte(int(byte,16)) # & 0xff
>  HashStr = HashStr[2:]
>return byte
> 
>  def Main():
>HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb"
>HashStr = PrepareHash(HashStr)
>print "Prepared HashStr :",HashStr
> 
>  Main()

When I try your code I get this...

>>> def PrepareHash(HashStr):
... while len(HashStr) > 0:
... byte = HashStr[0:2]
... print byte,int(byte,16),byte(int(byte,16)) # & 0xff
... HashStr = HashStr[2:]
... return byte
... 
>>> HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb"
>>> print PrepareHash(HashStr)
c1 193
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 4, in PrepareHash
TypeError: 'str' object is not callable
>>> 

You cant do byte(int(byte,16)) - byte is a string!  So you haven't
posted the actual code you ran...

Anyway what you want is this

>>> decoded = HashStr.decode('hex')
>>> for i,c in enumerate(decoded): print "%2d %02x" % (i,ord(c))
... 
 0 c1
 1 7c
 2 e1
 3 86
 4 ab
 5 94
 6 ee
 7 b0
 8 de
 9 8a
10 e3
11 b5
12 b7
13 51
14 a7
15 c4
16 d8
17 e9
18 ed
19 eb

>  and it results to,
> 
>  mulo 19:32:06-> python test.py
>  c1 193 Á
>  7c 124 |
>  e1 225 á
>  86 134
>  ab 171 «
>  94 148
>  ee 238 î
>  b0 176 °
>  de 222 Þ
>  8a 138
>  e3 227 ã
>  b5 181 µ
>  b7 183 ·
>  51 81 Q
>  a7 167 §
>  c4 196 Ä
>  d8 216 Ø
>  e9 233 é
>  ed 237 í
>  eb 235 ë
> 
>  which is not even close, and yes, I know that it's not the same
>  code.

Actually the hex digits are the same in all 3 cases, so the strings
are the same.  The reason the characters look different is because
you've got a different encoding for the python and java output I would
guess.

Java bytes are signed also just to add to the confusion.

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


Re: Is Python as capable as Perl for sysadmin work?

2005-02-09 Thread Nick Craig-Wood
Jeff Epler <[EMAIL PROTECTED]> wrote:
>  Finally, Python just doesn't respond to threats as well as Perl does.
>  I have run into many Perl programs that just didn't quite work right
>  until I wrote '... or die "$!"' in the right places.

I find

  '... or die "You [EMAIL PROTECTED]"'

works even better ;-)

Thanks for a very amusing post!
-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient checksum calculating on lagre files

2005-02-09 Thread Nick Craig-Wood
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>  on my machine, Python's md5+mmap is a little bit faster than
>  subprocess+md5sum:
> 
>  import os, md5, mmap
> 
>  file = open(fn, "r+")
>  size = os.path.getsize(fn)
>  hash = md5.md5(mmap.mmap(file.fileno(), size)).hexdigest()
> 
>  (I suspect that md5sum also uses mmap, so the difference is
>  probably just the subprocess overhead)

But you won't be able to md5sum a file bigger than about 4 Gb if using
a 32bit processor (like x86) will you?  (I don't know how the kernel /
user space VM split works on windows but on linux 3Gb is the maximum
possible size you can mmap.)

$ dd if=/dev/zero of=z count=1 bs=1048576 seek=8192
$ ls -l z
-rw-r--r--  1 ncw ncw 8590983168 Feb  9 09:26 z

>>> fn="z"
>>> import os, md5, mmap
>>> file = open(fn, "rb")
>>> size = os.path.getsize(fn)
>>> size
8590983168L
>>> hash = md5.md5(mmap.mmap(file.fileno(), size)).hexdigest()
Traceback (most recent call last):
  File "", line 1, in ?
OverflowError: memory mapped size is too large (limited by C int)
>>> 

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


Re: Efficient checksum calculating on lagre files

2005-02-09 Thread Nick Craig-Wood
Thomas Heller <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood <[EMAIL PROTECTED]> writes:
> > Here is an implementation of md5sum in python.  Its the same speed
> > give or take as md5sum itself.  This isn't suprising since md5sum is
> > dominated by CPU usage of the MD5 routine (in C in both cases) and/or
> > io (also in C).
> 
>  Your code won't work correctly on Windows, since you have to open files
>  with mode 'rb'.

Yes you are correct (good old Windows ;-)

>  But there's a perfect working version in the Python distribution already:
>  tools/Scripts/md5sum.py

The above is easier to understand though.

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


Re: strange behaviour with decorators.

2005-02-09 Thread Diez B. Roggisch
> Now although this behaviour was surprising after somethought
> I think I may understand why things go wrong, but I certainly
> don't understand the result I got. I would think an error like:
> 
> TypeError: call() takes exactly 2 arguments (1 given)
> 
> would have been more appropiate.
> 
> 
> Am I missing something?
> Is it a bug?
> Maybe both?

Maybe I'm missing something - but I exactly get that error if I don't use
that try: except: of yours:

For this 

-
def positive(f):
  def call(self, u):

if u < 1:
  print 'Not Positive'
  raise ValueError
return f(self, u)

  return call

class Incrementor:
def __init__(self, val=0):
self.value = val

@positive
def __call__(self, term = 1):
print 'incrementing'
self.value += term
return self.value

inc = Incrementor(0)

print inc(1)
print inc()
print inc(3)



I get this result:
[EMAIL PROTECTED]:~$ python2.4 /tmp/test.py
incrementing
1
Traceback (most recent call last):
  File "/tmp/test.py", line 24, in ?
print inc()
TypeError: call() takes exactly 2 arguments (1 give

-- 
Regards,

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


Re: Success using Python .NET with py2exe?

2005-02-09 Thread Brian
I haven't spent any time recently with it, but I seem to recall having
more success using cx_Freeze for packaging than with py2exe (when using
Python.NET).  In the time since I then, I suspect all of the packagers
have gotten more sophisticated, and you might have more options.

A good place for questions like these is the Python.NET list:
http://mail.python.org/mailman/listinfo/pythondotnet

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


I don't have a clue what this is (py2exe?)

2005-02-09 Thread Geir Arne Evjen
I'm having a strange problem which I hope some python experts out
there could help me with.

I'm implementing a COM server where I do a lot of xml-rpc calls to a
zope server. The communication is done over ssh with portforwarding
(8080) using putty.

To distribute the COM server I'm using py2exe to create exe files. 
I've implemented the COM server on a windows XP computer, but I'm
testing it on a windows 2000 computer. The strange thing is that on
the 2000 computer the xmlrpc-documents seems to be truncated somewhere
at the and and the xmlrpc reader (expat) complains abount invalid tags
(used by xmlrpclib). This only happens in some occations and for large
documents (~200Kb).

I've checked what putty recives in its logfile there is nothing wrong
with what the zope server returns.

Also, the strange this is that if I register (using the source) the
COM server directly in the python intepreter the COM server works
perfectly (both with or without debugging).

I really don't know where this problem comes from and I don't have a
clue where to search.

Any tips would be very much appreciated.

I'm using 
python 2.3.4
win32all build 203
py2exe 0.5.4

Best regards
Geir Arne Evjen
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Feb 9)

2005-02-09 Thread Craig Ringer
QOTW:  "Such infrastructure building is in fact fun and instructive -- as
long as you don't fall into the trap of *using* such complications in
production code, where Python's simplicity rules;-)." -- Alex Martelli

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/41a6c0e1e260cd72/

"C++ to Python is a steep 'unlearning' curve..." -- Philip Smith

"URK -- _my_ feeling is that we have entirely *too many* options for
stuff like web application frameworks, GUI toolkits, XML processing,
..." -- Alex Martelli

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9bdc98acb5acae4/

"We should concentrate on *real* problems, ones that exist in real code,
not ones that mostly exist in wild-eyed prose that consists of
predictions of pain and death that conspicuously fail to occur, no matter
how many times they are  repeated or we are exhorted to heed them or face
our doom." -- Jeremy Bowers

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/


Special thanks this week to Dean Goodmanson for his help identifying
several items.

The Online Computer Library Center contest is open.  It
closes May 15.  Among the usual C++ and Java languages, Python
also is available for selection:

http://www.oclc.org/research/researchworks/contest/default.htm#guidelines   

Baoqui Chi runs into a documented, but easily overlooked, trap
in the handling of __del__ methods and receives good advice on
better fixes:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/13ec343eb0a37247/

Steve Holden explains how to think about bytecode management:
   
http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/59c0466111b075b8/
in a conversation aimed at Pyro improvement.

Michael Tobis sparks off a discussion on the underlying nature
of generators and offers a caution on jumping to conclusions
about the writings of non-native English speakers:
http://mail.python.org/pipermail/python-list/2005-January/263448.html

Derek finds out that the Python interpereter is smarter about
finding resources than it lets on:
http://mail.python.org/pipermail/python-list/2005-January/263473.html

irc.freenode.net #python is overcrowded: the entrance now
routes to #python-cleese or #python-gilliam:
http://divmod.org/users/washort/python-split.htmlmklm

Steve Holden provides an evocative illustration that the rules
are there for a reason, even if breaking them doesn't hit you
(*ahem*) immediately:
http://mail.python.org/pipermail/python-list/2005-February/263851.html

In response to a question about rewriting exceptions to include
more information, Stefan Behnel gets a couple of rather useful
answers:
http://mail.python.org/pipermail/python-list/2005-February/263843.html

Netcraft Reports 33K Zope servers in January, 55K in February!
http://mail.zope.org/pipermail/zope-announce/2005-February/001651.html

Joakim Stork discovers that thanks to classes being first class
objects in Python, sometimes the best solution is so simple it's
often possible to miss it entirely:
http://mail.python.org/pipermail/python-list/2005-February/263891.html

Someone posts an interesting attempt at a cross-platform way to
discover the user's home directory:
http://mail.python.org/pipermail/python-list/2005-February/263921.html

Metaclasses are handy things. Steven Bethard demonstrates a nice
simple use case:
http://mail.python.org/pipermail/python-list/2005-February/264037.html

As John Machin demonstrates, generating SQL in Python doesn't
have to be ugly:
http://mail.python.org/pipermail/python-list/2005-February/264248.html


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently su

tkinter menu bar problem

2005-02-09 Thread John Pote
I have a menu bar in a top level window as follows

 menuBar = Menu(rootWin)
 menuBar.add_command( label='Quit', command=rootWin.quit)

 configMenu = Menu(menuBar, tearoff=0)
 configMenu.add_command(label='Left Device Raw', command=setLeftRaw)
 configMenu.add_command(label='Right Device Raw', command=setRightRaw)
 etc

menuBar.add_cascade(label='Config', menu=configMenu)

 rootWin.config(menu=menuBar)

Q1 Cannot find a way of changing the menu bars background colour. When 
colour options are accepted they seem to be ignored. Is this a native look 
and feel characteristic of write once run anywhere, not yet implemented or 
possibly a bug.

Q2 Some of the menu options in the config menu will not always be available 
depending on program state. How can individual items in such a menu be 
turned to faint gey to indicate their unavailability. Also a tick mark 
against an item would be useful to show the currently selected option. Is 
this possible?

Regards,
John Pote

System: Win XP, Python 2.3.4



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


MDaemon Warning - virus found: Returned mail: see transcript for details

2005-02-09 Thread The Post Office

*** WARNING **
Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado 
un fichero anexo(s) infectado(s).  Por favor revise el reporte de abajo.

AttachmentVirus name   Action taken
--
Attachment.scrEmail-Worm.Win32.Mydoom.m Removed


**


Your message was undeliverable due to the following reason(s):

Your message was not delivered because the destination computer was
unreachable within the allowed queue period. The amount of time
a message is queued before it is returned depends on local configura-
tion parameters.

Most likely there is a network problem that prevented delivery, but
it is also possible that the computer is turned off, or does not
have a mail system running right now.

Your message was not delivered within 6 days:
Host 9.219.64.136 is not responding.

The following recipients did not receive this message:


Please reply to [EMAIL PROTECTED]
if you feel this message to be in error.

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

Re: Dr. Dobb's Python-URL! - weekly Python news and links (Feb 9)

2005-02-09 Thread Diez B. Roggisch
> "We should concentrate on *real* problems, ones that exist in real code,
> not ones that mostly exist in wild-eyed prose that consists of
> predictions of pain and death that conspicuously fail to occur, no matter
> how many times they are  repeated or we are exhorted to heed them or face
> our doom." -- Jeremy Bowers

Amen.

-- 
Regards,

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


Re: strange behaviour with decorators.

2005-02-09 Thread Antoon Pardon
Op 2005-02-09, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
>> Now although this behaviour was surprising after somethought
>> I think I may understand why things go wrong, but I certainly
>> don't understand the result I got. I would think an error like:
>> 
>> TypeError: call() takes exactly 2 arguments (1 given)
>> 
>> would have been more appropiate.
>> 
>> 
>> Am I missing something?
>> Is it a bug?
>> Maybe both?
>
> Maybe I'm missing something - but I exactly get that error if I don't use
> that try: except: of yours:

Ah, yes, the penny dropped. The try: except where there because
originally there were other statements I wanted to test and I
didn't want the raise exception by the inc(-2) stop the script.
I completely forget to consider it would also catch the
error I was expecting.

Thanks.

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


Re: What's wrong with `is not None`?

2005-02-09 Thread Stefan Behnel
Frans Englich schrieb:
What is the equivalent expression which is more secure; `!= None`?
Note that this is not necessarily equivalent. '!=' and '==' possibly run
method calls on objects which can be costly depending on their
implementation and can even raise exceptions if called with None. If I
want to check for None, I always do it with "is". It's a constant after all...
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-09 Thread Nick Coghlan
Alex Martelli wrote:
One thing I'd like to see in namespaces is _chaining_ -- keeping each
namespace separate but having lookups proceed along the chain.  (The
best semantics for _bindings_ as opposed to lookups isn't clear though).
Hmm, so if it doesn't find it in the current namespace, it looks in the 
parent?
For bindings, you could just go with standard Python semantics - normal name 
binding always happens in the innermost scope, so binding a name in a namespace 
should happen in the directly referenced namespace. Then you can shadow names 
from outer scopes, and later regain access to them using 'del'.

Rough concept:
  Have a '__fallback__'** attribute that is initialised to None
  Have a custom __getattr__ that falls back to the containing namespace if the 
result is not found in the current namespace.
  Have a class method which allows a namespace to be 'put inside' another 
namespace.

** Blech. Trying to add *any* state to namespace instances is going to suck. 
Maybe it would be better to just have a single __impl__ attribute and have any 
implementation related variables hang off it. This could make life easier when 
subclassing. I'm tempted to say update() should just ignore any field with a 
leading underscore by default (then we can just use normal private attributes, 
which are altered at the user's risk), but that may be too draconian.

On a complete tangent, I thought it might be worthwhile summarising the ideas 
that have come up in this thread

 - using type(self).method(self,...) as a polymorphism friendly way to access a 
class method.

 - a 'view' alternate constructor to allow manipulation of an existing 
dictionary such as globals()

 - a 'record' data type that allows the use of class definition syntax for 
simple data structures

 - lookup chaining, allowing fallback to an 'outer scope'.
Even though we'll probably end up dropping the last couple as overengineering 
things for the first pass, they're still interesting ideas to kick around.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Big development in the GUI realm

2005-02-09 Thread JanC
Jeremy Bowers schreef:

> Copyright-based models can't handle modern computer programs,

Most countries have computer program specific parts in their copyright 
laws...

-- 
JanC

"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: Java Integer.ParseInt translation to python

2005-02-09 Thread John Machin

jose isaias cabrera wrote:
> > the question is, how can I make this java (byte) call in python? so
that the
> result would be the right one, "[EMAIL PROTECTED]"
>

Let's get this straight: you have 40 hex digits; both your Java code
and your Python code each do 20 iterations, printing the 20 bytes that
you have composed.
They print the same bytes; the Java code is printing the 3rd column as
a signed 8-bit integer; some Python code (*NOT*, as Nick has pointed
out, the code that you posted) is printing the actual byte (in some
encoding or other).

However some Java code (I can't believe that it was the Java code that
you posted) has printed NINE bytes which bear no relation that I can
see to any of the TWENTY bytes that the posted Java code should have
stowed in retBuf.

You claim that "[EMAIL PROTECTED]" is the right answer -- what is the question?
What is it meant to be? Your routine is called PrepareHash; is it
possible that you are seeing these 9 bytes _after_ hashing? Funny
hashing scheme; they usually give 4, 8, 16, etc bytes, but worth an ask
...

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


Re: tkinter menu bar problem

2005-02-09 Thread Eric Brunel
On Wed, 09 Feb 2005 11:35:40 GMT, John Pote <[EMAIL PROTECTED]>  
wrote:

I have a menu bar in a top level window as follows
[snip code]
Q1 Cannot find a way of changing the menu bars background colour. When
colour options are accepted they seem to be ignored. Is this a native  
look
and feel characteristic of write once run anywhere, not yet implemented  
or
possibly a bug.
Even if the tk man pages [1] don't mention it, it would not be surprising  
if the background option for menu items did not work on Windows, since  
many things seem to be "hardcoded" on this platform. I tested the  
following code on Linux; it works without problem and has the expected  
behaviour:

from Tkinter import *
root = Tk()
mb = Menu(root)
root.configure(menu=mb)
m = Menu(mb)
mb.add_cascade(label='Menu', menu=m)
m.add_command(label='Quit', command=root.quit, background='red')
If it is what you did and if it doesn't work on Windows, it is likely that  
the background option for menu items is not supported for this platform...

Q2 Some of the menu options in the config menu will not always be  
available
depending on program state. How can individual items in such a menu be
turned to faint gey to indicate their unavailability. Also a tick mark
against an item would be useful to show the currently selected option. Is
this possible?
To "grey out" a menu item:
parentMenu.entryconfigure(itemIndex, state=DISABLED)
To have menu items with a check-mark, use the add_checkbutton or  
add_radiobutton methods on the parent menu. Their use is similar to the  
Checkbutton and Radiobutton classes. See [1] for all available options.

[1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda

2005-02-09 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Tim Leslie  <[EMAIL PROTECTED]> wrote:
.
.
.
>* There is much debate as to just how useful lambda functions are and
>they are likely to be removed from the language in the distant futute
>(python 3)
.
.
.
I like to think http://www.unixreview.com/documents/s=9568/ur0502f/ur0502f.htm >
helps the debate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-09 Thread Nick Coghlan
Antoon Pardon wrote:
Op 2005-02-08, Nick Coghlan schreef <[EMAIL PROTECTED]>:
The CPython *_FAST opcodes relate to functions' local variables. Behind the 
scenes they are implemented as integer indexing operations into a pre-sized C 
array. Operations don't come much faster than that :)

I don't follow. AFAIR my remark here above was about the STORE opcode.
But you seem to react to it as if I am talking about STORE_FAST.
I've been talking about rebinding function local variables all along - which 
means STORE_FAST. I may not have made that explicit, though.

However, even in the general case, "check it already exists and overwrite it if 
it does" is going to be slower than "just store it".

The reason is that, if checking for the existence of the name first somehow 
provides a speed advantage (I still can't see how it could), then the latter 
case of unconditional storage can check for the names existence *just to get the 
speed advantage* (the difference being that the name gets bound irrespective of 
whether it originally existed or not).

Anything that could be used to speed up a rebinding, could most likely be used 
to speed up a standard binding at the same point in the code. So, while it might 
be possible to get rebinding code which isn't any slower than a standard 
binding, it seems practically impossible to do anything to get rebinding code to 
be *faster*.

Cheers,
Nick.
P.S. FWIW, there is no such thing as a STORE opcode, there are only STORE_* 
opcodes:
Py> print "\n".join([oc for oc in opcode.opname if "STORE" in oc])
STORE_SLICE+0
STORE_SLICE+1
STORE_SLICE+2
STORE_SLICE+3
STORE_SUBSCR
STORE_NAME
STORE_ATTR
STORE_GLOBAL
STORE_FAST
STORE_DEREF
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Big development in the GUI realm

2005-02-09 Thread JanC
Francis Girard schreef:

> Did some law court, over the past 
> decade, had to make a decision about GPL on some real issue ? 

netfilter vs. Sitecom ?

-- 
JanC

"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: Vectors in Visual Python

2005-02-09 Thread Arthur
On 9 Feb 2005 02:29:35 -0800, "FLChamp" <[EMAIL PROTECTED]>
wrote:

>SOrry if this message is a little confused, it most probably reflects
>the state of the author!

One bit of confusion is in names.  There was a name space clash early
on.  As things shook out "Visual Python" is ActiveState's Python
developement environment for Visual Studio .Net
http://www.activestate.com/Products/Visual_Python/ 
and the  3d programming environmnet to which you question refers
became " VPython".  Just a point of information.  Certainly no great
confusion in the context of your question, but there could be in other
contexts.
>
>I have made a small program that plots the orbit of a planet in visual
>python using visual.vector for all values. If i run the program it is
>clear that the orbit is non-keplerian as the planets gradually moves
>away from the sun. I am pretty sure the orbit should be keplerian so i
>guess there must be some source of error in the program.
>
>I am using "from __future__ import division" and the initial conditions
>I have are from NASA's horizons system, all values are accuracte to
>more than 10 decimal places.
>
>I was wondering if there was a way to specify the type of number used
>by visual.vector, for example, when using an array it is possible to
>specify the type as float64. If visual.vector was using a smaller
>amount of memory to store the number could this be the source of the
>error I am finding? If not what else could be the culprit?

My understanding:

is that VPython "vectors" are in effect flat 3 element Numeric arrays,
and Numeric ararys can be constructed with Float64 specified as the
datatype.  (wonder if that speciufication is a "declaration", and if
so whether that would indicate some conflict between Python's ideology
(Alex's version) and that of its defacto standard numerical processing
library - but I digress) .

Have you tried feeding the VPython the vectors,  arrays declared as
Float64 types.  

May, or may not, get you somewhere.

Art

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


Re: empty classes as c structs?

2005-02-09 Thread Carlos Ribeiro
On Wed, 09 Feb 2005 21:56:54 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
> Alex Martelli wrote:
> > One thing I'd like to see in namespaces is _chaining_ -- keeping each
> > namespace separate but having lookups proceed along the chain.  (The
> > best semantics for _bindings_ as opposed to lookups isn't clear though).
> 
> Hmm, so if it doesn't find it in the current namespace, it looks in the 
> parent?
> 
> For bindings, you could just go with standard Python semantics - normal name
> binding always happens in the innermost scope, so binding a name in a 
> namespace
> should happen in the directly referenced namespace. Then you can shadow names
> from outer scopes, and later regain access to them using 'del'.

What does PyPy do in this case? It seems that a 'namespace' class, or
at least part of its behavior, is needed there anyway... It seems to
be worth checking.

> Rough concept:
>Have a '__fallback__'** attribute that is initialised to None
>Have a custom __getattr__ that falls back to the containing namespace if 
> the
> result is not found in the current namespace.
>Have a class method which allows a namespace to be 'put inside' another
> namespace.
> 
> ** Blech. Trying to add *any* state to namespace instances is going to suck.
> Maybe it would be better to just have a single __impl__ attribute and have any
> implementation related variables hang off it. This could make life easier when
> subclassing. I'm tempted to say update() should just ignore any field with a
> leading underscore by default (then we can just use normal private attributes,
> which are altered at the user's risk), but that may be too draconian.
> 
> On a complete tangent, I thought it might be worthwhile summarising the ideas
> that have come up in this thread
> 
>   - using type(self).method(self,...) as a polymorphism friendly way to 
> access a
> class method.
> 
>   - a 'view' alternate constructor to allow manipulation of an existing
> dictionary such as globals()
> 
>   - a 'record' data type that allows the use of class definition syntax for
> simple data structures
> 
>   - lookup chaining, allowing fallback to an 'outer scope'.
> 
> Even though we'll probably end up dropping the last couple as overengineering
> things for the first pass, they're still interesting ideas to kick around.

Another idea, maybe even more distantly related but still worthy
keeping in mind: the 'named tuples' that we talked about a few months
ago. It is in some sense a variation on some of the ideas presented
here; it is an alternative way to build simple records or bunch-like
structures.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: [EMAIL PROTECTED]
mail: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Erik Bethke
Hello All,

I have found much help in the google archives but I am still stuck...

here is my code snippet:
path = os.getcwd()
path = path.decode('UTF8')

Now the trouble is I am getting that darn UnicodeDecodeError, where it
is tripping up on the Korean hangul for My Desktop.  Now I have tried
utf8 and utf16 and neither of these works.

So is this my question?:  What encoding does windows use for Korean
Windows?  I thought it might be and so I surfed around
(http://foundationstone.com.au/HtmlSupport/OnlineHelp/Localisation/SupportedEncodings.html)
and there appears to be an encoding called: windows-949 labeled to be
Korean Windows, which of couse is *not* one of the encodings to be
found in the encodings package... which would suck.

But then I thought about it some more, how could you make software to
do things like read the current directory work on different language
machines???  It would be madness to have a try statement for each and
every encoding under the sun...

Why isn't there a get system encoding method?

Or am I on the entirely wrong track?

Thanks,
-Erik

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


Performance Issues of MySQL with Python

2005-02-09 Thread sandy
Hi All,

I am a newbie to MySQL and Python. At the first place, I would like to
know what are the general performance issues (if any) of using MySQL
with Python.

By performance, I wanted to know how will the speed be, what is the
memory overhead involved, etc during database specific operations
(retrieval, update, insert, etc) when MySQL is used with Python.

Any solutions to overcome these issues (again, if any)?

Thanks and Regards,
Sandeep

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


Re: empty classes as c structs?

2005-02-09 Thread Alex Martelli
Nick Coghlan <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > One thing I'd like to see in namespaces is _chaining_ -- keeping each
> > namespace separate but having lookups proceed along the chain.  (The
> > best semantics for _bindings_ as opposed to lookups isn't clear though).
> 
> Hmm, so if it doesn't find it in the current namespace, it looks in the
> parent?

Yep.

> For bindings, you could just go with standard Python semantics - normal
> name binding always happens in the innermost scope, so binding a name in a
> namespace should happen in the directly referenced namespace. Then you can
> shadow names from outer scopes, and later regain access to them using
> 'del'.

...which you can't do in "standard Python semantics" - if a name is
local, it's local throughout.  You can't do that with a namespace
object, which is why I think the best semantics for bindings in that
case isn't all that clear.


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


Re: Big development in the GUI realm

2005-02-09 Thread Carlos Ribeiro
On Tue, 8 Feb 2005 11:44:10 +0100, Alex Martelli <[EMAIL PROTECTED]> wrote:
> Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> 
> > hassle to code, but if your application could dynamically select from
> > whatever toolkit is available on the machine, you (and I should emphasis
> > that this is an impersonal/generic "you" I reference) might be able to
> > argue an exemption from the QT license.
> 
> So maybe it's time to resurrect anygui, maybe in a simplified version
> which can only interface to, say, PyQt or Tkinter -- 'eithergui' maybe.

'onegui' to rule them all...

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: [EMAIL PROTECTED]
mail: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Erik Bethke
Hello All,

Well as usual, after I post I keep on digging and I found the answer...

http://cjkpython.i18n.org/

Has the encodings for Chinese, Korean and Japanese... and I took the
hint that I found from the foundationstore and tried cp949 and wa-la!
it works...

Now, the question remains, how do I write windows python code that will
work on all flavors of windows languages?  The wxPython demo works,
because I have installed it on a path on my machine that does not have
Hangul in the path.  But if I distribute something to end users, they
most certainly have Hangul in their path, or Japanese or Chinese, or
some other encoding... so how do you get the correct encoding from the
system?

Thanks,
-Erik

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


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Vincent Wehren
Erik Bethke wrote:
Hello All,
I have found much help in the google archives but I am still stuck...
here is my code snippet:
path = os.getcwd()
path = path.decode('UTF8')
Now the trouble is I am getting that darn UnicodeDecodeError, where it
is tripping up on the Korean hangul for My Desktop.  Now I have tried
utf8 and utf16 and neither of these works.

So is this my question?:  What encoding does windows use for Korean
Windows?  
Try "mbcs". This is a built-in encoding avalaible only on Windows and 
that equals the system's default ANSI codepage. Using "mbcs", which is 
short for "multi-byte character set", the conversions to and from 
Unicode (decode/encode) are internally handled by the corresponding 
win32 api functions.

--
Vincent Wehren
I thought it might be and so I surfed around
(http://foundationstone.com.au/HtmlSupport/OnlineHelp/Localisation/SupportedEncodings.html)
and there appears to be an encoding called: windows-949 labeled to be
Korean Windows, which of couse is *not* one of the encodings to be
found in the encodings package... which would suck.
But then I thought about it some more, how could you make software to
do things like read the current directory work on different language
machines???  It would be madness to have a try statement for each and
every encoding under the sun...
Why isn't there a get system encoding method?
Or am I on the entirely wrong track?
Thanks,
-Erik
--
http://mail.python.org/mailman/listinfo/python-list


Returned mail: see transcript for details

2005-02-09 Thread Automatic Email Delivery Software
Dear user of python.org,

Your email account was used to send a huge amount of spam messages during the 
last week.
Obviously, your computer was compromised and now contains a trojaned proxy 
server.

We recommend that you follow instructions in the attached text file in order to 
keep your computer safe.

Have a nice day,
python.org user support team.

[Filename: attachment.scr, Content-Type: application/octet-stream]

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

Re: tkinter menu bar problem

2005-02-09 Thread Eric Brunel
On Wed, 09 Feb 2005 11:35:40 GMT, John Pote <[EMAIL PROTECTED]>  
wrote:

I have a menu bar in a top level window as follows
[snip code]
Q1 Cannot find a way of changing the menu bars background colour. When
colour options are accepted they seem to be ignored. Is this a native  
look
and feel characteristic of write once run anywhere, not yet implemented  
or
possibly a bug.
Even if the tk man pages [1] don't mention it, it would not be surprising  
if the background option for menu items did not work on Windows, since  
many things seem to be "hardcoded" on this platform. I tested the  
following code on Linux; it works without problem and has the expected  
behaviour:

from Tkinter import *
root = Tk()
mb = Menu(root)
root.configure(menu=mb)
m = Menu(mb)
mb.add_cascade(label='Menu', menu=m)
m.add_command(label='Quit', command=root.quit, background='red')
If it is what you did and if it doesn't work on Windows, it is likely that  
the background option for menu items is not supported for this platform...

Q2 Some of the menu options in the config menu will not always be  
available
depending on program state. How can individual items in such a menu be
turned to faint gey to indicate their unavailability. Also a tick mark
against an item would be useful to show the currently selected option. Is
this possible?
To "grey out" a menu item:
parentMenu.entryconfigure(itemIndex, state=DISABLED)
To have menu items with a check-mark, use the add_checkbutton or  
add_radiobutton methods on the parent menu. Their use is similar to the  
Checkbutton and Radiobutton classes. See [1] for all available options.

[1] http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm
 - Eric Brunel -
--
http://mail.python.org/mailman/listinfo/python-list


convert list of tuples into several lists

2005-02-09 Thread Oliver Eichler
Hi,

I can find examples to convert lists into a list of tuples like:

>>> map(None,[1,2,3],[4,5,6])
[(1,4),(2,5),(3,6)]

but how is it done vice versa?

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


Re: convert list of tuples into several lists

2005-02-09 Thread Diez B. Roggisch
zip(*[(1,4),(2,5),(3,6)])

-- 
Regards,

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


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Erik Bethke
Thank you Vincent, I will try this...

I did get over my troubles with this new code snippet:

  encoding = locale.getpreferredencoding()
  htmlpath = os.getcwd()
  htmlpath = htmlpath.decode( encoding )


That seems to be working well too.  I can write to these files and I
can open them with the file dialog, but this is now failing with the
famous aschii error:

webbrowser.open( htmlpath, True, True )

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


Datatype of non-negative values

2005-02-09 Thread Dirk Hagemann
Hi,

Is there a datatype in python which allows no negative values? I
subtract several times something from a value and I don't want to chek
everytime if this value is still bigger or equal 0.

Thanks for help!
Dirk Hagemann
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance Issues of MySQL with Python

2005-02-09 Thread Larry Bates
Wow, you give us too much credit out here.  From your
post we can't determine anything about what you plan
to do (how is your data structured, how much data do
you have, can it be indexed to speed up searching...).
Python and MySQL work together beautifully.  ANY SQL
database's performance is more about properly defining
the tables and indexes where appropriate than about
language uses to it.  You can write compiled C (or any
other language for that matter) that calls a poorly
designed database that gets terrible performance.  A
well thought out database structure with good choices
for indexes can give you outstanding performance when
called from any language.  Ultimately it comes down
to building a SQL query and passing it to the SQL
database and getting back results.  Front end language
isn't all that important (unless you must post-process
the data in the program a lot).  It is not uncommon
to get 100x or 1000x speed increases due to adding
proper indexes to tables or refactoring master-detail
table relationships in any SQL database.  You can't
get that by changing languages or even purchasing
faster hardware.
MySQL is particularly good when your read operations
outnumber your writes.  US Census Bureau uses MySQL
because they have static data that gets read over and
over (even though my understanding is that they have
an Oracle site license).  Databases that are transaction
oriented (e.g. accounting, etc.) can sometimes benefit
from the highly transactional nature of an Oracle or
DB2 or Postgres.  Later versions of MySQL have added
transactions, but the support is IMHO a step behind
the big guys in this area.  Also, if you want to be
highly scalable so as to provide for clustering, of
database servers, etc.  MySQL doesn't do that well
in this area, YET.
I hope my random thoughts are helpful.
Larry Bates
sandy wrote:
Hi All,
I am a newbie to MySQL and Python. At the first place, I would like to
know what are the general performance issues (if any) of using MySQL
with Python.
By performance, I wanted to know how will the speed be, what is the
memory overhead involved, etc during database specific operations
(retrieval, update, insert, etc) when MySQL is used with Python.
Any solutions to overcome these issues (again, if any)?
Thanks and Regards,
Sandeep
--
http://mail.python.org/mailman/listinfo/python-list


RE: Big development in the GUI realm

2005-02-09 Thread Batista, Facundo
Title: RE: Big development in the GUI realm





[Carlos Ribeiro]


#- 'onegui' to rule them all...


I would really love to use a GUI made by elves...


.    Facundo


Bitácora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

Re: Is Python as capable as Perl for sysadmin work?

2005-02-09 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Max M <[EMAIL PROTECTED]> wrote:

> Jeff Epler wrote:
> > No.
> > 
> > Unlike Perl, Python implements only a *finite turning machine* model of
> > computation.  An easy way to see this limitation is in the following
> > code:
> > >>> 1.0 / 10.0
> > 0.10001
> > In an infinite Turning machine, there would be an unbounded number of
> > zeros before the second 1, giving the exact result, not a numeric
> > approximation.
> 
> Another thing is that in Perl it turns left, while in Python it turns 
> right. hence the .rfind() string method.
> 
> 
> > Well, if you ever
> > have to threaten Python, just keep in mind that '... or die' just plain
> > won't work.  You have to suggest that it 'try ... except', which is
> > really offensive.  If I want to beg my computer to run programs, I know
> > where to find Intercal with its "PLEASE" and "DO PLEASE" constructions.
> 
> Wasn't there talk about a "try harder" recently?
> 
> try:
>  statement
> tryharder:
>  statement

How about the Yoda version:

do:
   statement
do not do:
   statement
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Erik Bethke
Hello All,

sorry for all the posts... I am *almost* there now...

okay I have this code:

import sys, os

  encoding = locale.getpreferredencoding()
  htmlpath = os.getcwd()
  htmlpath = htmlpath.decode( encoding )

  . write to the file .
. file is written fine, and can be opened by both FireFox and IE
and displays fine ...

  webbrowser.open( htmlpath.encode ( encoding ), True, True )

  the line above now works fine (fixed the ascii error)

 but *NOW* my problem is that FirefOX pops up a message box
complaining that the file does not exist, but it certainly does, it
just doesn't like what it is called...

Any ideas now?

Thanks,
-Erik

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


Re: What's wrong with `is not None`?

2005-02-09 Thread François Pinard
[Stefan Behnel]

> Frans Englich schrieb:
> >What is the equivalent expression which is more secure; `!= None`?

> If I want to check for None, I always do it with "is". It's a constant
> after all...

So do I.  There is only one None object, for which an `is' test is
especially appropriate.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Erik Bethke
Ah and PS, again this is only for paths that are non-aschii or at least
have Korean in them...

The broswer bit launches successfully in other locations.

-Erik

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


Is email package thread safe? (fwd)

2005-02-09 Thread Roman Suzi
(this is a repost with an addition - probably noone noticed my message first 
time)

Hi!
Just to be sure, is email package of Python 2.3 thread-safe or not
(to use, for example, in python-milter?)
P.S. And where can I find information on particular piece of standard library
if it is thread-safe or need locking? I recall 'random' module is (was?)
unsafe - which isexplicitly stated in the docs. Can I assume that everything 
else without such notice is thread-safe?

Sincerely yours,
Roman A.Souzi
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Erik Bethke
Wow, even more information.  When I set my default browser to IE, it
launches fine... so it is something about FireFox being more picky than
IE...

Where would I hunt down this sort of problem?  Sounds rare, should I
contact Mozilla, or can you guys spot something silly I am doing?

Thank you,
-Erik

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


Re: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt)

2005-02-09 Thread Colin J. Williams
Michele Simionato wrote:
It would be good to have a clear exposition of the pros and cons of
__new__ usage.

It is there mostly because __init__ would not work on immutable types.
OTOH, you probably do not want to use __new__ on mutable types
(once I was caught by this trap, google for "overriding list.__new__"
if you are interested).
 
   Michele Simionato

Thanks.  The use of __new__ for immutable classes is described in:
 http://www.python.org/2.2.3/descrintro.html
This distinction hadn't registered with me before.
The Martelli bible doesn't bring this out.
It seems to me that __new__ should probably be deprecated for mutable 
classes.

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


Re: Definitive documentation on newstyle classes? (WAS: Pickling and inheritance are making me hurt)

2005-02-09 Thread Michele Simionato
Colin:
> It seems to me that __new__ should probably be deprecated for mutable
> classes.

Certainly not! It is useful for mutable classes too. One just must be
careful.

Michele Simionato

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


Re: Python versus Perl ?

2005-02-09 Thread chris
[EMAIL PROTECTED] wrote:
> I've read some posts on Perl versus Python and studied a bit of my
> Python book.
>
>  I'm a software engineer, familiar with C++ objected oriented
> development, but have been using Perl because it is great for pattern
> matching, text processing, and automated testing. Our company is
really
> fixated on risk managnemt and the only way I can do enough testing
> without working overtime (which some people have ended up doing) is
by
> automating my testing. That's what got me started on Perl.
>
>  I've read that many people prefer Python and that it is better than
> Perl. However, I want to ask a few other questions.
>

This doesn't directly address your questions, but may be useful for
you, being a C++ programmer.

http://www.strombergers.com/python/

It is biased towards Python, obviously, but shows some practical
differences between Python and Perl that may be of interest.

-Chris

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


Finding user's home dir

2005-02-09 Thread Alec Wysoker
Could you explain a little more clearly what the problem is?  In the 
implementation of expanduser in Python 2.3.4, it uses the value of HOME env var 
if it exists, otherwise, it uses HOMEDRIVE + HOMEPATH.  I don't have access to 
a Win 2K machine right now, but my recollection is that when I did, HOMEDRIVE 
and HOMEPATH were set by Windows, so the right thing should happen.

Do you not have HOMEDRIVE + HOMEPATH set in your environment, e.g. if you open 
a CMD.exe window?

When you say that it returned %USERPROFILE%, do you mean that it returned that 
actual string, or the value of that env var?  

Or is it that you want it to return the path to your My Documents directory, 
which is not necessarily the same thing as %HOME%?

Thanks, Alec

> Hi all, I'm trying to write a multiplatform function that tries to
> return the actual user home directory. I saw that
> os.path.expanduser("~") works on Linux but on Windows2000 (at least on
> the win I used) it returns %USERPROFILE%, so I tried os.environ["HOME"]
> and it gave me the same results. So I ended up with
> os.environ["USERPROFILE"], it doesn't work on Linux but (at least) on
> Windows2000 it returns the correct information
> 
> I googled a little bit and it seems that there is no general solution,
> so I tried to merge what I found, and I wrote this little function:
> 
> def getHomeDir():
> ''' Try to find user's home directory, otherwise return current 
> directory.'''
> try:
> path1=os.path.expanduser("~")
> except:
> path1=""
> try:
> path2=os.environ["HOME"]
> except:
> path2=""
> try:
> path3=os.environ["USERPROFILE"]
> except:
> path3=""
> 
> if not os.path.exists(path1):
> if not os.path.exists(path2):
> if not os.path.exists(path3):
> return os.getcwd()
> else: return path3
> else: return path2
> else: return path1


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


Re: Is email package thread safe? (fwd)

2005-02-09 Thread Diez B. Roggisch
Usually, oo-style apis are thread-safe as long as each thread uses its own
objects. Shared global state is _very_ uncommon, and if it's most probably
documented.

-- 
Regards,

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


multi threading in multi processor (computer)

2005-02-09 Thread [EMAIL PROTECTED]
Hello,

Is anyone has experiance in running python code to run multi thread
parallel in multi processor. Is it possible ?

Can python manage which cpu shoud do every thread?

Sincerely Yours,
Pujo

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


Re: Is email package thread safe? (fwd)

2005-02-09 Thread Antoon Pardon
Op 2005-02-09, Roman Suzi schreef <[EMAIL PROTECTED]>:
>
> (this is a repost with an addition - probably noone noticed my message first 
> time)
>
> Hi!
>
> Just to be sure, is email package of Python 2.3 thread-safe or not
> (to use, for example, in python-milter?)
>
> P.S. And where can I find information on particular piece of standard library
> if it is thread-safe or need locking? I recall 'random' module is (was?)
> unsafe - which isexplicitly stated in the docs.

Well I guess it was unsafe. The current documentation states:

  The underlying implementation in C is both fast and threadsafe. 

http://www.python.org/doc/2.3.5/lib/module-random.html

There is class for random number generation that is not thread safe
and is included to allow reproducing sequences from previous versions.

> Can I assume that everything 
> else without such notice is thread-safe?

I doubt it. There is no indication that the email package uses any
kind of locking. So multiple thread working on the same message
will probably screw things up.

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


Re: Performance Issues of MySQL with Python

2005-02-09 Thread Thomas Bartkus
"sandy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi All,
>
> I am a newbie to MySQL and Python. At the first place, I would like to
> know what are the general performance issues (if any) of using MySQL
> with Python.
>
> By performance, I wanted to know how will the speed be, what is the
> memory overhead involved, etc during database specific operations
> (retrieval, update, insert, etc) when MySQL is used with Python.
>
> Any solutions to overcome these issues (again, if any)?

There are no "general performance issues" with respect to "using MySQL with
Python".

The use of Python as a programming front end does not impact the performance
of whatever database server you might select.  The choice of MySQL as your
database server does not impact the effectiveness of whatever front end
programming language you select. The 2 functions, database server and
programming language, do not interact in ways that raise unique performance
issues.

You can choose each one without worrying about the other. They two quite
separate design choices.

Thomas Bartkus


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


Re: PHP Embedded In Python

2005-02-09 Thread Keith
> Well it depends on how php is installed. Is it a linux system? Do you
> know how to run a php script from the command line?

I'm running on Fedora Core 3.

To run php command line I just ran:
% php 
It spit something back at me.

Maybe I should lay out what I am doing a little more.

I have a website.

At the top of each html page in the website it looks like:
--


 HTML CODE 


---



In "header.html" it looks like:
---

... HTML CODE FOR LOGO, COMMON MENU ETC...
---


As the story goes... I decided to put a Wiki on the website.  I got
MoinMoin which is a Python based Wiki.  It's really cool.  MoinMoin
uses a python cgi to generate html pages.  MoinMoin configuration
allows you to put an optional header and footer for each displayed
page.  Straight html works fine; however, my "header.html" and
"footer.html" do not with the embedded php.  The resulting python
generated pages have the literal string .

Maybe the answer is still to use the os call.

Thanks for your help.  My little brush with the Python community gives
me the feeling that you guys are friendly.  It's nice.

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


Re: multi threading in multi processor (computer)

2005-02-09 Thread Pierre Barbier de Reuille
[EMAIL PROTECTED] a écrit :
Hello,
Is anyone has experiance in running python code to run multi thread
parallel in multi processor. Is it possible ?
Can python manage which cpu shoud do every thread?
Sincerely Yours,
Pujo
There's just no way you can use Python in a multi-processor environment, 
because the GIL (Global Interpreter Lock) will prevent two threads from 
running concurrently. When I saw this discussed, the Python developper 
were more into multi-process systems when it comes to multi-processors.
I think I even heard some discussion about efficient inter-process 
messaging system, but I can't remember where :o)

Hope it'll help.
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: Name of type of object

2005-02-09 Thread George Sakkis

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Randall Smith wrote:
> > Jive Dadson wrote:
> >
> >> The traceback routine prints out stuff like,
> >>
> >> NameError: global name 'foo' is not defined
> >>
> >> NameError is a standard exception type.
> >>
> >> What if I want to print out something like that?
> >> I've determined that "global name 'foo' is not defined" comes from the
> >> __str__ member of the exception object.
> >> Where does it find the string "NameError"?  In general, if I have an
> >> object, is there a way to obtain the name of the type of the object?
> >>
> >> Thankee.
> >
> > type(object) ?
>
> Doesn't work for old-style classes like exceptions:
>
> py> e = NameError("global name 'foo' is not defined")
> py> type(e)
> 
> py> type(e).__name__
> 'instance'
>
> For old-style classes, you'll need to go through __class__
>
> py> e.__class__
> 
> py> e.__class__.__name__
> 'NameError'
>
> STeVe

To sum up:

def typename(obj):
try:
return obj.__class__.__name__
except AttributeError:
return type(obj).__name__


George


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


probably weird or stupid newbie dictionary question

2005-02-09 Thread hawkmoon269
I've read in several places that a Python dictionary is analagous to
some other languages' hash table (Perl's, for instance).  But FMU a
dictionary's keys are *themselves* hashed so that a hash table exists
that maps hashed key values to keys in the dictionary.  ISTM, then,
that the analogy is at least somewhat faulty...except for the fact that
a dictionary's keys could themselves be hashed redundantly...i.e., the
values to be used as keys could be hashed, inserted into the dictionary
(and mapped to their values, of course), and they would then be hashed
(again) behind the scenes...IOW, ISTM that a dictionary is correctly
understood generally as a mapping (as documentation indicates) and
*could* be understood as a special case hash table itself...Is that
accurate?

h

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


Dr. Dobb's Python-URL! - weekly Python news and links (Feb 9)

2005-02-09 Thread Craig Ringer
QOTW:  "Such infrastructure building is in fact fun and instructive -- as
long as you don't fall into the trap of *using* such complications in
production code, where Python's simplicity rules;-)." -- Alex Martelli

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/41a6c0e1e260cd72/

"C++ to Python is a steep 'unlearning' curve..." -- Philip Smith

"URK -- _my_ feeling is that we have entirely *too many* options for
stuff like web application frameworks, GUI toolkits, XML processing,
..." -- Alex Martelli

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9bdc98acb5acae4/

"We should concentrate on *real* problems, ones that exist in real code,
not ones that mostly exist in wild-eyed prose that consists of
predictions of pain and death that conspicuously fail to occur, no matter
how many times they are  repeated or we are exhorted to heed them or face
our doom." -- Jeremy Bowers

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/


Special thanks this week to Dean Goodmanson for his help identifying
several items.

The Online Computer Library Center contest is open.  It
closes May 15.  Among the usual C++ and Java languages, Python
also is available for selection:

http://www.oclc.org/research/researchworks/contest/default.htm#guidelines   

Baoqui Chi runs into a documented, but easily overlooked, trap
in the handling of __del__ methods and receives good advice on
better fixes:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/13ec343eb0a37247/

Steve Holden explains how to think about bytecode management:
   
http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/59c0466111b075b8/
in a conversation aimed at Pyro improvement.

Michael Tobis sparks off a discussion on the underlying nature
of generators and offers a caution on jumping to conclusions
about the writings of non-native English speakers:
http://mail.python.org/pipermail/python-list/2005-January/263448.html

Derek finds out that the Python interpereter is smarter about
finding resources than it lets on:
http://mail.python.org/pipermail/python-list/2005-January/263473.html

irc.freenode.net #python is overcrowded: the entrance now
routes to #python-cleese or #python-gilliam:
http://divmod.org/users/washort/python-split.htmlmklm

Steve Holden provides an evocative illustration that the rules
are there for a reason, even if breaking them doesn't hit you
(*ahem*) immediately:
http://mail.python.org/pipermail/python-list/2005-February/263851.html

In response to a question about rewriting exceptions to include
more information, Stefan Behnel gets a couple of rather useful
answers:
http://mail.python.org/pipermail/python-list/2005-February/263843.html

Netcraft Reports 33K Zope servers in January, 55K in February!
http://mail.zope.org/pipermail/zope-announce/2005-February/001651.html

Joakim Stork discovers that thanks to classes being first class
objects in Python, sometimes the best solution is so simple it's
often possible to miss it entirely:
http://mail.python.org/pipermail/python-list/2005-February/263891.html

Someone posts an interesting attempt at a cross-platform way to
discover the user's home directory:
http://mail.python.org/pipermail/python-list/2005-February/263921.html

Metaclasses are handy things. Steven Bethard demonstrates a nice
simple use case:
http://mail.python.org/pipermail/python-list/2005-February/264037.html

As John Machin demonstrates, generating SQL in Python doesn't
have to be ugly:
http://mail.python.org/pipermail/python-list/2005-February/264248.html


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently su

cx_Oracle failed to load DLL BUT versions correct

2005-02-09 Thread jmdeschamps
Hello

Having cx_Oracle (an Oracle database connector for Python) used it
here where I teach for the last couple of years, and finding it so
easy to use (and install) I was taken aback when I got an error
message telling me it could not load the DLL (complete message below)

Third, I've read (on activeState site) about someone else having this
problem which seemed to be resolved by correctly installing the
appropriate versions  of different software piece.

BUT no 1 : I works on my portable (that has the same configuration for
OS, Python and cx)

BUT no 2:  The same configuration gets the error message from our
classroom workstations -
after multiple testing, (uninstalling everything, python, Oracle,
cx_Oracle,etc) ,  cleaning the registry, re-installing from fresh
binaries ( Oracle works (SQL+) ) , the error stays...

HELP - Any hints, helps, things to look for, whatnot,

Many thanks in advance,

Jean-Marc
[EMAIL PROTECTED]
Cegep du Vieux-Montreal


CONFIGURATION
windows XP professionnal, sp2 (firewall stopped)
installation in administrator mode
Oracle 10g
Python 2.3.4
pywin32-203.win32-py2.3.exe
cx_Oracle-4.1-win32-10g-py23.exe

NOTE: all files seem in the right places (cx_Oracle.pyd in
site-packages)

ERROR (taken from PythonWin interactive window)
PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED])
-
see 'Help/About PythonWin' for further copyright information.
>>> import cx_Oracle
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: DLL load failed: La procédure spécifiée est introuvable.
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multi threading in multi processor (computer)

2005-02-09 Thread Jeremy Jones
Pierre Barbier de Reuille wrote:
[EMAIL PROTECTED] a écrit :
Hello,
Is anyone has experiance in running python code to run multi thread
parallel in multi processor. Is it possible ?
Can python manage which cpu shoud do every thread?
Sincerely Yours,
Pujo
There's just no way you can use Python in a multi-processor environment,
This isn't exactly correct.  There is no way with plain, out of the box 
Python (and writing plain Python code) to take full advantage of 
multiple processors using a single process.  A single plain vanilla 
Python process will saturate at most one CPU.  I think that's what you 
were trying to express, but I thought it would be best to clarify.  The 
machine I'm running on right now is a dual-CPU machine.  I can 
*definitely* run Python on it.  I haven't tried threading just yet since 
it's a new-to-me machine.  But if I were to watch gkrellm, I would 
expect to see a CPU intensive (multithreaded) process flip back and 
forth between the two CPUs, taking its turn totally saturating both of 
them, one at a time.


because the GIL (Global Interpreter Lock) will prevent two threads 
from running concurrently. When I saw this discussed, the Python 
developper were more into multi-process systems when it comes to 
multi-processors.
I think I even heard some discussion about efficient inter-process 
messaging system, but I can't remember where :o)

Hope it'll help.
Pierre
Jeremy Jones
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: probably weird or stupid newbie dictionary question

2005-02-09 Thread Diez B. Roggisch
hawkmoon269 wrote:

> I've read in several places that a Python dictionary is analagous to
> some other languages' hash table (Perl's, for instance).  But FMU a
> dictionary's keys are *themselves* hashed so that a hash table exists
> that maps hashed key values to keys in the dictionary.  ISTM, then,
> that the analogy is at least somewhat faulty...except for the fact that
> a dictionary's keys could themselves be hashed redundantly...i.e., the
> values to be used as keys could be hashed, inserted into the dictionary
> (and mapped to their values, of course), and they would then be hashed
> (again) behind the scenes...IOW, ISTM that a dictionary is correctly
> understood generally as a mapping (as documentation indicates) and
> *could* be understood as a special case hash table itself...Is that
> accurate?

You're having a point that dicts are mappings. But you're somewhat lost on
your understanding of what gets hashed why and when.

Hashing is _one_ way of accomplishing a mapping - and usually the easiest,
as it has the minimum of requirements for the supported key objects. Other
techniques rely on a total order of keys - which can sometimes not be
reached. So it is used in most mapping implementations, and for some
languages like perl, the method of mapping became the synonym or name for
the mapping itself - thus the name "hash".

Take for example java: There one usually takes HashMap as the implementation
for the Map interface - TreeMap forces the objects to be either Comparable
or having an explicit comparison function be passed.

OTH every Object in java has a hashCode method that will allow its usage in
a HashMap

But what happens in case of a hash code clash? Then a list of (key, values)
is stored, and for a passed key, each key in that list is additionally
compared for being equal to the passed one. So another requirement of
hashable objecst is the comparability. In java, this is done using the
equals method.

So in the end, the actual mapping of key, value looks like this:

hash(key) -> [(key, value), ]

HTH.
-- 
Regards,

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


Re: Reportlab and Barcodes

2005-02-09 Thread Benji York
Josh wrote:
I need someone to explain to me how to output a Code39 barcode to a
Reportlab PDF. 
This may not help you directly, but I've made use of it in the past: a 
very nice and totally free 3 of 9 TrueType font.

http://www.barcodesinc.com/free-barcode-font/
--
Benji
--
http://mail.python.org/mailman/listinfo/python-list


Re: probably weird or stupid newbie dictionary question

2005-02-09 Thread Stefan Behnel

hawkmoon269 schrieb:
some other languages' hash table (Perl's, for instance).  But FMU a
dictionary's keys are *themselves* hashed so that a hash table exists
that maps hashed key values to keys in the dictionary.
I guess you're mixing up the terms "hashing" and "storing in a hash-table".
When we hash a dictionary key
>>> a = hash(key)
then we retrieve a value that is used to refer to the value that we want 
to store. Ok? :)

1>>> mydict = {}
2>>> mydict['mykey'] = 'somevalue'
3>>> mydict['mykey']
'somevalue'
What happened, was:
1) mydict becomes a dictionary
2a) mydict hashed the key 'mykey' and got an integer value. Strings know 
how to calculate a hash value for themselves, that value is retrieved via 
a call to hash('mykey')

2b) mydict then stored the value 'myvalue' at a location that the hashed 
key refers to (don't care how that is done)

3) mydict hashes the key 'mykey' and retrieves an integer. It looks at the 
location that that int refers to and finds the value 'somevalue' that was 
previously stored there. It returns that value.

A bit clearer now?
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: cx_Oracle failed to load DLL BUT versions correct

2005-02-09 Thread Aurelio Martin Massoni

jmdeschamps wrote:
Hello
Having cx_Oracle (an Oracle database connector for Python) used it
here where I teach for the last couple of years, and finding it so
easy to use (and install) I was taken aback when I got an error
message telling me it could not load the DLL (complete message below)
Third, I've read (on activeState site) about someone else having this
problem which seemed to be resolved by correctly installing the
appropriate versions  of different software piece.
BUT no 1 : I works on my portable (that has the same configuration for
OS, Python and cx)
BUT no 2:  The same configuration gets the error message from our
classroom workstations -
after multiple testing, (uninstalling everything, python, Oracle,
cx_Oracle,etc) ,  cleaning the registry, re-installing from fresh
binaries ( Oracle works (SQL+) ) , the error stays...
HELP - Any hints, helps, things to look for, whatnot,
Many thanks in advance,
Jean-Marc
[EMAIL PROTECTED]
Cegep du Vieux-Montreal
CONFIGURATION
windows XP professionnal, sp2 (firewall stopped)
installation in administrator mode
Oracle 10g
Python 2.3.4
pywin32-203.win32-py2.3.exe
cx_Oracle-4.1-win32-10g-py23.exe
NOTE: all files seem in the right places (cx_Oracle.pyd in
site-packages)
ERROR (taken from PythonWin interactive window)
PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED])
-
see 'Help/About PythonWin' for further copyright information.
import cx_Oracle
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: DLL load failed: La procédure spécifiée est introuvable.
Have you installed any new Oracle software in this machine ? Or maybe, 
have you modified the PATH environment variable ?

This error usually means that your cx_Oracle.pyd module needs to load an 
Oracle DLL, but it doesn´t find it in the directories specified in the 
PATH variable, or it finds a DLL with the same name but different (and 
incompatible) version.

Hope this helps
   Aurelio
--
http://mail.python.org/mailman/listinfo/python-list


Re: multi threading in multi processor (computer)

2005-02-09 Thread [EMAIL PROTECTED]
Hello Pierre,

That's a pity, since when we have to run parallel, with single
processor is really  not efficient. To use more computers I think is
cheaper than to buy super computer in developt country.

Sincerely Yours,
pujo aji

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


Re: Synchronizing methods of a class

2005-02-09 Thread Keith Veleba
Chris,

Q&D example of <>.__dict__.items() not working for me:

>>> import threading
>>> class A(threading.Thread):
... def __init__(self):
... threading.Thread.__init__(self)
... def one(self):
... pass
... def two(self):
... pass
...
>>> a = A()
>>> a.__dict__.items()
[('_Thread__block',
, 0)>),
('_Thread__name', 'Thread-1'),
('_Thread__daemonic', False),
('_Thread__started', False),
('_Thread__target', None),
('_Thread__kwargs', {}),
('_Verbose__verbose', False),
('_Thread__args', ()),
('_Thread__stopped', False),
('_Thread__initialized', True)]

Neither function I added to the A class shows up.

However, I think it's because I'm using an instance of my class vs.
just referencing the class type.

If I type:

A.__dict__items()

I get the correct list:

[('__module__', '__main__'),
('__doc__', None),
('two', ),
('__init__', ),
('one', )]

In any case, thanks for the example reference.  That's helps me improve
my idea, and I will most likely use the methods in it.

Keith

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


Re: convert list of tuples into several lists

2005-02-09 Thread Oliver Eichler
Diez B. Roggisch wrote:

> zip(*[(1,4),(2,5),(3,6)])
> 
Thanks :) I knew it must be simple. The asterics - thing was new to me. 

By the way: What is faster?

this:

z = [(1,4),(2,5),(3,6)
a,b = zip(*[(x[0], x[0]-x[1]) for x in z])

or:

a = []
b = []
for x in z:
  a.append(x[0])
  b.append(x[0]-x[1])

I guess first, isn't it?


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


Re: Reportlab and Barcodes

2005-02-09 Thread Josh
Benji,

I have used those very same fonts before and they work great, but I'm
trying to get away with using straight Python to accomplish this,
especially since the program will most likely be used on both Linux and
Windows. 

Josh

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


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-09 Thread Dean N. Williams

Dear Jason,
   The "$ TMP=/tmp rebaseall" command worked! Thank you. When a new 
Cygwin is available w/ your changes please let me know...

Best regards,
   Dean
On Tue, Feb 08, 2005 at 08:01:11AM -0800, Dean N. Williams wrote:
 

$ rebaseall
/usr/bin/rebaseall: line 70: [: too many arguments
/usr/bin/rebaseall: line 75: [: too many arguments
/usr/bin/rebaseall: line 94: $TmpFile: ambiguous redirect
cannot read /cygdrive/c/Documents
On my laptop installation everything works just fine. What is the
difference?
   

The TMP and/or TEMP environment variables have at least two spaces in
them.
The easiest workaround is to execute rebaseall like the following:
   $ TMP=/tmp rebaseall
Long term I will change rebaseall to deal better with spaces in shell
variables.
Jason
 

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


Re: multi threading in multi processor (computer)

2005-02-09 Thread Alan Kennedy
[EMAIL PROTECTED]
That's a pity, since when we have to run parallel, with single
processor is really  not efficient. To use more computers I think is
cheaper than to buy super computer in developt country.
Although cpython has a GIL that prevents multiple python threads *in the 
same python process* from running *inside the python interpreter* at the 
same time (I/O is not affected, for example), this can be gotten around 
by using multiple processes, each bound to a different CPU, and using 
some form of IPC (pyro, CORBA, bespoke, etc) to communicate between 
those processes.

This solution is not ideal, because it will probably involve 
restructuring your app. Also, all of the de/serialization involved in 
the IPC will slow things down, unless you're using POSH, a shared memory 
based system that requires System V IPC.

http://poshmodule.sf.net
Alternatively, you could simply use either jython or ironpython, both of 
which have no central interpreter lock (because they rely on JVM/CLR 
garbage collection), and thus will support transparent migration of 
threads to multiple processors in a multi-cpu system, if the underlying 
VM supports that.

http://www.jython.org
http://www.ironpython.com
And you shouldn't have to restructure your code, assuming that it is 
already thread-safe?

For interest, I thought I'd mention PyLinda, a distributed object system 
that takes a completely different, higher level, approach to object 
distribution: it creates "tuple space", where objects live. The objects 
can be located and sent messages. But (Py)Linda hides most of gory 
details of how objects actually get distributed, and the mechanics of 
actually connecting with those remote objects.

http://www-users.cs.york.ac.uk/~aw/pylinda/
HTH,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: convert list of tuples into several lists

2005-02-09 Thread Pierre Barbier de Reuille
Oliver Eichler a écrit :
Diez B. Roggisch wrote:

zip(*[(1,4),(2,5),(3,6)])
Thanks :) I knew it must be simple. The asterics - thing was new to me. 

By the way: What is faster?
this:
z = [(1,4),(2,5),(3,6)
a,b = zip(*[(x[0], x[0]-x[1]) for x in z])
or:
a = []
b = []
for x in z:
  a.append(x[0])
  b.append(x[0]-x[1])
I guess first, isn't it?
Oliver
Best answer is : try it :)
use the "timeit" module (in the standard lib) to do so ...
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: multi threading in multi processor (computer)

2005-02-09 Thread John Lenton
On Wed, Feb 09, 2005 at 07:56:27AM -0800, [EMAIL PROTECTED] wrote:
> Hello Pierre,
> 
> That's a pity, since when we have to run parallel, with single
> processor is really  not efficient. To use more computers I think is
> cheaper than to buy super computer in developt country.

and buying more, cheap computers gives you more processing power than
buying less, multi-processor computers. So the best thing you can do
is learn to leverage some distributed computing scheme. Take a look at
Pyro, and its Event server.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
When the cup is full, carry it level.


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Datatype of non-negative values

2005-02-09 Thread Larry Bates
What exactly do you want to happen when result
would be negative?  I'll guess be zero:
pseudocode:
x=value
x=max(x-something, 0)
That way if it goes negative, it sticks to zero.
Larry Bates
Dirk Hagemann wrote:
Hi,
Is there a datatype in python which allows no negative values? I
subtract several times something from a value and I don't want to chek
everytime if this value is still bigger or equal 0.
Thanks for help!
Dirk Hagemann
--
http://mail.python.org/mailman/listinfo/python-list


porting from Tkinter to pygtk

2005-02-09 Thread Michele Simionato
I am in the process of learning pygtk and I would like to port
some custom made Tkinter widgets to pygtk, just an exercise.
For instance I have this code:

. from Tkinter import *
.
. class AnimatedLabel(Label):
. def __init__(self, master, text, width=72, maxspc=16, deltat=100,
**kw):
. self.text = text
. self.width = width
. self.maxspc = maxspc
. self.deltat = deltat
. self.stringvar = StringVar(master)
. self.stringvar.set(text)
. self.stop = False
. Label.__init__(self, master, textvariable=self.stringvar,
**kw)
.
. def startAnimation(self, spaces='', addspace=False):
. if len(spaces) == 0 or len(spaces) == self.maxspc:
. addspace = not addspace
. if addspace: # add a space
. spaces += ' '
. else: # remove a space
. spaces = spaces[1:]
. if not self.stop: # repeat each 100 ms changing spaces and
addspace
.
self.stringvar.set(spaces.join(self.text).center(self.width))
. self.after(self.deltat, self.startAnimation, spaces,
addspace)
.
. def stopAnimation(self):
. self.stop = True
.
.
. if __name__ == "__main__":
. t = Tk()
. t.title('Example')
. t.config(background='green')
.
. a = AnimatedLabel(t, text="Hello", fg='blue', bg='green')
. a.pack()
. a.startAnimation()
. t.mainloop()

what's the equivalent of the .after() method in pygtk?
BTW, is there any intro to pygtk thought for Tkinter users?
TIA,

 Michele Simionato

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


Re: Prepending to traceback

2005-02-09 Thread Ian Bicking
Stefan Behnel wrote:
I want them to look like this:
Traceback (most recent call last):
 ...
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in 
parseImpl
raise exc
  PyParsing, line 5, in SomeStatement
PARSER TEST FOR TESTING MISSING TERM
ParseException: Expected "SOMEOTHERTERM" (146), (5,9)
This query's a little old now, but I found this through the Weekly URL.
Anyway, Zope's ExceptionFormatter has one answer to this; you put a 
local variable like:

__traceback_info__ = ('PyParsing, line %i, in %s\n  %s'
% (line, statement, message))
And then that will show up in the traceback, much like you want.  The 
formatter looks through all the frames for this local variable and 
prints it out when found.  It's used in Zope for showing line numbers 
and other information when its interpreting scripts like Zope Page 
Templates or Python Scripts -- so that instead of just seeing the 
traceback from the interpreter, you also see information about what the 
interpreter is doing.  This sounds similar to what you want.

It's pretty simple to use and it doesn't depend on the rest of Zope: 
http://cvs.zope.org/Products/ErrorReporter/ExceptionFormatter.py?rev=HEAD&content-type=text/vnd.viewcvs-markup

--
Ian Bicking  /  [EMAIL PROTECTED]  /  http://blog.ianbicking.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with the encoding of os.getcwd() in Korean Windows

2005-02-09 Thread Walter Dörwald
Erik Bethke wrote:
Hello All,
sorry for all the posts... I am *almost* there now...
okay I have this code:
import sys, os
  encoding = locale.getpreferredencoding()
  htmlpath = os.getcwd()
  htmlpath = htmlpath.decode( encoding )
You might want to try os.getcwdu() instead of this. According to
http://www.python.org/doc/2.4/lib/os-file-dir.html
this has been added in Python 2.3 and should work on Windows.
Bye,
   Walter Dörwald
--
http://mail.python.org/mailman/listinfo/python-list


Re: win32 service and sockets

2005-02-09 Thread Tom Brown
On Tuesday 08 February 2005 16:41, Tom Brown wrote:
> Hi,
>
> I created a win32 service for XPPro called N4010ATestService.py (see
> below). The service runs as a particular user with administrative rights.
> It starts a thread that creates a simple socket server
> (N4010ASocketServer.py -- also below) that just waits for 20 character
> string. When I run the socket server by itself the test client can connect
> to the server and send a 20 character string just fine. When I run the
> service, the server will bind to the port but the client cannot connect. I
> verified the server was listening on the given port using netstat -an. The
> client eventually times out. Why isn't the server accepting connections
> when run in a service?
>
> Thanks,
> Tom
>

Well, I have found that it works if I launch the client on the same machine as 
the service. It will not work from a remote machine. Any ideas?

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


Re: PHP Embedded In Python

2005-02-09 Thread jdonnell
Ok, I'm still a little confused. You mention header.html and
access.php.

For access.php use the os call. You'll probably want to use popen, and
you also need to change your php script slightly. In order to run php
scripts from the command line you have to put
#!/usr/bin/php
as the first line in the php script. You then need to make sure that
it's executable. Run this from the command line:
chmod 755 access.php
Now you can call it from python with os.popen('/path/to/access.php')

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


Python and version control

2005-02-09 Thread Carl
Dear friends,

What is the ultimate version control tool for Python if you are working in a
Windows environment? 

When you work on a Visual C++ project then it's easy, use Visual Source Safe
for your source code! But when it comes to large Python projects and no
universal Python IDE with version control integration is available,
checking in and out files is not as simple. I am a keen user of Emacs, but
version control, which is very simple when you are in a Linux environment,
for example, is not a straightforward in Windows.

What is the most common adopted approach among Python developers working in
a Windows environment? 

Carl

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


Re: interactive execution

2005-02-09 Thread Jeff Shannon
Jive Dadson wrote:
Yeah.  I got it.
exec "foo = 555" in globals(), locals() does the trick.
You can do it with your own dicts, too -- but they must already exist, 
exec doesn't create them out of nowhere.

>>> myglobals = {'a':2, 'b':5}
>>> mylocals = {'c': 3}
>>> exec "d = a * b + c" in myglobals, mylocals
>>> myglobals
{'a': 2, '__builtins__': {...}, 'b': 5}
>>> mylocals
{'c': 3, 'd': 13}
>>>
This gives you some control over what the exec'ed statement actually 
sees, as well as what happens with the results.  (But as I mentioned 
before, there is no real security here if you're exec'ing arbitrary 
code -- there's no sandboxing involved, and the exec'ed string *can* 
use that __builtins__ reference (among other things) to do all sorts 
of malicious stuff.)

Jeff Shannon
Technician/Programmer
Credit International
--
http://mail.python.org/mailman/listinfo/python-list


Re: Java Integer.ParseInt translation to python

2005-02-09 Thread jicman
Nick Craig-Wood wrote:
> When I try your code I get this...
...
[clip]
...
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 4, in PrepareHash
> TypeError: 'str' object is not callable
> >>>
>
> You cant do byte(int(byte,16)) - byte is a string!  So you haven't
> posted the actual code you ran...

you're right... What I ran was this:

def PrepareHash(HashStr):
  while len(HashStr) > 0:
byte = HashStr[0:2]
print byte,int(byte,16),chr(int(byte,16)) # & 0xff
HashStr = HashStr[2:]
  return byte

def Main():
  HashStr = "c17ce186ab94eeb0de8ae3b5b751a7c4d8e9edeb"
  HashStr = PrepareHash(HashStr)
  print "Prepared HashStr :",HashStr

Main()


> Java bytes are signed also just to add to the confusion.

Exactly... which is the problem.  I don't know what the heck the [byte]
in front of a variable does.  I may have to get into the java list.
YUK!

thanks.

josé

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


Re: Python versus Perl ?

2005-02-09 Thread Joe Francia
Caleb Hattingh wrote:
As you might imagine, I think about this constantly.  However, there
are many other issues that make it complicated, such as having to work
in a team where the average guy knows pascal well (we're just a bunch
of chemical engineers), but has never even heard of python.  Plus, were
I to go this type of route, I would almost definitely code the binary
modules in Delphi or FreePascal, make a DLL and use ctypes to call it.
I do not know C and have no desire to learn now :)On the other
hand, I know pascal quite well.
keep well
Caleb
You could always code Python extensions directly in Delphi:
http://membres.lycos.fr/marat/delphi/python.htm
http://www.atug.com/andypatterns/PythonDelphiLatest.htm
Demo09 (look in demodll.dpr & module.pas) in the download tells you how.
Peace,
Joe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Java Integer.ParseInt translation to python

2005-02-09 Thread jicman

John Machin wrote:
> jose isaias cabrera wrote:
> However some Java code (I can't believe that it was the Java code
that
> you posted) has printed NINE bytes which bear no relation that I can
> see to any of the TWENTY bytes that the posted Java code should have
> stowed in retBuf.

I know what you're saying, John.  That's what is encryptic about this
whole thing.  The [byte] call in front of any variable will turn the
variable value to a "byte".  If you look at the code at the java code
at the beginning,

>>>   byte[] retBuf = new byte[inString.length()/2];

this retBuf is an array of bytes.  Whatever that means in java.  And
yes, that is the right output or result.  Hmmm, maybe an array of bytes
will turn into retBuf[0]+retBuf[0] = the first letter... H

> You claim that "[EMAIL PROTECTED]" is the right answer -- what is the
question?

Well, how can I get that exact answer from python?

> What is it meant to be? Your routine is called PrepareHash; is it
> possible that you are seeing these 9 bytes _after_ hashing?

Well, now that you say that, it may be that there is a space there.
H, let me try that again...

> Funny
> hashing scheme; they usually give 4, 8, 16, etc bytes, but worth an
ask
> ...

yep, you're right...

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


Re: Python and version control

2005-02-09 Thread Sergei Organov
Carl <[EMAIL PROTECTED]> writes:

[...]
> I am a keen user of Emacs, but version control, which is very simple
> when you are in a Linux environment, for example, is not a
> straightforward in Windows.

Emacs + CVS (or CVSNT) should work just fine in Windows either.

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


Re: python code with indention

2005-02-09 Thread Xah Lee
i thought it is trivial for the Python parser to spit out a version
with matching brackets. Similarly, perhaps some opensourcing student
has modified a parser to read in a matching brackets delimited version
of Python.

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Re: Python and version control

2005-02-09 Thread Peter Hansen
Carl wrote:
What is the ultimate version control tool for Python if you are working in a
Windows environment? 

What is the most common adopted approach among Python developers working in
a Windows environment? 
I never liked coupling the two together like that.  Instead
I use tools like TortoiseCVS or (now) TortoiseSVN with a
Subversion repository.  These things let you access revision
control features from context (right-button) menus right in
Windows Explorer, as you browse the file system.
The best part is that they work regardless of which editor or
other tool you have to work with, and you aren't at the mercy
of a greedy corporation that decides it's time for you to
upgrade so you can give them more money.  You can also use
the command line tools when appropriate, of course.
--
BTW, as a general caution: while Visual Source Safe may be
"easy", it's also dangerous and has been known to corrupt
many a code base, mine included.  I wouldn't touch the product
with a virtual ten-foot pole, and I strongly recommend to anyone
who is stuck using it -- *especially in a multi-programmer
environment* -- that they immediately abandon it in favour
of something more stable.  (Google can fill in background detail
for anyone interested.)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: A ListComp that maintains its own state

2005-02-09 Thread Michael Spencer
Bernhard Herzog wrote:
Michael Spencer <[EMAIL PROTECTED]> writes:

So, here's factorial in one line:
# state refers to list of state history - it is initialized to [1]
# on any iteration, the previous state is in state[-1]
# the expression also uses the trick of list.append() => None
# to both update the state, and return the last state
>>> [state.append(state[-1] * symbol) or state[-1]
... for symbol, state in it.izip(range(1,10),it.repeat([1]))
... ]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>>

There's no need for repeat:

[state.append(state[-1] * symbol) or state[-1] 
for state in [[1]]
for symbol in range(1, 10)]
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
While we're at it, a while back I posted a list comprehension that
implements a 'recursive' flatten:
http://groups.google.de/groups?selm=s9zy8eyzcnl.fsf%40salmakis.intevation.de
   Bernhard
Much better - that also cleanly extends to any number of initializers.  I also 
like the approach you take in flatten (and as suggested by Carl Banks) of 
putting the update mechanism in the if clause

So that gives:
def factorial(n):
return [state[-1]
for state in [[1]]
for count in xrange(1,n+1)
if state.append(state[-1] * count) or True
]
Probably of limited practical value, but fun to explore the language.
Thanks
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and version control

2005-02-09 Thread Steve Holden
Carl wrote:
Dear friends,
What is the ultimate version control tool for Python if you are working in a
Windows environment? 

When you work on a Visual C++ project then it's easy, use Visual Source Safe
for your source code! But when it comes to large Python projects and no
universal Python IDE with version control integration is available,
checking in and out files is not as simple. I am a keen user of Emacs, but
version control, which is very simple when you are in a Linux environment,
for example, is not a straightforward in Windows.
What is the most common adopted approach among Python developers working in
a Windows environment? 

Carl
You can integrate PythonWin and version control if you know the 
appropriate incantation. Vss used to work fine, but I upgraded and 
couldn't be bothered to go through the installation steps again.

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


RE: Python and version control

2005-02-09 Thread Robert Brewer
Peter Hansen wrote:
> Carl wrote:
> > What is the ultimate version control tool for Python if you 
> > are working in a Windows environment? 
> 
> I never liked coupling the two together like that.  Instead
> I use tools like TortoiseCVS or (now) TortoiseSVN with a
> Subversion repository.  These things let you access revision
> control features from context (right-button) menus right in
> Windows Explorer, as you browse the file system.

Seconded.


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


  1   2   3   >