Re: What is a type error?

2006-07-11 Thread Marshall
Joachim Durchholz wrote:
 Marshall schrieb:
  Joachim Durchholz wrote:
  Chris Smith schrieb:
  For example, I wrote that example using variables of type int.  If we
  were to suppose that we were actually working with variables of type
  Person, then things get a little more complicated.  We would need a few
  (infinite classes of) derived subtypes of Person that further constrain
  the possible values for state.  For example, we'd need types like:
 
  Person{age:{18..29}}
 
  But this starts to look bad, because we used to have this nice
  property called encapsulation.  To work around that, we'd need to
  make one of a few choices: [...] (c) invent some kind of generic
  constraint language so that constraints like this could be expressed
  without exposing field names. [...] Choice (c), though, looks a
  little daunting.
  That's not too difficult.
  Start with boolean expressions.
  If you need to check everything statically, add enough constraints that
  they become decidable.
 
  I'm not sure I understand. Could you elaborate?

 Preconditions/postconditions can express anything you want, and they are
 an absolutely natural extensions of what's commonly called a type
 (actually the more powerful type systems have quite a broad overlap with
 assertions).
 I'd essentially want to have an assertion language, with primitives for
 type expressions.

Now, I'm not fully up to speed on DBC. The contract specifications,
these are specified statically, but checked dynamically, is that
right? In other words, we can consider contracts in light of
inheritance, but the actual verification and checking happens
at runtime, yes?

Wouldn't it be possible to do them at compile time? (Although
this raises decidability issues.) Mightn't it also be possible to
leave it up to the programmer whether a given contract
was compile-time or runtime?

I've been wondering about this for a while.


Marshall

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


Re: Accessors in Python (getters and setters)

2006-07-11 Thread ZeD
Bruno Desthuilliers wrote:

 I decided to change the name of an attribute. Problem is I've used the
 attribute in several places spanning thousands of lines of code. If I
 had encapsulated the attribute via an accessor, I wouldn't need to do
 an unreliable and tedious search and replace
 find and grep are usually mostly reliable for this kind of tasks.

you mean sed :)

sed 's/oldName/newName/g' oldFile  newFile

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


Re: threading troubles

2006-07-11 Thread [EMAIL PROTECTED]
sreekant wrote:
 Hi folks

 What am I doing wrong in the following? I just want to run fluidsynth in
 the background.

Others have pointed you at os.popen.  In non-crippled languages, use
processes (e.g. popen) when you wish to preserve the years of hard work
that OS designers put into protected memory.  Use threads only when you
know why you want to abandon such and share all memory.   95% or more
of the time when you're making the multiprocessing decision, threads
are the wrong choice.  5% (or less) of the time they're indispensable.
But if you're just looking for asychronous processing and don't know
why you need to abandon memory protection, go with processes.

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


Re: urllib2 on Windows Vista

2006-07-11 Thread Martin v. Löwis
Sriram Krishnan wrote:
 I'm running Python 2.4.3 on Windows Vista June CTP. I'm not able to
 open any site using the urllib2 and related family of modules

I think you need to break the error further down. Try httplib instead
of urllib, and see what connect does. Then break this down into socket
calls (reading the source of httplib.connect, and executing it manually
in single-stepping), so that you know what the precise arguments passed
to getaddrinfo are.

FWIW, 11001 is WSAHOST_NOT_FOUND, which suggests that you have
DNS configured incorrectly.

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


Re: threading troubles

2006-07-11 Thread Piet van Oostrum
 sreekant [EMAIL PROTECTED] (S) wrote:

S Hi folks
S What am I doing wrong in the following? I just want to run fluidsynth in
S the background.
S #
S class MyThread(threading.Thread):
S def __init__(self, cmd, callback):
S self.__cmd = cmd
S self.__callback = callback
S threading.Thread.__init__(self)

S def run(self):
S os.system(self.__cmd)
S self.__callback('abcd')
S return


S cmd=midiplay+' '+fmidi
S xc=MyThread(cmd,addlog)
S xc.start()


S ##
S midiplay is 'fluidsynth -ni /home/mysndfont.sf2 mymidi.mid'
S addlog is a function which prints the log.

S If I run it only with xc.start() it does not run the program as in
S os.system. However if I  put
S xc.start()
S xc.run()

S then it starts and runs it in foreground with my pygtk ui non responsive.

You shouldn't call run() yourself. It is for the thread library itself.
I tried your example with cmd='ls -l' and it works. If I put a print
'started' after the xc.start(), it prints that before the output of ls -l,
indicating that ls -l is running in  the background. (Of course the actual
order is up to the scheduler.) Maybe running it inside a pygtk program
could be different but I wouldn't know why.
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: document

2006-07-11 Thread nhnh -cuncon
Please send me an anti-virus version. I can not read your attacked file!python-list@python.org wrote:  Please read the document. 
		Want to be your own boss? Learn how on  Yahoo! Small Business. 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Detecting 64bit vs. 32bit Linux

2006-07-11 Thread Lawrence D'Oliveiro
In article [EMAIL PROTECTED],
 Robin Becker [EMAIL PROTECTED] wrote:

Michael Yanowitz wrote:
..
 
 I need to detect whether the operating system I am running on (not the 
 Python version) is 64bit or 32bit. One requirement is that I need to 
 include support for non-Intel/AMD architectures.
 
 The standard C way would be to check sizeof(void *).
so on those old ARM RISC OSes with 32 bit arithmetic would I get sizeof(void 
*) 
== 4 when the address bus was 26 bits wide?

And the original 68000-based Macs where you would get the same 
sizeof(void *), but the address bus was only 24 bits wide. Nevertheless, 
you were supposed to pretend that addresses were a full 32 bits in size. 
The programs that didn't got into trouble later.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for modem App

2006-07-11 Thread Bayazee
Any Idea !!!???

---
First Iranian Python  Programming Community -- www.Python.ir

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


Re: language design question

2006-07-11 Thread Fredrik Lundh
Bryan wrote:

 and how do you make sure that everything subclasses this base class ?

 in this hypothetical case, i was assuming len() would be put in object and 
 every
 class subclasses object implicitly or explicitly (ie, new style classes only).
 if it was done that way, would len(obj) == obj.len() in all cases?

why should *everything* be forced to have a length ?

/F 



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


How to terminate a main script?

2006-07-11 Thread Helmut Jarausch
Hi,

I'm still looking for an elegant and clear means to
terminate the main script in Python.

Unfortunately, Python doesn't allow a 'return'
instruction in the main script.

Using sys.exit(0) produces an error
message which looks dangerous to an
uninitiated user.

The same is true for an exception.

And setting a 'flag' and testing
at several place for 'fall through'
is ugly and error-prone.

So what is a good choice?

Many thanks for a hint,

Helmut Jarausch

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


Re: Accessors in Python (getters and setters)

2006-07-11 Thread Bruno Desthuilliers
ZeD wrote:
 Bruno Desthuilliers wrote:
 
 
I decided to change the name of an attribute. Problem is I've used the
attribute in several places spanning thousands of lines of code. If I
had encapsulated the attribute via an accessor, I wouldn't need to do
an unreliable and tedious search and replace

find and grep are usually mostly reliable for this kind of tasks.
 
 
 you mean sed :)

No, I meant find and grep.

 sed 's/oldName/newName/g' oldFile  newFile
 
Yeah, fine - as long as your pretty sure the same name is not used in
other contexts in any of the source files...

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python fails to load under wamp

2006-07-11 Thread Ant

 I suggest you search the download files on Xampp's sourceforge site and
 look for an older version with Apache 2.0.55 . I'm not sure, but I
 think xampp version 1.5.1 will be ok

I did this just a few days ago, you could be right, but version 1.5.1
had no release notes, and a dodgy release number (151), so I thought it
safer to go for 1.5.0 which definitely has Apache 2.0.55 (1.5.2 has
version 2.2.something), and people were concentrating harder when it
was released ;-).

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


Re: How to terminate a main script?

2006-07-11 Thread Fredrik Lundh
Helmut Jarausch wrote:

 Using sys.exit(0) produces an error
 message which looks dangerous to an
 uninitiated user.

sys.exit(0) doesn't print anything at all.

$ python
 import sys
 sys.exit(0)
$

however, sys.exit() raises an exception to tell the runtime that it wants
to terminate the program, so if you're using a catch-all exception handler
that treats all exceptions as dangerous errors, it'll look like a dangerous
error too.

the solution is simple: don't do that.  instead of writing:

try:
...
except:
print OMG! Ponies!

write

try:
...
except (SystemExit, KeyboardInterupt):
raise
except:
print OMG! Ponies!

/F 



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


Re: mod_python fails to load under wamp

2006-07-11 Thread Ant

   Uh... this may sound silly, but aren't .so files UNIX/Linux/Solaris
 shared object files...

Yes, but apache uses them (or at least the same file extension) for
modules on Windows and Linux, so mod_python.so is correct.

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


Re: free python hosting !

2006-07-11 Thread Bruno Desthuilliers
Bayazee wrote:
 hi
 i want a free hosting for python .

Then setting up your own hosting might be a good solution - if you can
have a decent internet connection.

 www.python.ir -- Persian Python Community !

I'm afraid I won't be able to contribute !-)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading troubles

2006-07-11 Thread sreekant
I decided in the end to use fork and all is well.

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


How to use images at the bachground?

2006-07-11 Thread arvind
hi all,
how to get out of the python shell which is executing a command?
how to use images in the background of a page in Tkinter?

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


Re: Restricted Access

2006-07-11 Thread Fredrik Lundh
iapain wrote:

 No, I cant change permission or delete the module, the best would be
 something to detect 'import os' in user code ..

trust me, implementing a restricted execution model for Python that actually
works is a *lot* harder than that.

googling for python restricted execution might give you some clues.

/F 



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


Re: help a newbie with a IDE/book combination

