Re: Next step after pychecker

2005-02-02 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
 > So I assume the language spec is basically the grammar and the
> Language Reference docs[1]?

Yes.  The de facto governing syntax specification is the grammar file in 
the source code from which the parser is generated.  I once read that it is 
an ll(1) grammar; perhaps the file itself says.  The grammar snippets in 
the Ref Manual are a humanized version, not constrained to be ll(1) but 
intended to equivalent.  The text, of course, adds the semantic meat.  Any 
discrepancy between that text and implementation behavior is a bug.  Such 
usually get fixed fairly quickly after being reported.

Terry J. Reedy




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


Re: Next step after pychecker

2005-02-02 Thread Alex Martelli
Philippe Fremy <[EMAIL PROTECTED]> wrote:

> Any other idea of a fun python improvement project I could join without
> too much hassle ? I can't help but thinking that pychecker ought to be
> able to do a better job.

Have a look at pypy -- around the key idea of reimplementing Python's
runtime in Python, type inferencing on a somewhat restricted ("not too
dynamic/meta at runtime") subset of Python plays a key role there.


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


Re: Who should security issues be reported to?

2005-02-02 Thread Fuzzyman

Paul Rubin wrote:
> "Fuzzyman" <[EMAIL PROTECTED]> writes:
> > The sourceforge bug tracker *is* the single right place to post
such
> > issues. The py-dev mailing list would be a second *useful* place to
> > post such a comment, although not really the right place. The OP
seemed
> > to want an individual with whom he could have a private
conversation
> > about it.
>
> I think he wanted a place to send a bug report that wouldn't be
> exposed to public view until the developers had a chance to issue a
> patch.  With bugzilla, for example, you can check a bug labelled
"this
> is a security bug, keep it confidential".  There's lots of dilemmas
> and some controversy about keeping any bug reports confidential in an
> open source system.  But the general strategy selected by Mozilla
> after much debate seems to mostly work ok.  It basically says develop
> a patch quickly, keep the bug confidential while the patch is being
> developed, and once the patch is available, notify distro maintainers
> to install it, and then after a short delay (like a couple days),
> publish the bug.
>
> Note that anyone with access to the bug (that includes the reporter
> and selected developers) can uncheck the box at any time, if they
> think the bug no longer needs to be confidential.  The bug then
> becomes visible to the public.

Sounds like a useful feature request to Sourceforge.
Regards,

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

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


Re: how to separate hexadecimal

2005-02-02 Thread jrlen balane
On Wed, 02 Feb 2005 17:36:04 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
> jrlen balane wrote:
> > i have a 4 digit hex number (2 bytes) and i want to separate it into 2
> > digit hex (1 byte each) meaning i want to get the upper byte and the
> > lower byte since i am going to add this two.
> > how am i going to do this?
> > should i treat it just like a normal string?
> > please help, thanks.
> >
> > ex. hexa = '0x87BE"  # what i want to do is:
> >   a = 0x87, b = 0xBE# so that i could do this:
> >   c = a + b#which should be equal to 0x145
> 
> divmod does what you want:
> 
> Py> val = 0x87be
> Py> hi, lo = divmod(val, 0x100)
> Py> hex(hi), hex(lo)
> ('0x87', '0xbe')
> Py> hex(hi + lo)
> '0x145'
> 
> Cheers,
> Nick.
> 
> --
> Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
> ---
>  http://boredomandlaziness.skystorm.net
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
would i be able to perform bitwise operation with the result?
say, i want to get the two's complement of the result, is this correct:

twos_complement = (~ hex(hi + lo)) + 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to separate hexadecimal

2005-02-02 Thread Paul Rubin
jrlen balane <[EMAIL PROTECTED]> writes:
> would i be able to perform bitwise operation with the result?
> say, i want to get the two's complement of the result, is this correct:
> 
> twos_complement = (~ hex(hi + lo)) + 1

You can do bit operations, but hex(n) is the hex string for n, which
is not what you want.

If you want the hex form of the two's complement, just say

   hex(-(hi+lo) & 0xff)

assuming you want one byte, or

   hex(-(hi+lo) & 0x)

for two bytes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-02 Thread Alex Martelli
Kartic <[EMAIL PROTECTED]> wrote:
   ...
> I am not sure what book you are using but I don't think it is a very
> good one.

Hmmm, considering he said it's "Python in a Nutshell", I disagree with
you;-).  If he had understood that he probably wanted to use lists, not
arrays, the top paragraph on p. 47 might have helped him -- "Assigning
to an item with an invalid index also raises an exception", and list
comprehensions are on p. 56.

But considering that in the first post he was just trying to assign to
an indexing on a name he had never bound at all, it seems to me that
starting with the Nutshell may simply have been a bit of "running before
you can walk".  The Nutshell does mention that names (variables) spring
into existence when you bind them, which implies they don't exist
previously, and thus you can't perform any operation on them (such as
binding an indexing on them) before you're bound them; but the Nutshell
doesn't extensively belabor the point.

I tried to explain this issue to another poster who recently appeared to
want to turn the Nutshell into a lay version of the Heart Sutra
("Therefore, Shariputra, in Python there are no declarations.  There is
no use strict, no option explicit, no implicit none; no type of a name
and no declaring of a name so that it can't be rebound, no defining of a
name's type and no omitting to define a name's type, ...").  In a quick
reference, there just isn't enough space to repeat every key point, much
less to belabor the implications of each; even if space were free,
having to skip through such repetitions would _waste_ time for the main
target audience -- people who know some Python and want to get reminded
of every detail about a certain subject, or just look up something
specific.  Trying to make a book that's both a hand-holding tutorial
_and_ a quick reference would produce a book that is not very good at
either task, IMHO.


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


Reference count question

2005-02-02 Thread cedric paille





Hi all, i'm working on an app that embed python 2.3 
with Gnu/Linux, and i'd like to have some precisions:
 
I'm making python's modules to extend my 
application's functions with a built in script editor.
At now all works very well, but i'd like to know if 
i'm not forgetting some references inc/dec
 
Here is a portion of my code:
 
static PyObject *Scene_GetNodeGraph(PyObject 
*self, PyObject *args){  NodeGraph* Ng = 
NodeGraph::GetInstance();  std::vector NodG;  
Ng->GetNodeGraph(NodG);  PyObject* List = 
PyList_New(NodG.size());  PyObject* Str = 
NULL;  std::vector::iterator it = 
NodG.begin();  int i = 0;  for (;it != 
NodG.end();it++)  {    Str = 
PyString_FromString(it->AsChar());PyList_SetItem(List,i,Str); 
i++;  }  return List;}
 
Can someone take a look at this and tell me if i 
must add some inc/decref ?
 
Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list

RE: Python checkin driver version on windows

2005-02-02 Thread Tim Golden
[Chris Jameyson]
| Is there a way to check driver version information on windows through
| Python?  
| 
| I'd like to pull driver version, digital sig from the same place that
| 'device manager' gets it's information.

It's possible that WMI can do it, although device etc. aren't
my area, so I'm not sure what to look for. If you can find
what you want in here:

http://groups-beta.google.com/group/microsoft.public.win32.programmer.wmi

(or anywhere else), I'm happy to help you to translate it to
Python WMI.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Printing Filenames with non-Ascii-Characters

2005-02-02 Thread Marian Aldenhövel
Hi,
Thank you very much, you have collectively cleared up some of the confusion.
English windows command prompt uses cp437 charset.
To be exact my Windows is german but I am not outputting to the command 
prompt
window. I am using eclipse with the pydev plugin as development platform and
the output is redirected to the console view in the IDE. I am not sure how
this affects the problem and have since tried a vanilla console too. The
problem stays the same, though.
I wonder what surprises are waiting for me when I first move this to my
linux-box :-). I believe it uses UTF-8 throughout.
> print d.encode('cp437')
So I would have to specify the encoding on every call to print? I am sure to
forget and I don't like the program dying, in my case garbled output would be
much more acceptable.
Is there some global way of forcing an encoding instead of the default
'ascii'? I have found references to setencoding() but this seems to have gone
away.
The issue is a terminal only understand certain character set.
I have experimented a bit now and I can make it work using encode(). The
eclipse console uses a different encoding than my windows command prompt, by
the way. I am sure this can be configured somewhere but I do not really care
at the moment.
> If you have  unicode string, like d in your case, you have to encode it before
it can be printed.
I got that now.
So encode() is a method of a unicode string, right?. I come from a background
of statically typed languages so I am a bit queasy when I am not allowed to
explicitly specify type.
How can I, maybe by print()-ing something, find out what type d actually is
of? Just to make sure and get a better feeling for the system?
Should d at any time not be a unicode string but some other flavour of string,
will encode() still work? Or do I need to write a function myPrint() that
distinguishes them by type and calls encode() only for unicode strings?
So how did you get a unicoded d to start with?
I have asked myself this question before after reading the docs for
os.listdir(). But I have no way of finding out what type d really is (see
question above :-)). So I was dead-reckoning.
Can I force a string to be of a certain type? Like
nonunicode=unicode.encode("specialencoding")
How would I do it the other way round? From encoded representation to full
unicode?
If 'somepath' is unicode,  os.listdir returns a list of unicode. 
> So why is somepath unicode?
> One possible source is XML parser, which returns string in unicode.
I get a root-directory from XML and I walk the filesystem from there. That
explains it.
Windows NT support unicode filename. I'm not sure about Linux. The 
result maybe slightly differ.
I think I will worry about that later. I can create files using german 
umlauts
on the linux box. I am sure I will find a way to move those names into my
Python program.
I will not move data between the systems so there will not be much of
a problem.
Ciao, MM
--
Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
http://www.marian-aldenhoevel.de
"There is a procedure to follow in these cases, and if followed it can
 pretty well guarantee a generous measure of success, success here
 defined as survival with major extremities remaining attached."
--
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-02 Thread Francis Girard
Le mercredi 2 Février 2005 00:28, Philippe Fremy a écrit :
> I really hope that pypy will provide that kind of choice. Give me python
> with eiffel like contracts, super speed optimisation thank to type
> inference and I will be super happy.

That's also my dream. Type inference not so much for speed but for safety. 
There are type fans (like most skilled C++ programmer), anti-type supporters 
(like the talented Alex Martelli). Type inference sits in the middle.

Didn't understand how pypy intend to support type inference. I read something 
about automatically translating Python into the "smooth blend" Pyrex. I am 
not sure what it exactly means and how they plan to face the problems we 
foresee.

Francis Girard

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


Re: pythonic equivalent of Mathematica's FixedPoint function

2005-02-02 Thread jelle
>You could probably write your own FixedPoint function without too much
>difficulty, with the only tricky part being for it to know when to
stop!

It would be quite interesting to have this kind of function. But
likely its far from trivial.
FixedPoint seems to be one of the core functions in Mathematica, where
many other functions are based on. Some additions such as FixedPoint
would make functional programming in Python more functional is suppose.
Or would anyone consider it sugar syntax for ??

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


Re: Save the Canvas!

2005-02-02 Thread Diez B. Roggisch
Sean McIlroy wrote:

> I'd like to be able to save a Tkinter Canvas in a format other than
> postscript (preferably gif). Is there a tool out there for
> accomplishing that? Any help will be much appreciated.

pnmtools - for converting.

-- 
Regards,

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


Re: Printing Filenames with non-Ascii-Characters

2005-02-02 Thread Marian Aldenhövel
Hi,
Don't be tempted to ever change sys.defaultencoding in site.py, this is 
site specific, meaning that if you ever distribute them, programs 
relying on this setting may fail on other people's Python installations.
But wouldn't that be correct in my case?
> If you're printing to the console, modern Pythons will try to guess the
> console's encoding (e.g. cp850).
But it seems to have quessed wrong. I don't blame it, I would not know of
any way to reliably figure out this setting.
My console can print the filenames in question fine, I can verify that by
simple listing the directory, so it can display more than plain ascii.
The error message seems to indicate that ascii is used as target.
So if I were to fix this in sity.py to configure whatever encoding is
actually used on my system, I could print() my filenames without explicitly
calling encode()?
If the program then fails on other people's installations that would mean
one of two things:
1) They have not configured their encoding correctly.
2) The data to be printed cannot be encoded. This is unlikely as it comes
   from a local filename.