2006-07-11 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Hi,
 
 I already have a couple of newbie books on Python itself, but would
 rather get started with a nice to use IDE and I am therefore looking
 for a good IDE to learn Python.  On my computer I have installed eric
 (http://ericide.python-hosting.com/) but it lacks any kind of useful
 documentation on its use.
 
 Is there a good IDE which would be well documented out there?

imho
You really don't need a full blown IDE to learn Python - any decent code
editor will do. Learning to use an IDE can take some time (even with a
good documentation), and you'll probably have more clues wrt/ IDE
choice/usage once you'll know at least the language basics.

Also, there's a problem with language-specific IDEs: you have to learn a
new IDE for each language. A good, extensible code editor (emacs, Vim,
etc) can be a better solution if you use different languages.
/imho


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread Fredrik Lundh
David Hopwood wrote:

 Yes, I'm well aware that most of this thread has been off-topic for c.l.p.m,
 but it is no less off-topic for the other groups (except possibly 
 c.l.functional),
 and I can't trim the Newsgroups line down to nothing.

is someone forcing your to post off-topic stuff against your will?  sounds 
scary.
do you want us to call the police?

/F 



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


Re: How to terminate a main script?

2006-07-11 Thread Ganesan Rajagopal
 Helmut Jarausch [EMAIL PROTECTED] writes:

 Using sys.exit(0) produces an error message which looks dangerous to an
 uninitiated user.

What message? Your program should exit silently when you call sys.exit(0). 

Ganesan

-- 
Ganesan Rajagopal

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


Re: function that modifies a string

2006-07-11 Thread Diez B. Roggisch
 I'm sorry, perhaps I'm being slow today, but just why are they dangerous?
 More dangerous than, say, mutable lists and mutable dicts? Unless I'm
 missing something, the worst that can happen is that people will write
 inefficient code, and they'll be caught out by the same sort of things
 that surprise newbies about lists. E.g. using a list as a default value
 in function definitions.

Well, they certainly aren't more dangerous than other mutable objects in
python. But in comparison to only dealing with immutable collections, using
immutable strings never made something impossible or even hard to do - at
least for me. Sometimes a bit harder to do efficiently.

So - the overall danger of mutability can be avoided with immutable strings
pretty neat, and thus one should (or could) go without them.

Regards,

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


Making HTTP requests using Twisted

2006-07-11 Thread rzimerman
I'm hoping to write a program that will read any number of urls from
stdin (1 per line), download them, and process them. So far my script
(below) works well for small numbers of urls. However, it does not
scale to more than 200 urls or so, because it issues HTTP requests for
all of the urls simultaneously, and terminates after 25 seconds.
Ideally, I'd like this script to download at most 50 pages in parallel,
and to time out if and only if any HTTP request is not answered in 3
seconds. What changes do I need to make?

Is Twisted the best library for me to be using? I do like Twisted, but
it seems more suited to batch mode operations. Is there some way that I
could continue registering url requests while the reactor is running?
Is there a way to specify a time out per page request, rather than for
a batch of pages requests?

Thanks!



#-

from twisted.internet import reactor
from twisted.web import client
import re, urllib, sys, time

def extract(html):
#do some processing on html, writing to stdout

def printError(failure):
print  sys.stderr, Error:, failure.getErrorMessage( )

def stopReactor():
print Now stopping reactor...
reactor.stop()

for url in sys.stdin:
url = url.rstrip()
client.getPage(url).addCallback(extract).addErrback(printError)

reactor.callLater(25, stopReactor)
reactor.run()

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


Re: What is a type error?

2006-07-11 Thread Marcin 'Qrczak' Kowalczyk
Chris Smith [EMAIL PROTECTED] writes:

 No what happens if right here you code
b := 16;
 
 Does that again change the type of b? Or is that an illegal 
 instruction, because b has the local type of (18..22)?

 It arranges that the expression b after that line (barring further 
 changes) has type int{16..16}, which would make the later call to 
 signContract illegal.

The assignment might be performed in a function called there, so it's
not visible locally.

Propagating constraints from conditionals is not applicable to mutable
variables, at least not easily.

I think that constant bounds are not very useful at all. Most ranges
are not known statically, e.g. a variable can span the size of an
array.

-- 
   __( Marcin Kowalczyk
   \__/   [EMAIL PROTECTED]
^^ http://qrnik.knm.org.pl/~qrczak/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making HTTP requests using Twisted

2006-07-11 Thread K.S.Sreeram
rzimerman wrote:
 I'm hoping to write a program that will read any number of urls from
 stdin (1 per line), download them, and process them. So far my script
 (below) works well for small numbers of urls. However, it does not
 scale to more than 200 urls or so, because it issues HTTP requests for
 all of the urls simultaneously, and terminates after 25 seconds.
 Ideally, I'd like this script to download at most 50 pages in parallel,
 and to time out if and only if any HTTP request is not answered in 3
 seconds. What changes do I need to make?
 
 Is Twisted the best library for me to be using? I do like Twisted, but
 it seems more suited to batch mode operations. Is there some way that I
 could continue registering url requests while the reactor is running?
 Is there a way to specify a time out per page request, rather than for
 a batch of pages requests?

Have a look at pyCurl. (http://pycurl.sourceforge.net)

Regards
Sreeram




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

Re: Howto or Tutorial for tokenize module for a newbie?

2006-07-11 Thread Fuzzyman

TY wrote:
 Hi,

 Can someone point me to a Howto or Tutorial for tokenize module for a
 newbie?  I read the documentation but it doesn't have a lot of info...

Here's another useful example :

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298

All the best,

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

  Thanks!

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


Generating all ordered substrings of a string

2006-07-11 Thread girish
Hi,
 I want to generate all non-empty substrings of a string of length =2.
Also,
each substring is to be paired with 'string - substring' part and vice
versa.
 Thus, ['abc'] gives me [['a', 'bc'], ['bc', 'a'], ['ab', 'c'], ['c',
'ab'], ['b', 'ac'], ['ac', 'b']] etc.
 Similarly, 'abcd' should give me [['a', 'bcd'], ['bcd', 'a'], ['abc',
'd'], ['d', 'abc'], ['b', 'acd'], ['acd', 'b'],['c', 'abd'], ['abd', 'c'],
['ab', 'cd'], ['cd', 'ab'], ['bc', 'ad'], ['ad', 'bc'], ['ac',
'bd'],['bd','ac']]

 I've tried the following but i cant prevent duplicates and i'm missing
some substrings:

 colocn = 'abcd'
 k = 4
 for i in range(k-1):
for j in range(1,k):
rule1 = [colocn[i:i+j],colocn[:i]+colocn[i+j:]]
rule2 = [colocn[:i]+colocn[i+j:],colocn[i:i+j]]
rules.append(rule1)
rules.append(rule2)
 rules
[['a', 'bcd'], ['bcd', 'a'], ['ab', 'cd'], ['cd', 'ab'], ['abc', 'd'],
['d', 'abc'], ['b', 'acd'], ['acd', 'b'], ['bc', 'ad'], ['ad', 'bc'],
['bcd', 'a'], ['a', 'bcd'], ['c', 'abd'], ['abd', 'c'], ['cd', 'ab'],
['ab', 'cd'], ['cd', 'ab'], ['ab', 'cd']]


Any ideas??

TIA,
girish




This message was sent using IMP, the Internet Messaging Program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: language design question

2006-07-11 Thread Steve Holden
Bryan wrote:
 Fredrik Lundh wrote:
 
Bryan wrote:


could you get the same result by putting these methods in base

  class object that everything subclasses?

and how do you make sure that everything subclasses this base class ?

/F

 
 in this hypothetical case, i was assuming len() would be put in object and 
 every 
 class subclasses object implicitly or explicitly (ie, new style classes 
 only). 
 if it was done that way, would len(obj) == obj.len() in all cases?
 
   isinstance(1, object)
True

What's 1 . len() ?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Making HTTP requests using Twisted

2006-07-11 Thread Fredrik Lundh
rzimerman wrote:

 Is Twisted the best library for me to be using? I do like Twisted, but
 it seems more suited to batch mode operations. Is there some way that I
 could continue registering url requests while the reactor is running?
 Is there a way to specify a time out per page request, rather than for
 a batch of pages requests?

there are probably ways to solve this with Twisted, but in case you want a
simpler alternative, you could use Python's standard asyncore module and
the stuff described here:

http://effbot.org/zone/effnews.htm

especially

http://effbot.org/zone/effnews-1.htm#storing-the-rss-data
http://effbot.org/zone/effnews-3.htm#managing-downloads

/F 



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


Re: Accessors in Python (getters and setters)

2006-07-11 Thread mystilleef
Hello,

Thanks for the responses. The reason I want to change the name of the
attribute is because it doesn't reflect the purpose of the attribute,
anymore. The attribute was originally a string object, but not anymore.
It is primarily a readability issue. There are also a few key
attributes I don't want developers, including myself, fiddling with.
Properties /accessors are good because they allow you to encapsulate
attributes so you can change implementations at will. Some of you have
argued I would have needed to change accessor names too if I had
misnamed them earlier. It's hard to say. I find myself changing the
names of attributes a lot more frequently than I do functions or
methods. Choosing a crappy attribute name is effortless for me,
especially during intense coding sessions. I usually realize I've
choosing a crappy attribute name the next day, sometimes even later.
However, I put a lot more effort into choosing method and function
names, especially when I know it may likely be a public API. Plus it's
really hard to choose crappy accessor name. 

Regards

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


Re: Looking for a HTML like rendering library (wishlist)

2006-07-11 Thread Stefan Behnel
Laszlo Nagy wrote:
 I'm looking for a library that can do the following:
 
* Parse a simple structured text file (XML or HTML etc.)
* Render its output to an image
* I would like to give the maximum width of the image (but not the
  minimum)
* I would like to use my custom TrueType fonts, and some basic
  formatting: colors, underline, numbered and bulleted lists
* I would like to embed some PNG (transparent) images, and align
  them inside the text
* The library should be able to calculate the size of the image
  before rendering
* The library should be able to render the image into memory
* It should be reasonably fast
* It should be independent of windowing toolkits (PIL is okay)
 
 
 Why I need this: create widgets in GUI applications, for example:
 
* A label that can display formatted text
* A new grid cell renderer that can display small images and text as
  well
* Hint window (tooltip) that has formatted text and images
* Create automatic signatures for e-mails (not GUI related)
* etc

After reading this, I still do not understand why you want to do this with
images. Virtually any GUI toolkit can display text, most can natively display
HTML, just look at Qt for a good example.

So why not just use the native features?

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


Re: How to use images at the bachground?

2006-07-11 Thread pipehappy
 hi all,
 how to get out of the python shell which is executing a command?
 how to use images in the background of a page in Tkinter?

on Unix, ctrl-c or ctrl-d may do the job.
on Windows, ctrl-z will do

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


Re: Augument assignment versus regular assignment

2006-07-11 Thread Antoon Pardon
On 2006-07-10, Terry Reedy [EMAIL PROTECTED] wrote:

 Antoon Pardon [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 I disagree. The += version only evaluates the index once, but still has
 to find the object twice.

 No it does not *have* to find the object twice and no it does *not* find 
 the object twice.  From the viewpoint of the interpreter, the purpose of 
 abbreviating 'objectexpression = objectexpression op arg' as 
 'objectexpression op=arg' is to avoid unnecessary recalculation

But is the viewpoint of the interpreter somehow relevant? IMO the
question is if the actual behaviour is compatible with what people
expect after having read the language reference. The viewpoint of
the interpreter IMO doesn't play a role in answering that question.

 But as far as I can interpret what is happening from the printed lines

 Your print get/set examples from your black-box testing miss the following 
 key point.  While the interpreter still has to *use* the object(s) twice, 
 once to get and once to set, it no longer has to *calculate* the objects 
 twice.

The language reference doesn't talk about objects. And IMO you
should be carefull if you want to use the word object here.
In the line: foo += 1, you can't talk about the object foo,
since foo will be bound to a different object after the assignment
than it was bound to before.

As I read the language reference the x stands for a target expression.
Now what does it mean to evaluate a target expression like col[key].
IMO it means finding the location of the item in the collection: the
bucket in the directory, the node in the tree ... grosso mode it
boils down to the call to __setitem__ or __getitem__ depending
on where the col[key] was located in the line (or if you prefer
the view from the interpreter it boils down to the BINARY_SUBSCR
and STORE_SUBSCR opcodes).

So if the language reference seems to implies that col[key] will
only be evaluated once in a line like: col[key] += 1 I expect
only one call from __setitem__ or __getitem__ (or only one
from BINARY_SUBSCR or STORE_SUBSCR)

Now I know python doesn't behave this way, but how python
actually behave can't be used as an argument that this
is the behaviour as described by the language reference.

So my question is: suppose I write my own collector,
where __setitem__ and __getitem__ have the same side effect.
How many times should/will this side effect occur in code like
col[key] += 1. As I read the language reference it should
happen only once, however that is not what happens. So if
the actual behaviour of python is what we want, which is
what I suspect, then the language reference should
clarify more what the supposed behaviour should be.

Now my reading of the language reference can be faulty,
but if you want to argue that, I would appreciate it
if you could explain how I have to read the language
reference in order to come to the conclusion that the
side effect in this example has to happen twice.

And even in this case would I suggest that the language
reference would better be made clearer, since I doubt
that I'm the only who will read the language reference
this way.

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


Re: How to terminate a main script?

2006-07-11 Thread Helmut Jarausch
Fredrik Lundh wrote:
 Helmut Jarausch wrote:
 
 Using sys.exit(0) produces an error
 message which looks dangerous to an
 uninitiated user.
 
 sys.exit(0) doesn't print anything at all.

Yes, sorry, I was trying in in 'idle'
There you get
Traceback (most recent call last):
   File pyshell#1, line 1, in -toplevel-
 sys.exit(0)
SystemExit: 0


-- 
Helmut Jarausch

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


Re: Global except condition

2006-07-11 Thread Steve Holden
Ernesto wrote:
 Within the scope of one Python file (say myFile.py), I'd like to print
 a message on ANY exception that occurs in THAT file, dependent on a
 condition.
 
 Here's the pseudocode:
 
 if anyExceptionOccurs():
   if myCondition:
 print Here's my global exception message
 
 
 Is this functionality possible in python?  If so, how?
 
What if your module defines a function, and then that function is called 
from some other module and raises an exception. Would you then want the 
global exception message to appear?

If so then I'm not sure that what you want is possible.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Global except condition

2006-07-11 Thread Fredrik Lundh
Ernesto wrote:

 Within the scope of one Python file (say myFile.py), I'd like to print
 a message on ANY exception that occurs in THAT file, dependent on a
 condition.

condition = True

def handle_any_exception(function):
def trampoline(*args, **kwargs):
try:
return function(*args, **kwargs)
except:
if not condition:
raise
print exception caught in, function.__name__
return n/a # default return value
return trampoline

@handle_any_exception
def myfunc(x):
return 1 / x

@handle_any_exception
def myotherfunc(filename):
return open(filename)

class MyClass:
@handle_any_exception
def mymethod(self):
raise ValueError(oops)

myfunc(1)
myfunc(0)
myotherfunc(hello.txt)
MyClass().mymethod()

/F 



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


Re: Accessors in Python (getters and setters)

2006-07-11 Thread Bruno Desthuilliers
mystilleef wrote:
 Hello,
 
 Thanks for the responses. The reason I want to change the name of the
 attribute is because it doesn't reflect the purpose of the attribute,
 anymore. The attribute was originally a string object, but not anymore.
 It is primarily a readability issue. There are also a few key
 attributes I don't want developers, including myself, fiddling with.
 Properties /accessors are good because they allow you to encapsulate
 attributes so you can change implementations at will. Some of you have
 argued I would have needed to change accessor names too if I had
 misnamed them earlier. It's hard to say. I find myself changing the
 names of attributes a lot more frequently than I do functions or
 methods. Choosing a crappy attribute name is effortless for me,
 especially during intense coding sessions. I usually realize I've
 choosing a crappy attribute name the next day, sometimes even later.
 However, I put a lot more effort into choosing method and function
 names, especially when I know it may likely be a public API. 

What you need to understand here is that in Python,
1/ methods *are* attributes
2/ every attribute whose name is not prefixed by a leading underscore is
considered part of the api ('__magic__' names being a special case).

So it has nothing to do with data vs method dichotomy (which makes no
sens in a languages where functions and methods are objects), only with
API vs implementation. You choosed a crappy name for an attribute
that's part of the API, so it's *exactly* the same case as if you had
chosen a crappy name for a public method in Java. Think of public data
attributes as magical getter/setters with the most straightforward
behaviour, and of properties as the way to override this default behaviour.

 Plus it's
 really hard to choose crappy accessor name. 

What about getMyCrappyAttributeName/setMyCrappyAttributeName ?-)



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Best command for running shell command

2006-07-11 Thread Donald Duck
I'm a little bit confused about what is the best way to run a shell command, 
if I want to run a command like

xx -a -b  yy

where I'm not interested in the output, I only want to make sure that the 
command was executed OK. How should I invoke this (in a Unix/linux 
environment)?

The command module seem to give the resulting output and the various popen 
commands seem to be similar.

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


Relying on the behaviour of empty container in conditional statements

2006-07-11 Thread horizon5
Hi,

my collegues and I recently held a coding style review.
All of the code we produced is used in house on a commerical project.
One of the minor issues I raised was the common idiom of specifing:

pre
if len(x)  0:
do_something()
/pre
Instead of using the language-defined bahviour, as stated by PEP8:

pre
- For sequences, (strings, lists, tuples), use the fact that empty
  sequences are false.

  Yes: if not seq:
   if seq:

  No: if len(seq)
  if not len(seq)
/pre

Without wishing to start a flame war, what are other's opinions on
this, is using len safer? If so why?

Arguments that have been presented for using codelen(x)  0/code to
test emptiness of a container include:
  - It's safer
  - Not relying on weird behaviour of the language
  - Explicit is better than implicit (as stated by 'this' module, Zen
of Python)

My own feeling is that I am willing to work with the behaviours defined
by Python, and treat the use of len in these cases as excessive
duplication (this is however, quite a minor point i agree).

Note that I have much more experience with the language (6-7 years),
whilst the majority of my collegues have about 1-2 years experience.

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


CPU or MB Serial number

2006-07-11 Thread Bayazee
Hi,
How can I get CPU Serial number , or motherboard serial number with
python . I need an idetification of a computer 
ThanX

---
iranian python community -- www.python.ir

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


Re: Best command for running shell command

2006-07-11 Thread Roy Smith
In article [EMAIL PROTECTED],
 Donald Duck [EMAIL PROTECTED] wrote:

 I'm a little bit confused about what is the best way to run a shell command, 
 if I want to run a command like
 
   xx -a -b  yy
 
 where I'm not interested in the output, I only want to make sure that the 
 command was executed OK. How should I invoke this (in a Unix/linux 
 environment)?

The most straight-forward way would be:

import os
status = os.system (xx -a -b  yy)
if status == 0:
   print it worked
else:
   print it failed

You might also want to look at the new (in 2.4) subprocess module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Relying on the behaviour of empty container in conditional statements

2006-07-11 Thread Bruno Desthuilliers
horizon5 wrote:
 Hi,
 
 my collegues and I recently held a coding style review.
 All of the code we produced is used in house on a commerical project.
 One of the minor issues I raised was the common idiom of specifing:
 
 pre
 if len(x)  0:
 do_something()
 /pre
 Instead of using the language-defined bahviour, as stated by PEP8:
 
 pre
 - For sequences, (strings, lists, tuples), use the fact that empty
   sequences are false.
 
   Yes: if not seq:
if seq:
 
   No: if len(seq)
   if not len(seq)
 /pre
 
 Without wishing to start a flame war, what are other's opinions on
 this, is using len safer? If so why?

I fail to see why it would be safer. But I clearly see a drawback to
explicitely testing length of objects : it doesn't work on unsized
objects (like None or 0 or False etc), so it makes code less generic
(wether this is a problem or not in a given context depends of course on
the context).

 Arguments that have been presented for using codelen(x)  0/code to
 test emptiness of a container include:
   - It's safer

cf above

   - Not relying on weird behaviour of the language

It's not a weird behaviour, it's a well defined and documented
behaviour. And it's not specific to Python.

   - Explicit is better than implicit (as stated by 'this' module, Zen
 of Python)

Given that this behaviour is well defined and documented, using if
[not] seq is perfectly explicit.

 My own feeling is that I am willing to work with the behaviours defined
 by Python, 

and use the common Python idiom.

 and treat the use of len in these cases as excessive
 duplication (this is however, quite a minor point i agree).

It's also not idiomatic and less generic.

 Note that I have much more experience with the language (6-7 years),
 whilst the majority of my collegues have about 1-2 years experience.

Do they still write code like the following ?

if someBooleanExpression == True:
   return True
else:
   return False

If yes, time to look for another place to work IMHO. Else, what do they
think of the above snippet, vs:

return someBooleanExpression

Do they think the first one is safer and/or more explicit ?-)

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Relying on the behaviour of empty container in conditional statements

2006-07-11 Thread Steven D'Aprano
On Tue, 11 Jul 2006 04:52:42 -0700, horizon5 wrote:

 Hi,
 
 my collegues and I recently held a coding style review.
 All of the code we produced is used in house on a commerical project.
 One of the minor issues I raised was the common idiom of specifing:
 
 pre
 if len(x)  0:
 do_something()
 /pre
 Instead of using the language-defined bahviour, as stated by PEP8:
 
 pre
 - For sequences, (strings, lists, tuples), use the fact that empty
   sequences are false.
 
   Yes: if not seq:
if seq:
 
   No: if len(seq)
   if not len(seq)
 /pre
 
 Without wishing to start a flame war, what are other's opinions on
 this, is using len safer? If so why?

What do you mean by safer? What sort of bad consequences are you trying
to avoid? What sort of errors do your colleagues think writing if seq
encourages?

Just waving hands in the air and saying Doing foo is safer is
meaningless. Safer than what? What are the costs and benefits of doing
foo? What are the consequences of failure?


 
 Arguments that have been presented for using codelen(x)  0/code to
 test emptiness of a container include:
   - It's safer

On the contrary, the longer test isn't safer, it is more dangerous because
there is a whole family of potential bugs that can occur when using that
idiom, but which can't occur in the shorter test.

For example, there are typos like writing len(x)  0 by mistake. (Or,
for that matter, len(x)  9.)

Do you have a function ln defined in the current scope? Then you better
hope that you don't mistype len(x) as ln(x).

Sure, the chances of these sorts of errors are small -- but not zero.
Write enough tests, and you will surely make them. But they are impossible
to make in the shorter if x idiom.


   - Not relying on weird behaviour of the language

There is nothing weird about it. Languages which don't accept arbitrary
objects as truth values are weird. Every object should know whether or not
it is nonempty/true or empty/false.


   - Explicit is better than implicit (as stated by 'this' module, Zen
 of Python)

if x: is explicit. It is explicitly asking, does x evaluate as true in a
Boolean context or as false?

In an object-oriented framework, it is bad practice for the developer to
concern himself with what makes an object true or false. Instead, you
should simply ask the object, are you true?

What happens when you decide that using a list (or tuple) for x is not the
right way to solve your problem? You change it to something like, say, a
binary tree. Now len(x)  0 is undefined, because trees don't have a
length. You could ask if height(x)  0 but calculating the height of a
tree is, in general, expensive. Better to simply ask the tree if it is
true or false.

Or, you subclass list to use a sentinel value. There may be some good
reason for not wanting to redefine the __len__ method of the subclass, so
the length of the subclassed list is ALWAYS positive, never zero. If you
have peppered your code with tests like if len(x)  0, you're in
trouble. You're in even greater trouble if some of those tests might be
called by *either* regular lists or by the new subclass. Now you have to
start turning your tests into something awful like this:

if (x.__class__ == ListWithSentinal and len(x)  1) or len(x)  0:

But if the subclass redefines the __nonzero__ method, and you use if x
as your test, you're done. One change, in one place, compared to
potentially hundreds of changes scattered all over your code.


There are times where your code is constrained by your data-type, e.g.
tests like if len(x)  5: or similar. But they are comparatively rare.
Why force simple true/false tests into that idiom?


 My own feeling is that I am willing to work with the behaviours defined
 by Python, and treat the use of len in these cases as excessive
 duplication (this is however, quite a minor point i agree).
 
 Note that I have much more experience with the language (6-7 years),
 whilst the majority of my collegues have about 1-2 years experience.

Sounds like they are still programming C or Java in Python.

Good luck teaching these young whipper-snappers. *wink*



-- 
Steven.

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


error occurs when using wmi module in child thread

2006-07-11 Thread Chen Houwu
--sample code begin-

import threading

import wmi

def run(*args):
c = wmi.WMI ()
memory=c.Win32_LogicalMemoryConfiguration()[0]
info='Total Virtual Memory: '\
+str(int(memory.TotalVirtualMemory)/1024)\
+'MB'
print info

print  Begin run() in main thread
run()

print Begin run() in child thread
thread=threading.Thread(target=run)
thread.start()


--sample code end---

--debug info begin--

Begin run() in main thread
Total Virtual Memory: 1375MB
Begin run() in child thread
Exception in thread Thread-1:
Traceback (most recent call last):
  File C:\my\Python24\lib\threading.py, line 444, in __bootstrap
self.run()
  File C:\my\Python24\lib\threading.py, line 424, in run
self.__target(*self.__args, **self.__kwargs)
  File F:\chen\code\SoftRepairer\script\test\test.py, line 6, in run
c = wmi.WMI ()
  File C:\my\Python24\Lib\site-packages\wmi.py, line 971, in connect
handle_com_error (error_info)
  File C:\my\Python24\Lib\site-packages\wmi.py, line 219, in
handle_com_error
raise x_wmi, \n.join (exception_string)
x_wmi: -0x7ffbfe1c - Invalid syntax

--debug info end

--info I have found-

exception raised at:
file: Python24\Lib\site-packages\win32com\client\__init__.py
line: 88
code: moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
context:

def Moniker(Pathname, clsctx = pythoncom.CLSCTX_ALL):
  
Python friendly version of GetObject's moniker functionality.
  
  moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
  dispatch = moniker.BindToObject(bindCtx, None,
pythoncom.IID_IDispatch)
  return __WrapDispatch(dispatch, Pathname, clsctx = clsctx)

I have compaired the 'Pathname' parameter between main thread and child
thread
when running, they are the same.

---end--

How can I solve the problem?
Thanks

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


Re: Restricted Access

2006-07-11 Thread iapain
 googling for python restricted execution might give you some clues.

I've already assumed that there is no rexec for me as i am using python
2.4. Yeah its much more difficult that my imagination. Should I go for
alternatives like
1. Assume every one who is using this webide, wont corrupt system
2. Use some tricks to encrypt the user path and do lots of replacement
on user code and o/p.

or something else?

Best!
iapain

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


Re: Restricted Access

2006-07-11 Thread Fredrik Lundh
iapain wrote:

 I've already assumed that there is no rexec for me as i am using python
 2.4. Yeah its much more difficult that my imagination. Should I go for
 alternatives like
 1. Assume every one who is using this webide, wont corrupt system
 2. Use some tricks to encrypt the user path and do lots of replacement
 on user code and o/p.

 or something else?

unless you're willing to build a restricted runtime that runs on top of the 
core inter-
preter, you should assume that anyone writing a Python script that's executed by
your program has access to everything that your Python process has access to...

/F 



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


Re: Relying on the behaviour of empty container in conditional statements

2006-07-11 Thread Daniel Dittmar
horizon5 wrote:
 Hi,
 
 my collegues and I recently held a coding style review.
 All of the code we produced is used in house on a commerical project.
 One of the minor issues I raised was the common idiom of specifing:
 
 pre
 if len(x)  0:
 do_something()
 /pre
 Instead of using the language-defined bahviour, as stated by PEP8:
[...]
 Without wishing to start a flame war, what are other's opinions on
 this, is using len safer? If so why?

All objects evaluate to a boolean, but not all objects support len.
So if someone passes x = iter ([]) to your method, then len (x) will 
result in an exception, whereas 'if x:' will happily (and wrongly) 
answer true.

On the other hand, maybe you should be able to accept iterators, and 
then the test would look different anyway.

 
 My own feeling is that I am willing to work with the behaviours defined
 by Python, and treat the use of len in these cases as excessive
 duplication (this is however, quite a minor point i agree).

I find

if parameters:

perfectly acceptable, as it allows parameters to be None as well.
On the other hand, I can't stand interpreting integers as booleans, so I 
wouldn't write

if count:

Everyone has their personal quirks.

 
 Note that I have much more experience with the language (6-7 years),
 whilst the majority of my collegues have about 1-2 years experience.
 

I guess they're coming from Java and not from Perl :-)

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


Re: error occurs when using wmi module in child thread

2006-07-11 Thread placid

Chen Houwu wrote:
 --sample code begin-

 import threading

 import wmi

 def run(*args):
   c = wmi.WMI ()
   memory=c.Win32_LogicalMemoryConfiguration()[0]
   info='Total Virtual Memory: '\
   +str(int(memory.TotalVirtualMemory)/1024)\
   +'MB'
   print info

 print  Begin run() in main thread
 run()

 print Begin run() in child thread
 thread=threading.Thread(target=run)
 thread.start()

I had the same problem and wmi module author (Tim Golden) gave me the
solution which;


import pythoncom

# call this function after the run function definition
pythoncom.CoInitialize()


So your function becomes;

 def run(*args):
pythoncom.CoInitialize()
c = wmi.WMI ()
memory=c.Win32_LogicalMemoryConfiguration()[0]
info='Total Virtual Memory: '\
+str(int(memory.TotalVirtualMemory)/1024)\
+'MB'
print info



-- Cheers

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


Re: Restricted Access

2006-07-11 Thread iapain
 unless you're willing to build a restricted runtime that runs on top of the 
 core inter-
 preter, you should assume that anyone writing a Python script that's executed 
 by
 your program has access to everything that your Python process has access 
 to...

I think using replacements I can ban atleast OS module and about files,
either i should ban file open or write my own module something like
rexec, truefully i dont know if I can write that one or not. I was
thinking that this gonna take few days but looking much more difficult.
Thanks Fred! for nice tutorials on www.

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


Re: error occurs when using wmi module in child thread

2006-07-11 Thread Chen Houwu
thanks to solve my big problem :-)
I will try it later.

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


Re: language design question

2006-07-11 Thread vdrab

isinstance(1, object)
 True

 What's 1 . len() ?

That's easy!
since 1 is actually syntactic sugar for set([set([])]), clearly 1.len()
== 1.

;-)
v.
(actually, make that frozenset([frozenset([])])...)

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