So wouldn't fixing site.py be the right thing to do? To enable Python to print
everything that can actually be printed and not barf at things it could print
but cannot because it defaults to plain ascii?
Ciao, MM
--
Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
http://www.marian-aldenhoevel.de
"There is a procedure to follow in these cases, and if followed it can
 pretty well guarantee a generous measure of success, success here
 defined as survival with major extremities remaining attached."
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Code Auditing Tool

2005-02-02 Thread Diez B. Roggisch
> I suppose that I am willing to lessen my expectations from _all_ to most.
> ;-) Regarding your example I could also do:
> 
> if something():
> def nothing(): return 0
> else:
> def nothing(): return 1
> 
> But this doesn't stop IDEs from attempting to do auto-completion.  I'm not
> trying to find hidden exceptions... just trying to easily get an idea of
> what could go wrong on each line of code.

There is AFAIK only one language that this can de accomplished - java, and
that's because of these checked exceptions of theirs. But checked
exceptions are considered harmful:

http://www.gcek.net/ref/books/sw/ooad/tip/#_Toc41169682

I totally agree with that - in java, I tend to throw SystemExceptions to rid
myself of endless try/catch clauses that obscure the real problem.

So - there is no way of knowing this. The only thing I can think of is to
keep some docs around that specify what exceptions to be expected, and that
tool of yours could try and see if it can identify a function/method by
name and notify you of the possible exceptions thrown. Might actually work
out quite well for the standardlib, if one does the work for annotating all
functions/methods properly.

-- 
Regards,

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


Re: Next step after pychecker

2005-02-02 Thread Philippe Fremy
Skip Montanaro wrote:
Francis> "Every well-formed expression of the language can be assigned a
Francis> type that can be deduced from the constituents of the
Francis> expression alone." Bird and Wadler, Introduction to Functional
Francis> Programming, 1988
Francis> This is certainly not the case for Python since one and the
Francis> same variable can have different types depending upon the
Francis> execution context. Example :
Francis> 1- if a is None:
Francis> 2-   b = 1
Francis> 3- else:
Francis> 4-   b = "Phew"
Francis> 5- b = b + 1
Francis> One cannot statically determine the type of b by examining the
Francis> line 5- alone.
Do you have an example using a correct code fragment?  It makes no sense to
infer types in code that would clearly raise runtime errors:
On the contrary, the point of type inference is to detect such errors. 
If the program was always well-formed, there would be no point in 
developing a type inference tool.

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


Apache & Python 500 Error

2005-02-02 Thread Christian
Hello,
i have an apache 1.3 server with python on debian. Python works fine but 
 the scripts wont´t work.

This easy script i want to do on apache:
#!/usr/bin/python
import os
os.getcwd()
in apache config i have done this:

AddHandler python-program .py
PythonHandler python
Order allow,deny
Allow from all
#PythonDebug On

the script is in this directory /var/www/python
but i get an 500 error everytime, with "every" script - why that - i´m 
newbie - sorry for that :)

greetings from germany to newsgroup
christian
--
http://mail.python.org/mailman/listinfo/python-list


Python for S60 mentioned in a mainstream Finnish e-news website

2005-02-02 Thread Ville Vainio
http://digitoday.fi/showPage.php?page_id=9&news_id=40179

Literal translation for those who can't read Finnish:

Nokia has published the Open Source Python language for Series 60
based mobile devices. The company states that the language makes it
easy for the wordwide Python community to execute commands and run
scripts and apps in the devices.

The language is available for free from the Nokia developer pages and
can be installed on a S60 device with an installation package.

- Python makes the mobile app devepment easy for the programmers who
  are looking for a rapid and developer friendly way to develop
  mobile applications, says Director Lee Epting from Forum Nokia.

Nokia believes that Python for Series 60 is a good fit for developing
prototype- and proof-of-concept apps. The company characterizes the
language as efficient and relatively easy to learn.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Filenames with non-Ascii-Characters

2005-02-02 Thread Max M
Marian Aldenhövel wrote:
 > If you're printing to the console, modern Pythons will try to guess the
 > console's encoding (e.g. cp850).
But it seems to have quessed wrong. I don't blame it, I would not know of
any way to reliably figure out this setting.
Have you set the coding cookie in your file?
Try adding this as the first or second line.
# -*- coding: cp850 -*-
Python will then know how your file is encoded
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


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

2005-02-02 Thread santiagogallarda

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

AttachmentVirus name   Action taken
--
mail.exe  Email-Worm.Win32.Mydoom.m Removed


**


The original message was received at Wed, 2 Feb 2005 10:30:06 +0100 from 
59.245.45.34

- The following addresses had permanent fatal errors -
python-list@python.org

- Transcript of session follows -
... while talking to python.org.:
554 ... Message is too large
554 ... Service unavailable

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

Re: Next step after pychecker

2005-02-02 Thread Francis Girard
To complete Philippe's answer :

As Bird and Wadler continue :

"The major consequence of the discipline imposed by strong-typing is that any 
expression which cannot be assigned a "sensible" type is regarded as not 
being well-formed and is rejected by the computer before evaluation. Such 
expression have _no_ value: they are simply regarded as illegal."

But Skip, I am sure that you can easily find an example by yourself. For 
example, replace "+" by a function that does different things depending on 
its argument type.

Francis Girard

Le mercredi 2 Février 2005 10:27, Philippe Fremy a écrit :
> Skip Montanaro wrote:
> > Francis> "Every well-formed expression of the language can be
> > assigned a Francis> type that can be deduced from the constituents of the
> > Francis> expression alone." Bird and Wadler, Introduction to Functional
> > Francis> Programming, 1988
> >
> > Francis> This is certainly not the case for Python since one and the
> > Francis> same variable can have different types depending upon the
> > Francis> execution context. Example :
> >
> > Francis> 1- if a is None:
> > Francis> 2-   b = 1
> > Francis> 3- else:
> > Francis> 4-   b = "Phew"
> > Francis> 5- b = b + 1
> >
> > Francis> One cannot statically determine the type of b by examining
> > the Francis> line 5- alone.
> >
> > Do you have an example using a correct code fragment?  It makes no sense
> > to infer types in code that would clearly raise runtime errors:
>
> On the contrary, the point of type inference is to detect such errors.
> If the program was always well-formed, there would be no point in
> developing a type inference tool.
>
>   Philippe

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


Re: Python Code Auditing Tool

2005-02-02 Thread Neil Benn
Diez B. Roggisch wrote:
I suppose that I am willing to lessen my expectations from _all_ to most.
;-) Regarding your example I could also do:
<
   


There is AFAIK only one language that this can de accomplished - java, and
that's because of these checked exceptions of theirs. But checked
exceptions are considered harmful:
http://www.gcek.net/ref/books/sw/ooad/tip/#_Toc41169682
I totally agree with that - in java, I tend to throw SystemExceptions to rid
myself of endless try/catch clauses that obscure the real problem.
   


Hello,
  I'm afraid that the only reliable way to gather what exceptions are 
raised is to read docs and/or come up with test cases.  This has been a 
bugbear of mine in Python as it's not common to find a nice :Exceptions: 
IOError , IllegalArgumentError  type of description in the docs.

   However if you want an incomplete test, you could parse the code and 
check for raises and retrieve the class name of the exception - however 
this would be patchy at best.  Therefore it would sort of negate the 
point of doing the analysis in the first place.

 Even in Java you cannot find every exception that will be 
thrown, only 'checked' exceptions but this is a percentage of all the 
exceptions (BTW why do you throw SystemException - it's a CORBA 
exception!  OK, it's a runtime exception but why not just simply extend 
RuntimeException?).  Also, if someone ever puts - catch (Exception e){} 
in their code they deserve to be kneecapped, IMHO the fault is with 
sloppy coding not with the supplied tools.

   Unfortunately its docs and testing again, that's why we get paid (if 
you're doing a job) or not paid (if you're doing it for fun!).  Although 
one language which comes closer is Eiffel which has require and ensure 
clauses on every method (following Meyer's Programming by contract 
philosophy).

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


Re: Save the Canvas!

2005-02-02 Thread Neil Benn
Sean McIlroy wrote:
I'd like to be able to save a Tkinter Canvas in a format other than
postscript (preferably gif). Is there a tool out there for
accomplishing that? Any help will be much appreciated.
Peace,
STM
 

I was massively disappointed, I thought this was a lead up to a protest 
march!

Save the Canvas!
Long live the ComboBox!!
Free the ScrollPane!!
   Sorry in a funny mood.
Cheers,
Neil
--
Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 46
D-01307
Dresden
Germany
Tel : +49 (0)351 4173 154
e-mail : [EMAIL PROTECTED]
Cenix Website : http://www.cenix-bioscience.com
--
http://mail.python.org/mailman/listinfo/python-list


CONTEST - What is the (best) solution?

2005-02-02 Thread python
In a file there can be several dictionaries like this
{Key11: Value11
Key12: Value12
Key13: Value13,
...
...
Key1n:Value1n}
{Key21: Value21
Key22: Value22
Key23: Value23,
...
...
Key2n:Value2n}
{Key31: Value31
Key32: Value32
Key33: Value33,
...
...
Key3n:Value3n}



{Keyn1: Valuen1
Keyn2: Valuen2
Keyn3: Value3,
...
...
Keynn:Valuenn}

Each pair in a dictionary is separated by CRLF and in each dictionary
numbers of pairs can be different.
I need to read only the the first and the last dictionaries.What is a
best solution?
Thanks
Lad

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


Re: Python Code Auditing Tool

2005-02-02 Thread Diez B. Roggisch
Hi,

>I'm afraid that the only reliable way to gather what exceptions are
> raised is to read docs and/or come up with test cases.  This has been a
> bugbear of mine in Python as it's not common to find a nice :Exceptions:
> IOError , IllegalArgumentError  type of description in the
> docs.
> 
> However if you want an incomplete test, you could parse the code and
> check for raises and retrieve the class name of the exception - however
> this would be patchy at best.  Therefore it would sort of negate the
> point of doing the analysis in the first place.

I don't want that  - the OP wants. I agree with you.
 
>   Even in Java you cannot find every exception that will be
> thrown, only 'checked' exceptions but this is a percentage of all the
> exceptions (BTW why do you throw SystemException - it's a CORBA
> exception!  OK, it's a runtime exception but why not just simply extend
> RuntimeException?).  Also, if someone ever puts - catch (Exception e){}
> in their code they deserve to be kneecapped, IMHO the fault is with
> sloppy coding not with the supplied tools.

Most probably I throw RuntimeException - that was out of my head, I luckily
I haven't been coding java too much lately :)

> Unfortunately its docs and testing again, that's why we get paid (if
> you're doing a job) or not paid (if you're doing it for fun!).  Although
> one language which comes closer is Eiffel which has require and ensure
> clauses on every method (following Meyer's Programming by contract
> philosophy).

Full ack again. 

-- 
Regards,

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


Re: Printing Filenames with non-Ascii-Characters

2005-02-02 Thread Marian Aldenhövel
Hi,
Have you set the coding cookie in your file?
Yes. I set it to Utf-8 as that's what I use for all my development.
Try adding this as the first or second line.
# -*- coding: cp850 -*-
Python will then know how your file is encoded
That is relevant to the encoding of source-files, right? How does it affect
printing to standard out?
If it would I would expect UTF-8 data on my console. That would be fine, it
can encode everything and as I have written in another posting in my case
garbled data is better than termination of my program.
But it uses 'ascii', at least if I can believe the error message it gave.
Ciao, MM
--
Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
http://www.marian-aldenhoevel.de
"There is a procedure to follow in these cases, and if followed it can
 pretty well guarantee a generous measure of success, success here
 defined as survival with major extremities remaining attached."
--
http://mail.python.org/mailman/listinfo/python-list


Is this a contradiction in the docs ?

2005-02-02 Thread Fuzzyman
The following two passages from the python documentation *appear* to
contradict each other. Equally possible (or more likely !) is that I
misunderstand it :

eval :
This function can also be used to execute arbitrary code objects (such
as those created by compile()). In this case pass a code object instead
of a string. The code object must have been compiled passing 'eval' as
the kind argument.