Re: language design question

2006-07-11 Thread Bryan
Fredrik Lundh wrote:
 Bryan wrote:
 
 and how do you make sure that everything subclasses this base class ?
 in this hypothetical case, i was assuming len() would be put in object and 
 every
 class subclasses object implicitly or explicitly (ie, new style classes 
 only).
 if it was done that way, would len(obj) == obj.len() in all cases?
 
 why should *everything* be forced to have a length ?
 
 /F 
 

good point.  you're right, everything should not have to be forced to have a 
length.  i thought ruby did something like putting length functionality in 
their 
highest level base class.  then subclasses would either inherit it or could 
modify it in their own class.  my coworker who knows ruby complains about 
python's len(obj) too.  so i assumed ruby implements this in their equivalent 
base object class.  i just briefly searched the ruby docs, but i can't seem to 
find it.  if it is done this way in ruby, then i wonder what happens what 
obj.length would return for objects that you would not normally associate as 
having a length, such as what steve holden mentioned 1.length.



bryan

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


Abuse of the object-nature of functions?

2006-07-11 Thread Ant
Hi all,

In a framework I've written to test out website, I use something like
the following to add functionality at various points:

#---
def do_work(callable, data):
assertion = False
try:
assertion = callable.is_assertion
except:
pass

out = callable(data)