compile:
The kind argument specifies what kind of code must be compiled; it can
be 'exec' if string consists of a sequence of statements, 'eval' if it
consists of a single expression, or 'single' if it consists of a single
interactive statement (in the latter case, expression statements that
evaluate to something else than None will be printed).

The docs for compile say that if you are creating a code object from a
sequence of statements you must use the kind argument 'exec'. Eval says
that if you are using the eval function you must use 'eval' as your
kind argument.

In practise I have found that using the eval function with code objects
compiled with 'exec' as the kind argument works fine. Is this a 'bug'
in the docs ?
Regards,

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

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


Re: how to separate hexadecimal

2005-02-02 Thread Nick Coghlan
Paul Rubin wrote:
jrlen balane <[EMAIL PROTECTED]> writes:
would i be able to perform bitwise operation with the result?
say, i want to get the two's complement of the result, is this correct:
twos_complement = (~ hex(hi + lo)) + 1

You can do bit operations, but hex(n) is the hex string for n, which
is not what you want.
If you want the hex form of the two's complement, just say
   hex(-(hi+lo) & 0xff)
assuming you want one byte, or
   hex(-(hi+lo) & 0x)
for two bytes.
More generally though, the "flip the bits and add one" of two's complement is 
just a hardware implementation trick for "2*n - x".

When not working at the hardware level, just go with the definition:
Py> def complement(val, limit=256):
...   if val >= limit or val < 0:
... raise ValueError("Value out of range for complemented format")
...   if val == 0:
... return 0
...   return limit - val
...
Py> hex(complement(0x55))
'0xab'
Py> hex(complement(0x55, 256*256))
'0xffab'
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for S60 mentioned in a mainstream Finnish e-news website

2005-02-02 Thread Ville Vainio
Of course there is the whole hog and more in the official Nokia press
release, this time in English:

http://press.nokia.com/PR/200501/978226_5.html

It also paints an accurate and quite positive picture of Python. Now
we just need ctypes or Symbianic Swig and world domination will be
ours ;-).

(Yeah, ctypes will probably be a problem because of the way Symbian
handles DLLs)

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Go visit Xah Lee's home page

2005-02-02 Thread Michael Goettsche
On Tuesday 01 February 2005 01:07, aurora wrote:
> Let's stop discussing about the perl-python non-sense. It is so boring.
>
> For a break, just visit Mr Xah Lee's personal page
> (http://xahlee.org/PageTwo_dir/Personal_dir/xah.html). You'll find lot of
> funny information and quotes from this queer personality. Thankfully no
> perl-python stuff there.
>
> Don't miss Mr. Xah Lee's recent pictures at
>
>http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html
>
> My favor is the last picture. Long haired Xah Lee sitting contemplatively
> in the living room. The caption says "my beautiful hair, fails to resolve
> the problems of humanity. And, it is falling apart by age."

I don't get why you guys blame Xah Lee as a person. 
Ok, he posts some bullshit, but that doesn't make him a bad person. Read the 
box about George Bush on his Homepage.. it shows that he is a well-thinking 
person. So, don't blame him in general.

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


python and visual C++

2005-02-02 Thread Olivier Ravard
Hi,

When I tryed to compile a python module using distutils under windows,
and there is an error message if we do not have Microsoft Visual C++ 6
installed.
This is because python have been compiled with MSVC6 and distutils wants it
in order to compile C++ python modules.

One of the reasons why I use python is because this is a free language. But
I need
a non free compilator to compile my C++ module !!! Choosing MSVC to compile
python is a strange choice since there are other free compilators like
MinGW.

I think that using another compilator should be possible in order to compile
python
modules since I use BOOST/MinGW to develop my own modules...

Diffrerent solutions appears :
- peoples who compile python for windows should use a free compilator
(MinGW or Microsoft Visual C++ Toolkit 2003 for example)
- modify distutils in order to use another compilator

Is there anyone that have experienced this "free" problem and is there a
solution
that I did not note. I don't want to buy MSVC...

Thanks

O.R.



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


Re: [perl-python] string pattern matching

2005-02-02 Thread Chris Smith
> Stephen Thorne <[EMAIL PROTECTED]> writes:

> On Tue, 01 Feb 2005 21:19:34 -0500, Chris Smith
> <[EMAIL PROTECTED]> wrote:
>> Falls into the 'cure worse than the disease' category.  It's
>> really just a prompt to explore the corners of Gnus, and
>> determine how to give X.L. the thorough ignoring he deserves.

> *headdesk*

> I'm using gmail, and I can set up the filter trivially
> (from:[EMAIL PROTECTED] -> delete), but I just wasn't thinking
> clearly. I was cursing not having the ability to use a procmail
> filter while the solution was right in front of me.

> Regards, Stephen.

There, there, friend; we've all reached for the Big, Fancy Hammer
(BFH) when there was a lazier way to do it. ;)
Best,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Logging

2005-02-02 Thread Neil Benn
Hello,
 I'm running a test and having issues with logging, if I call 
logging.shutdown() and then want to start the logging going again then I 
get a problem as if I call shutdown, I can't get the root logger again, 
such as :

.>>> import logging
.>>> objTestLogger = logging.getLogger()
.>>> objTestLogger.setLevel(logging.INFO)
.>>> objTestLogger.addHandler(logging.FileHandler('c:\\test.log'))
.>>> objTestLogger.info("THIS IS A TEST")
.>>> logging.shutdown()
.>>> objTestLogger = logging.getLogger()
.>>> objTestLogger.setLevel(logging.INFO)
.>>> objTestLogger.info("THIS IS A TEST")
.Traceback (most recent call last):
.  File "", line 1, in ?
.  File "c:\program files\python23\lib\logging\__init__.py", line 893, 
in info
.apply(self._log, (INFO, msg, args), kwargs)
.  File "c:\program files\python23\lib\logging\__init__.py", line 994, 
in _log
.self.handle(record)
.  File "c:\program files\python23\lib\logging\__init__.py", line 1004, 
in handle
.self.callHandlers(record)
.  File "c:\program files\python23\lib\logging\__init__.py", line 1037, 
in callHandlers
.hdlr.handle(record)
.  File "c:\program files\python23\lib\logging\__init__.py", line 592, 
in handle
.self.emit(record)
.  File "c:\program files\python23\lib\logging\handlers.py", line 103, 
in emit
.self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
.ValueError: I/O operation on closed file
.>>>

   This means that I any code that write or use, if it calls 
logging.shutdown the logging is buggered for that process - is my 
analysis correct?

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


Re: Go visit Xah Lee's home page

2005-02-02 Thread Daniel Bickett
I thought we had resolved to stop giving this troll so much negative
attention. Most of us know that that only increases the problem, and
yet now I see a handful of topics at the top-most of this list devoted
solely to him. I think we should go with the idea of a program that
tags his perl-python threads, and simply put him out of mind.

As for your statement in his defense, Michael, his "views" (if one
chooses to give him that much credit) are by no means profound. It
happens to be somewhat of a bandwagon to criticize Bush and cite those
very same "facts". Every now and then I'll get amused by what he is
doing with perl-python, and how he intentionally makes those mistakes,
but then when we have a real conversation it just makes me angry.

-- 
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logging

2005-02-02 Thread Neil Benn
Neil Benn wrote:
Hello,
 I'm running a test and having issues with logging, if I call 
logging.shutdown() and then want to start the logging going again then 
I get a problem as if I call shutdown, I can't get the root logger 
again, such as :

.
Previous code missed out a line :
.>>> import logging
.>>> objTestLogger = logging.getLogger()
.>>> objTestLogger.setLevel(logging.INFO)
.>>> objTestLogger.addHandler(logging.FileHandler('c:\\test.log'))
.>>> objTestLogger.info("THIS IS A TEST")
.>>> logging.shutdown()
.>>> objTestLogger = logging.getLogger()
.>>> objTestLogger.setLevel(logging.INFO)
.>>> objTestLogger.addHandler(logging.FileHandler('c:\\test.log'))
.>>> objTestLogger.info("THIS IS A TEST")
.Traceback (most recent call last):
. File "c:\program files\python23\lib\logging\__init__.py", line 679, in 
emit
.self.stream.write("%s\n" % msg)
.ValueError: I/O operation on closed file
.>>>

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


Re: Python for S60 mentioned in a mainstream Finnish e-news website

2005-02-02 Thread Thomas Heller
Ville Vainio <[EMAIL PROTECTED]> writes:

> Of course there is the whole hog and more in the official Nokia press
> release, this time in English:
>
> http://press.nokia.com/PR/200501/978226_5.html
>
> It also paints an accurate and quite positive picture of Python. Now
> we just need ctypes or Symbianic Swig and world domination will be
> ours ;-).
>
> (Yeah, ctypes will probably be a problem because of the way Symbian
> handles DLLs)

How *does* symbian handle DLLs?

Curious,

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


Re: python and visual C++

2005-02-02 Thread Robin Becker
Olivier Ravard wrote:
... use another compilator
Is there anyone that have experienced this "free" problem and is there a
solution
that I did not note. I don't want to buy MSVC...
Thanks
O.R.

Googled mingw lib for python brings me to
http://www.mingw.org/MinGWiki/index.php/Python%20extensions
which may help
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


access to serial port

2005-02-02 Thread Pawe³ Chrobak
Hi

How to take access to serial port (rs232) ??
Is't possible??  Just tell me guy's where I can take o look
Now I work under Windows XP but finally I need to make script to communicate 
witch
GSM modem under Linux. There will be a typical AT commands

Thanks 


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


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Pierre Barbier de Reuille
Fuzzyman a écrit :
The following two passages from the python documentation *appear* to
contradict each other. Equally possible (or more likely !) is that I
misunderstand it :
eval :
This function can also be used to execute arbitrary code objects (such
as those created by compile()). In this case pass a code object instead
of a string. The code object must have been compiled passing 'eval' as
the kind argument.
compile:
The kind argument specifies what kind of code must be compiled; it can
be 'exec' if string consists of a sequence of statements, 'eval' if it
consists of a single expression, or 'single' if it consists of a single
interactive statement (in the latter case, expression statements that
evaluate to something else than None will be printed).
The docs for compile say that if you are creating a code object from a
sequence of statements you must use the kind argument 'exec'. Eval says
that if you are using the eval function you must use 'eval' as your
kind argument.
In practise I have found that using the eval function with code objects
compiled with 'exec' as the kind argument works fine. Is this a 'bug'
in the docs ?
Regards,
Fuzzy
http://www.voidspace.org.uk/python/index.shtml
IMO, it's just logical the code sent to "eval" was compiled with "eval" 
as the kind argument. But don't forget the documentation is kind of 
"abstract" and that CPython is _just_ an implementation (ok, it's the 
reference implementation) of python. You'd better follow the doc if you 
want your code to work on other Python implementation (ie. JPython, ...).

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


Re: web camera or else ? 15-30 fps processing of camera videos.

2005-02-02 Thread Newbie
Folks:

here is a small summary:

For Linux based system, xawt seems to be the solution:
http://linux.bytesex.org/xawtv/
where one can get access to the stream from any device that has a video
output.

For win32, it looks like the solution is this:
http://videocapture.sourceforge.net/
where one has to use the python programming language.

Great help, thank you all,

Jake.


Matt D wrote:
> Newbie wrote:
> > I am doing some robotics projects but my main area of interest is
> > trying out several algorithms for the processing of the stream of
data
> > coming from the video.
>
> 
>
> Same for me!  From what I can tell, a cheap webcam will "just work"
with
> a recent version of windows - i.e. plug it in using USB and then you
can
> have programmatic access to the data and grab frames very easily.
This
> setup works fine with my digital camera working as a webcam - real
£10
> webcams should be the same.  Not sure what Linux compatibility is
like
> these days - for that I know for a fact that the Hauppauge USB WinTV
> thing works (or at least the hardware version I have works) with
Linux.
>
> For linux I found this (now on the wayback archive - original page is

> now 404):
>
http://web.archive.org/web/20020322015936/http://staff.aist.go.jp/naoyuki.ichimura/research/tips/v4ln_e.htm
>
> Hopefully that is some help.
>
> Oh by the way, speed on a modern machine shouldn't be an issue - my
> badly written prototype in visual basic of all things (dont laugh -
> seemed like a good idea at the time!) was tracking a single coloured
> object reliably at significantly greater than 30fps (it automatically

> altered the window it searched in based on size and amount of
movement
> of the object - at times it was approaching 100fps) on a modest by
> today's standards 1.4ghz pc, using a 320x240 stream.

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


Re: Next step after pychecker

2005-02-02 Thread Steve Holden
Skip Montanaro wrote:
Francis> "Every well-formed expression of the language can be assigned a
Francis> type that can be deduced from the constituents of the
Francis> expression alone." Bird and Wadler, Introduction to Functional
Francis> Programming, 1988
Francis> This is certainly not the case for Python since one and the
Francis> same variable can have different types depending upon the
Francis> execution context. Example :
Francis> 1- if a is None:
Francis> 2-   b = 1
Francis> 3- else:
Francis> 4-   b = "Phew"
Francis> 5- b = b + 1
Francis> One cannot statically determine the type of b by examining the
Francis> line 5- alone.
Do you have an example using a correct code fragment?  It makes no sense to
infer types in code that would clearly raise runtime errors:
>>> "Phew" + 1
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
Also, note that the type assigned to an expression may be nothing more than
"object".  Clearly that wouldn't be very helpful when trying to write an
optimizing compiler, but it is a valid type.
Skip
So reaplce the plus sign with an asterisk ...
regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for S60 mentioned in a mainstream Finnish e-news website

2005-02-02 Thread Ville Vainio
> "Thomas" == Thomas Heller <[EMAIL PROTECTED]> writes:

>> (Yeah, ctypes will probably be a problem because of the way Symbian
>> handles DLLs)

Thomas> How *does* symbian handle DLLs?

By ordinal, so the dll does not include the symbol name (in order to
keep the size small). Linker finds the ordinals from the .LIB file
that corresponds to the DLL.

(Someone who knows better might want to correct me if I'm wrong).

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-02 Thread Steve Holden
Pierre Barbier de Reuille wrote:
[EMAIL PROTECTED] a écrit :
Thank you guys.
My function should multiply every element  of a list, for example
"something"
and "something" can be an integer or another list.
If it deals with integer than it is ok, but
If it deals with list than it become false for example list*2 =
listlist, and what I really want is to mutlitply its member.
That's why I need to know the type of my data in "something".

As stated by another comment, I would do something like :
def multiply(object, factor):
  try:
return [ multiply(i,factor) for i in object ]
  except TypeError:
return object*factor
This function will, recursively multiply a nested list of numbers by 
"factor" ...

As a matter of good practice it's usually considered unwise to shadow 
names of system types like "dict" and "object", though there wouldn't be 
any problems in this case except the infinite recursion. Which 
definitely *would* be a problem.

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: set, dict and other structures

2005-02-02 Thread bearophileHUGS
Leif K-Brooks:

>They look exactly the same speed-wise to me:

There's a little overhead, you can see it with a bigger test:

.from time import clock
.n = 1*10**6
.
.t1 = clock()
.d = set()
.for i in xrange(n):
.  d.add(i)
.t2 = clock()
.for i in xrange(n):
.  d.remove(i)
.t3 = clock()
.d = set(xrange(n))
.t4 = clock()
.print round(t2-t1,2), round(t3-t2,2), round(t4-t3,2), round(t4-t1,2)
.
.t1 = clock()
.d = {}
.for i in xrange(n):
.  d[i] = None
.t2 = clock()
.for i in xrange(n):
.  del d[i]
.t3 = clock()
.d = {}.fromkeys(xrange(n))
.t4 = clock()
.print round(t2-t1,2), round(t3-t2,2), round(t4-t3,2), round(t4-t1,2)

--

Jeremy Bowers:

>I don't see a success pattern for it; I'd say they foundered on trying
to shoot for the moon in advance, instead of starting to write code and
incrementally improving it.<

I agree, their ideas seem too much abstract and big (and the resulting
code looks sloow); I am aiming to something quite simpler, like the
"sets" python module of Py2.3 (but the after the python version
development & testing, a C version can be useful, just like the set
objects in Py2.4).
My (simple) graph module is already nearly done ^_^

>Trying to create a graph library that meets any significant percentage
of
the needs of the people who would use it is quite non-trivial.<

This is right. But:
1) I've found some implementations of graphs:
- One inside Gato: http://www.zpr.uni-koeln.de/~gato/About/
- http://pygraphlib.sourceforge.net/dist/
- http://pygraphlib.sourceforge.net/doc/public/pygraphlib-module.html
- http://www.ics.uci.edu/~eppstein/PADS/
Some modules from Julien Burdy can be found, etc. I think I can find 5
different graph python modules, this number tells me that there's some
people that need/want them.
2) A graph data structure written in C probably cannot be the right one
for every person, because there are so many kinds of graphs... but if
it's fast and general enough and it's already there (and simple
enough!), then most people will start using it, adjusting their needs
to it...

--

Giovanni Bajo:

>In fact, for a moment I wondered if dict.keys() was already of type
set in 2.4, because it could have made sense.<

Well, I presume sometimes you need a list, so maybe something like
dict.keysset() can be a better idea.


>Of course, there are some nitpicks.<

Yes.


>For instance, in the last case the dictionary at the intersection
should probably hold a tuple of two values, one coming from each
dictionary (since the intersection finds the items whose key is present
in both dictionaries, but the value can obviously be different).<

There are other possibilities.


>Another solution would be to say that set-like operations, like (d1 &
d2),
return an iterator to a sequence of keys *only*, in this case the
sequence of
keys available in both dictionaries.<

Right ^_^

Then let's see something:

a = {}.fromkeys(range(10),0)
b = {}.fromkeys(range(5,13),1)

1) a - b ==> dict
Its meaning can be something like:
r = {}
for k in set(a).difference(b): r[k] = a[k]

For functional programming people, it can even mean something like:
r = {}
scan(curry(r.__setitem__(Blank, a[k])), set(a).difference(b))
(Unlike map, scan does not build up a new expression to return.)


2) a + b ==> dict
Its meaning:
r = a.copy()
r.update(b)


3) The intersection is a bit tricky. I don't like the idea of resulting
a dict with tuple values, with both the values of the shared keys. The
other idea is nicer:
a.intersection(b)
Its possible meaning:
3a) set(a).intersection(b)
Alternative meaning:
3b) list(set(a).intersection(b))
(Instead of adding this intersection to dicts, it can just be made a
quite faster dict=>set conversion to make set(a).intersection(b) fast.)


4) Another possibility is less common, but easy to implement, so this
is optional:
a.xor(b)
Its meaning:
r = {}
for x in a: if x not in b: r[x] = r[a]
for x in b: if x not in a: r[x] = r[b]

(Probably there are better ways to implement them, here I've just used
python as a kind of pseudocode).

Bear hugs,
Bearophile

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


Prepending to traceback

2005-02-02 Thread Stefan Behnel
Hi!
I'm writing a parser using pyparsing and I would like to augment the 
ParserException tracebacks with information about the actual error line *in 
the parsed text*. Pyparsing provides me with everything I need (parsed line 
and column), but is there a way to push that information on the traceback?

To make it a bit clearer, tracebacks currently look like this:
Traceback (most recent call last):
 ...
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in parseImpl
raise exc
ParseException: Expected "SOMEOTHERTERM" (146), (5,9)
I want them to look like this:
Traceback (most recent call last):
 ...
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in parseImpl
raise exc
  PyParsing, line 5, in SomeStatement
PARSER TEST FOR TESTING MISSING TERM
ParseException: Expected "SOMEOTHERTERM" (146), (5,9)
where "PARSER TEST FOR TESTING MISSING TERM" is a line parsed by pyparsing 
that leads to raising a ParseException. I wouldn't mind too much not having 
the original traceback, though I'd prefer it. I remember having read somewhere 
that there is a way to embed an exceptions in another one, that might help.

How can I alter or create such Tracebacks?
Thanks,
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: access to serial port

2005-02-02 Thread Diez B. Roggisch
> How to take access to serial port (rs232) ??
> Is't possible??  Just tell me guy's where I can take o look
> Now I work under Windows XP but finally I need to make script to
> communicate witch
> GSM modem under Linux. There will be a typical AT commands

As always: Google is your friend:

google: python serial port

-- 
Regards,

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


Re: how to separate hexadecimal

2005-02-02 Thread Nick Coghlan
Nick Coghlan wrote:
When not working at the hardware level, just go with the definition:
Py> def complement(val, limit=256):
...   if val >= limit or val < 0:
... raise ValueError("Value out of range for complemented format")
...   if val == 0:
... return 0
...   return limit - val
...
Py> hex(complement(0x55))
'0xab'
Py> hex(complement(0x55, 256*256))
'0xffab'
Or there's the simplest definition:
Py> def complement(val, limit=256):
...   return (limit - val) % limit
...
Py> hex(complement(0x55))
'0xab'
Py> hex(complement(-0x55))
'0x55'
Py> hex(complement(0xab))
'0x55'
Py> hex(complement(-0xab))
'0xab'
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Fuzzyman

Pierre Barbier de Reuille wrote:
> Fuzzyman a écrit :
> > The following two passages from the python documentation *appear*
to
> > contradict each other. Equally possible (or more likely !) is that
I
> > misunderstand it :
> >
> > eval :
> > This function can also be used to execute arbitrary code objects
(such
> > as those created by compile()). In this case pass a code object
instead
> > of a string. The code object must have been compiled passing 'eval'
as
> > the kind argument.
> >
> >
> > compile:
> > The kind argument specifies what kind of code must be compiled; it
can
> > be 'exec' if string consists of a sequence of statements, 'eval' if
it
> > consists of a single expression, or 'single' if it consists of a
single
> > interactive statement (in the latter case, expression statements
that
> > evaluate to something else than None will be printed).
> >
> > The docs for compile say that if you are creating a code object
from a
> > sequence of statements you must use the kind argument 'exec'. Eval
says
> > that if you are using the eval function you must use 'eval' as your
> > kind argument.
> >
> > In practise I have found that using the eval function with code
objects
> > compiled with 'exec' as the kind argument works fine. Is this a
'bug'
> > in the docs ?
> > Regards,
> >
> > Fuzzy
> > http://www.voidspace.org.uk/python/index.shtml
> >
>
> IMO, it's just logical the code sent to "eval" was compiled with
"eval"
> as the kind argument. But don't forget the documentation is kind of
> "abstract" and that CPython is _just_ an implementation (ok, it's the

> reference implementation) of python. You'd better follow the doc if
you
> want your code to work on other Python implementation (ie. JPython,
...).
>

Yes.. but that would mean that eval could only run code objects that
"consist[s] of a single expression".. which I doubt is the reality or
the intention.

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



> Pierre

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


Re: Save the Canvas!

2005-02-02 Thread Fuzzyman
Not that funny !   ;-)
Regards,

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

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


Re: set, dict and other structures

2005-02-02 Thread bearophileHUGS
r = {}
for x in a: if x not in b: r[x] = r[a]
for x in b: if x not in a: r[x] = r[b]

I know, this is wrong :-]
This looks better:
r = {}
for x in a: if x not in b: r[x] = a[x]
for x in b: if x not in a: r[x] = b[x]

Bearophile

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


Re: access to serial port

2005-02-02 Thread Nick Coghlan
Pawe³ Chrobak wrote:
Hi
How to take access to serial port (rs232) ??
Is't possible??  Just tell me guy's where I can take o look
The same place you should always look - Google.
Keywords: python serial
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Apache & Python 500 Error

2005-02-02 Thread Fuzzyman
What does the error log report ?

It is *possible*  that you are getting an error 500 because your are
not emitting valid headers.

Try this instead :

#!/usr/bin/python

print 'Content-Type: text/plain\r'
print '\r'
import os
print os.getcwd()
Regards,


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

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


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Steve Holden
Fuzzyman wrote:
The following two passages from the python documentation *appear* to
contradict each other. Equally possible (or more likely !) is that I
misunderstand it :
eval :
This function can also be used to execute arbitrary code objects (such
as those created by compile()). In this case pass a code object instead
of a string. The code object must have been compiled passing 'eval' as
the kind argument.
compile:
The kind argument specifies what kind of code must be compiled; it can
be 'exec' if string consists of a sequence of statements, 'eval' if it
consists of a single expression, or 'single' if it consists of a single
interactive statement (in the latter case, expression statements that
evaluate to something else than None will be printed).
The docs for compile say that if you are creating a code object from a
sequence of statements you must use the kind argument 'exec'. Eval says
that if you are using the eval function you must use 'eval' as your
kind argument.
In practise I have found that using the eval function with code objects
compiled with 'exec' as the kind argument works fine. Is this a 'bug'
in the docs ?
Regards,
"Dear List:
I live close to a railroad, and the tracks are surrounded by a fence 
with large signs saying 'Walking on the tracks can be dangerous'.