if assertion:
print Test  % (Failed, Suceeded)[out]

return out

def get_assn(fn):
def wrapper(*args, **kw):
return fn(*args, **kw)
out = wrapper
out.is_assertion = True
return out

def funct(data):
return True

x = funct
y = get_assn(funct)

do_work(x, data)
do_work(y, data)

#---

The idea is that I can mark some functions as being assertions, and use
the same function for applying the callable to the data and optionally
printing some information. This way I needn't worry whether the
callable is a custom object or a simple function.

The question is, is this a reasonable thing to do? It works, but is it
considered bad practice to add attributes to functions? And are there
any dangers?

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


Multi-threaded FTP Question

2006-07-11 Thread dbandler
I'm trying to use ftp in python in a multi-threaded way on a windows
box - python version 2.4.3.  Problem is that it appears that it's only
possible to have five instances/threads at one point in time.  Errors
look like:

   File C:\Python24\lib\ftplib.py, line 107, in __init__
self.connect(host)
  File C:\Python24\lib\ftplib.py, line 132, in connect
self.welcome = self.getresp()
  File C:\Python24\lib\ftplib.py, line 208, in getresp
resp = self.getmultiline()
  File C:\Python24\lib\ftplib.py, line 194, in getmultiline
line = self.getline()
  File C:\Python24\lib\ftplib.py, line 184, in getline