I have walked on the tracks several times, however, and I don't see why 
the railway company put those signs there. In fact I'm walking along the 
tracks right now as I enter this post on my hand-held, and

[message ends with sound of locomotive horn followed by an ugly squelch]."
That's the kind of practice best avoided. Are you breaking the rules 
just for the fun of it?

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


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

2005-02-02 Thread Jason Tishler
Dean,

On Tue, Feb 01, 2005 at 08:01:13AM -0800, Dean N. Williams wrote:
> I am getting the following error message from the Python build:
> 
> Traceback (most recent call last):
>  File "", line 1, in ?
>  File "/usr/local/ASD_work/cdat/lib/python2.4/lib-tk/Tkinter.py", line 
> 38, in ?
>import _tkinter # If this fails your Python may not be configured for Tk
> ImportError: No module named _tkinter
> Python Tkinter import failed.
> 
> 
> Have you seen this type of error message before?

No.

> I've attached the following log files for each build.

It appears you did not carefully read the build logs yourself:

building '_tkinter' extension
gcc -shared -Wl,--enable-auto-image-base 
build/temp.cygwin-1.5.12-i686-2.4/_tkinter.o 
build/temp.cygwin-1.5.12-i686-2.4/tkappinit.o -L/usr/X11R6/lib64 
-L/usr/X11R6/lib -L/usr/local/ASD_work/cdat/lib -L/usr/local/lib -L. -ltk8.4 
-ltcl8.4 -lpython2.4 -o build/lib.cygwin-1.5.12-i686-2.4/_tkinter.dll