if not line: raise EOFError
EOFError

Is it possible to have more than five simultaneous ftp connections?

Thanks.

Derek

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


Re: Abuse of the object-nature of functions?

2006-07-11 Thread Fredrik Lundh
Ant [EMAIL PROTECTED] wrote:

 The question is, is this a reasonable thing to do?

absolutely.  a test framework DSL is a perfectly valid use case for
function attributes.

 It works, but is it considered bad practice to add attributes to functions?

nope (at least not in small doses ;-)

 And are there any dangers?

nope.

/F 



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


Re: Best command for running shell command

2006-07-11 Thread Thomas Nelson
Yes, I highly recommend the subprocess module.  subprocess.call() can
do almost anything you want to do, and the options are all pretty
intuitive  Whenever I need to write quick scripts for myself, it's what
I use.

THN


Roy Smith wrote:
 In article [EMAIL PROTECTED],
  Donald Duck [EMAIL PROTECTED] wrote:

  I'm a little bit confused about what is the best way to run a shell command,
  if I want to run a command like
 
  xx -a -b  yy
 
  where I'm not interested in the output, I only want to make sure that the
  command was executed OK. How should I invoke this (in a Unix/linux
  environment)?

 The most straight-forward way would be:

 import os
 status = os.system (xx -a -b  yy)
 if status == 0:
print it worked
 else:
print it failed
 
 You might also want to look at the new (in 2.4) subprocess module.

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


Re: Multi-threaded FTP Question

2006-07-11 Thread Jeremy Jones
On 11 Jul 2006 06:45:42 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
I'm trying to use ftp in python in a multi-threaded way on a windowsbox - python version 
2.4.3.Problem is that it appears that it's onlypossible to have five instances/threads at one point in time.Errorslook like: File C:\Python24\lib\ftplib.py, line 107, in __init__self.connect
(host)File C:\Python24\lib\ftplib.py, line 132, in connectself.welcome = self.getresp()File C:\Python24\lib\ftplib.py, line 208, in getrespresp = self.getmultiline()
File C:\Python24\lib\ftplib.py, line 194, in getmultilineline = self.getline()File C:\Python24\lib\ftplib.py, line 184, in getlineif not line: raise EOFErrorEOFError
Is it possible to have more than five simultaneous ftp connections?Would you mind posting your code? Are you trying to pass the same FTP connection object to all 5 threads?
-- Jeremy M. Joneshttp://jeremymjones.com
 
-- 
http://mail.python.org/mailman/listinfo/python-list

pyExcelerator - Can I read and modify an existing Excel-WorkBook?

2006-07-11 Thread Marco Aschwanden

Hi

I would like to
   1. import an existing Excel-sheet (a template)
   2. and add some data to it
   3. and save it under a different name afterwards.

To me it seems, that pyExcelerator does not support the reading for  
modification of an Excel-sheet. It allows only the parse_xls but I would  
like to keep the formatting in the template.

Did I miss a load, read or open function in pyExcelerator that would  
hand me back a WorkBook?

Greetings,
Marco


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


Re: free python hosting !

2006-07-11 Thread John Salerno
Luis M. González wrote:

 I'm curious, why it didn't work?
 I sent them an email recently, asking about mod_python support, and
 they replied afirmatively, and very quickly. They also said that they
 can install other scripts on demand.
 But I never tried them though...
 I'd like to know more about your experience with this hosting, if
 possible.

Their support was always great, and they tried several things to get it 
to work, but I soon got the feeling that although they support 
mod_python, they didn't really have it set up correctly. They tried 
different variations of setting up the proper handlers, but nothing ever 
worked for me, whereas other places I've tried with mod_python, it 
simply works when you go to a .psp page, for example.

Perhaps by now they've fixed it. It is certainly cheap enough to give a 
shot, and they allow you a few months in which you can cancel and get a 
refund.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Relying on the behaviour of empty container in conditional statements

2006-07-11 Thread Maric Michaud
Le mardi 11 juillet 2006 13:52, horizon5 a écrit :
 Arguments that have been presented for using codelen(x)  0/code to
 test emptiness of a container include:
   - It's safer
   - Not relying on weird behaviour of the language
   - Explicit is better than implicit (as stated by 'this' module, Zen
 of Python)
Too bad.
From the doc :

__nonzero__(  self)
 Called to implement truth value testing, and the built-in operation bool(); 
should return False or True, or their integer equivalents 0 or 1. When this 
method is not defined, __len__() is called, if it is defined (see below). If 
a class defines neither __len__() nor __nonzero__(), all its instances are 
considered true. 


So, the bool(container) *is* the test for emptiness for all container in 
python.
What is weird is to not follow the semantic of the language.

'if len(container) : means if container's length is not zero, while if 
container : means if container is empty.
Using the second is far better because a random container can implement a 
faster algorithm to test its emptiness (the __nonzero__ method for any 
container in python).


-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restricted Access

2006-07-11 Thread Steven D'Aprano
On Tue, 11 Jul 2006 06:21:39 -0700, iapain wrote:

 unless you're willing to build a restricted runtime that runs on top of the 
 core inter-
 preter, you should assume that anyone writing a Python script that's 
 executed by
 your program has access to everything that your Python process has access 
 to...
 
 I think using replacements I can ban atleast OS module and about files,

How are you planning on banning the module? Are you thinking about using
source code scanning to detect risky code?

What about modules which export os? It's one thing to ban os, but
did you remember to ban glob.os? How about site.os? And netrc.os? And and
and and...

What about this line of code?

my_innocent_object = __import__(''.join([chr(110+x) for x in [1, 5]]))


Creating a restricted execution environment is *hard*. As far as I know,
even Microsoft has never attempted it. And for all of Sun's resources and
talent, security holes are sometimes found even in Java.



-- 
Steven

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


Re: Abuse of the object-nature of functions?

2006-07-11 Thread Fredrik Lundh
Sybren Stuvel wrote:

 Ant enlightened us with:
 try:
 assertion = callable.is_assertion
 except:
 pass

 Try to make a habit out of catching only the exceptions you know will
 be thrown. Catching everything generally is a bad idea. In this case,
 my bet is that catching AttributeError is enough.

and

assertion = hasattr(callable, is_assertion)

is even nicer (and can be done as part of the if-statement after the call, in-
stead of in a separate try/except before the call)

/F 



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


Re: pyExcelerator - Can I read and modify an existing Excel-WorkBook?

2006-07-11 Thread Larry Bates
Marco Aschwanden wrote:
 
 Hi
 
 I would like to
   1. import an existing Excel-sheet (a template)
   2. and add some data to it
   3. and save it under a different name afterwards.
 
 To me it seems, that pyExcelerator does not support the reading for
 modification of an Excel-sheet. It allows only the parse_xls but I
 would like to keep the formatting in the template.
 
 Did I miss a load, read or open function in pyExcelerator that
 would hand me back a WorkBook?
 
 Greetings,
 Marco
 
 
If you are on Windows, you may find using COM interface to
actual Excel application easier.

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


Re: CPU or MB Serial number

2006-07-11 Thread marc . wyburn

Bayazee wrote:
 Hi,
 How can I get CPU Serial number , or motherboard serial number with
 python . I need an idetification of a computer 
 ThanX

 ---
 iranian python community -- www.python.ir

If you are on a windows box with WMI (2000 or above) you can use
Python, win32com extentions to get it.  The WMI stuff is easily
accessible with Tim Goldens wrapper
http://tgolden.sc.sabren.com/python/wmi.html

 import wmi
 c = wmi.WMI()
 for s in c.Win32_Processor():
... print s
...

instance of Win32_Processor
{
AddressWidth = 32;
Architecture = 0;
Availability = 3;
Caption = x86 Family 15 Model 2 Stepping 4;
CpuStatus = 1;
CreationClassName = Win32_Processor;
CurrentClockSpeed = 1794;
CurrentVoltage = 15;
DataWidth = 32;
Description = x86 Family 15 Model 2 Stepping 4;
DeviceID = CPU0;
ExtClock = 100;
Family = 2;
L2CacheSize = 0;
Level = 15;
LoadPercentage = 7;
Manufacturer = GenuineIntel;
MaxClockSpeed = 1794;
Name =   Intel(R) Pentium(R) 4 CPU 1.80GHz;
PowerManagementSupported = FALSE;
ProcessorId = 3FEBFBFF0F24;
ProcessorType = 3;
Revision = 516;
Role = CPU;
SocketDesignation = Microprocessor;
Status = OK;
StatusInfo = 3;
Stepping = 4;
SystemCreationClassName = Win32_ComputerSystem;
SystemName = LON42;
UpgradeMethod = 4;
Version = Model 2, Stepping 4;
};

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


Re: Restricted Access

2006-07-11 Thread iapain

 my_innocent_object = __import__(''.join([chr(110+x) for x in [1, 5]]))

Thats really smart way, yeah i had plan to scan and detect but I think
its not gonna work.

 Creating a restricted execution environment is *hard*. As far as I know,
 even Microsoft has never attempted it. And for all of Sun's resources and
 talent, security holes are sometimes found even in Java.

Does that mean there is no way to implement restricted enviorment?

Best!
iapain

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


Re: What is a type error?

2006-07-11 Thread David Hopwood
Chris Smith wrote:
 David Hopwood [EMAIL PROTECTED] wrote:
 
Maybe I'm not understanding what you mean by complete. Of course any
type system of this expressive power will be incomplete (whether or not
it can express conditions 3 to 5), in the sense that it cannot prove all
true assertions about the types of expressions.
 
 Ah.  I meant complete enough to accomplish the goal in this subthread, 
 which was to ensure that the compiler knows when a particular int 
 variable is guaranteed to be greater than 18, and when it is not.

I don't think that placing too much emphasis on any individual example is
the right way of thinking about this. What matters is that, over the range
of typical programs written in the language, the value of the increased
confidence in program correctness outweighs the effort involved in both
adding annotations, and understanding whether any remaining run-time checks
are guaranteed to succeed.

Look at it this way: suppose that I *need* to verify that a program has
no range errors. Doing that entirely manually would be extremely tedious.
If the compiler can do, say, 90% of the work, and point out the places that
need to be verified manually, then that would be both less tedious, and
less error-prone.

-- 
David Hopwood [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Identifying apparently unused globals

2006-07-11 Thread skip

At work we have a fairly large application (about 20 packages, 300+ modules)
that looks like we might be heading into a bit of a plateau stage.  Now
seems like a good time to identify and delete old, unused code that's flown
under the radar screen for awhile simply because nobody was looking for it.
Trouble is, most of that unused code consists of module-level classes,
functions and variables, so it's hard to distinguish mechanically from code
that *is* used.  Is there a tool out there that will slurp in a number of
packages, identify all the global names then remove those that it determines
are referenced?  (Yes, I know it's impossible to do this in general.  We
have one very restricted exec statement and no eval() calls, so I'm not too
worried about that sort of obfuscation.)

Thx,

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


Re: Best command for running shell command

2006-07-11 Thread iapain
 where I'm not interested in the output, I only want to make sure that the
 command was executed OK. How should I invoke this (in a Unix/linux
 environment)?

Remember few things about executing program within python
1. Create a subprocess or child process and execute it.
2. You should use Timeout stratagy i.e your execution took more than
provided time then timeout this process. In linux/unix you may use
singnal alarm to implement it.

Best!

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


os.access() problem

2006-07-11 Thread Phil Schmidt
I just got a new PC with Windows XP, and I want to run Leo on it. Leo
uses the os.access() function to check for read-only files. For some
reason, os.access(filename, os.W_OK) always returns false.

I wrote a 2-liner Python script to just test os.access on any file.
I have tried this with Python 2.4 and 2.5b1.
I have uninstalled and re-installed Python and Leo.
I have fiddled with file permissions on the target files as well as on
the Python installation itself.
I have used cacls to check the access control lists (and although I'm
not exactly certain what to do with this information, it appears to be
ok - I think).

None of the above has helped me to identify or fix the problem.

A scan of the Python newsgroup suggests that os.access() may not be the
best way to check for read-only, but the discussion is a bit deeper
than my understanding, so I'm not sure there's anything to it in this
case.

I realize this must be a Windows permissions thing, but I just can't
figure it out. I'm no expert in Windows security beyond basic
permissions, so I could be missing something simple. Can anyone offer
any suggestions?

Thanks,
Phil

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


Re: Abuse of the object-nature of functions?

2006-07-11 Thread Peter Otten
Fredrik Lundh wrote:

 Sybren Stuvel wrote:
 
 Ant enlightened us with:
 try:
 assertion = callable.is_assertion
 except:
 pass

 Try to make a habit out of catching only the exceptions you know will
 be thrown. Catching everything generally is a bad idea. In this case,
 my bet is that catching AttributeError is enough.
 
 and
 
 assertion = hasattr(callable, is_assertion)
 
 is even nicer (and can be done as part of the if-statement after the call,
 in- stead of in a separate try/except before the call)

You would normally expect that you can turn off a flag by setting it to
False instead of deleting it -- which is also how the OP's code works. So I
would prefer

assertion = getattr(callable, is_assertion, False)

if you forgo the explicit try...except.

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


Re: Restricted Access

2006-07-11 Thread Diez B. Roggisch
iapain wrote:

 
 my_innocent_object = __import__(''.join([chr(110+x) for x in [1, 5]]))
 
 Thats really smart way, yeah i had plan to scan and detect but I think
 its not gonna work.
 
 Creating a restricted execution environment is *hard*. As far as I know,
 even Microsoft has never attempted it. And for all of Sun's resources and
 talent, security holes are sometimes found even in Java.
 
 Does that mean there is no way to implement restricted enviorment?

In a nutshell: yes, especially if not designed from ground up that way. If
you need it, the best thing to do is to put some distance between your code
and the possibly malicious one, using some RPC.

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


timeit module for comparing the performance of two scripts

2006-07-11 Thread Phoe6
Hi,
   Following are my files.
In the format:

Filename

content


config1.txt

#DataBase Repository file
dbRepository = omsa_disney.xml


config2.txt

# Configfile for sendmail

[Sendmail]
userprefix = testuser


pyConfig.py

import re

def pyConfig():
fhandle = open( 'config1.txt', 'r' )
arr = fhandle.readlines()
fhandle.close()

hash = {}

for item in arr:
txt = item.strip()
if re.search( '^\s*$', txt ):
continue
if re.search( '^#.*$', txt ):
continue
if not re.search( '^\s*(\w|\W)+\s*=\s*(\w|\W)+\s*$', txt ):
continue
hash[txt.split( '=' )[0].strip().lower()] = txt.split( '='
)[1].strip()

print hash['dbrepository']


pyConparse.py

from ConfigParser import ConfigParser

def pyConParse():
configparser = ConfigParser()
configparser.read('config2.txt')
print configparser.get('Sendmail','userprefix')



Question is:
How do I compare the performance of pyConfig.py vs pyConparse.py using
timeit module?
I tried it as the way it is mentioned in the example, but when I do
Timer(pyConfig(),from __main__ import pyConfig), it imports
pyConfig in infinite loop. ( How does the python doc example on timeit
work? Anyone tried it?)

I just need to compare pyConfig.py and pyParse.py. ( And as general
question x.py and y.py)
How I can do it? Please consider this as a newbie question as well.

Thanks,
Senthil

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


Re: std in and stdout

2006-07-11 Thread Peter Otten
Juergen Huber wrote:

 how would i fix the following problem:
 
 now i have an input file with a fix name and an output file!
 i have this two files hardcoded written in the sourcecode of this
 function!
 
 in the future i will start this script with the command line.
 the syntax should be look like this:
 
 Python Function | Source File|   Output File
 ---
 fileanalyse.pysourcefile.csv filenalyse.txt
 
 i will call the programm always with the commandline, that i could type in
 various filenames for the input and output files!
 
 could anybody help me?!

Are you perhaps looking for sys.argv? The following example takes filenames
from the command line and defaults to stdin/stdout:

import sys

def analyse(instream, outstream):
pass # your code

instream = sys.stdin
outstream = sys.stdout

if len(sys.argv)  1:
instream =  open(sys.argv[1])
if len(sys.argv)  2:
outstream = open(sys.argv[2], w)

analyse(instream, outstream)

instream.close()
outstream.close()

Peter

PS: You might be interested in posting to the oh so quiet german-language
de.comp.lang.python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Abuse of the object-nature of functions?

2006-07-11 Thread Fredrik Lundh
Peter Otten wrote:

 You would normally expect that you can turn off a flag by setting it to
 False instead of deleting it -- which is also how the OP's code works. So I
 would prefer

 assertion = getattr(callable, is_assertion, False)

agreed (but note that the OP used a decorator to set the attribute, so you could
consider it an implementation detail...)

/F 



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


Re: Augument assignment versus regular assignment

2006-07-11 Thread Piet van Oostrum
 Antoon Pardon [EMAIL PROTECTED] (AP) wrote:

AP As I read the language reference the x stands for a target expression.
AP Now what does it mean to evaluate a target expression like col[key].
AP IMO it means finding the location of the item in the collection: the
AP bucket in the directory, the node in the tree ... grosso mode it
AP boils down to the call to __setitem__ or __getitem__ depending
AP on where the col[key] was located in the line (or if you prefer
AP the view from the interpreter it boils down to the BINARY_SUBSCR
AP and STORE_SUBSCR opcodes).

AP So if the language reference seems to implies that col[key] will
AP only be evaluated once in a line like: col[key] += 1 I expect
AP only one call from __setitem__ or __getitem__ (or only one
AP from BINARY_SUBSCR or STORE_SUBSCR)

You need both the __setitem__ and the __getitem__ otherwise it won't work.
I think the evaluated once clause is for cases like:

f(a)[g(b)] += 1

where f and/or g have side effects. These side effects should then take
place only once. Side effects in __setitem__ and __getitem__ is not what it
is talking about.
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading troubles

2006-07-11 Thread Piet van Oostrum
 sreekant [EMAIL PROTECTED] (S) wrote:

S I decided in the end to use fork and all is well.

But how are you doing the callback then? From your code it looks like the
callback is called after the external command finishes. The callback would
then be called in the child process, not in the parent process, I think. Or
do you have a solution for that?
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: timeit module for comparing the performance of two scripts

2006-07-11 Thread Fredrik Lundh
Phoe6 [EMAIL PROTECTED] wrote:

 How do I compare the performance of pyConfig.py vs pyConparse.py using
 timeit module?

$ python -m timeit -s import pyConfig pyConfig.pyConfig()
$ python -m timeit -s import pyConparse pyConparse.pyConParse()

note that timeit runs the benchmarked function multiple times, so you may want
to remove the print statements.

/F 



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


Re: Python in a nutshell - new edition ?

2006-07-11 Thread Anthony Baxter
End of July is our aggressive but still-achievable target: everythingwas scheduled from the start to hit OSCON '06 (and the release of Python
2.5 -- whether 2.5 final will be out at OSCON is still uncertain,though).Currently the schedule has Python 2.5 final due August 8th, and RC1 August 1st. That means that we'll be out just after OSCON. 

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