/usr/local/ASD_work/cdat/lib/libtk8.4.a(tkWindow.o)(.text+0x1093):tkWindow.c: 
undefined reference to `_XDestroyWindow'
...
collect2: ld returned 1 exit status

Hence, you were unsuccessful building _tkinter.  This is why the import
above fails.

> [snip]
> 
> What else am I missing to do?

Using the pre-built Python and Tcl/Tk packages that are part of the
standard Cygwin distribution instead of attempting to build your own.

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: access to serial port

2005-02-02 Thread Pawel Chrobak

> Keywords: python serial
>

Great, I needed exactly this information ( pyserial) . Thanks a lot ;)


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


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

2005-02-02 Thread Jason Tishler
Dean,

Please keep your replies on-list.

On Wed, Feb 02, 2005 at 05:06:30AM -0800, Dean N. Williams wrote:
> It appears that I built the  Tcl/Tk libraries, but for some reasons
> they are not correct. So I am using the Tcl/Tk libraries that were
> distributed with Cygwin. This seemed to work... Now I set the
> TCL_LIBRARY and TK_LIBRARY environment, but I get the following error
> when trying to run idle.
>
> [Dean [EMAIL PROTECTED] ...ASD_work/bin]$ ./idle
> C:\cygwin\usr\local\ASD_work\bin\python2.4.exe (3164): *** unable to 
> remap C:\cygwin\bin\cygssl-0.9.7.dll to same address as parent(0x74) 
> != 0x75
>  5 [main] python2.4 2144 sync_with_child: child 3164(0x650) died 
> before initialization with status code 0x1
>   7241 [main] python2.4 2144 sync_with_child: *** child state child 
> loading dlls
> Traceback (most recent call last):
>  File "./idle", line 5, in ?
>main()
>  File "/usr/local/ASD_work/lib/python2.4/idlelib/PyShell.py", line 
> 1355, in main
> [snip]
>  File "/usr/local/ASD_work/lib/python2.4/os.py", line 488, in _spawnvef
>pid = fork()
> OSError: [Errno 11] Resource temporarily unavailable
>
> Does this have to do with rebaseall?

Yes.  Rebase your system (via rebaseall) following the instructions in
the Cygwin Python but remember to use the "-T" option to specify the
DLLs you built locally.  After rebasing you should be good to go.

> thanks again for all your help...

You are welcome.

Maybe three times is a charm? :,(  Why don't you use the pre-built
Python that is part of the standard Cygwin distribution?

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
In a file there can be several dictionaries like this
(snip)
I need to read only the the first and the last dictionaries.What is a
best solution?
Depends on your definition of 'best solution'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread Fuzzyman
Can your dictionaries contain dictionaries ?

If not you can read the file and cut at the first '}' and the last '{'.
The two chunks will then be a single dictionary which can be eval'd.

*However* your example above does not show ',' between all of the
pairs... but only some. This will bugger you royally (because you can't
even replace '\n' with ','). You'd then need to parse the two chunks
and correct.
Regards,


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

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


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

2005-02-02 Thread Jason Tishler
Dean,

Please keep your replies on-list.

On Wed, Feb 02, 2005 at 05:14:21AM -0800, Dean N. Williams wrote:
> I am trying to do the following according to your notes:
> 
> 3. Due to issues with Cygwin's fork() and DLL base address conflicts,
> one should rebase their Cygwin system to prevent fork() failures.  Use
> the following procedure to rebase your system:
> 
>a. install the Cygwin rebase package (if necessary)
>b. shutdown all Cygwin processes
>c. start bash (do not use rxvt)
>d. execute rebaseall (in the bash window)
> 
> I think this is why idle fails. So I did the above:
> 
> [Dean [EMAIL PROTECTED] ...ASD_work/bin]$ rebaseall
> ReBaseImage (/usr/bin/cygexpat-0.dll) failed with last error = 6
> 
> What am I doing wrong here?

It appears you did not follow step b above.  Did you shutdown *all*
Cygwin processes include services?

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-02 Thread Pierre Barbier de Reuille
Steve Holden a écrit :
Pierre Barbier de Reuille wrote:
[EMAIL PROTECTED] a écrit :
Thank you guys.
My function should multiply every element  of a list, for example
"something"
and "something" can be an integer or another list.
If it deals with integer than it is ok, but
If it deals with list than it become false for example list*2 =
listlist, and what I really want is to mutlitply its member.
That's why I need to know the type of my data in "something".

As stated by another comment, I would do something like :
def multiply(object, factor):
  try:
return [ multiply(i,factor) for i in object ]
  except TypeError:
return object*factor
This function will, recursively multiply a nested list of numbers by 
"factor" ...

As a matter of good practice it's usually considered unwise to shadow 
names of system types like "dict" and "object", though there wouldn't be 
any problems in this case except the infinite recursion. Which 
definitely *would* be a problem.
Oops ... indeed, I usually try not to do so ^_^
That's why I usually use "obj" more than "object" and that most of the 
time I use a name more _on the topic_ ...

Thx for the correction :)
Pierre
regards
 Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Pierre Barbier de Reuille
Fuzzyman a écrit :

Yes.. but that would mean that eval could only run code objects that
"consist[s] of a single expression".. which I doubt is the reality or
the intention.
Regards,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
[Sorry, I deleted the commented lines because they were completely 
unreadable anyway]

It's exactly what eval is for : evaluate a single expression and return 
its result ! Try with strings : you can't even evaluate a statement ! 
You can only evaluate an expression !

And what would be the return result of a sequence of statement ?
If you want to execute a sequence, you want to use exec, not eval ...
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: The next Xah-lee post contest

2005-02-02 Thread Luis M. Gonzalez

alex23 wrote:
> Luis M. Gonzalez wrote:
> > I kind of like this guy... it's like he has a few bugs in his
brain,
> > but other parts are surprisingly interesting.
>
> Which bits especially impress you, the rampant misogyny or the
> unwarranted intellectual arrogance?


I didn't say that I'm "impressed". I just said that some things he says
are somewhat interesting, funny and weird.
I think he, as character, is a little bit excentric and far from
nornal, but he is absolutely harmless.
And to tell you the truth, I don't understand the animosity and
aggressiveness demonstrated against him.
Those who are offended by his posts, should just go ahead and read
someone else's posts intead of starting World War III.

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


Re: MySQLdb - Tuples

2005-02-02 Thread Andy Dustman
#33
#! /usr/bin/env python
import MySQLdb
db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root',
passwd='thkhgfgd')
c=db.cursor()
c.execute('select person from persons order by person')
for (person,) in c: # or c.fetchall() (may be more portable)
print person


If you return more than one column, then you don't need the parentheses
for the tuple unpacking. MySQLdb (and all other DB API databases)
return rows as tuples, so if you only select one column, you get a
tuple of one item.

(google groups eats leading spaces)

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


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Fuzzyman

Steve Holden wrote:
> Fuzzyman wrote:
>
> > The following two passages from the python documentation *appear*
to
> > contradict each other. Equally possible (or more likely !) is that
I
> > misunderstand it :
> >
> > eval :
> > This function can also be used to execute arbitrary code objects
(such
> > as those created by compile()). In this case pass a code object
instead
> > of a string. The code object must have been compiled passing 'eval'
as
> > the kind argument.
> >
> >
> > compile:
> > The kind argument specifies what kind of code must be compiled; it
can
> > be 'exec' if string consists of a sequence of statements, 'eval' if
it
> > consists of a single expression, or 'single' if it consists of a
single
> > interactive statement (in the latter case, expression statements
that
> > evaluate to something else than None will be printed).
> >
> > The docs for compile say that if you are creating a code object
from a
> > sequence of statements you must use the kind argument 'exec'. Eval
says
> > that if you are using the eval function you must use 'eval' as your
> > kind argument.
> >
> > In practise I have found that using the eval function with code
objects
> > compiled with 'exec' as the kind argument works fine. Is this a
'bug'
> > in the docs ?
> > Regards,
> >
>
> "Dear List:
>
> I live close to a railroad, and the tracks are surrounded by a fence
> with large signs saying 'Walking on the tracks can be dangerous'.
>
> I have walked on the tracks several times, however, and I don't see
why
> the railway company put those signs there. In fact I'm walking along
the
> tracks right now as I enter this post on my hand-held, and
>
> [message ends with sound of locomotive horn followed by an ugly
squelch]."
>
> That's the kind of practice best avoided. Are you breaking the rules
> just for the fun of it?
>

Hmm documentation on code objects says :

Code objects are returned by the built-in compile() function and can be
extracted from function objects through their func_code attribute.

A code object can be executed or evaluated by passing it (instead of a
source string) to the exec statement or the built-in eval() function.

It mentions no such restriction. I didn't properly absorb the 'must' in
the eval description..

Hmmm... my code will *never* need to run on anything other than CPython
because I use py2exe to turn it into a frozen python distribution. So
if it was always safe in CPython then that would be fine for me.

The reason I like eval is that "If both dictionaries are omitted, the
expression is executed in the environment where eval is called".
However I think exec might do the same thing anyway. I'll just switch
to exec.

Regards,

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

> regards
>   Steve
> --
> Meet the Python developers and your c.l.py favorites March 23-25
> Come to PyCon DC 2005  http://www.python.org/pycon/2005/
> Steve Holden   http://www.holdenweb.com/

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


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Fuzzyman

Pierre Barbier de Reuille wrote:
> Fuzzyman a écrit :
> >
> >
> > Yes.. but that would mean that eval could only run code objects
that
> > "consist[s] of a single expression".. which I doubt is the reality
or
> > the intention.
> >
> > Regards,
> > Fuzzyman
> > http://www.voidspace.org.uk/python/index.shtml
> >
>
> [Sorry, I deleted the commented lines because they were completely
> unreadable anyway]
>

That's alright - I *have* to read via google, which hides quoted lines
anyway..

> It's exactly what eval is for : evaluate a single expression and
return
> its result ! Try with strings : you can't even evaluate a statement !

> You can only evaluate an expression !
>

Right.

> And what would be the return result of a sequence of statement ?
>

:-) I'm not interested in the return result. The code object is run in
the current namespace, so I use it to run scripts.

> If you want to execute a sequence, you want to use exec, not eval ...
>

Yup - I've swapped them over in my code.

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

> Pierre

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


Re: Next step after pychecker

2005-02-02 Thread Sylvain Thenault
On Tue, 01 Feb 2005 16:27:48 -0600, John Roth wrote:

> 
> "Sylvain Thenault" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote:
>>
>> Did you take a look at the starkiller [1] and pypy projects [2] ?
> 
> Has anything happened to Starkiller since PyCon 2004? The latest mention I
> can find on Google is a blog entry (by Ted Leung) on Aug 30 saying he
> wished someone would give the author some money to finish it and publish
> it.

nothing I'm aware of. Some people talked about it, but no news from
starkiller's author. However some posts mention that it already has some
usable output now.

-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org


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


Re: type of simple object

2005-02-02 Thread Colin J. Williams
[EMAIL PROTECTED] wrote:
Thank you guys.
My function should multiply every element  of a list, for example
"something"
and "something" can be an integer or another list.
If it deals with integer than it is ok, but
If it deals with list than it become false for example list*2 =
listlist, and what I really want is to mutlitply its member.
That's why I need to know the type of my data in "something".
By the way I am new in python, I heard that it has a MatLab
capabilities, How good is that? Since It would be very nice when we can
do what MatLab do in python.
Sincerely Yours,
pujo
If you are looking for MatLab like facilities you might consider 
numarray, available from sourceforge.

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


Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0)

2005-02-02 Thread Leeuw van der, Tim

Hi,

I'm using the following combination of software:
- Pydev Eclipse plugin (pydev 0.8.5)
- eclipse 3.0.1 
- windows XP SP1
- pygtk 2.4.1
- GTK 2.6.1 (for windows32 native)

When trying to get a list of possible completions for the 'gtk' import object, 
the python interpreter crashes. Happens with all versions listed in the 
subject: python 2.3.4, 2.3.5rc1, 2.4.0.

I understand that this isn't a useful report (yet) for anyone to look into the 
problem, but I'd please like to get any hints on how to get more useful 
crashdumps etc. to help debugging this.

cheers,

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


Re: how to write a tutorial

2005-02-02 Thread Xah Lee
in the doc for re module
http://python.org/doc/lib/module-re.html

4.2.2 on Matching vs Searching
http://python.org/doc/lib/matching-searching.html

Its mentioning of Perl is irrelevant, since the majority reading that
page will not have expertise with Perl regex. The whole section should
be deleted, because it only adds confusion. (later section 4.2.3 on
search and match methods plainly indicated their difference.)

(the mentioning of perl there is a combination of author masterbation,
ass kissing, and Python fanaticism. All together innocently done as
ignorance of standard authors.)

A detailed explanation of their difference or the mentioning of Perl
should be in FAQ or such material.

in section 4.2.6 Examples, there needs to be more and simple examples.
(e.g. http://xahlee.org/perl-python/regex.html.) The beginning large
section about some scaf() should be deleted for the same reason as the
Perl above.

-

in section 11.12.2 SMTP Examples
http://python.org/doc/lib/SMTP-example.html

the example given is turgid.

In a tutorial or documentation, you want to give example as short and
to the point as possible. In this case, it is illustrating how to use
smtplib, not how to preamble with nice command line interface. A better
example would be like:

import smtplib
smtpServer='smtp.yourdomain.com';
fromAddr='[EMAIL PROTECTED]';
toAddr='[EMAIL PROTECTED]';
text='''Subject: test test

Hi ...
'''

server = smtplib.SMTP(smtpServer)
server.set_debuglevel(1)
server.sendmail(fromAddr, toAddr, text)
server.quit()
Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


webbrowser.py

2005-02-02 Thread Jeremy Sanders
It occurs to me that webbrowser could be more intelligent on Linux/Unix
systems. Both Gnome and KDE have default web browsers, so one could use
their settings to choose the appropriate browser.

I haven't been able to find a freedesktop common standard for web browser,
however.

Firefox now sets itself as a "default browser" on startup, so python could
also look for a similar setting.

webbrowser could identify whether it was running under KDE/Gnome (maybe
scan the processes?), identify the correct desktop's browser (or just use
Gnome, maybe), and start that web browser.

Comments?

Jeremy

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


Re: Hey, get this! [was: import from database]

2005-02-02 Thread Steve Holden
Steve Holden wrote:
Peter Otten wrote:
Steve Holden wrote:

This is even stranger: it makes it if I import the module a second time:

[second import seems to succeed]
Maybe you are experiencing some version confusion? What you describe 
looks
much like the normal Python 2.3 behaviour (with no import hook involved)
whereas you seem to operate on the 2.4 library.
A partially initialized module object is left behind in sys.modules 
and seen
by further import attempts.

I agree that this is 2.3-like behavior, but Python cannot lie ...
[EMAIL PROTECTED] ~/Projects/Python/dbimp
$ python
Python 2.4 (#1, Dec  4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
 >>>
Just to make things simpler, and (;-) to appeal to a wider audience, 
here is a program that doesn't use database at all (it loads the entire 
standard library into a dict) and still shows the error.

What *I* would like to know is: who is allowing the import of bsddb.os, 
thereby somehow causing the code of the os library module to be run a 
second time.

#
# Establish standard library in dict
#
import os
import glob
import sys
import marshal
import new
def importpy(dct, path, modname, package):
c = compile(file(path).read(), path, "exec")
dct[modname] = (marshal.dumps(c), package, path)
if package:
print "Package", modname, path
else:
print "Module", modname, path
def importall(dct, path, modlist):
os.chdir(path)
for f in glob.glob("*"):
if os.path.isdir(f):
fn = os.path.join(path, f, "__init__.py")
if os.path.exists(fn):
ml = modlist + [f]
importpy(dct, fn, ".".join(ml), 1)
importall(dct, os.path.join(path, f), ml)
elif f.endswith('.py') and '.' not in f[:-3] and f != 
"__init__.py":
importpy(dct, os.path.join(path, f), 
".".join(modlist+[f[:-3]]), 0)

class dbimporter(object):
def __init__(self, item, *args, **kw):
##print "dbimporter: item:", item, "args:", args, "keywords:", kw
if item != "*db*":
raise ImportError
print "Accepted", item
def find_module(self, fullname, path=None):
print "find_module:", fullname, "from", path
if fullname not in impdict:
#print "Bailed on", fullname
return None
else:
print "found", fullname, "in db"
return self
def load_module(self, modname):
print "load_module:", modname
if modname in sys.modules:
return sys.modules[modname]
try:
row = impdict[modname]
except KeyError:
#print modname, "not found in db"
raise ImportError, "DB module %s not found in modules"
code, package, path = row
code = marshal.loads(code)
module = new.module(modname)
sys.modules[modname] = module
module.__name__ = modname
module.__file__ = path # "db:%s" % modname
module.__loader__ = dbimporter
if package:
module.__path__ = sys.path
exec code in module.__dict__
print modname, "loaded:", repr(module), "pkg:", package
return module
def install():
sys.path_hooks.append(dbimporter)
sys.path_importer_cache.clear() # probably not necessary
sys.path.insert(0, "*db*") # probably not needed with a metea-path 
hook?

if __name__ == "__main__":
impdict = {}
for path in sys.argv[1:]:
importall(impdict, path, [])
install()
import bsddb
Running this against a copy of the Python 2.4 standard library in C:\Lib 
gives me

[...]
Module _strptime C:\Lib\_strptime.py
Module _threading_local C:\Lib\_threading_local.py
Module __future__ C:\Lib\__future__.py
Accepted *db*
find_module: bsddb from None
found bsddb in db
load_module: bsddb
find_module: bsddb._bsddb from None
find_module: bsddb.sys from None
find_module: bsddb.os from None
find_module: bsddb.nt from None
find_module: bsddb.ntpath from None
find_module: bsddb.stat from None
Traceback (most recent call last):
  File "C:\Steve\Projects\Python\dbimp\dictload.py", line 79, in ?
import bsddb
  File "C:\Steve\Projects\Python\dbimp\dictload.py", line 65, in 
load_module
exec code in module.__dict__
  File "C:\Lib\bsddb\__init__.py", line 62, in ?
import sys, os
  File "C:\Python24\lib\os.py", line 133, in ?
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, 
altsep,
ImportError: No module named path

The 2.3 bsddb library doesn't cause the same problems (and even loads 
into 2.4 quite nicely). Lots of modules *will* import, and most packages 
don't seem to cause problems. Anyone give me a pointer here?

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/ma

Re: Hey, get this!

2005-02-02 Thread Bernhard Herzog
Steve Holden <[EMAIL PROTECTED]> writes:

> What *I* would like to know is: who is allowing the import of bsddb.os,
> thereby somehow causing the code of the os library module to be run a
> second time.

I would guess (without actually running the code) that this part is
responsible:

>  if package:
>  module.__path__ = sys.path

You usually should initialize a package's __path__ to an empty list.
The __init__ module will take care of modifying it if necessary.

   Bernhard

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


Re: web camera or else ? 15-30 fps processing of camera videos.

2005-02-02 Thread The Artist Formerly Known as Kap'n Salty
JGCASEY wrote:
The Artist Formerly Known as Kap'n Salty wrote:
Newbie wrote:
I am doing some robotics projects but my main area of interest is
trying out several algorithms for the processing of the stream of
data
coming from the video.
I am wondering what type of camera I should invest in. Either I
could
buy a web cam and hope I can find a driver I could either modify or
use. i.e. every frame is somehow stored on the computer
automagically
or I could buy a camera not unlike the AVRcam
(http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try
to
do the processing once the data has been streamed to the nearest
computer ? or should I use an expensive video card, some CCTV
camera
and a frame grabber to digitize photos so they can be processed
afterwards. I expect my processing algorithms to handle at least 15
frames per second framerate once they are working ont the final
set-up.
My constraints are that I would like to avoid as much as possible
complex set-ups even if that means buying a more expensive camera
set-up. For the prototyping, I would like to try my algorithms out
using a combination of python and matlab (all very slow) and then
expect the same architecture (image files location and flow) with
speedier set-up like python+psyco or C. All the processing would be
done on a computer dedicated for that. Windows or Linux are
possible.
An easy approach to this is to use a wireless camera on your robot,
with
the receiver attached to a frame grabber on a remote host. This
allows
you your choice of camera (stand alone video transmitters are widely
available), and you are not limited to only processing hardware you
can
carry on board your robot. You also get full FPS. Frame-grabber cards

are inexpensive and widely available for both Windows and Linux.

I wanted to go down that path but cannot get
information on how to access the images from
the tv receiver card in real time using my
own software.
Do you use Java?
John Casey
I do, but not for image processing. There IS a multi-media SDK out there 
for java that handles video capture -- google should help you out here 
(I can't recall the site). I'm not entirely sure how mature it is. I 
looked a couple of years back and decided to avoid it. It likely does 
not support all platforms, since video capture drivers vary a good bit 
by platform. This all may have changed, however.

On Windows, you'll use DirectShow (part of DirectX) to get incoming 
frames. There's also the deprecated VFW (Video for Windows).

On linux, there's Video for Linux.
In either case, the APIs are not difficult to use. You should never have 
to access the hardware directly.

Note that whether you get the video from a webcam or framegrabber, the 
APIs are the same. I've actually abstracted some of the DirectX stuff 
out to the point that I can get frames from a video file *or* a camera 
the same way.

--
(Replies: cleanse my address of the Mark of the Beast!)
Teleoperate a roving mobile robot from the web:
http://www.swampgas.com/robotics/rover.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0)

2005-02-02 Thread Stefan Behnel
Leeuw van der, Tim schrieb:
I'm using the following combination of software:
- Pydev Eclipse plugin (pydev 0.8.5)
- eclipse 3.0.1 
- windows XP SP1
- pygtk 2.4.1
- GTK 2.6.1 (for windows32 native)
First of all, try tightening the field. Are all of these packages needed to 
reproduce the error? Try to start the interpreter in a command line window and 
see if it happens there, too. That eliminates Eclipse.


When trying to get a list of possible completions for the 'gtk' import object, the python interpreter crashes. Happens with all versions listed in the subject: python 2.3.4, 2.3.5rc1, 2.4.0.
Might be a problem with GTK for Windows, I don't know.
Type
import gtk
Does that crash? Or is it something like
dir(gtk)
Try different versions of GTK and pygtk. Look at the pygtk homepage to see 
which combination is known to work.

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


Re: Is this a contradiction in the docs ?

2005-02-02 Thread Stefan Behnel
Fuzzyman schrieb:
Hmmm... my code will *never* need to run on anything other than CPython
because I use py2exe to turn it into a frozen python distribution. So
if it was always safe in CPython then that would be fine for me.
No one will ever need more than 640K of RAM and BTW, my program will be 
replaced well before the year 1, so four digits for the year should be 
enough...

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


Re: test_socket.py failure

2005-02-02 Thread x2164
Nick Coghlan <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> >  At the interactive python prompt i did/got the following:
> > 
> >   bash-2.04$ ./python 
> >   Python 2.4 (#1, Jan 29 2005, 10:31:35) 
> >   [GCC 2.95.3 20010315 (release)] on linux2
> >   Type "help", "copyright", "credits" or "license" for 
> >  more information.
> >   >>> import socket
> >   >>> socket.getservbyname('daytime', 'tcp')
> >   13
> >   
> ># The 13 looks ok but look what happen 
> ># when i asked only for the service, like
> ># the line that fails in test_socket.
> >   
> >   >>> socket.getservbyname('daytime')   
> >   Traceback (most recent call last):
> > File "", line 1, in ?
> >   socket.error: service/proto not found
> >   >>>

> Hmm, when the second argument is omitted, the system call looks like:

> getservbyname("daytime", NULL);

> Based on "man getservbyname" on my Linux PC, that should give
> the behaviour we 
> want - any protocol will match.

> However:

> Linux 2.6.4-52-default (Suse 9.1)
> Glibc 2.3.3
> gcc   3.3.3

> So it may be that your older platform doesn't have this
> behaviour - I'd be very 
> interested in what 'man getservbyname' has to say.

> Cheers,
> Nick.

> -- 
> Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
> ---
>  http://boredomandlaziness.skystorm.net

hey Nick,

Just took a look at the man page for getservbyname on this
system and it doesn't mention passing NULL as the second
argument.  The pertinents: ;-)

Linux kernel 2.6.10
Glibc 2.2.5
gcc   2.95.3

I'd say your probably right about there being a difference
in the behaviour of getservbyname between libc 2.2.5 and 
and libc-2.3.3 given the differences in man pages and 
observed return values. I'll try and compare the libcs'
getservbyname codes and let you know a little later in 
the day.

I wonder if the developers wanted to tie the python source
code so closely to a glibc version and possibly gnu-libc
specific?

   
pete jordan
x2164 at mailcityDOTcom
miami, florida


-- 


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


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread python

Fuzzyman wrote:
> Can your dictionaries contain dictionaries ?
>
> If not you can read the file and cut at the first '}' and the last
'{'.
> The two chunks will then be a single dictionary which can be eval'd.
>
> *However* your example above does not show ',' between all of the
> pairs... but only some. This will bugger you royally (because you
can't
> even replace '\n' with ','). You'd then need to parse the two chunks
> and correct.
> Regards,
>
>
Hi Fuzzy,
dictionaries can NOT contain dictionaries.
I re-checked and I would need only the last dictionary.
Any idea how I could do that?
Thanks
Lad.

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


new style exception handleing

2005-02-02 Thread Ola Natvig
Hi all
Does anybody know why it's not possible to raise Exceptions which are 
types (new-style-classes). I know all standard exceptions are classic 
classes, but if you make a custom exception which both inherits from a 
exception class and a new-style one the it causes a type error when raised.

>>> class b(Exception, object): pass
>>> raise b
Traceback (most recent call last):
  File "", line 1, in -toplevel-
raise b
TypeError: exceptions must be classes, instances, or strings 
(deprecated), not type

This is weird, I think. Are there any issues about raising types as 
exceptions that I can't think of ?

--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hey, get this!

2005-02-02 Thread Steve Holden
Bernhard Herzog wrote:
Steve Holden <[EMAIL PROTECTED]> writes:

What *I* would like to know is: who is allowing the import of bsddb.os,
thereby somehow causing the code of the os library module to be run a
second time.

I would guess (without actually running the code) that this part is
responsible:

if package:
module.__path__ = sys.path

You usually should initialize a package's __path__ to an empty list.
The __init__ module will take care of modifying it if necessary.
   Bernhard
Thanks, Bernhard, that appeared to fix the problem. The error certainly 
went away, anyway ... now I can do more experimentation.

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Prepending to traceback

2005-02-02 Thread Thomas Guettler
Am Wed, 02 Feb 2005 13:55:24 +0100 schrieb Stefan Behnel:

> Hi!
> 
> I'm writing a parser using pyparsing and I would like to augment the 
> ParserException tracebacks with information about the actual error line *in 
> the parsed text*. Pyparsing provides me with everything I need (parsed line 
> and column), but is there a way to push that information on the traceback?

Hi,

have a look at the source of ParseException. I guess there
is attribute which holds the string. If the attribute is "msg",
you could do it like this:

try:

except ParseException, e:
e.msg="Textbefore %s" % e.msg
raise e

(code is not tested)

 Thomas
 

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread Fuzzyman
What about the syntax ? Will it have commas in the right place ?
(never, always, or sometimes ? - sometimes is much worse than never or
always).

*damn* - problem is that '{' might appear as one of the values
*So*... read the file in as a list of lines and strip each line.
Dictionaries will always start where '{' is the first character. Anyway
- you could always explicitly check if each line ends with a ',' and if
it doesn't add one...)
(*warning* UNTESTED)

>handle = open('filename', 'r')
>thefile =  handle.readlines()
>handle.close()
>
>dictindex = []
>i = 0
>while i < len(thefile)-1:
>if line.startswith('{'):
>dictindex.append(i)
>i += 1
>lastdict = ' '.join(thefile[dictindex[-1]:]
>print eval(lastdict)

Checking if each line ends with a ',' (except for the last line) should
be easy !
HTH

Regards,

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

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


Re: Hey, get this! [was: import from database]

2005-02-02 Thread Just
In article <[EMAIL PROTECTED]>,
 Steve Holden <[EMAIL PROTECTED]> wrote:

> Just to make things simpler, and (;-) to appeal to a wider audience, 
> here is a program that doesn't use database at all (it loads the entire 
> standard library into a dict) and still shows the error.
> 
> What *I* would like to know is: who is allowing the import of bsddb.os, 
> thereby somehow causing the code of the os library module to be run a 
> second time.
[ ... ]

Maybe this?:
>  if package:
>  module.__path__ = sys.path

I'm fairly sure this should read

   module.__path__ = ["*db*"]

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


Re: How run valgrind on Python C extensions?

2005-02-02 Thread System Administrator

Chris> I have Python C extensions that are giving me seg faults that I'd
Chris> like to run valgrind on.

Chris> Can I use valgrind on these through python??  HOW???

Just run Python under valgrind's control.  It will automatically take care
of it for you.

Chris> Is it easy or must I do some work like recompiling python source
Chris> with the -g extension?

Should not be necessary.

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


Re: Python Code Auditing Tool

2005-02-02 Thread System Administrator

>> Does anybody know of a tool that can tell me all possible exceptions
>> that might occur in each line of code?  What I'm hoping to find is
>> something like the following:

Paul> That is impossible.  The parameter to the raise statement is a
Paul> class object, which can be anything.

Sure, but in all but the rarest of cases the first arg to raise is a
specific exception, probably one of the standard exceptions.  In the Python
code in the distribution (ignoring the test directory where all sorts of
mischief is done to stress things), here are the most common words following
"raise" where "raise" is the first word on the line:

% find . -name '*.py' \
> | egrep -v '\./test' \
> | xargs egrep '^ *raise ' \
> | awk '{print $3}' \
> | sed -e 's/[(,].*//' \
> | sort \
> | uniq -c \
> | sort -rn \
> | head -15
 246 ValueError
 227 aetools.Error
 216 Error
 124 TypeError
 101 error
  75 RuntimeError
  53 IOError
  36 NotImplementedError
  36 ImportError
  36 EOFError
  31 SyntaxError
  23 KeyError
  23 AttributeError
  22 DistutilsPlatformError
  21 UnicodeError

Without checking, my guess is that #5 ("error") is one of a handful of
exception classes defined at module scope (ftplib, anydbm, sre_constants,
poplib, among others all define such an exception class), and not a variable
that accepts multiple values as in your example.

In short, while not perfect, simply grepping for '^ *(class|def|raise) ' and
printing the first and second words of each output line would probably give
you a pretty good idea of what gets raised where.

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


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread Larry Bates
Assumptions:
1) You actually meant to have commas between each key value pair
(which your example DOES NOT have).
2) File can be read into memory
3) All the key and value variables are actually defined in the
local namespace or they are literal values instead of references
to variables.
This works:
Key11=11
Value11='V11'
Key12=12
Value12='12'
Key13=13
Value13='V13'
Key21=21
Value21='V21'
Key22=22
Value22='V22'
Key23=32
Value23='V23'
Key31=31
Value31='V31'
Key32=32
Value32='V32'
Key33=33
Value33='V33'
testdata='''
{Key11: Value11,\n
Key12: Value12,\n
Key13: Value13}\n
{Key21: Value21,\n
Key22: Value22,
Key23: Value23}\n
{Key31: Value31,\n
Key32: Value32,\n
Key33: Value33}\n
'''
#
# Or read data from a file
#
# f=open(file, 'r')
# testdata=f.read()
# f.close()
#
dictlist=testdata.replace('\n','').split('{')
firstdictstr='{'+dictlist[2]
lastdictstr='{'+dictlist[-1]
firstdict=eval(firstdictstr)
lastdict=eval(lastdictstr)
print "firstdict=", firstdict
print "lastdict=", lastdict
firstdict=eval(firstdictstr)
lastdict=eval(lastdictstr)
Larry Bates
[EMAIL PROTECTED] wrote:
In a file there can be several dictionaries like this
{Key11: Value11
Key12: Value12
Key13: Value13,
...
...
Key1n:Value1n}
{Key21: Value21
Key22: Value22
Key23: Value23,
...
...
Key2n:Value2n}
{Key31: Value31
Key32: Value32
Key33: Value33,
...
...
Key3n:Value3n}



{Keyn1: Valuen1
Keyn2: Valuen2
Keyn3: Value3,
...
...
Keynn:Valuenn}
Each pair in a dictionary is separated by CRLF and in each dictionary
numbers of pairs can be different.
I need to read only the the first and the last dictionaries.What is a
best solution?
Thanks
Lad
--
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-02 Thread System Administrator

Francis> But Skip, I am sure that you can easily find an example by
Francis> yourself. For example, replace "+" by a function that does
Francis> different things depending on its argument type.

Sure.  I was thinking of the optimization use of type inferencing,
forgetting the subject of the note.

Coming back to this:

1- if a is None:
2-   b = 1
3- else:
4-   b = "Phew"
5- b = b + 1

pychecker should be able to warn you today (but it doesn't) that you are
using b to refer to objects of two different types.  It's not type
inferencing, but it would probably be a reasonable addition to its suite of
things it checks.

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


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread Fuzzyman
Doesn't work if '{' or '}' can appear in the values.
Regards,

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

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


Re: Python Code Auditing Tool

2005-02-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
System Administrator  <[EMAIL PROTECTED]> wrote:
>
>>> Does anybody know of a tool that can tell me all possible exceptions
>>> that might occur in each line of code?  What I'm hoping to find is
>>> something like the following:
>
>Paul> That is impossible.  The parameter to the raise statement is a
>Paul> class object, which can be anything.
>
>Sure, but in all but the rarest of cases the first arg to raise is a
>specific exception, probably one of the standard exceptions.  In the Python
>code in the distribution (ignoring the test directory where all sorts of
>mischief is done to stress things), here are the most common words following
>"raise" where "raise" is the first word on the line:
>
>% find . -name '*.py' \
>> | egrep -v '\./test' \
>> | xargs egrep '^ *raise ' \
>> | awk '{print $3}' \
>> | sed -e 's/[(,].*//' \
>> | sort \
>> | uniq -c \
>> | sort -rn \
>> | head -15
> 246 ValueError
> 227 aetools.Error
> 216 Error
> 124 TypeError
> 101 error
>  75 RuntimeError
>  53 IOError
>  36 NotImplementedError
>  36 ImportError
>  36 EOFError
>  31 SyntaxError
>  23 KeyError
>  23 AttributeError
>  22 DistutilsPlatformError
>  21 UnicodeError

It's kind of interesting (scarry?) that in roughly 20% of the cases
nothing more specific than Error is raised.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prepending to traceback

2005-02-02 Thread Larry Bates
Replace system exception hook with your on function that gets
called when exception is raised (not fully tested):
#
# Define a function that is called when system exception happens
#
def excepthook(self, type, value, tb):
#
# This function allows the user to redefine what happens if the program
# aborts due to an uncaught exception.
import traceback
#
# Prepend your lines to tblines list here
#
tblines=['PyParsing, line 5, in SomeStatement\n',
 'PARSER TEST FOR TESTING MISSING TERM\n']
#
# Get traceback lines and append the current session log
#
tblines.extend(traceback.format_exception(type, value, tb))
map(sys.stdout.writelines, tblines)  # Always write exceptions to screen
sys.exit(2)
#
# At top of your main program:
# Set the sys.excepthook so I can clean up properly if main program aborts
#
sys.excepthook=excepthook
Larry Bates

Stefan Behnel wrote:
Hi!
I'm writing a parser using pyparsing and I would like to augment the 
ParserException tracebacks with information about the actual error line 
*in the parsed text*. Pyparsing provides me with everything I need 
(parsed line and column), but is there a way to push that information on 
the traceback?

To make it a bit clearer, tracebacks currently look like this:
Traceback (most recent call last):
 ...
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in 
parseImpl
raise exc
ParseException: Expected "SOMEOTHERTERM" (146), (5,9)

I want them to look like this:
Traceback (most recent call last):
 ...
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 456, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 727, in 
parseImpl
raise exc
  PyParsing, line 5, in SomeStatement
PARSER TEST FOR TESTING MISSING TERM
ParseException: Expected "SOMEOTHERTERM" (146), (5,9)

where "PARSER TEST FOR TESTING MISSING TERM" is a line parsed by 
pyparsing that leads to raising a ParseException. I wouldn't mind too 
much not having the original traceback, though I'd prefer it. I remember 
having read somewhere that there is a way to embed an exceptions in 
another one, that might help.

How can I alter or create such Tracebacks?
Thanks,
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb - Tuples

2005-02-02 Thread Georg Brandl
Andy Dustman wrote:
> #33
> #! /usr/bin/env python
> import MySQLdb
> db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root',
> passwd='thkhgfgd')
> c=db.cursor()
> c.execute('select person from persons order by person')
> for (person,) in c: # or c.fetchall() (may be more portable)
> print person
> 
> 
> If you return more than one column, then you don't need the parentheses
> for the tuple unpacking.

You don't need the parentheses for one element either:

for person, in c:
print person

works perfectly. Note the trailing comma.

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


Re: how to write a tutorial

2005-02-02 Thread Xah Lee
i've noticed that in Python official doc
http://python.org/doc/lib/module-re.html
and also How-To doc
http://www.amk.ca/python/howto/regex/

both mentions the book "Mastering Regular Expressions" by Jeffrey
Friedl.

I suggest it be dropped in both places. The mentioning of this book in
the Perl/Python community is mostly a fawning behavior and confession
that the author is among "in the know". This book and its mentioning is
a cultish behavior among OpenSource morons.

Most of the time, its mentioning as a reference is irrelevant. 99% uses
of regex are the simplest uses. Spending time to read this book of
specialization, from economy perspective, is a waste of time.
Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


RE: Newbie Question

2005-02-02 Thread Joel Eusebio
Hi Jeremy & Robey

Acces_log:

172.16.38.6 - - [01/Feb/2005:17:36:14 -0800] "GET /test.py HTTP/1.1" 404 276
"-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"
172.16.38.6 - - [01/Feb/2005:17:41:44 -0800] "GET /test/mptest.py/formLogin
HTTP/1.1" 404 293 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;
.NET CLR 1.1.4322)"

Error_log:

[Wed Feb 02 08:55:18 2005] [notice] mod_python: (Re)importing module
'mod_python.publisher'
[Wed Feb 02 08:55:18 2005] [notice] mod_python: (Re)importing module 'test'
with path set to '['/var/www/html']'

Httpd.conf:

LoadModule python_module modules/mod_python.so

#
Order allow,deny
Allow from all
AddHandler mod_python .py
Options Indexes Includes FollowSymlinks Multiviews
PythonHandler mod_python.publisher
PythonDebug On




   AddHandler mod_python .py
   AllowOverride None
   PythonHandler mod_python.publisher
   PythonDebug On

Thanks again,

Joel


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Jeremy
Bowers
Sent: Tuesday, February 01, 2005 5:47 PM
To: python-list@python.org
Subject: Re: Newbie Question

On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote:
> Whenever I access test.py from my browser it says "The page cannot be
> found" , I have the file on /var/www/html, what did I miss?
> 
>  Thanks in advance,
> Joel

In general, you will need to post the relevant entries from your Apache
error log and access log. A lot of things can go wrong between your Python
script and final output. 

However, if you're getting a 404, it means that you haven't associated the
URL to the file correctly. Again, a lot of things can prevent this, so
you're also going to need to post the relevant Apache configuration files.
Without that, I can't be any more specific.

I'm also concerned that you are conflating mod_python with Python CGI,
which work completely differently when it comes to associating code to
URLs. In general, you won't access a mod_python script by typing in a
URL to a file; that will either try to run it as a CGI or just display it
(depending on the configuration). But we'll work on this when you post the
necessary information and we can see what you are trying to do.
-- 
http://mail.python.org/mailman/listinfo/python-list

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


Re: Apache & Python 500 Error

2005-02-02 Thread Jeremy Bowers
On Wed, 02 Feb 2005 10:28:46 +0100, Christian wrote:

> Hello,
> 
> i have an apache 1.3 server with python on debian. Python works fine but
>   the scripts wontÂt work.

I know what your problem is.

But first, check your apache error log. Then you will know what your error
is, too.

If you can't fix it after you try to fix the error in the log, or you
don't understand the log entry, post your program and all relevant log
entries. You did good posting your Apache configuration, but we also need
the log entries.

That said, fuzzyman is right, but keep this in mind for future help
requests.
-- 
http://mail.python.org/mailman/listinfo/python-list


Hash of class from instance

2005-02-02 Thread Joakim Storck
Hello,

Is there any way that I can find the hash value of a class from an
instance?

>>> class A:
... pass
...
>>> a = A()
>>> hash(A)
10782976
>>> hash(a)
12251904
>>>

What I want is a function that returns the value of 'hash(A)':
> a.getHashOfClass()
10782976

Is this possible?

/Joakim

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


Re: CONTEST - What is the (best) solution?

2005-02-02 Thread Jeremy Bowers
On Wed, 02 Feb 2005 02:35:03 -0800, python wrote:
> Each pair in a dictionary is separated by CRLF and in each dictionary
> numbers of pairs can be different.
> I need to read only the the first and the last dictionaries.What is a
> best solution?
> Thanks
> Lad

Who cares about the best solution? Odds are, your process is disk-bound
anyhow. 

Is this a thinly-veiled attempt to get someone to provide you *a*
solution, or do you already have one and you are seriously asking for a
better one? Because I'd say, take the easiest programming route: Parse the
first dict into a variable, then just loop until you run out of file,
storing a parsed dict in the "last" variable and just naturally letting
later ones overwrite earlier ones.

If you want something "best"-er than that (heh heh), you're going to have
to tell us how you are measuring better-ness.
-- 
http://mail.python.org/mailman/listinfo/python-list


Hash of class from instance

2005-02-02 Thread Joakim Storck
Hello,

Is there any way that I can find the hash value of a class from an
instance?

>>> class A:
... pass
...
>>> a = A()
>>> hash(A)
10782976
>>> hash(a)
12251904
>>>

What I want is a function that returns the value of 'hash(A)':
> a.getHashOfClass()
10782976

Is this possible?

/Joakim

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


Re: Hash of class from instance

2005-02-02 Thread Duncan Booth
Joakim Storck wrote:

> Is there any way that I can find the hash value of a class from an
> instance?
> 

You only had to post the question once. It seems a strange thing to want, 
but just do:

hash(a.__class__)

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


Re: Hash of class from instance

2005-02-02 Thread Joakim Storck
Thanks!

Not so strange I think, the hash values of classes will be used as keys
in a dictionary that serve as an object pool.

Sorry about the double posting, I got a 'server error' message the
first time, so I figured it hadn't gone trhough.

/Joakim

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


Re: how to write a tutorial

2005-02-02 Thread Dan Perl

"Xah Lee" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> i've noticed that in Python official doc
> http://python.org/doc/lib/module-re.html
> and also How-To doc
> http://www.amk.ca/python/howto/regex/
>
> both mentions the book "Mastering Regular Expressions" by Jeffrey
> Friedl.
>
> I suggest it be dropped in both places. The mentioning of this book in
> the Perl/Python community is mostly a fawning behavior and confession
> that the author is among "in the know". This book and its mentioning is
> a cultish behavior among OpenSource morons.
>
> Most of the time, its mentioning as a reference is irrelevant. 99% uses
> of regex are the simplest uses. Spending time to read this book of
> specialization, from economy perspective, is a waste of time.
> Xah

We should drop the olympics too.  99% of  people don't practice any of those 
sports at a competitive level.  Who the hell does pole vaulting or throws a 
javelin?

Sorry, maybe I should have posted this in the "next Xah Lee post contest" 
thread.

Dan 


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


Re: what's OOP's jargons and complexities?

2005-02-02 Thread Bradd W. Szonye
Grumble <[EMAIL PROTECTED]> wrote:
> Pascal Bourguignon wrote:
> 
>> You forgot to mention the coordinates of your secret mountain compound:
>> 
>>28 deg 5 min N, 86 deg 58 min E
> 
> Mount Everest?

Shhh!
-- 
Bradd W. Szonye
http://www.szonye.com/bradd
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 2.4.0)

2005-02-02 Thread Leeuw van der, Tim
Hi all,

I can use this version of gtk and PyGtk to run simple programs. There seems to 
be no problem with the code-completion in PythonWin.
I can do: dir(gtk) without problems after importing the gtk module of PyGtk, 
when I use idle or console. (Python version for this test: python2.4, python 
2.3.5rc1)

I already knew that I could run simple PyGtk programs with this combination of 
Python, PyGtk, and Gtk. Also knew already, that the code completion in the 
PythonWin IDE works.
The crash comes when invoked from pydev under eclipse. So I can't remove them 
from the equation (I mentioned the problem also on the Pydev Sourceforge-forum, 
but decided to post here since it's the interpreter crashing).

It's the "send/don't send" type of error box, so I choose "don't send" at that 
point since that will only send crash info to Microsoft... no point in that! :-)

It could of course be a problem in the GTK DLLs and I haven't yet had time to 
test with older GTK versions. Hopefully I can try that tomorrow.

cheers,

--Tim


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Stefan Behnel
Sent: Wednesday, February 02, 2005 3:59 PM
To: python-list@python.org
Subject: Re: Crashing Python interpreter! (windows XP, python2.3.4, 2.3.5rc1, 
2.4.0)



Leeuw van der, Tim schrieb:
> I'm using the following combination of software:
> - Pydev Eclipse plugin (pydev 0.8.5)
> - eclipse 3.0.1 
> - windows XP SP1
> - pygtk 2.4.1
> - GTK 2.6.1 (for windows32 native)

First of all, try tightening the field. Are all of these packages needed to 
reproduce the error? Try to start the interpreter in a command line window and 
see if it happens there, too. That eliminates Eclipse.


> When trying to get a list of possible completions for the 'gtk' import 
> object, the python interpreter crashes. Happens with all versions listed in 
> the subject: python 2.3.4, 2.3.5rc1, 2.4.0.

Might be a problem with GTK for Windows, I don't know.

Type
import gtk
Does that crash? Or is it something like
dir(gtk)

Try different versions of GTK and pygtk. Look at the pygtk homepage to see 
which combination is known to work.

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


  1   2   3   >