Re: What is a type error?

2006-07-11 Thread Chris Smith
David Hopwood [EMAIL PROTECTED] wrote:
 I don't think that placing too much emphasis on any individual example is
 the right way of thinking about this. What matters is that, over the range
 of typical programs written in the language, the value of the increased
 confidence in program correctness outweighs the effort involved in both
 adding annotations, and understanding whether any remaining run-time checks
 are guaranteed to succeed.

Are you really that short on people to disagree with?

In this particular branch of this thread, we were discussing George's 
objection that it would be ridiculous for a type system to check that a 
variable should be greater than 18.  There is no such thing as placing 
too much emphasis on what we were actually discussing.  If you want to 
discuss something else, feel free to post about it.  Why does it bother 
you that I'm considering George's point?

-- 
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: timeit module for comparing the performance of two scripts

2006-07-11 Thread Phoe6
Fredrik Lundh wrote:

 $ python -m timeit -s import pyConfig pyConfig.pyConfig()
 $ python -m timeit -s import pyConparse pyConparse.pyConParse()

 note that timeit runs the benchmarked function multiple times, so you may want
 to remove the print statements.

Thanks a lot Fredrik!. I did not know that timeit runs benchmarked
function multiple times. I got scared with multiple prints and thought
import pyConfig has put it in infinite loop and I had killed the
program.

I could use Timer function as well.

Thanks,
Senthil

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


Re: What is a type error?

2006-07-11 Thread Chris Smith
Marcin 'Qrczak' Kowalczyk [EMAIL PROTECTED] wrote:
 Chris Smith [EMAIL PROTECTED] writes:
  No what happens if right here you code
 b := 16;
  
  Does that again change the type of b? Or is that an illegal 
  instruction, because b has the local type of (18..22)?
 
  It arranges that the expression b after that line (barring further 
  changes) has type int{16..16}, which would make the later call to 
  signContract illegal.
 
 The assignment might be performed in a function called there, so it's
 not visible locally.

Indeed, I pointed that out a few messages ago.  That doesn't mean it's 
impossible, but it does mean that it's more difficult.  Eventually, the 
compiler will have to stop checking something, somewhere.  It certainly 
doesn't, though, have to stop at the first functional abstraction it 
comes to.  The ways that a function modifies the global application 
state certainly ought to be considered part of the visible API of that 
function, and if we could reasonably express that in a type system, then 
that's great!  Granted, designing such a type system for an arbitrary 
imperative language seems a little scary.

 Propagating constraints from conditionals is not applicable to mutable
 variables, at least not easily.

Certainly it worked in the code from my original response to George.  
Regardless of whether it might not work in more complex scenarios (and I 
think it could, though it would be more challenging), it still doesn't 
seem reasonable to assert that the technique is not applicable.  If the 
type system fails, then it fails conservatively as always, and some 
programmer annotation and runtime check is needed to enforce the 
condition.

 I think that constant bounds are not very useful at all. Most ranges
 are not known statically, e.g. a variable can span the size of an
 array.

I think you are overestimating the difficulties here.  Specialized 
language already exist that reliably (as in, all the time) move array 
bounds checking to compile time; that means that there exist at least 
some languages that have already solved this problem.  Going back to my 
handy copy of Pierce's book again, he claims that range checking is a 
solved problem in theory, and the only remaining work is in how to 
integrate it into a program without prohibitive amounts of type 
annotation.

-- 
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
-- 
http://mail.python.org/mailman/listinfo/python-list


Subject: RELEASED Python 2.5 (beta 2)

2006-07-11 Thread Anthony Baxter
On behalf of the Python development team and the Python
community, I'm happy to announce the second BETA release
of Python 2.5.

This is an *beta* release of Python 2.5. As such, it is not
suitable for a production environment. It is being released
to solicit feedback and hopefully discover bugs, as well as
allowing you to determine how changes in 2.5 might impact
you. If you find things broken or incorrect, please log a
bug on Sourceforge.

In particular, note that changes to improve Python's support
of 64 bit systems might require authors of C extensions
to change their code. More information (as well as source
distributions and Windows installers) are available from the
2.5 website:

http://www.python.org/2.5/

A Universal Mac OSX Installer will be available shortly - in
the meantime, Mac users can build from the source tarballs.

Since the first beta, a large number of bug fixes have been
made to Python 2.5 - see the release notes (available from
the 2.5 webpage) for the full details.

There has been one very small new feature added - the
sys._current_frames() function was added. This is extremely
useful for tracking down deadlocks and related problems - 
a similar technique is already used in the popular 
DeadlockDebugger extension for Zope. It is not possible to 
do this sort of debugging from outside the Python core safely 
and robustly, which is why we've snuck this in after the 
feature freeze.

As of this release, Python 2.5 is now in *feature freeze*.
Unless absolutely necessary, no functionality changes will
be made between now and the final release of Python 2.5.

The plan is for this to be the final beta release. We should
now move to one or more release candidates, leading to
a 2.5 final release early August. PEP 356 includes the
schedule and will be updated as the schedule evolves. At
this point, any testing you can do would be greatly, greatly
appreciated.

The new features in Python 2.5 are described in Andrew
Kuchling's What's New In Python 2.5. It's available from
the 2.5 web page.

Amongst the language features added include conditional
expressions, the with statement, the merge of try/except
and try/finally into try/except/finally, enhancements to
generators to produce a coroutine kind of functionality, and
a brand new AST-based compiler implementation.

New modules added include hashlib, ElementTree, sqlite3,
wsgiref and ctypes. In addition, a new profiling module
cProfile was added.

Enjoy this new release,
Anthony

Anthony Baxter
[EMAIL PROTECTED]
Python Release Manager
(on behalf of the entire python-dev team)


pgpefHF3jJ6yF.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pyExcelerator - Can I read and modify an existing Excel-WorkBook?

2006-07-11 Thread Gregory Piñero
I'm pretty sure it doesn't support reading an existing document.  That
would be useful.

On 7/11/06, Larry Bates [EMAIL PROTECTED] wrote:
 Marco Aschwanden wrote:
 
  Hi
 
  I would like to
1. import an existing Excel-sheet (a template)
2. and add some data to it
3. and save it under a different name afterwards.
 
  To me it seems, that pyExcelerator does not support the reading for
  modification of an Excel-sheet. It allows only the parse_xls but I
  would like to keep the formatting in the template.
 
  Did I miss a load, read or open function in pyExcelerator that
  would hand me back a WorkBook?
 
  Greetings,
  Marco
 
 
 If you are on Windows, you may find using COM interface to
 actual Excel application easier.

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



-- 
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: timeit module for comparing the performance of two scripts

2006-07-11 Thread Fredrik Lundh
Phoe6

 $ python -m timeit -s import pyConfig pyConfig.pyConfig()
 $ python -m timeit -s import pyConparse pyConparse.pyConParse()

 note that timeit runs the benchmarked function multiple times, so you may 
 want
 to remove the print statements.

 Thanks a lot Fredrik!. I did not know that timeit runs benchmarked
 function multiple times. I got scared with multiple prints and thought
 import pyConfig has put it in infinite loop and I had killed the
 program.

 I could use Timer function as well.

for cases like this, the command form gives a better result with less effort; 
it picks
a suitable number of iterations based on how fast the code actually runs, 
instead of
using a fixed number, and it also runs the test multiple times, and picks the 
smallest
observed time.

/F 



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


Re: syslog best practices -- when to call closelog?

2006-07-11 Thread Cameron Laird
In article [EMAIL PROTECTED],
J Rice [EMAIL PROTECTED] wrote:

I have a question:

When should syslog.closelog() be called?  I have a daemon that spends
most of its time asleep and quiet, but writes messages to the mail log
when active.  Should I open the log at the start and keep it open until
the program closes?  This seems much simpler than issuing three
commands everytime I want to write to the log.

The program will essentially be running constantly.  Is having the log
constantly open a problem?  What happens if the program crashes or is
killed without a closelog()?  

Jeff


In your terms, it's entirely safe to leave open the handle to syslog.
The operating system takes responsibility for cleanup on shutdown of
your application.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restricted Access

2006-07-11 Thread Cameron Laird
In article [EMAIL PROTECTED],
iapain [EMAIL PROTECTED] wrote:
.
.
.
Does that mean there is no way to implement restricted enviorment?
.
.
.
The most knowledgeable people have effectively given up, in
regard to Python.

As it happens, though, Tcl *does* admit quite an interesting
restricted-execution model.  Tcl was widely used in the '90s
for agent experiments, and its safe interpreters are 
arguably more reliable than Java's restricted environment.
Tcl is also roughly comparable to Python in its power and
convenience for the individual developer.  Should you want to
pursue this subject, URL: http://wiki.tcl.tk/safe  and URL:
http://wiki.tcl.tk/interp  might interest you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread Darren New
Marshall wrote:
 Now, I'm not fully up to speed on DBC. The contract specifications,
 these are specified statically, but checked dynamically, is that
 right? 

Yes, but there's a bunch more to it than that. The handling of 
exceptions, an in particular exceptions caused by failed pre/post 
conditions, is an integral part of the process.

Plus, of course, pre/post condition checking is turned off while 
checking pre/post conditions. This does make sense if you think about it 
long enough, but it took me several months before I realized why it's 
necessary theoretically rather than just practically.

 Wouldn't it be possible to do them at compile time? 

For some particularly simple ones, yes. For others, like the chess 
pieces are in a position it is legal to get to from a standard opening 
set-up, it would be difficult. Anything to do with I/O is going to be 
almost impossible to write a checkable postcondition for, even at 
runtime. After this call, the reader at the other end of the socket 
will receive the bytes in argument 2 without change.

As far as I understand it, Eiffel compilers don't even make use of 
postconditions to optimize code or eliminate run-time checks (like null 
pointer testing).

-- 
   Darren New / San Diego, CA, USA (PST)
 This octopus isn't tasty. Too many
 tentacles, not enough chops.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread Darren New
Marcin 'Qrczak' Kowalczyk wrote:
 The assignment might be performed in a function called there, so it's
 not visible locally.

In Hermes, which actually does this sort of constraint propagation, you 
don't have the ability[1] to munge some other routine's[2] local 
variables, so that becomes a non-issue. You wind up with some strange 
constructs, tho, like an assignment statement that copies and a 
different assignment statement that puts the rvalue into the variable on 
the left while simultaneously destroying whatever variable held the rvalue.


[1] You do. Just not in a way visible to the programmer. The compiler 
manages to optimize out most places that different names consistantly 
refer to the same value.

[2] There aren't subroutines. Just processes, with their own address 
space, to which you send and receive messages.

-- 
   Darren New / San Diego, CA, USA (PST)
 This octopus isn't tasty. Too many
 tentacles, not enough chops.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread Darren New
Chris Smith wrote:
 Specialized 
 language already exist that reliably (as in, all the time) move array 
 bounds checking to compile time; 

It sounds like this means the programmer has to code up what it means to 
index off an array, yes? Otherwise, I can't imagine how it would work.

x := read_integer_from_stdin();
write_to_stdout(myarray[x]);

What does the programmer have to do to implement this semantic in the 
sort of language you're talking about? Surely something somewhere along 
the line has to  fail (for some meaning of failure) at run-time, yes?

-- 
   Darren New / San Diego, CA, USA (PST)
 This octopus isn't tasty. Too many
 tentacles, not enough chops.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread Marshall
Chris Smith wrote:

 Going back to my
 handy copy of Pierce's book again, he claims that range checking is a
 solved problem in theory, and the only remaining work is in how to
 integrate it into a program without prohibitive amounts of type
 annotation.

This is in TAPL? Or ATTPL? Can you cite it a bit more specifically?
I want to reread that.


Marshall

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


Re: Restricted Access

2006-07-11 Thread K.S.Sreeram
Steven D'Aprano wrote:
 Creating a restricted execution environment is *hard*. As far as I know,
 even Microsoft has never attempted it. And for all of Sun's resources and
 talent, security holes are sometimes found even in Java.

Java is not the only restricted execution environment around.
Javascript, as implemented by most browsers, is an excellent lightweight
restricted execution environment, and there are many browsers which have
good implementations.

Regards
Sreeram



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

win32 and System Font Size

2006-07-11 Thread Fuzzyman
Hello all,

I'm writing a windows application with a Tkinter GUI.

Tkinter ignores the Windows user setting for system default font size -
which can be 'normal', 'large' or 'extra large'.

Does anyone know how to retrieve this information from the win32api, or
using win32com ?

All the best,


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

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


Re: Abuse of the object-nature of functions?

2006-07-11 Thread Ant
Sybren wrote:
 Try to make a habit out of catching only the exceptions you know will
 be thrown.

Yes - you are right of course - this was just a minimal example of
course to illustrate the sort of thing I'm using function attriutes
for.

Fredrik Lundh wrote:
 Peter Otten wrote:
  assertion = getattr(callable, is_assertion, False)

I like this way of doing it, as it is possible I may have a function
that could feasibly be either an assertion or otherwise depending on
context.

 agreed (but note that the OP used a decorator to set the attribute, so you 
 could
 consider it an implementation detail...)

The main reason for using a decorator was to avoid problems like the
following whilst providing an easy way of adding the attribute:

 def assn_or_other(data):
... return False
...
 # I want x to be treated as normal.
... x = assn_or_other

 # I want y to be an assertion
... y = assn_or_other
 y.is_assertion = True
 x.is_assertion
True

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


Re: Identifying apparently unused globals

2006-07-11 Thread Simon Forman
[EMAIL PROTECTED] wrote:
 At work we have a fairly large application (about 20 packages, 300+ modules)
 that looks like we might be heading into a bit of a plateau stage.  Now
 seems like a good time to identify and delete old, unused code that's flown
 under the radar screen for awhile simply because nobody was looking for it.
 Trouble is, most of that unused code consists of module-level classes,
 functions and variables, so it's hard to distinguish mechanically from code
 that *is* used.  Is there a tool out there that will slurp in a number of
 packages, identify all the global names then remove those that it determines
 are referenced?  (Yes, I know it's impossible to do this in general.  We
 have one very restricted exec statement and no eval() calls, so I'm not too
 worried about that sort of obfuscation.)

 Thx,

 Skip

I haven't used it myself, but pychecker
(http://pychecker.sourceforge.net/) is supposed to be able to perform
such stunts.  From the page: Types of problems that can be found
include: Unused globals and locals (module or variable)

HTH,
~Simon

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


Re: Restricted Access

2006-07-11 Thread iapain
 The most knowledgeable people have effectively given up, in
 regard to Python.

I guess now I am up with only one option, i.e hope that user input code
wont be evil to the system. **which is rarely possible**

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


Re: Abuse of the object-nature of functions?

2006-07-11 Thread Carl J. Van Arsdall
Sybren Stuvel wrote:
 Ant enlightened us with:
   
 try:
 assertion = callable.is_assertion
 except:
 pass
 

 Try to make a habit out of catching only the exceptions you know will
 be thrown. Catching everything generally is a bad idea. In this case,
 my bet is that catching AttributeError is enough.

   
What about doing exception kind of like a C switch statement with a 
default case:

try:
  do_something()
except TypeError:
  fix_something()
except:
  print Unknown error, you are doomed
  traceback.print_exc()  #something to print the traceback
  exit_gracefully()

Is this frowned upon?  You still handle the error and you know where it 
happened and what happened.  Anything wrong with this?  I don't like the 
idea of my system crashing for any reason.

-carl


-- 

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

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


Re: Restricted Access

2006-07-11 Thread Paul Rubin
K.S.Sreeram [EMAIL PROTECTED] writes:
 Java is not the only restricted execution environment around.
 Javascript, as implemented by most browsers, is an excellent lightweight
 restricted execution environment, and there are many browsers which have
 good implementations.

And we hear about browser security bugs all the time, for which the
workaround is shut off javascript.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread George Neuner
On Tue, 11 Jul 2006 14:59:46 GMT, David Hopwood
[EMAIL PROTECTED] wrote:

What matters is that, over the range
of typical programs written in the language, the value of the increased
confidence in program correctness outweighs the effort involved in both
adding annotations, and understanding whether any remaining run-time checks
are guaranteed to succeed.

Agreed, but ...


Look at it this way: suppose that I *need* to verify that a program has
no range errors. Doing that entirely manually would be extremely tedious.
If the compiler can do, say, 90% of the work, and point out the places that
need to be verified manually, then that would be both less tedious, and
less error-prone.

All of this presupposes that you have a high level of confidence in
the compiler.  I've been in software development for going in 20 years
now and worked 10 years on high performance, high availability
systems.  In all that time I have yet to meet a compiler ... or
significant program of any kind ... that is without bugs, noticeable
or not.

I'm a fan of static typing but the major problem I have with complex
inferencing (in general) is the black box aspect of it.  That is, when
the compiler rejects my code, is it really because a) I was stupid, b)
the types are too complex, or c) the compiler itself has a bug.  It's
certainly true that the vast majority of my problems are because I'm
stupid, but I've run into actual compiler bugs far too often for my
liking (high performance coding has a tendency to uncover them).

I think I understand how to implement HM inferencing ... I haven't
actually done it yet, but I've studied it and I'm working on a toy
language that will eventually use it.  But HM itself is a toy compared
to an inferencing system that could realistically handle some of the
problems that were discussed in this and Xah's expressiveness thread
(my own beef is with *static* checking of range narrowing assignments
which I still don't believe can be done regardless of Chris Smith's
assertions to the contrary).

It seems to me that the code complexity of such a super-duper
inferencing system would make its bug free implementation quite
difficult and I personally would be less inclined to trust a compiler
that used it than one having a less capable (but easier to implement)
system.

George
--
for email reply remove / from address
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-11 Thread Chris Smith
Marshall [EMAIL PROTECTED] wrote:
 Chris Smith wrote:
  Going back to my
  handy copy of Pierce's book again, he claims that range checking is a
  solved problem in theory, and the only remaining work is in how to
  integrate it into a program without prohibitive amounts of type
  annotation.
 
 This is in TAPL? Or ATTPL? Can you cite it a bit more specifically?
 I want to reread that.

It's TAPL.  On further review, I may have done more interpretation than 
I remembered.  In particular, the discussion is limited to array bounds 
checking, though I don't see a fundamental reason why it wouldn't extend 
to other kinds of range checking against constant ranges as we've been 
discussing here.

Relevant sections are:

Page 7 footnote: Mentions other challenges such as tractability that 
seem more fundamental, but those are treated as trading off against 
complexity of annotations; in other words, if we didn't require so many 
annotations, then it might become computationally intractable.  The next 
reference better regarding tractability.

Section 30.5, pp. 460 - 465: Gives a specific example of a language 
(theoretical) developed to use limited dependent types to eliminate 
array bounds checking.  There's a specific mention there that it can be 
made tractable because the specific case of dependent types needed for 
bounds checking happens to have efficient algorithms, although dependent 
types are intractable in the general case.

I'm afraid that's all I've got.  I also have come across a real-life 
(though not general purpose) languages that does bounds checking 
elimination via these techniques... but I can't find them now for the 
life of me.  I'll post if I remember what it is, soon.

-- 
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying apparently unused globals

2006-07-11 Thread skip

Simon I haven't used it myself, but pychecker
Simon (http://pychecker.sourceforge.net/) is supposed to be able to
Simon perform such stunts.  From the page: Types of problems that can
Simon be found include: Unused globals and locals (module or variable)

Thanks.  I've used both pylint and pychecker.  I'm not aware that either one
can do what I want.  Here's a trivial example:

Module a.py:

RED = red
BLUE = blue

Module b.py:

import a
print a.RED

Considering modules a and b as a whole program, a.BLUE is unused anywhere in
the program.

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


  1   2   3   >