[ANN] Release 0.65.3 of Task Coach

2007-10-20 Thread Frank Niessink
Hi,

I'm happy to announce release 0.65.3 of Task Coach. This bugfix
release fixes one critical bug that affects users on the Windows
platform and several minor bugs that affect users on all platforms.

Bugs fixed:

* Don't leak GDI objects on Windows.
* Don't notify of new version when the user has just installed that version.
* Mail disappears from Outlook when dropped in TaskCoach. Try to use
Outlook to open mail attachment when it's the default mailer.
* Mail task doesn't work.
* Categories not sorted correctly.


What is Task Coach?

Task Coach is a simple task manager that allows for hierarchical
tasks, i.e. tasks in tasks. Task Coach is open source (GPL) and is
developed using Python and wxPython. You can download Task Coach from:

http://www.taskcoach.org

In addition to the source distribution, packaged distributions are
available for Windows XP/Vista, Mac OSX, and Linux (Debian and RPM format).

Note that Task Coach is alpha software, meaning that it is wise to back
up your task file regularly, and especially when upgrading to a new release.

Cheers, Frank
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ANN: cssutils 0.9.4a1

2007-10-20 Thread Christof Hoeke
what is it
--
A Python package to parse and build CSS Cascading Style Sheets.


main changes since 0.9.3
-
for full details see the relevant README file 
http://cssutils.googlecode.com/svn/tags/TAG_0.9.4a1/README.txt

main changes
- **FEATURE**: Added a new module ``cssutils.codec`` that registers 
a codec that can be used for encoding and decoding CSS. 
(http://www.w3.org/TR/2006/WD-CSS21-20060411/syndata.html#q23)

 - **FEATURE**: Added implementation of ``stylesheets.MediaQuery`` 
which are part of  stylesheets.MediaList. See the complete spec at 
http://www.w3.org/TR/css3-mediaqueries/ for details.

 + **API CHANGE**: ``CSSNamespacerule.uri`` is renamed to 
``CSSNamespaceRule.namespaceURI`` which is defined is CSSOM. ``uri`` is 
deprecated and still available but the constructor parameter is named 
``namespaceURI`` in any case now.

 + **API CHANGE**: As ``stylesheets.MediaQuery`` is implemented now 
all classes using an instance of ``stylesheets.MediaList`` are presented 
slightly different. Until now a simple list of string was given, now the 
list contains MediaQuery objects.

 + **API CHANGE**: ``_Property`` has been renamed to 
``css.Property`` and is used in context of ``CSSStyleDeclaration`` and 
``MediaQuery``. Attribute ``Property.value`` has been *de-deprecated* 
and may be used normally now (again). The Property constructor has only 
optional parameters now.

 + **API CHANGE**: Removed experimental class 
``SameNamePropertyList`` which was used in ``CSSStyleDeclaration`` and 
also method ``CSSStyleDeclaration.getSameNamePropertyList``. A new 
method ``CSSStyleDeclaration.getProperties()`` has been added which is 
simpler and more useful

 + **API CHANGE**: renamed attribute ``namespaces`` of CSSStyleSheet 
and Selector to ``prefixes`` as they really are the prefixes of declared 
namespaces

 + BUGFIX: Tantek hack (using ``voice-family``) should work now as 
SameNamePropertyList is removed and properties are kept in order

 - **CHANGE**: A completely new tokenizer and mostly also the parser 
have been reimplemented in this release. Generally it should be much 
more robust and more compliant now. It will have new errors and also 
some slight details in parsing are changed.

 + **Documentation**: Added some docs in reStructuredText format 
including a basic server to view it as HTML. The HTML may be published 
as well.


license
---
cssutils is published under the LGPL.


download

for download options for cssutils 0.9.4a1 - 071020 see 
http://cthedot.de/cssutils/

cssutils needs
* Python 2.4 or higher (tested with Python 2.5 on Vista only)


bug reports, comments, etc are very much appreciated!
thanks
Christof
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: class vs type

2007-10-20 Thread Stargaming
On Fri, 19 Oct 2007 12:21:25 -0400, Colin J. Williams wrote:

 Hrvoje Niksic wrote:
 Colin J. Williams [EMAIL PROTECTED] writes:
 
 In Python Types and Objects, Shalabh Chaturvedi says (in the Python
 3.0 documentation - New Style Classes)

 The term class is traditionally used to imply an object created by
 the class statement. However, classes are now synonymous with types.
 Built-in types are usually not referred to as classes. This book
 prefers using the term type for both built-in and user created types.

 Do we need two different words to describe what is essentially the
 same thing?
 
 We don't, not anymore, which is why the author chooses the word type
 for both in the last sentence.
 In this case, why do we continue to use the word class to generate a
 type?
[snip]
 Doesn't Python 3 provide an opportunity to move away from discussions
 about new_style vs old-style?  This an opportunity to treat old-style
 as a historical artefact, not requiring current explanation.


So, do we have to decide between 'instance' and 'object' as well?

Old-style classes *are* deprecated in favor of new-style classes 
(whoops!) but the term 'class' is still valid (IMO). It's a common phrase 
in the OO-world and removing it from a Python programmer's vocabulary 
(what essentially wouldn't work so well, I suspect) won't help.

If you're speaking about just the syntax, well okay, this could be 
sensible in some unification-focussed vocabulary-minimalistic manner. But 
combining the class _statement_ and the type _expression_ would 
essentially change class definitions into expressions.

Cheers,
Stargaming
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SQLObject - Connect to established DB with non-int 'id' field

2007-10-20 Thread Diez B. Roggisch
Sean DiZazzo schrieb:
 Hi all,
 
 I am just beginning with TurboGears and have run into a problem with
 SQLObject.
 
 I'm trying to connect to an established mysql DB, and use TurboGears
 to display results from the DB only.  The problem is that the DB
 already has an 'id' field that is a string as opposed to an int.
 SQLObject complains because it wants to use the id field for it's own
 purposes.
 
 How can I use TurboGears to get data out of this DB?

http://sqlobject.org/FAQ.html#non-integer-ids

While I personally prefer SQLObject over SQLAlchemy, the latter has 
better legacy-database-support. Maybe a switch would be the better solution.

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


Re: SQLObject - Connect to established DB with non-int 'id' field

2007-10-20 Thread Sean DiZazzo
On Oct 19, 11:51 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Sean DiZazzo schrieb:

  Hi all,

  I am just beginning with TurboGears and have run into a problem with
  SQLObject.

  I'm trying to connect to an established mysql DB, and use TurboGears
  to display results from the DB only.  The problem is that the DB
  already has an 'id' field that is a string as opposed to an int.
  SQLObject complains because it wants to use the id field for it's own
  purposes.

  How can I use TurboGears to get data out of this DB?

 http://sqlobject.org/FAQ.html#non-integer-ids

 While I personally prefer SQLObject over SQLAlchemy, the latter has
 better legacy-database-support. Maybe a switch would be the better solution.

 Diez

doh...I swear I looked there!  This time I see it.  Thanks.

~Sean

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


Re: __main__ : What is this?

2007-10-20 Thread Peter Otten
Steven D'Aprano wrote:

 On Sat, 20 Oct 2007 00:26:22 +, Matimus wrote:
 
 The common pattern:
 
 if __name__ == __main__:
   # do stuff
 
 IMHO better written:
 
 if __main__ == __name__:
 # do stuff
 
 Apart from looking weird, what's the difference?

In C this style is sometimes propagated as a means to avoid accidental
assignment:

if (main=main) {...} /* valid C, always true */
if (main=main) {...} /* syntax error */

In Python it would be cargo cult.

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


SWIG-PYTHON - Problem in header file inclusion

2007-10-20 Thread abarun22
Hi
I am facing a problem while including a C header file in the SWIG
interface file.  However the problem does not occur when i directly
copy the contents of header file in the same place.

My interface file read as follows.
/*  interface file dep.i  */
%module dep
%{
#include dep.h
%}
%inline %{
extern int  ReadDep (char* fname, DONfic* don, int nb2, int nb4);
%}

And my header file consists of the structure DONfic as shown below.
/* Header file dep.h */
typedef struct _DONfic {
   intnb_dep, nb_inc_dep, ncasec_dep;
   intmax_dep;
} DONfic;

From python i tried to access the C structure as a python class as
shown below.
/* File pydep.py*/
 import dep
...
 d = dep.DONfic()
Gives the following error message

Traceback (most recent call last):
 File pydep.py, line 5, in ?
   d = dep.DONfic()
AttributeError: 'module' object has no attribute 'DONfic'
The problem is that i cannot get access to the structure if i directly
include the file dep.h. On the other hand if i copy the contents of
the header file and paste it directly in to the header section of the
SWIG interface file it works.
It works for the following interface file .
%module dep
%{
typedef struct _DONfic {
   intnb_dep, nb_inc_dep, ncasec_dep;
   intmax_dep;
} DONfic;
%}
%inline %{
extern int  ReadDep (char* fname, DONfic* don, int nb2, int nb4);
%}


I tried out lot of options and does n't seems to work. Any suggestions
or ideas are most welcome.

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


is this a feasible solution??

2007-10-20 Thread [EMAIL PROTECTED]
chech wat is happening here..

http://www.createthefuturecontest.com/pages/view/entriesdetail.html?entryID=798

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


Re: open remote terminal

2007-10-20 Thread Fabian Braennstroem
Hi Steve,

Steve Holden wrote:

 Fabian Braennstroem wrote:
 Hi,
 
 I would like to use python to start an terminal, e.g. xterm, and login on
 a remote machine using rsh or ssh. This could be done using 'xterm -e ssh
 machine', but after the login I would like to jump to a given directory.
 Does anyone have an idea how to do this with python?
 
 Regards!
 Fabian
 
 pexpect would be the usual solution, I believe, if you could get it to
 interact correctly with your virtual terminal.
 
http://pexpect.sourceforge.net/

Thanks for the advice!
Fabian

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


Re: pyparsing batch file

2007-10-20 Thread Fabian Braennstroem
Hi Paul,

Paul McGuire wrote:

 On Oct 17, 4:47 pm, Fabian Braennstroem [EMAIL PROTECTED] wrote:
 snip
 Unfortunately, it does not parse the whole file names with
 the underscore and I do not know yet, how I can access the
 line with 'define/boundary-conditions'. Every 'argument' of
 that command should become a separate python variable!?
 Does anyone have an idea, how I can achieve this!?
 Regards!
 Fabian
 
 You are trying to match keps1500_500.dat with the expression
 Word(alphanums).  Since the filename contains characters other than
 alphas and numbers, you must add the remaining characters (. and
 _) to the expression.  Try changing:
 
 write= Word(alphanums)
 
 to:
 
 write= Word(alphanums+._)
 
 
 To help you to parse /define/boundary-conditions in velocity-inlet 10
 0.1 0.1 no 1, we would need to know just what these arguments are,
 and what values they can take.  I'll take a wild guess, and propose
 this:
 
 real = Combine(integer + . + integer)
 defineBoundaryConditions = /define/boundary-conditions + \
 oneOf(in out inout)(direction) + \
 Word(alphanums+-)(conditionName) + \
 integer(magnitude) + \
 real(initialX) + \
 real(initialY) + \
 oneOf(yes no)(optional) + \
 integer(normal)
 
 (Note I am using the new notation for setting results names,
 introduced in 1.4.7 - simply follow the expression with (name),
 instead of having to call .setResultsName.)
 
 And here is a slight modification to your printout routine, using the
 dump() method of the ParseResults class:
 
 for tokens in defineBoundaryConditions.searchString(data):
 print
 print Boundary Conditions = + tokens.conditionName
 print tokens.dump()
 print
 print 50*-
 
 
 prints:
 
 Boundary Conditions = velocity-inlet
 ['/define/boundary-conditions', 'in', 'velocity-inlet', '10', '0.1',
 '0.1', 'no', '1']
 - conditionName: velocity-inlet
 - direction: in
 - initialX: 0.1
 - initialY: 0.1
 - magnitude: 10
 - normal: 1
 - optional: no

Great! Thanks for the very good explanation! 

Regards!
Fabian





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


How can i store pickle dumps data ?

2007-10-20 Thread Abandoned
Hi..
I have some dictionary as {2:3, 4:6, 5:7.}
I want to pickle to these dictionary and save to database but i
couldn't..

My code for adding..
a=eval(dict)
a=pickle.dumps(a, -1)
cursor2.execute(INSERT INTO cache VALUES ('%s', %s), (x[0],a))
conn2.commit()

i try in UTF-8 postresql database (data type BYTEA) and it gives me
this error:
 psycopg2.ProgrammingError: invalid byte sequence for encoding UTF8:
 0x80
 HINT:  This error can also happen if the byte sequence does not match
 the encoding expected by the server, which is controlled by
 client_encoding.

i try in LATIN5 postgresql database (data type BYTEA) and it add first
10 element and than gives me this error:
cursor2.execute(INSERT INTO cache VALUES ('%s', %s), (x[0],a))
psycopg2.ProgrammingError: invalid input syntax for type bytea

i try in LATIN5 (data type TEXT) and it add all element but when i
want to load it give me this error:
pickle.loads(SELECTED_DATA);
EOFError


Now how can i store the pickle data ?
Which encoding and which data type ?
Please help me i'm sorry my bad english.
King Regards..

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


Display all properties with reflection

2007-10-20 Thread sccs cscs
Hello,
I like create a methode that display all the properties of an instance of 
classe with their value.
I try the following code: see def __str__ (self) methode.
But it displays only the instance attributes values not the properties and 
their value.
In pseudo-code:
For Each Properties :
   print  property_name,  property_value

It is possible ? Where is the collection of properties into the Python Object 
Metamodele?

Thank you.
Zorgi

class PhysicalObject(Subject):

Base class for physical Object
They inherit from Subject whose contract are:
def attach(self, observer)
def detach(self, observer)
def notify(self, modifier = None)


def __init__(self, World, Space, ThePhysicalProperties):



#Initialize Subject-Observers mecanism
Subject.__init__(self)
self.__name  = None


...
def __str__ (self):

Return a string that describe the value of all attributes for the 
instance

result = None
msgList = [%s ---%s%(str(attribute), str(value)) for (attribute, 
value) in  self.__dict__.items()]
msgList.sort()
result  = \n\n%s instance : % (self.__class__.__name__)
result += \n.join (msgList)
return result

 
Name   = property(fget = __getName,   fset = 
__setName)
Position   = property(fget = __getPosition,   fset = 
__setPosition)
LinearVelocity = property(fget = __getLinearVelocity, fset = 
__setLinearVelocity)
AngularVelocity= property(fget = __getAngularVelocity, fset = 
__setAngularVelocity)
RotationMatrice= property(fget = __getRotationMatrice,fset = 
__setRotationMatrice)
Masse  = property(fget = __getMass,  fset = 
__setMass)
GravityMode= property(fget = __getGravityMode,fset = 
__setGravityMode)




 
-
 Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Running another python interpreter

2007-10-20 Thread Simon Pickles
This is very nearly perfect. I have a second console window. 
Unfortunately, the first is waiting for the second to close. Is there 
anyway to specify the equivalent of os.P_NOWAIT?

Gabriel Genellina wrote:
 --- Simon Pickles [EMAIL PROTECTED] escribió:

   
 os.spawnl(os.P_NOWAIT, sys.executable,
 sys.executable, gateway.py)
 ... works but both process output to the same
 interpreter window. Is there a way to run another
 interpreter window containing gateway.py?
 

 Use the subprocess module, passing CREATE_NEW_CONSOLE into creationflags:

 subprocess.call([sys.executable, gateway.py, other, arguments],
  creationflags = subprocess.CREATE_NEW_CONSOLE)

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


Re: open remote terminal

2007-10-20 Thread Fabian Braennstroem
Fabian Braennstroem wrote:

 Hi Steve,
 
 Steve Holden wrote:
 
 Fabian Braennstroem wrote:
 Hi,
 
 I would like to use python to start an terminal, e.g. xterm, and login
 on a remote machine using rsh or ssh. This could be done using 'xterm -e
 ssh machine', but after the login I would like to jump to a given
 directory. Does anyone have an idea how to do this with python?
 
 Regards!
 Fabian
 
 pexpect would be the usual solution, I believe, if you could get it to
 interact correctly with your virtual terminal.
 
http://pexpect.sourceforge.net/

I actually gave it a first very simple try:

import pexpect
child=pexpect.spawn('xterm')
child.sendline('ls')

Unfortunately nothing happens expect the start of xterm!? Does anyone have
an idea, what I am doing wrong?
Fabian

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


Re: how to iterate over sequence and non-sequence ?

2007-10-20 Thread stef mientki
Paul Hankin wrote:
 On Oct 19, 5:38 pm, stef mientki [EMAIL PROTECTED] wrote:
   
 ... snip hand-coded debugger
 I couldn't come up with a better solution ;-)
 

 Does pdb not suffice?
   
thanks very much Paul,
Never heard of that before,
I looked it up, just 1 page in my book of 500 pages ;-)
I'm certainly going to study that.

 Even if it doesn't; you can look up variables without using exec,
 using locals()['x'] or globals()['x']

   
Didn't know that either,
I'll try.

thanks,
Stef Mientki
 --
 Paul Hankin

   

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


Re: how to iterate over sequence and non-sequence ?

2007-10-20 Thread stef mientki
snip
 def user_program():
   x = 5; _debug(2)
   global x,i
   _debug (3)
   for i in xrange(10):
   _debug (3)
   x = x + 1; _debug (4)
 

 You do know that Python exposes all of it's compilation / AST / whatever 
 machinery, don't you ? IOW, you can take a textual program, compile it 
 to a code object, play with the AST, add debug hooks, etc... Perhaps you 
 should spend a little more time studying the modules index ?
   
thanks Bruno,
but you're talking about terminology I don't know:
compilation / AST / IOW / module index ???

But to be honest it's not my main goal.
My goal is to write a functional simulator.
You can compare it with a little travelling,
I want to go from A to B.
Normally I'ld travel by bus or train,
but in this case there isn't going a bus to B.
So in this case I take a car,
ask someone how to start it,
and drive to B.

But anyway thanks very much for this and other answers.
cheers,
Stef Mientki


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


what is the difference between the two kinds of brackets?

2007-10-20 Thread [EMAIL PROTECTED]
hi

what is the difference between the two kinds of brackets?
I tried a few examples but I can't make out any real difference:
lst = [10, 20, 30]
print lst[0]
print lst[2]
print lst
lst = (10, 20, 30)
print lst[0]
print lst[2]
print lst

lst = [10, 20, 40, string, 302.234]
print lst[0:2]
print lst[:3]
print lst[3:]
lst = (10, 20, 40, string, 302.234)
print lst[0:2]
print lst[:3]
print lst[3:]

10
30
[10, 20, 30]
10
30
(10, 20, 30)
[10, 20]
[10, 20, 40]
['string', 302.233998]
(10, 20)
(10, 20, 40)
('string', 302.233998)

Are these two kinds of brackets mean the same thing in the list
context? Thanks.

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


Re: how to iterate over sequence and non-sequence ?

2007-10-20 Thread stef mientki
Steven D'Aprano wrote:
 On Fri, 19 Oct 2007 18:38:06 +0200, stef mientki wrote:

   
 I don't have pointers, I've just names (at least I think). Let me
 explain a little bit more,
 I want to simulate / debug a user program, the user program might look
 like this:

x = 5
for i in xrange(10):
x = x + 1
 


 I thought you were writing a JAL interpreter:

 http://en.wikipedia.org/wiki/JAL_(compiler)

   
hi Steven, you're completely right,
in fact I want to some more: also taken hardware and physics into account.
You can see one of my first demo's here, to see what I mean:
   http://stef.mientki.googlepages.com/jalspy_demo_robot1a.html
and some more demos can be found over here:
   
http://oase.uci.kun.nl/~mientki/data_www/pic/jalspy/jalspy_animated_demos.html
In fact we already used the simulator a number of times in real 
applications with great success,
but didn't release it yet, because you still need Python knowledge to 
run it reliable.
 but the code above is Python.
   
Yes, right again ;-)
The simulator translates JAL into Python,
In the beginning I thought that was the easiest,
I'm not sure about that anymore at the moment,
but on the other hand that's just replacing one module.
 Python already has a debugger. Try this:

 import pdb
 help(pdb)

   
Yes, Paul also pointed me into that direction,
and to be honest, I expected there would be such a module,
but I never searched for it, because 
If I see that I can cook dinner,
when I (very seldom) test the program  (I'm writing) in the debug mode,
(assuming the IDE uses the same pdb),
then this is far too slow :-(

I'll report back what my experiences are with pdb.

cheers,
Stef Mientki



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


Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread Thomas Jollans
On Saturday 20 October 2007, [EMAIL PROTECTED] wrote:
 hi

 what is the difference between the two kinds of brackets?
 I tried a few examples but I can't make out any real difference:

Lists are mutable, tuples aren't:

Python 2.4.4 (#2, Aug 16 2007, 00:34:54)
[GCC 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)] on linux2
Type help, copyright, credits or license for more information.
 l = [1,2,3]
 t = (1,2,3)
 type(l)
type 'list'
 type(t)
type 'tuple'
 l[0]
1
 t[0]
1
 l[0] = 12
 t[0] = 12
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: object does not support item assignment


Also, parentheses can be skipped (as in t = 1,2,3), the comma is the maker for 
a tuple (exception: empty tuple == (), but one-element-tuple == (foo,))


-- 
  Regards,   Thomas Jollans
GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu
Hacker key http://hackerkey.com/:
v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6


signature.asc
Description: This is a digitally signed message part.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread James Stroud
[EMAIL PROTECTED] wrote:
 hi
 
 what is the difference between the two kinds of brackets?
 I tried a few examples but I can't make out any real difference:
 Are these two kinds of brackets mean the same thing in the list
 context? Thanks.


The square ones designate lists:

 http://docs.python.org/tut/node7.html

The rounded ones designate tuples:

 http://docs.python.org/tut/node7.html#SECTION00730

The short of it is that lists can change and tuples can not.

commentaryThe long of it is that there are deep computer-science 
issues that distinguish the two and the differences become more 
important the more you know (presumably). However, I have been 
programming this language for 5 years, and I still can't figure out the 
necessity for having both. I have heard all of the arguments, however 
but none are terribly pursuasive./commentary

Practically speaking, however, if you don't know which one to use, then 
use the square kind.

James


-- 
James Stroud
UCLA-DOE Institute of Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help with my first Twisted program

2007-10-20 Thread Bjoern Schliessmann
McCann, Brian wrote:

 I posted this to the Twisted list...figured I'd try here too.

Didn't you get an answer? The cracks for special topics are usually
there.
 
 to work right.  Looking through the API docs I found
 connectionLost(), which I put in my protocol class (EchoProtocol
 in the example), but it's
 never getting called.  Here's my connectionLost def:
 
 def connectionLost(self,reason):
 print lost:%s %reason
 self.serialServerSocket.close()
 self.alive = False
 self.serialSocketReadThread.join()
 
 Can someone please tell me what I'm doing wrong?

No, since the definition of a never called function won't help.

Try the following standard strategy: Make a copy of your project and
reduce it (removing functionality) until the error doesn't appear
anymore. If it does *not* vanish, post your short code here or in
the Twisted list.

Regards  happy hunting,


Björn

-- 
BOFH excuse #366:

ATM cell has no roaming feature turned on, notebooks can't connect

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


Re: vote for Python - PLEASE

2007-10-20 Thread Bjoern Schliessmann
Steven D'Aprano wrote:
 It's an Internet poll. By definition, the results are meaningless.

Regrettably, there are many people that don't share your definition.

Also, why would there be telephone votings in TV if they were
meaningless to the default watcher? :) 

Regards,


Björn

-- 
BOFH excuse #225:

It's those computer people in X {city of world}.  They keep stuffing
things up.

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


Re: vote for Python - PLEASE

2007-10-20 Thread Amit Khemka
On 10/19/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 On Oct 18, 6:12 pm, Monty Taylor [EMAIL PROTECTED] wrote:
  Hey everybody,
 
  MySQL has put up a poll onhttp://dev.mysql.comasking what your primary
  programming language is.

 But it doesn't ask that, it asks what your
 primary programming language is FOR DEVELOPING
 MYSQL APPLICATIONS.

 In my case, there is no such language (even though
 I primarily use Python) BECAUSE I DON'T USE MYSQL.


  Even if you don't use MySQL - please go stick
  in a vote for Python. I'm constantly telling folks that Python needs
  more love, but PHP and Java are kicking our butts...
 
  (I know the world would be a better place if the poll were honest,

 There is dishonestly and there's outright lying

  but
  I'd rather that people got the message that they should do more python
  development work!)

 Maybe the Python community doesn't need your help.

I do use mysql with python bindings, but it was a pleasant surprise to
see python was ahead of other languages. Though i too doubt the
meaning and genuineness of such internet polls. But may be there are
similar people in every community who would try to spread the word and
get more votes for 'their' language, hence actually helping to
normalize the results !

 However even if the poll results do not accurately reflect the
intended purpose, they may be, just may be, give an idea of size of
community and just how much that 'one' lie they will live with to see
'their' language ahead ;-) !

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


Re: Elisp Tutorial: HTML Syntax Coloring Code Block

2007-10-20 Thread Steve Holden
Byung-Hee HWANG wrote:
[... whole article quoted ...]
 +1 ;;
 BTW, what is G2/1.0? Is that Emacs-like editor?
 
I can't tell you that, but I do know that someone who quotes a whole 
lengthy article like that just to ask a simple question isn't being very 
considerate of their readers.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it

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


Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread Steve Lamb
On 2007-10-20, James Stroud [EMAIL PROTECTED] wrote:
commentaryThe long of it is that there are deep computer-science 
 issues that distinguish the two and the differences become more 
 important the more you know (presumably). However, I have been 
 programming this language for 5 years, and I still can't figure out the 
 necessity for having both. I have heard all of the arguments, however 
 but none are terribly pursuasive./commentary

The quick answer is that tuples can be indexes into directories while
lists cannot.  This doesn't seem like that big of a deal until you realize it
allows you to group related but distict bits of data together to form an index
while retaining their individual identity.  A simplistic example would be if
you had a map with x,y coordinates and you wanted to place items on that map
at their location.

[EMAIL PROTECTED]:~} python
Python 2.4.4 (#2, Aug 16 2007, 02:03:40) 
[GCC 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)] on linux2
Type help, copyright, credits or license for more information.
 x = 1
 y = 1
 coord = (x, y)
 map = {}
 map[coord] = Something at x%s, y%s % coord
 map
{(1, 1): 'Something at x1, y1'}
 map[(1,1)]
'Something at x1, y1'
 if map.has_key(coord):
... print Found it!
... 
 if map.has_key((1,1)):
... print Found it!
... 
Found it!
 for loc in map:
... print X: %s, Y: %s - %s % (loc[0], loc[1], map[loc])
... 
X: 1, Y: 1 - Something at x1, y1

The lists cannot be indexes to directories because they are mutable.  
[1. 1] might not be [1, 1] the next time you look for it.  (1, 1) always will.  

-- 
 Steve C. Lamb | But who decides what they dream?
   PGP Key: 1FC01004   |   And dream I do...  
---+-

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


Re: open remote terminal

2007-10-20 Thread Rafael Sachetto
Take a look at this documentation:

http://pexpect.sourceforge.net/pxssh.html

On 10/20/07, Fabian Braennstroem [EMAIL PROTECTED] wrote:

 Fabian Braennstroem wrote:

  Hi Steve,
 
  Steve Holden wrote:
 
  Fabian Braennstroem wrote:
  Hi,
 
  I would like to use python to start an terminal, e.g. xterm, and login
  on a remote machine using rsh or ssh. This could be done using 'xterm
 -e
  ssh machine', but after the login I would like to jump to a given
  directory. Does anyone have an idea how to do this with python?
 
  Regards!
  Fabian
 
  pexpect would be the usual solution, I believe, if you could get it to
  interact correctly with your virtual terminal.
 
 http://pexpect.sourceforge.net/

 I actually gave it a first very simple try:

 import pexpect
 child=pexpect.spawn('xterm')
 child.sendline('ls')

 Unfortunately nothing happens expect the start of xterm!? Does anyone have
 an idea, what I am doing wrong?
 Fabian

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




-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Dealing with funny characters

2007-10-20 Thread sophie_newbie
Hi, I want to store python text strings that characters like é Č
in a mysql varchar text field. Now my problem is that mysql does not
seem to accept these characters. I'm wondering if there is any way I
can somehow encode these characters to appear as normal characters
and then decode them when I want to get them out of the database
again?

-Thanks.

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

Re: __main__ : What is this?

2007-10-20 Thread Duncan Booth
Matt McCredie [EMAIL PROTECTED] wrote:

 or, as I prefer:
 
 a = 'c' == b
 
 It is just habit from writing so much C code that way. In C the
 reasoning is that if you have mistyped it, you will catch the issue at
 compile time instead of runtime (which is potentially much more
 difficult to debug). I'm used to seeing that pattern. In terms of
 natural language I do agree with you. It really is just my _humble_
 opinion. I can't make a huge argument for it in Python. To be honest,
 I didn't give it much thought before I wrote it. I am simply used to
 doing it that way, and being irked whenever I see it written the other
 way in C or C++ (and perhaps unjustifiably Python).

Alternatively you could just tell your C compiler to regard dodgy looking 
assignments as an error and stop worrying about it. Much less hassle all 
round.

e.g. For gcc -Werror -Wparentheses, for Microsoft compiler -W4 -WX, or an 
appropriate #pragma in a header file for each.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elisp Tutorial: HTML Syntax Coloring Code Block

2007-10-20 Thread Byung-Hee HWANG
Steve,

On Sat, 2007-10-20 at 08:30 -0400, Steve Holden wrote:
 Byung-Hee HWANG wrote:
 [... whole article quoted ...]
  +1 ;;
  BTW, what is G2/1.0? Is that Emacs-like editor?
  
 I can't tell you that, but I do know that someone who quotes a whole 
 lengthy article like that just to ask a simple question isn't being very 
 considerate of their readers.

You're the only guy who has read the my comment. Thanks!

-- 
Byung-Hee HWANG * مجاهدين
InZealBomb, Kyungpook National University, KOREA

What I care about is that you obviously don't love me.
-- Kay Adams, Chapter 25, page 359
-- 
http://mail.python.org/mailman/listinfo/python-list

weakref pitfall

2007-10-20 Thread Odalrick
I'm trying to write a simple game and decided I need an eventmanager.

code
import weakref
from collections import defaultdict

class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )

def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter

def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None  )

def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )

eventmanager = _EventManager()

__all__ = [ eventmanager ]
/code

Fairly simple, yet there was some strange bug that prevented my game
from exiting.

I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.

Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?

code
import pygame
from eventmanager import eventmanager

class MainGame( object ):
def __init__( self, width=1024, height=768 ):
#Initialize PyGame
pygame.init()
self.width = width
self.height = height
self.quit_game = False
#Create the Screen
self.screen = pygame.display.set_mode( ( self.width,
self.height ) )
eventmanager.register( self.handle_quit, pygame.QUIT )
eventmanager.register( self.handle_quit, pygame.KEYDOWN,
key_filter( pygame.K_ESCAPE ) )

def mainloop( self ):
handle_event = eventmanager.handle_event
self.quit_game = False
while not self.quit_game:
for event in pygame.event.get():
handle_event( event )

def handle_quit( self, event=None ):
self.quit_game = True

def key_filter( key ):
def filter( event ):
return event.key == key
return filter

def handle_print_event( event ):
print str( event )

if __name__ == __main__:
game = MainGame()
game.mainloop()
/code

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


Re: Dealing with funny characters

2007-10-20 Thread Paul Hankin
On Oct 20, 2:13 pm, sophie_newbie [EMAIL PROTECTED] wrote:
 Hi, I want to store python text strings that characters like é Č
 in a mysql varchar text field. Now my problem is that mysql does not
 seem to accept these characters. I'm wondering if there is any way I
 can somehow encode these characters to appear as normal characters
 and then decode them when I want to get them out of the database
 again?

Use unicode strings, and use the 'encode' and 'decode' methods. Mysql
has utf8 support for varchars, so that seems a likely encoding to use.
If you're stuck with ascii, you can use 'unicode_escape' if you're
only accessing it from python.

But first read this excellent article on 'funny' characters:
http://www.joelonsoftware.com/articles/Unicode.html

--
Paul Hankin

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

Re: weakref pitfall

2007-10-20 Thread Paul Hankin
On Oct 20, 2:47 pm, Odalrick [EMAIL PROTECTED] wrote:
 I'm trying to write a simple game and decided I need an eventmanager.

 code
 import weakref
 from collections import defaultdict

 class _EventManager( object ):
 def __init__( self ):
 self._handled_events =
 defaultdict( weakref.WeakKeyDictionary )

 def register( self, handler, event_type, filter=None ):
 self._handled_events[event_type][handler] = filter

 def deregister( self, handler, event_type ):
 self._handled_events[event_type].pop( handler, None  )

 def handle_event( self, event ):
 event_type = event.type
 for handler, filter in
 self._handled_events[event_type].items():
 if filter == None or filter(event):
 handler( event )

 eventmanager = _EventManager()

 __all__ = [ eventmanager ]
 /code

 Fairly simple, yet there was some strange bug that prevented my game
 from exiting.

 I think what happened was that when __init__ ends, self goes out of
 scope, and by extension so does self.handle_quit, Now there are no
 more refeences to self.handle_quit, because weakrefs don't count, and
 the event gets automatically dropped from my eventmanager. I thought
 that wouldn't happen because handle_quit is part of the class and
 instance MainGame.

 Am I right in my guess? If so, how should I adress this bug? If not,
 what is the bug?

The next stage in debugging is to think of a test that will prove your
guess right or wrong. I'd remove weakrefs from your event manager and
see if your code starts working.

I'd suggest you're a bit confused about your event manager's API: you
have register/deregister methods and are also using weakrefs to
provide auto-deregistering. I don't know your code, but this looks
like a mistake to me - can you justify (to yourself) that you need
both ways?

--
Paul Hankin

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


Re: where do I need to tab?

2007-10-20 Thread Scott David Daniels
Gabriel Genellina wrote:
 En Fri, 19 Oct 2007 23:24:30 -0300, Scott David Daniels 
 ...
 OK, you have a mix of Python 3,0 and current (2.5.1) Python.
 
 All examples are OK for 2.5

You are absolutely correct.  Sorry for the misinformation.  I've been
working on 2.3, 2.4, 2.5, and trying 3.0 alphas and had shoved the
(a if b else c) expression to the wrong group mentally.  I try to
stay working in the subset that exists or can be hand-implemented,
so I avoid the 2.5 code so often that I forgot it was ther.

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


Re: Dealing with funny characters

2007-10-20 Thread Gert-Jan
sophie_newbie schreef:
 Hi, I want to store python text strings that characters like é Č
 in a mysql varchar text field. Now my problem is that mysql does not
 seem to accept these characters. I'm wondering if there is any way I
 can somehow encode these characters to appear as normal characters
 and then decode them when I want to get them out of the database
 again?


It seems you'll have to use Unicode in your program rather than 'plain' 
strings.

Before storing an unicode textstring in a database or a file, you must 
encode it using an appropriate encoding/codepage, for example:

outputstring = unicodeobject.encode('utf-8')


This is not an easy subject. But it isn't very hard either. Please 
search the Python documentation using these keywords: Unicode, decoding 
and encoding.


But you should read this first: 
http://www.joelonsoftware.com/articles/Unicode.html
It's an entertaining introduction to the world of codepages and unicode :-)


Regards,
Gert-Jan

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

Re: vote for Python - PLEASE

2007-10-20 Thread Robin Becker
Monty Taylor wrote:
 Hey everybody,
 
 MySQL has put up a poll on http://dev.mysql.com asking what your primary 
 programming language is. Even if you don't use MySQL - please go stick 
 in a vote for Python. I'm constantly telling folks that Python needs 
 more love, but PHP and Java are kicking our butts...
 
 (I know the world would be a better place if the poll were honest, but 
 I'd rather that people got the message that they should do more python 
 development work!)
 
 Thanks!
 Monty
well I did vote as we use python+mysql; I dispute the value of kicking 
our butts though. When I voted python was running at 39.8% about equal 
to java+php (41.4%).
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can i store pickle dumps data ?

2007-10-20 Thread Diez B. Roggisch
Abandoned schrieb:
 Hi..
 I have some dictionary as {2:3, 4:6, 5:7.}
 I want to pickle to these dictionary and save to database but i
 couldn't..
 
 My code for adding..
 a=eval(dict)
 a=pickle.dumps(a, -1)
 cursor2.execute(INSERT INTO cache VALUES ('%s', %s), (x[0],a))
 conn2.commit()
 
 i try in UTF-8 postresql database (data type BYTEA) and it gives me
 this error:
 psycopg2.ProgrammingError: invalid byte sequence for encoding UTF8:
 0x80
 HINT:  This error can also happen if the byte sequence does not match
 the encoding expected by the server, which is controlled by
 client_encoding.
 
 i try in LATIN5 postgresql database (data type BYTEA) and it add first


http://mail.python.org/pipermail/python-list/2004-September/280867.html


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


Re: weakref pitfall

2007-10-20 Thread Odalrick
On 20 Okt, 16:21, Paul Hankin [EMAIL PROTECTED] wrote:

 The next stage in debugging is to think of a test that will prove your
 guess right or wrong. I'd remove weakrefs from your event manager and
 see if your code starts working.

 I'd suggest you're a bit confused about your event manager's API: you
 have register/deregister methods and are also using weakrefs to
 provide auto-deregistering. I don't know your code, but this looks
 like a mistake to me - can you justify (to yourself) that you need
 both ways?

 --
 Paul Hankin

Yes, I did a test with a standard dict and that removed the bug,
should have mentioned that.

And, no, I'm not sure I need both. Currently I'm using the standard
dict.

I'm fairly sure I'll need to manually deregister sometimes, buttons
and whatnot, but automatic deregistration sounds nice for later when
I'll have hundreds of sprites flying around.


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


Re: weakref pitfall

2007-10-20 Thread Peter Otten
Odalrick wrote:

 I'm trying to write a simple game and decided I need an eventmanager.
 
 code
 import weakref
 from collections import defaultdict
 
 class _EventManager( object ):
 def __init__( self ):
 self._handled_events =
 defaultdict( weakref.WeakKeyDictionary )
 
 def register( self, handler, event_type, filter=None ):
 self._handled_events[event_type][handler] = filter
 
 def deregister( self, handler, event_type ):
 self._handled_events[event_type].pop( handler, None  )
 
 def handle_event( self, event ):
 event_type = event.type
 for handler, filter in
 self._handled_events[event_type].items():
 if filter == None or filter(event):
 handler( event )
 
 eventmanager = _EventManager()
 
 __all__ = [ eventmanager ]
 /code
 
 Fairly simple, yet there was some strange bug that prevented my game
 from exiting.
 
 I think what happened was that when __init__ ends, self goes out of
 scope, and by extension so does self.handle_quit, Now there are no
 more refeences to self.handle_quit, because weakrefs don't count, and
 the event gets automatically dropped from my eventmanager. I thought
 that wouldn't happen because handle_quit is part of the class and
 instance MainGame.

No, self is yet another reference to the _EventManager instance which
survives the __init__() call because it is also referenced by the
global variable eventmanager.
On the other hand, self.handle_quit creates a new bound-method object every
time which doesn't even live as long as __init__().
 
 Am I right in my guess? If so, how should I adress this bug? If not,
 what is the bug?

The easiest option, to forget about weakrefs, seems to be the best
here. The other option is to keep a reference to the bound method, e. g.:

class MainGame(object):
def __init__(self, ...):
# put a bound method into the MainGame instance
# you can use a different attribute name if you want
hq = self.handle_quit = self.handle_quit
# register it
eventmanager.register(hq, ...)

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


pydoc script.py vs. pydoc scriptpy

2007-10-20 Thread BartlebyScrivener
On Debian Etch, if ~/mypyscripts is in my bash PATH and also in
PYTHONPATH, I get the following pydoc behaviors. Maybe this is
intentional. I'm just checking to be sure I don't have something
misconfigured in my environment.

If I have two scripts or modules  in ~/mypyscripts: one script.py and
one scriptpy (no extension), and do:

$pydoc script

I get the documentation strings for script.py.

However, if I do:

$pydoc scriptpy

I get no doc strings, even if I am in the ~/mypyscripts directory,
error message:
no Python documentation found for 'scriptpy'

Instead I must do:

$pydoc ~/mypyscripts/scriptpy

even though ~/mypyscripts is in both PATH and PYTHONPATH

Took me awhile to sort this out. Is this the way pydoc is supposed to
work?

thanks,

rpd

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


Re: Noob: Loops and the 'else' construct

2007-10-20 Thread Thorsten Kampe
* Dustan (Fri, 19 Oct 2007 11:39:04 -)
 On Oct 19, 3:12 am, Thorsten Kampe [EMAIL PROTECTED] wrote:
  So a for/else loop is exactly the same thing as a for loop with the
  else clause outside the loop (except for break)?
 
 Am I missing something here? It sounds to me like you just described
 two identical constructs.

#
for i in range(10):
print i
else:
print 'the end!'
#

is the same else

#
for i in range(10):
print i
print 'the end!'
#
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can i store pickle dumps data ?

2007-10-20 Thread Abandoned
On Oct 20, 5:32 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Abandoned schrieb:





  Hi..
  I have some dictionary as {2:3, 4:6, 5:7.}
  I want to pickle to these dictionary and save to database but i
  couldn't..

  My code for adding..
  a=eval(dict)
  a=pickle.dumps(a, -1)
  cursor2.execute(INSERT INTO cache VALUES ('%s', %s), (x[0],a))
  conn2.commit()

  i try in UTF-8 postresql database (data type BYTEA) and it gives me
  this error:
  psycopg2.ProgrammingError: invalid byte sequence for encoding UTF8:
  0x80
  HINT:  This error can also happen if the byte sequence does not match
  the encoding expected by the server, which is controlled by
  client_encoding.

  i try in LATIN5 postgresql database (data type BYTEA) and it add first

 http://mail.python.org/pipermail/python-list/2004-September/280867.html

 Diez- Hide quoted text -

 - Show quoted text -

Yes this is wonderfull.
I am very happy thank you very much Diez.

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


Re: Dealing with funny characters

2007-10-20 Thread John Nagle
Gert-Jan wrote:
 sophie_newbie schreef:
 Hi, I want to store python text strings that characters like é Č
 in a mysql varchar text field. Now my problem is that mysql does not
 seem to accept these characters. I'm wondering if there is any way I
 can somehow encode these characters to appear as normal characters
 and then decode them when I want to get them out of the database
 again?
 
 
 It seems you'll have to use Unicode in your program rather than 'plain' 
 strings.
 
 Before storing an unicode textstring in a database or a file, you must 
 encode it using an appropriate encoding/codepage, for example:
 
 outputstring = unicodeobject.encode('utf-8')

No, no, that's wrong.  MySQL and the Python interface to it understand
Unicode.  You don't want to convert data to UTF-8 before putting it in a
database; the database indexing won't work.

Here's how to do it right.

First, tell MySQL, before you create your MySQL tables, that the tables are
to be stored in Unicode:

ALTER database yourdatabasename DEFAULT CHARACTER SET utf8;

You can also do this on a table by table basis, or even for single fields,
but you'll probably get confused if you do.

Then, when you connect to the database in Python, use something like this:

db = MySQLdb.connect(host=localhost,
use_unicode = True, charset = utf8,
user=username, passwd=password, db=database)

That tells MySQLdb to talk to the database in Unicode, and it tells the database
(via charset) that you're talking Unicode.

Within Python, you can use Unicode as well.  If you have a Unicode text
editor, you can create Python source files in Unicode and have Unicode text
constants in quotes.  If you do this, you should put

# -*- coding: UTF-8 -*-

as the first line of Python files.  Quoted constants should be written
as

s = u'Test'

rather than

s = 'Test'

Instead of str(), use unicode().

Once everything is set up like this, you can pass Unicode in and out of MySQL
databases freely, and all the SQL commands will work properly on Unicode data.

John Nagle





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

what version python and wxPython comes with Mac OS X Leopard

2007-10-20 Thread chewie54
Hi All,

Does anyone know what version of Python and wxPython comes with the
new Mac OS X Leopard?

Thanks

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


Re: where do I need to tab?

2007-10-20 Thread Paul Hankin
On Oct 20, 3:00 am, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
 print b if ((b  a) and (b  (a * b))) else a

Everyone else has already pointed out that you need 2.5. As a matter
of style, the above line can be written more cleanly:

print b if a  b  a * b else a

--
Paul Hankin

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


Re: Dealing with funny characters

2007-10-20 Thread Diez B. Roggisch
No, no, that's wrong.  MySQL and the Python interface to it understand
 Unicode.  You don't want to convert data to UTF-8 before putting it in a
 database; the database indexing won't work.

I doubt that indexing has anything to do with it whatsoever.

Here's how to do it right.
 
First, tell MySQL, before you create your MySQL tables, that the 
 tables are
 to be stored in Unicode:
 
 ALTER database yourdatabasename DEFAULT CHARACTER SET utf8;
 
 You can also do this on a table by table basis, or even for single fields,
 but you'll probably get confused if you do.
 
Then, when you connect to the database in Python, use something like 
 this:
 
 db = MySQLdb.connect(host=localhost,
 use_unicode = True, charset = utf8,
 user=username, passwd=password, db=database)
 
 That tells MySQLdb to talk to the database in Unicode, and it tells the 
 database
 (via charset) that you're talking Unicode.

You confuse unicode with utf-8 here. And while this appears to be 
nitpicking, it is important to write this small program and meditate the 
better part of an hour in front of it running:

while True:
 print utf-8 is not unicode


You continue to make that error below, so I snip that.

The important part is this: unicode is a standard that aims to provide a 
codepoint for each and every character that humankind has invented. And 
python unicode objects can also represent all characters one can imagine.

However, unicode as such is an abstraction. Harddisks, network sockets, 
databases and the like don't deal with abstractions though - the eat 
bytes. Which makes it necessary to encode unicode objects to 
byte-strings when serializing them. Thus there are the thingies called 
encodings: latin1 for most characters used in westen europe for example. 
But it is limited to 256 characters (actually, even less), chinese or 
russian customers won't get too happy with them.

So some encodings are defined that are capable of encoding _ALL_ unicode 
codepoints. Either by being larger than one byte for each character. Or 
by providing escape-mechanisms. The former are e.g. UCS4 (4 bytes per 
character), the most important member of the latter is utf-8. Which uses 
ascii + escapes to encode all codepoints.

Now what does that mean in python?

First of all, the coding:-declaration: it tells python which encoding to 
use when dealing with unicode-literals, which are the

usomething

thingies. If you use a coding of latin1, that means that the text

uö

is expected to be one byte long, with the proper value that depicts the 
german umlaut o in latin1. Which is 0xf6.

If coding: is set to utf-8, the same string has to consist not of one, 
but of two bytes: 0xc3 0xb6.

So, when editing files that are supposed to contain funny characters, 
you have to

  - set your editor to save the file in an appropriate encoding

  - specify the same encoding in the coding:-declaration

Regarding databases: they store bytes. Mostly. Some allow to store 
unicode by means of one of the fixed-size-encodings, but you pay a 
storage-size penalty for that.

So - you we're right when you said that one can change the encoding a db 
uses, on several levels even.

But that's not all that is to it. Another thing is the encoding the 
CONNECTION expects byte-strings to be passed, and will use to render 
returned strings in. The conversion from and to the used storage 
encoding is done automagically.

It is for example perfectly legal (and unfortunately happens 
involuntarily) to have a database that internally uses utf-8 as storage, 
potentially being able to store all possible codepoints.

But due to e.g. environmental settings, opened connections will deliver 
the contents in e.g. latin1. Which of course will lead to problems if 
you try to return data from the table with the topmost chines first names.

So you can alter the encoding the connection delivers and expects 
byte-strings in. In mysql, this can be done explcit using

cursor.execute(set names encoding)

Or - as you said - as part of a connection-string.

db = MySQLdb.connect(host=localhost,
 use_unicode = True, charset = utf8,
 user=username, passwd=password, db=database)


But there is more to it. If the DB-API supports it, then the API itself 
will decode the returned strings, using the specified encoding, so that 
the user will only deal with real unicode-objects, greatly reducing 
the risk of mixing byte-strings with unicode-objects. That's what the 
use_unicod-parameter is for: it makes the API accept and deliver 
unicod-objects. But it would do so even if the charset-parameter was 
latin1. Which makes me repeat the lesson from the beginning:

while True:
 print utf-8 is not unicode


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

Re: Display all properties with reflection

2007-10-20 Thread Gabriel Genellina
En Sat, 20 Oct 2007 06:03:55 -0300, sccs cscs [EMAIL PROTECTED] escribi�:

 Hello,
 I like create a methode that display all the properties of an instance  
 of classe with their value.
 I try the following code: see def __str__ (self) methode.
 But it displays only the instance attributes values not the properties  
 and their value.
 In pseudo-code:
 For Each Properties :
print  property_name,  property_value

 It is possible ? Where is the collection of properties into the Python  
 Object Metamodele?

Is this what you want, using dir()?

py class A(object):
...   x = 1
...   @property
...   def y(self): return 2
...
py a=A()
py a.z=3
py
py dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',  
'__hash__', '__init__', '__module__', '__new__', '__reduce__',  
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'x',  
'y', 'z']
py for name in dir(a):
...   if name[:1]=='_': continue
...   print name, getattr(a,name)
...
x 1
y 2
z 3
py

You may want to filter out some values, methods by example. If you usually  
don't store functions as attributes, checking if the attribute itself has  
a __call__ attribute may be enough:

py class B(A):
...   def method1(self): pass
...   @classmethod
...   def method2(cls): pass
...   @staticmethod
...   def method3(): pass
...   def foo(self):
... self.some_var = 1
... def some_function(a):
...   return hello!
... self.some_function = some_function
...
py b=B()
py b.foo()
py dir(b)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',  
'__hash__', '__init__', '__module__', '__new__', '__reduce__',  
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__',  
'foo', 'method1', 'method2', 'method3', 'some_function', 'some_var', 'x',  
'y']
py for name in dir(b):
...   if name[:1]=='_': continue
...   value = getattr(b,name)
...   if hasattr(value, '__call__'): continue
...   print name,'=',value
...
some_var = 1
x = 1
y = 2
py

-- 
Gabriel Genellina

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

Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread Paul Hankin
On Oct 20, 11:15 am, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
 what is the difference between the two kinds of brackets?
 I tried a few examples but I can't make out any real difference:

The main difference in the language between tuples and lists is that
tuples (...) are immutable, and lists [...] are mutable.  That means
you should use lists rather than tuples if you need a mutable
structure (for example, if you want to extend it later), and use
tuples when you need an immutable structure (for example, if you're
constructing dict keys).

Perhaps my opinion is coloured by using other languages where the
distinction between list and tuple is stronger, but when I don't need
my data to be immutable or mutable, I use something like these rules
of thumb:
If each index has a particular meaning (for example (x, y) for
describing 2d coordinates), use tuples.
If the data is uniform (ie each element of the list/tuple has the same
meaning - for example, all the filenames in a directory), use lists.
If the data has a fixed length, use tuples.
If the data has an unknown - possibly unbounded - length, use lists.
If everything else is equal, use tuples.

HTH
--
Paul Hankin

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


Re: Running another python interpreter

2007-10-20 Thread Gabriel Genellina
En Sat, 20 Oct 2007 06:12:23 -0300, Simon Pickles [EMAIL PROTECTED]  
escribi�:

 This is very nearly perfect. I have a second console window.
 Unfortunately, the first is waiting for the second to close. Is there
 anyway to specify the equivalent of os.P_NOWAIT?

Use the more generic version:

subprocess.Popen([sys.executable, gateway.py, other, arguments],  
creationflags = subprocess.CREATE_NEW_CONSOLE)

For more info on the subprocess module, see  
http://docs.python.org/lib/module-subprocess.html

-- 
Gabriel Genellina

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

Re: Noob: Loops and the 'else' construct

2007-10-20 Thread Diez B. Roggisch
MRAB schrieb:
 On Oct 19, 4:11 am, Gabriel Genellina [EMAIL PROTECTED]
 wrote:
 En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus [EMAIL PROTECTED]
 escribió:

 I have just come across a site that discusses Python's 'for' and
 'while' loops as having an (optional) 'else' structure.
 At first glance I interpreted it as being a bit like the 'default'
 structure in PHP's switch block... But the switch block isn't a loop,
 so, I am now confused as to the reason for using 'else' with the for
 and while loops...
 A few quick tests basically show that statements in the else structure
 are executed at the fulfillment of the loop's expression (ie, no
 break).
 A `while` loop tests a condition: if it evaluates to true, keep cycling;
 if it is false, stop. The `else` clause is executed when the condition is
 false, as in any `if` statement. If you exit the loop by using `break`,
 the `else` part is not executed (because you didn't get out of the loop by
 determining the condition falseness)

 You can think of a `for` loop as meaning `while there are remaining
 elements to be iterated, keep cycling` and the `else` clause applies when
 there are no more elements. A `break` statement does not trigger the else
 clause because the iteration was not exhausted.

 Once you get the idea, it's very simple.

 It's useful when you want to search for an item and to do something if
 you don't find it, eg:
 
 for i in items:
 if is_wanted(i):
 print Found it
 break
 else:
 print Didn't find ir

Wrong. It's not:

for i in []:
 print i
else:
 print I'm reached, too

prints out I'm reached, too

The else will ONLY not get executed when the loop is left prematurely 
through a break:

for i in [1]:
 print i
 break
else:
 print I'm reached, too

won't print the I'm ...


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


Re: vote for Python - PLEASE

2007-10-20 Thread Diez B. Roggisch
Bjoern Schliessmann schrieb:
 Steven D'Aprano wrote:
 It's an Internet poll. By definition, the results are meaningless.
 
 Regrettably, there are many people that don't share your definition.
 
 Also, why would there be telephone votings in TV if they were
 meaningless to the default watcher? :) 

Because it costs 50cent to call, which makes a useless and most of the 
time heavily biased poll a nice source of income. Or why do you think 
even the larger TV-stations show call-in-TV-shows at night?

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


cgi scripts in Mac OS X

2007-10-20 Thread Brian Shine
I'm trying to get cgi scripts to work.  I can link to the python  
script, but instead of running and producing an output, it prints the  
script on the page.  I've obviously missed a step in setting it up,  
but I can't see what it is.

Thanks in advance,
Brian Shine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cgi scripts in Mac OS X

2007-10-20 Thread Jeff McNeil
Your web server needs to be told to execute Python scripts.  You can
handle it a few different ways, depending on your environment.

1. Place your .py script inside of a ScriptAlias'd /cgi-bin/ directory
which will force it to be executed.

2. Rename your .py script to .cgi and add an 'AddHandler cgi-script
.cgi' to your Apache configuration

3. Add an AddHandler cgi-script .py to your Apache configuration.

This of course assumes that Apache is configured in a way that would
allow execution and whatnot.  Do yourself a favor and give
'http://httpd.apache.org/docs/2.2/howto/cgi.html' a read over as it's
going to cover a lot more than I just did.

Jeff

On 10/20/07, Brian Shine [EMAIL PROTECTED] wrote:
 I'm trying to get cgi scripts to work.  I can link to the python
 script, but instead of running and producing an output, it prints the
 script on the page.  I've obviously missed a step in setting it up,
 but I can't see what it is.

 Thanks in advance,
 Brian Shine
 --
 http://mail.python.org/mailman/listinfo/python-list

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


traceback over C API - still not working...

2007-10-20 Thread Sami Vaisanen
This is becoming utterly painful process I found out that the return
value from format_exception function is NOT a list, i.e. PyList_Check()
fails. PySequence_Check() succeeds but then PySequence_List() gives me
back -1. So wtf?

I must say the API is crap on this part. Im trying to get error
information regarding previous error and if all i get back is another
error indicator, then what am I supposed to do? Recursive error handling?
Sounds like da bomb!

The API should have two levels of error handling. First level should
expose a conventional error code mechanism for checking for bad params
etc. Only if the error code says that there was a python error during
evaluation/compilation should one need to use this mechanism. 

Just my two cents.

Thanks for help.



void get_python_error_info(string info)
{
GIL g;

PyObject* type  = NULL;
PyObject* value = NULL;
PyObject* trace = NULL;
PyErr_Fetch(type, value, trace);

py_ref ref_type(type);
py_ref ref_value(value);
py_ref ref_trace(trace);

py_ref name(PyString_FromString(traceback));
py_ref module(PyImport_Import(name.get()));
if (!module)
{
PyErr_Clear();
return;
}
PyObject* list = NULL;
if (trace)
{
py_ref fun(PyObject_GetAttrString(module.get(), format_exception));
if (fun)
list = PyObject_CallFunctionObjArgs(type, value, trace, NULL);
PyErr_Clear();
}
else
{
py_ref fun(PyObject_GetAttrString(module.get(), 
format_exception_only));
if (fun)
list = PyObject_CallFunctionObjArgs(type, value, NULL);
PyErr_Clear();
}
if (list  PySequence_Check(list))
{
Py_ssize_t len = PySequence_Size(list);
  
for (Py_ssize_t i=0; ilen; ++i)
{
  // bla bla
}
}
Py_XDECREF(list);
PyErr_Clear();
}





 Hello group,

 I'm trying to get the Python exception information (message and  
 traceback)
 stored into a string in my C++ code. However all i get back is the string
 None.

This is what you get (actually None\n) when there is no error set.

 All the checks pass and all pointers get a value from the python
 API calls. I've also tried with a different function such as
 PyObject_CallFunctionObjArgs but the result is the same.

Since you already know the three components (type, value, trace), I'd use  
traceback.format_exception instead (and remove the PyErr_Restore call -  
I'm unsure if it works the way you expect it).
In this case you have to pass three arguments, so yes, use  
PyObject_CallFunctionObjArgs (remember the final NULL). Beware:  
format_exception returns a formatted list, not a string. You have to  
concatenate all the elements (either using ''.join or repeteadly calling  
PyString_Concat)

 void get_python_exception(string message, string traceback)
 {
 GIL g;
PyObject* type  = NULL;
 PyObject* value = NULL;
 PyObject* trace = NULL;
PyErr_Fetch(type, value, trace);
py_ref ref_type(type);
 py_ref ref_value(value);
 py_ref ref_trace(trace);
py_ref name(PyString_FromString(traceback));
 py_ref module(PyImport_Import(name.get()));
 if (module)
 {
 py_ref fun(PyObject_GetAttrString(module.get(), format_exc));
 if (fun)
 {
 PyErr_Restore(type, value, trace);
 ref_type.release();
 ref_value.release();
 ref_trace.release();
py_ref ret(PyObject_CallObject(fun.get(), NULL));
 if (ret  PyString_Check(ret.get()))
 {
 char* str = PyString_AsString(ret.get());
 message = str;
 traceback = traceback not available;
 return;
 }
 }
 }
 message   = message not available;
 traceback = traceback not available;
 }




-- 
Gabriel Genellina

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


Re: what version python and wxPython comes with Mac OS X Leopard

2007-10-20 Thread Horace Enea
According to this Apple web page, Python 2.5 will be supported

http://www.apple.com/macosx/technology/unix.html

Horace


In article [EMAIL PROTECTED],
 chewie54 [EMAIL PROTECTED] wrote:

 Hi All,
 
 Does anyone know what version of Python and wxPython comes with the
 new Mac OS X Leopard?
 
 Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Get the instance name from a list by Reflection

2007-10-20 Thread sccs cscs
Hello,
I cannot find into documentation how to get the instance name. I found the 
attributes __dict__,__class__ ,__bases__ __name__ ,
but if i have the code:

class A :pass
a1 = A ()
a2 = A ()
aList = [a1,a2]
for elem in aList :
print elem.__instance_name__ ???

I expect to have a1 a2 ...
But it does not work ...
help please
Zorgi

 
-
 Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -- 
http://mail.python.org/mailman/listinfo/python-list

Re: logging module - restricted mode error

2007-10-20 Thread Vinay Sajip
On 16 Oct, 04:14, Paul Rudin [EMAIL PROTECTED] wrote:
 I'm occasionally seeing tracebacks like this:

 Traceback (most recent call last):
   File logging/__init__.py, line 744, in emit
   File logging/__init__.py, line 630, in format
   File logging/__init__.py, line 421, in format
 RuntimeError: instance.__dict__ not accessible in restricted mode

 I'm not sure what it means. Googling leads me to
 http://docs.python.org/lib/restricted.html but that says that those
 modules were disabled in 2.3 and I'm running 2.5.1. In any case I'm
 not using them (although it could be that one of the 3rd party modules
 I'm using does something.)

 Could someone please explain what this error means?

Can you say a little bit more about the execution environment? For
example, are you running under mod_python? If so, which version?

When googling, did you search for the exact text of the error message?
For example, did you see the following post?

http://mail-archives.apache.org/mod_mbox/httpd-python-dev/200404.mbox/[EMAIL 
PROTECTED]

Vinay Sajip

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


Re: Get the instance name from a list by Reflection

2007-10-20 Thread Jean-Paul Calderone
On Sat, 20 Oct 2007 21:10:34 +0200 (CEST), sccs cscs [EMAIL PROTECTED] wrote:
Hello,
I cannot find into documentation how to get the instance name. I found the 
attributes __dict__,__class__ ,__bases__ __name__ ,
but if i have the code:

class A :pass
a1 = A ()
a2 = A ()
aList = [a1,a2]
for elem in aList :
print elem.__instance_name__ ???

I expect to have a1 a2 ...
But it does not work ...
help please
Zorgi

$ python
Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
 class A: pass
...
 a1 = A()
 a2 = A()
 aList = [a1, a2]
 import __main__
 from twisted.python.reflect import objgrep, isSame
 for elem in aList:
... objgrep(__main__, elem, isSame)
...
['.aList[0]', '.elem', '.a1']
['.aList[1]', '.elem', '.a2']


Don't see how this could help,

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


Re: Get the instance name from a list by Reflection

2007-10-20 Thread Carsten Haese
On Sat, 2007-10-20 at 21:10 +0200, sccs cscs wrote:
 Hello,
 I cannot find into documentation how to get the instance name.

That's because this is, in general, impossible. An object can have any
number of names, even zero names, and an object doesn't know which names
it has.

Why do you think you need to find out an object's name?

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Distributed RVS, Darcs, tech love

2007-10-20 Thread j.oke
On 20 Ott, 05:28, Xah Lee [EMAIL PROTECTED] wrote:


yes-and-no.

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


Re: Distributed RVS, Darcs, tech love

2007-10-20 Thread llothar

 I love math. I respect Math. I'm nothing but a menial servant to
 Mathematics.

Programming and use cases are not maths. Many mathematics are
the worst programmers i've seen because they want to solve things and
much more often you just need heuristics. Once they are into exact
world they loose there capability to see the factor of relevance in
algorithms.

And they almost never match the mental model that the average
user has about a problem.

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


Re: cgi scripts in Mac OS X

2007-10-20 Thread James Stroud
Jeff McNeil wrote:
 Your web server needs to be told to execute Python scripts.  You can
 handle it a few different ways, depending on your environment.
 
 1. Place your .py script inside of a ScriptAlias'd /cgi-bin/ directory
 which will force it to be executed.
 
 2. Rename your .py script to .cgi and add an 'AddHandler cgi-script
 .cgi' to your Apache configuration
 
 3. Add an AddHandler cgi-script .py to your Apache configuration.
 
 This of course assumes that Apache is configured in a way that would
 allow execution and whatnot.  Do yourself a favor and give
 'http://httpd.apache.org/docs/2.2/howto/cgi.html' a read over as it's
 going to cover a lot more than I just did.

I want to reply to Jeff instead of the original posting, so you don't go 
through all this trouble.

The apache distro with OS X is configured to execute python cgi scripts 
out of the box, so (2) and (3) above are unnecessary on OS X = 10.3.

So, the OS X specific instructions would be


1. move the script to /Library/WebServer/CGI-Executables:

  sudo mv my_script.py /Library/WebServer/CGI-Executables/my_script.cgi

2. make sure its executable

  sudo chmod a+x /Library/WebServer/CGI-Executables/my_script.cgi

3. add this sh-bang line to the top of the script:

  #! /usr/bin/env python

4. use the localhost path as the action to your script (ellipses mean
the rest of the attributes of the form tag):

  form ... action='http://localhost/cgi-bin/my_script.cgi ...

5. make sure that Personal Web Sharing is enabled in the Sharing
Preference Pane

6. pat self on back for using a REAL operating system and not some
trash operating system that $ucks real hard:

  http://tinyurl.com/2aoqpf


James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA  90095

http://www.jamesstroud.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: vote for Python - PLEASE

2007-10-20 Thread Bjoern Schliessmann
Diez B. Roggisch wrote:
 Bjoern Schliessmann schrieb:

 Also, why would there be telephone votings in TV if they were
 meaningless to the default watcher? :)
 
 Because it costs 50cent to call, which makes a useless and most of
 the time heavily biased poll a nice source of income. Or why do
 you think even the larger TV-stations show call-in-TV-shows at
 night?

You're partially right. But those are mostly no polls but lotteries
(often with tricky or ridiculously simple questions). Simple polls
are quite rare, comparatively.

Regards,


Björn

-- 
BOFH excuse #301:

appears to be a Slow/Narrow SCSI-0 Interface problem

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


using request variable in python web program

2007-10-20 Thread sami
Hi

I am trying to write a facebook application in python - I have been
programming simple desktop applications till now and am not really
familiar with web apps

Pyfacebook is the wrapper for the REST based Facebook API - there is a
simple example for its usage as shown below:

def simple_web_app(request, api_key, secret_key):
fb = Facebook(api_key, secret_key, request.GET['auth_token'])
fb.auth_getSession()

A Django-based tutorial and source is available here:
http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial

I really don't want to use a framework for the time being and just
want an app up and running

My question is - how do you create the request object which will be
passed into the simple_web_app(request, api_key, secret_key) function
here - is there somewhere I can read into it?

I have been googling for hours and there seems to be no simple,
straightforward example for this - PHP rules when it comes to simple
web programming apps - either I am not looking at the right places but
it's very hard to get up and running quickly for web apps in Python -
maybe DiveIntoPython needs a section devoted for web programming

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


Re: traceback over C API - still not working...

2007-10-20 Thread Gabriel Genellina
En Sat, 20 Oct 2007 14:47:52 -0300, Sami Vaisanen [EMAIL PROTECTED]  
escribi�:

 This is becoming utterly painful process I found out that the return
 value from format_exception function is NOT a list, i.e. PyList_Check()
 fails. PySequence_Check() succeeds but then PySequence_List() gives me
 back -1. So wtf?

It seems very unlikely, since the traceback module is written in Python.  
It clearly returns a list.

 py_ref fun(PyObject_GetAttrString(module.get(),  
 format_exception));
 if (fun)
 list = PyObject_CallFunctionObjArgs(type, value, trace,  
 NULL);

Of course, you get a list if you actually call the function...

-- 
Gabriel Genellina

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

Re: Get the instance name from a list by Reflection

2007-10-20 Thread Gabriel Genellina
En Sat, 20 Oct 2007 16:10:34 -0300, sccs cscs [EMAIL PROTECTED] escribi�:

 I cannot find into documentation how to get the instance name. I found  
 the attributes __dict__,__class__ ,__bases__ __name__ ,
 but if i have the code:

In general, you can't. There is no such thing as the instance name.
See  
http://www.python.org/doc/faq/programming/#how-can-my-code-discover-the-name-of-an-object

-- 
Gabriel Genellina

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

Re: ACM SIGAPL / APL2007 Conference / Montreal / one week away

2007-10-20 Thread rbe
On Oct 15, 5:22 am, Mike Kent [EMAIL PROTECTED] wrote:
 Conference page
 // with links to program details //
 (updated Friday 10/12)

http://www.sigapl.org/apl2007.html...

At APL2007, I'll be announcing the release of the APEX APL compiler,
version 0.0.0, under GPL Version 2.
If you can't wait until then, you can download it for Dyalog Linux at
www.snakeisland.com.

Bob

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


Re: using request variable in python web program

2007-10-20 Thread Paul Boddie
On 21 Okt, 00:21, sami [EMAIL PROTECTED] wrote:

 def simple_web_app(request, api_key, secret_key):
 fb = Facebook(api_key, secret_key, request.GET['auth_token'])
 fb.auth_getSession()

 A Django-based tutorial and source is available 
 here:http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial

 I really don't want to use a framework for the time being and just
 want an app up and running

Something like CGI, mod_python or Python's standard library
BaseHTTPServer might be good enough. Or you could try WebStack if you
can't decide. See these links for details:

http://wiki.python.org/moin/CgiScripts
http://www.modpython.org/
http://wiki.python.org/moin/BaseHttpServer
http://www.python.org/pypi/WebStack

 My question is - how do you create the request object which will be
 passed into the simple_web_app(request, api_key, secret_key) function
 here - is there somewhere I can read into it?

The request object in this case is specifically a Django request
object; this can be deduced from usage of the request.GET attribute
which is specific to Django. If you decided to use another framework,
you'd need to rewrite this part; for example in WebStack...

class FacebookResource:
def respond(self, trans):
try:
auth_token = trans.get_fields_from_path()['auth_token'][0]
fb = Facebook(api_key, secret_key, auth_token)
fb.auth_getSession()
...
except KeyError: # no auth token
...

I'm sure others can suggest their own preferred solutions.

 I have been googling for hours and there seems to be no simple,
 straightforward example for this - PHP rules when it comes to simple
 web programming apps - either I am not looking at the right places but
 it's very hard to get up and running quickly for web apps in Python -
 maybe DiveIntoPython needs a section devoted for web programming

There's only consensus around WSGI as some kind of standard in Python
Web programming, but it isn't likely to get you very far without
forcing you to choose extra components to make the work bearable (eg.
to read query/form values), so it isn't the one way of doing things at
the level that PHP presumably offers (which is why it's presumably
easier to find advice on such matters all over the Web for PHP).

Most people advocate particular frameworks instead of WSGI, and as
you've noticed people do seem to like Django quite a lot. The problem
with this state of affairs is that you need to make up front choices
when testing out frameworks, and after the legwork of setting stuff
up, if you don't like what you've seen you've got to back out and do
similar (but different) stuff for your next choice of framework.

However, it shouldn't be too bad to set Django up, really, especially
if people have taken some time to explain something very close to what
you want to do using Django. Moreover, there's a Google group (django-
users) where you could ask general questions, and I imagine that
people will be quite happy to help you out. But I can totally
understand that creating databases and installing various packages
seems somewhat peripheral to a task which could arguably be done using
a CGI script (as far as I can see).

Paul

P.S. I'm not too impressed by the lack of a common high-level Web API
for Python, either. However, I've mostly ignored the discussions and
stuck with my own API (WebStack) in the knowledge that if it doesn't
work for me, at least I know how I might fix it.

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


Re: Elisp Tutorial: HTML Syntax Coloring Code Block

2007-10-20 Thread Steve Holden
Byung-Hee HWANG wrote:
 Steve,
 
 On Sat, 2007-10-20 at 08:30 -0400, Steve Holden wrote:
 Byung-Hee HWANG wrote:
 [... whole article quoted ...]
 +1 ;;
 BTW, what is G2/1.0? Is that Emacs-like editor?

 I can't tell you that, but I do know that someone who quotes a whole 
 lengthy article like that just to ask a simple question isn't being very 
 considerate of their readers.
 
 You're the only guy who has read the my comment. Thanks!
 
Try asking again without the lengthy quote!

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread Steven D'Aprano
On Sat, 20 Oct 2007 12:43:31 +, Steve Lamb wrote:

 The quick answer is that tuples can be indexes into directories
 while lists cannot.


A note on terminology: the things inside curly brackets {} are called 
dictionaries, or dicts, not directories. And the things you use to store 
data in dictionaries are called keys, not indexes:

# Lists have indexes:
L = ['x', 'y', 'z']
L[0] # returns the item in position 0

# Dicts have keys:
D = {'a': 'x', 2: 'y', 7.8: 'z'}
D['a'] # returns the item with key 'a'



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


Re: Distributed RVS, Darcs, tech love

2007-10-20 Thread Daniel Pitts
On Oct 20, 2:04 pm, llothar [EMAIL PROTECTED] wrote:
  I love math. I respect Math. I'm nothing but a menial servant to
  Mathematics.

 Programming and use cases are not maths. Many mathematics are
 the worst programmers i've seen because they want to solve things and
 much more often you just need heuristics. Once they are into exact
 world they loose there capability to see the factor of relevance in
 algorithms.

 And they almost never match the mental model that the average
 user has about a problem.

I read somewhere that for large primes, using Fermat's Little Theorem
test is *good enough* for engineers because the chances of it being
wrong are less likely than a cosmic particle hitting your CPU at the
exact instant to cause a failure of the same sort.  This is the
primary difference between engineers and mathematicians.

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


Selection error...

2007-10-20 Thread Abandoned
Hi..
I want to select datas but some datas give me this error:

psycopg2.ProgrammingError: invalid byte sequence for encoding UTF8:
0xc720
HINT:  This error can also happen if the byte sequence does not match
the encoding expected by the server, which is controlled by
client_encoding.

My select command:
cursor.execute(SELECT id from templinks where url='%s'% URL)

This problem occured only select data when i try insert the same data
it doesn't give me error..
Note: My database is UTF-8 and the URLS come from different web sites'
html code
How can i fix this problem ?
I'm sorry my bad english..

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


Re: Distributed RVS, Darcs, tech love

2007-10-20 Thread Benjamin A'Lee
On Fri, Oct 19, 2007 at 08:28:14PM -0700, Xah Lee wrote:
[snip...]

Inflammatory and irrelevant. Why not ask questions about Darcs on the
Darcs list, or are you worried that there may be too many people there
who can tell you what a load of rubbish you're talking?

Ben


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

Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread Steve Lamb
On 2007-10-21, Steven D'Aprano [EMAIL PROTECTED] wrote:
 A note on terminology: the things inside curly brackets {} are called 
 dictionaries, or dicts, not directories. And the things you use to store 
 data in dictionaries are called keys, not indexes:

Thanks for catching that.  Kids, don't late night post while waiting for
the other computer to do its thing.

-- 
 Steve C. Lamb | But who decides what they dream?
   PGP Key: 1FC01004   |   And dream I do...  
---+-

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


Re: Distributed RVS, Darcs, tech love

2007-10-20 Thread George Neuner
On Sun, 21 Oct 2007 01:20:47 -, Daniel Pitts
[EMAIL PROTECTED] wrote:

On Oct 20, 2:04 pm, llothar [EMAIL PROTECTED] wrote:
  I love math. I respect Math. I'm nothing but a menial servant to
  Mathematics.

 Programming and use cases are not maths. Many mathematics are
 the worst programmers i've seen because they want to solve things and
 much more often you just need heuristics. Once they are into exact
 world they loose there capability to see the factor of relevance in
 algorithms.

 And they almost never match the mental model that the average
 user has about a problem.

I read somewhere that for large primes, using Fermat's Little Theorem
test is *good enough* for engineers because the chances of it being
wrong are less likely than a cosmic particle hitting your CPU at the
exact instant to cause a failure of the same sort.  This is the
primary difference between engineers and mathematicians.

An attractive person of the opposite sex stands on the other side of
the room.  You are told that your approach must be made in a series of
discrete steps during which you may close half the remaining distance
between yourself and the other person.

Mathematician: But I'll never get there!

Engineer: I'll get close enough.


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


Re: Distributed RVS, Darcs, tech love

2007-10-20 Thread Lew
George Neuner wrote:
 An attractive person of the opposite sex stands on the other side of
 the room.  You are told that your approach must be made in a series of
 discrete steps during which you may close half the remaining distance
 between yourself and the other person.
 
 Mathematician: But I'll never get there!
 
 Engineer: I'll get close enough.

Mechanician (to the researcher): Hey, you look pretty good.  What's your sign?

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


Re: Selection error...

2007-10-20 Thread Carsten Haese
On Sat, 2007-10-20 at 18:28 -0700, Abandoned wrote:
 Hi..
 I want to select datas but some datas give me this error:
 
 psycopg2.ProgrammingError: invalid byte sequence for encoding UTF8:
 0xc720
 HINT:  This error can also happen if the byte sequence does not match
 the encoding expected by the server, which is controlled by
 client_encoding.
 
 My select command:
 cursor.execute(SELECT id from templinks where url='%s'% URL)

Haven't we told you before not to use the % operator to fill values into
a query? Use parameter binding:

cursor.execute(SELECT id from templinks where url=%s, (URL,) )

 This problem occured only select data when i try insert the same data
 it doesn't give me error..
 Note: My database is UTF-8 and the URLS come from different web sites'
 html code

Your string probably contains latin-1 encoded text. Try
URL.decode('latin-1').encode('utf-8') to transcode it into utf-8.

Hope this helps,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Selection error...

2007-10-20 Thread Carsten Haese
On Sat, 20 Oct 2007 21:06:31 -0700, Dennis Lee Bieber wrote
 On Sat, 20 Oct 2007 22:47:23 -0400, Carsten Haese [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:
 
  Haven't we told you before not to use the % operator to fill values into
  a query? Use parameter binding:
  
  cursor.execute(SELECT id from templinks where url=%s, (URL,) )
 
   And check the adapter documentation with regards to the placeholder
 it uses... It may just want a ? instead of %s

The OP uses psycopg2, which unfortunately uses %s parameter notation. But I
agree, it's worth noting that the parameter style may vary between different
DB-API implementations (until the next version of DB-API, when supporting at
least qmark and named parameter styles becomes mandatory, yay!).

--
Carsten Haese
http://informixdb.sourceforge.net

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


[issue1061] ABC caches should use weak refs

2007-10-20 Thread Georg Brandl

Georg Brandl added the comment:

Attaching a new patch; this one passes regrtest -R:: of test_io without
apparent reference leaks.

--
assignee: georg.brandl - gvanrossum
Added file: http://bugs.python.org/file8577/wr.diff

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1061
__Index: Doc/library/weakref.rst
===
--- Doc/library/weakref.rst (Revision 58557)
+++ Doc/library/weakref.rst (Arbeitskopie)
@@ -28,24 +28,27 @@
 binary image objects, you may wish to associate a name with each.  If you used 
a
 Python dictionary to map names to images, or images to names, the image objects
 would remain alive just because they appeared as values or keys in the
-dictionaries.  The :class:`WeakKeyDictionary` and :class:`WeakValueDictionary`
-classes supplied by the :mod:`weakref` module are an alternative, using weak
-references to construct mappings that don't keep objects alive solely because
-they appear in the mapping objects.  If, for example, an image object is a 
value
-in a :class:`WeakValueDictionary`, then when the last remaining references to
-that image object are the weak references held by weak mappings, garbage
-collection can reclaim the object, and its corresponding entries in weak
-mappings are simply deleted.
+dictionaries.  The :class:`WeakKeyDictionary`, :class:`WeakValueDictionary`
+and :class:`WeakSet` classes supplied by the :mod:`weakref` module are an
+alternative, using weak references to construct mappings that don't keep 
objects
+alive solely because they appear in the container objects.
+If, for example, an image object is a value in a :class:`WeakValueDictionary`,
+then when the last remaining references to that image object are the weak
+references held by weak mappings, garbage collection can reclaim the object,
+and its corresponding entries in weak mappings are simply deleted.
 
 :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
 in their implementation, setting up callback functions on the weak references
 that notify the weak dictionaries when a key or value has been reclaimed by
-garbage collection.  Most programs should find that using one of these weak
-dictionary types is all they need -- it's not usually necessary to create your
-own weak references directly.  The low-level machinery used by the weak
-dictionary implementations is exposed by the :mod:`weakref` module for the
-benefit of advanced uses.
+garbage collection.  :class:`WeakSet` implements the :class:`set` interface,
+but keeps weak references to its elements, just like a
+:class:`WeakKeyDictionary` does.
 
+Most programs should find that using one of these weak container types is all
+they need -- it's not usually necessary to create your own weak references
+directly.  The low-level machinery used by the weak dictionary implementations
+is exposed by the :mod:`weakref` module for the benefit of advanced uses.
+
 Not all objects can be weakly referenced; those objects which can include class
 instances, functions written in Python (but not in C), methods (both bound and
 unbound), sets, frozensets, file objects, generators, type objects, DBcursor
@@ -179,6 +182,12 @@
Return a list of weak references to the values.
 
 
+.. class:: WeakSet([elements])
+
+   Set class that keeps weak references to its elements.  An element will be
+   discarded when no strong reference to it exists any more.
+
+
 .. data:: ReferenceType
 
The type object for weak references objects.
Index: Lib/weakref.py
===
--- Lib/weakref.py  (Revision 58557)
+++ Lib/weakref.py  (Arbeitskopie)
@@ -337,3 +337,108 @@
 d[ref(key, self._remove)] = value
 if len(kwargs):
 self.update(kwargs)
+
+
+class WeakSet:
+def __init__(self, data=None):
+self.data = set()
+def _remove(item, selfref=ref(self)):
+self = selfref()
+if self is not None:
+self.data.discard(item)
+self._remove = _remove
+if data is not None:
+self.update(data)
+
+def __iter__(self):
+for itemref in self.data:
+item = itemref()
+if item is not None:
+yield item
+
+def __contains__(self, item):
+return ref(item) in self.data
+
+def __reduce__(self):
+return (self.__class__, (list(self),),
+getattr(self, '__dict__', None))
+
+def add(self, item):
+self.data.add(ref(item, self._remove))
+
+def clear(self):
+self.data.clear()
+
+def copy(self):
+return self.__class__(self)
+
+def pop(self):
+while True:
+itemref = self.data.pop()
+item = itemref()
+if item is not None:
+return item
+
+def remove(self, item):
+

[issue1306] Embedded python reinitialization

2007-10-20 Thread Karemir

New submission from Karemir:

Hi, 
I'm embedding stackless python in a c++ application under linux. When I 
try to Finalize and Initialize again, I'm getting errors. this is a 
sample code that doesn't work:

int main() {
Py_Initialize();
Py_Finalize();
Py_Initialize();
Py_Finalize();
}

Second call to Init throws out a nice Segmentation Fault. Here's a 
stack trace:

PyDict_SetItem (op=0x0, key=0x2ab1a4c8, value=0x6bab20) at 
Objects/dictobject.c:616
616 if (!PyDict_Check(op)) {
Current language:  auto; currently c
(gdb) bt
#0  PyDict_SetItem (op=0x0, key=0x2ab1a4c8, value=0x6bab20) at 
Objects/dictobject.c:616
#1  0x00476ac9 in PyDict_SetItemString (v=0x0, 
key=Variable key is not available.
) at Objects/dictobject.c:2178
#2  0x004ea77f in PyErr_PrintEx (set_sys_last_vars=1) at 
Python/pythonrun.c:1098
#3  0x004ebfb9 in Py_InitializeEx (install_sigs=1) at 
Python/pythonrun.c:995
#4  0x0044a8cc in main () at main.cpp:23

I'm using gcc 3.4.6, and Python 2.5.1 Stackless 3.1b3.

--
components: Interpreter Core
messages: 56603
nosy: Karemir
severity: urgent
status: open
title: Embedded python reinitialization
type: crash
versions: Python 2.5

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1306
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Guido van Rossum

Guido van Rossum added the comment:

Thanks for persevering!!!

The dangers of switching between fileno(fp) and fp are actually well
documented in the C and/or POSIX standards. The problem is caused in
PyFile_FromFileEx() -- it creates a Python file object from the file
descriptor. The fix actually only works because we're not using the
FILE struct once PyTokenizer_FindEncoding() is called. I think it
would be better to move the lseek() into call_find_module() so the
FILE abstraction is not broken by PyTokenizer_FindEncoding().

I think there's still a bug or two lurking in this area: first, each
time you call imp.find_module() you leak a FILE object; second, the
encoding allocated in PyTokenizer_FindEncoding() is leaked.

You're right that a lot of this could be avoided if we used file
descriptors consistently. It seems find_module() itself doesn't read
the file; it just needs to know that it's possible to open the file.

Rewriting everywhere that uses PyFile_FromFile[Ex] to use file
descriptors doesn't seem too hard; there are only a few places.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Guido van Rossum

Guido van Rossum added the comment:

Sorry, I was wrong about the encoding leak; you fixed that. The
FILE/fd issue is real though.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1294] Management of KeyboardInterrupt in cmd.py

2007-10-20 Thread BULOT

BULOT added the comment:

Well, I made it with a diff -ruN, it works fine on my ubuntu.
It is only a ctrl-C management only, not a ctrl-D.
What do you mean by broken?
Regards.
Stephbul

2007/10/19, Guido van Rossum [EMAIL PROTECTED]:


 Guido van Rossum added the comment:

 Hmm...  I don't think this is the right thing to do.  The code is broken
 in several ways.  I recommend you find someone to help you come up with
 a better patch in comp.lang.python.

 --
 keywords: +patch

 __
 Tracker [EMAIL PROTECTED]
 http://bugs.python.org/issue1294
 __


Added file: http://bugs.python.org/file8578/unnamed

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1294
__Well, I made it with a diff -ruN, it works fine on my ubuntu. brIt is only a 
ctrl-C management only, not a ctrl-D.brWhat do you mean by 
broken?brRegards.brStephbulbrbrbrdivspan 
class=gmail_quote2007/10/19, Guido van Rossum lt;
a href=mailto:[EMAIL PROTECTED][EMAIL PROTECTED]/agt;:/spanblockquote 
class=gmail_quote style=border-left: 1px solid rgb(204, 204, 204); margin: 
0pt 0pt 0pt 0.8ex; padding-left: 1ex;brGuido van Rossum added the comment:
brbrHmm...nbsp;nbsp;I don#39;t think this is the right thing to 
do.nbsp;nbsp;The code is brokenbrin several ways.nbsp;nbsp;I recommend 
you find someone to help you come up withbra better patch in 
comp.lang.python.brbr--brkeywords: +patch
brbr__brTracker lt;a 
href=mailto:[EMAIL PROTECTED][EMAIL PROTECTED]/agt;brlt;a 
href=http://bugs.python.org/issue1294;http://bugs.python.org/issue1294/agt;br
__br/blockquote/divbr

___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Christian Heimes

Christian Heimes added the comment:

Guido van Rossum wrote:
 You're right that a lot of this could be avoided if we used file
 descriptors consistently. It seems find_module() itself doesn't read
 the file; it just needs to know that it's possible to open the file.
 
 Rewriting everywhere that uses PyFile_FromFile[Ex] to use file
 descriptors doesn't seem too hard; there are only a few places.

If I understand you right you want to alter the interface of
PyFile_FromFile and PyFile_FromFileEx from

PyFile_FromFileEx(FILE *fp, char *name, char *mode, int (*close)(FILE*),
int buffering, char *encoding, char *newline)

to

PyFile_FromFileEx(int fd, char *name, char *mode, int (*close)(FILE*),
int buffering, char *encoding, char *newline)

?

I could write a patch and remove int (*close)(FILE*), too. It's no
longer used by the functions.

Christian

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Christian Heimes

Christian Heimes added the comment:

 Yes, I think you got it.

Guido, Brett, how much of the code should I change? import.c is mainly
using file pointers. Should I replace all operations on FILE with
operations on a file descriptor?

Christian

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Guido van Rossum

Guido van Rossum added the comment:

 Guido, Brett, how much of the code should I change? import.c is mainly
 using file pointers. Should I replace all operations on FILE with
 operations on a file descriptor?

I think find_module() should return a file descriptor (fd), not a
FILE*, but most of the rest of the code should call fdopen() on that
fd. Only call_find_module() should use the fd to turn it into a Python
file object. Then the amount of change should be pretty minimal.

I recommend changing the name of the API used to turn a fd into file
object while we're at it; that's one of the few guidelines we have for
C API changes.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Christian Heimes

Christian Heimes added the comment:

Guido van Rossum wrote:
 I think find_module() should return a file descriptor (fd), not a
 FILE*, but most of the rest of the code should call fdopen() on that
 fd. Only call_find_module() should use the fd to turn it into a Python
 file object. Then the amount of change should be pretty minimal.

K, I understand.

 I recommend changing the name of the API used to turn a fd into file
 object while we're at it; that's one of the few guidelines we have for
 C API changes.

Is PyFile_FromFd and PyFile_FromFdEx fine with you or do you prefer a
different name like PyFile_FromFD and PyFile_FromFDEx or
PyFile_FromFileDescriptor?

I've another question. The os.tmpfile method is using tmpfile() which
returns a file pointer. Do I have to dup its file number and explictely
close the file pointer as shown below or is a simple fileno() enough? I
haven't found sample code how to use a file descriptor after the file
pointer is closed.

static PyObject *
posix_tmpfile(PyObject *self, PyObject *noargs)
{
FILE *fp;
int fd;

fp = tmpfile();
if (fp == NULL)
return posix_error();
fd = dup(fileno(fp));
if (fd == -1)
return posix_error();
fclose(fp);
return PyFile_FromFD(fd, tmpfile, w+b);
}

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Guido van Rossum

Guido van Rossum added the comment:

 Is PyFile_FromFd and PyFile_FromFdEx fine with you or do you prefer a
 different name like PyFile_FromFD and PyFile_FromFDEx or
 PyFile_FromFileDescriptor?

Let's have a single function PyFile_FromFd(fd, name, mode, buffering,
encoding, newline).

 I've another question. The os.tmpfile method is using tmpfile() which
 returns a file pointer. Do I have to dup its file number and explictely
 close the file pointer as shown below or is a simple fileno() enough?

You should dup it; if you don't dup it, the fd will be closed when you
call fclose(), rendering it useless; or when you don't call fclose(),
you leak a FILE struct each time.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1263] PEP 3137 patch - str8/str comparison should return false

2007-10-20 Thread Brett Cannon

Brett Cannon added the comment:

Attached is a fix for modulefinder.

It is an ugly hack as modulefinder took the numeric opcode numbers from
dis and passed them to chr().  But that doesn't work since that returns
Unicode.  So I took those single characters and passed them to str8().

Once str8() has its constructor match bytes() then the chr() call can be
ditched and the dis values can be tossed into a single-item list.

Added file: http://bugs.python.org/file8579/fix_modulefinder.diff

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1263
__

fix_modulefinder.diff
Description: Binary data
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1263] PEP 3137 patch - str8/str comparison should return false

2007-10-20 Thread Brett Cannon

Brett Cannon added the comment:

Attached is a fix for sqlite3.

First issue was that the dictionary that was being used to store
converters was having keys in Python code as Unicode but being compared
against str8 in C.

The second issue was that when an object was serialized using
__conform__ and a Unicode object was returned, it was being unserialized
as a str8 no matter what type of argument was returned.  That makes the
most sense if only a single type is going to be returned, so I left it
as such and fixed the test to decode str8 to UTF-8 if passed to __init__.

Added file: http://bugs.python.org/file8580/sqlite_fix.diff

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1263
__

sqlite_fix.diff
Description: Binary data
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1307] smtpd.SMTPServer throws exception on MAIL command with no arg

2007-10-20 Thread Derek Shockey

New submission from Derek Shockey:

smtpd.SMTPChannel contains a bug such that when connected to an 
SMTPServer (or any subclass thereof), issuing a MAIL command with no 
argument closes the socket and gives this error on the server:

(type 'exceptions.TypeError':'NoneType' object is unsubscriptable ... 
smtpd.py|__getaddr|212])

The desired result is of course is to respond with a 501 Syntax error. 
The problem arises because the arg parameter passed to each smtp_* 
command handler function is None when there is no argument. arg is 
passed on to __getaddr which attempts a slice on the None object.

A check for None in __getaddr that returns will allow the existing code 
to issue the appropriate 501 Syntax error.

--
components: Library (Lib)
messages: 56616
nosy: dshockey
severity: normal
status: open
title: smtpd.SMTPServer throws exception on MAIL command with no arg
versions: Python 2.5

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1307
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1263] PEP 3137 patch - str8/str comparison should return false

2007-10-20 Thread Brett Cannon

Brett Cannon added the comment:

Attached is a patch to fix test_str.

Basically there were a bunch of redundant tests for making sure that
calling str() on an object called it's __str__ method.  str8 no longer
is directly relevant since it is no longer an actual string type.

Added file: http://bugs.python.org/file8581/fix_test_str.diff

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1263
__

fix_test_str.diff
Description: Binary data
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1263] PEP 3137 patch - str8/str comparison should return false

2007-10-20 Thread Brett Cannon

Brett Cannon added the comment:

Attached is a fix for test_subprocess.

Simply had to change a call to str8() to str().

I am going to run the test suite, but that should leave only test_struct
failing and that can be fixed as soon as Guido makes a call on whether
str8 or str should be used for the string formats.

Added file: http://bugs.python.org/file8582/fix_test_subprocess.diff

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1263
__

fix_test_subprocess.diff
Description: Binary data
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1307] smtpd.SMTPServer throws exception on MAIL command with no arg

2007-10-20 Thread Derek Shockey

Derek Shockey added the comment:

Very simple patch that adds a ternary operator to skip the call to 
__getaddr if there is no arg.

Added file: http://bugs.python.org/file8583/smtpd.diff

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1307
__

smtpd.diff
Description: Binary data
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1302] Fixes for profile/cprofile

2007-10-20 Thread Christian Heimes

Christian Heimes added the comment:

The new patch does a far more better job. I had the idea after a
discussion with Alexandre on #python and a small debugging session.

The tests for profile, cProfile and doctest are failing on my Linux box
because Py_FileSystemDefaultEncoding is UTF-8 but PyUnicode_Decode()
has a shortcut for utf-8 only. I've added a tolower loop and shortcuts
for UTF-16 and UTF-32 to PyUnicode_Decode(). 

I've also disabled the tests on system with a fs encoding that isn't
built in.

--
nosy: +alexandre.vassalotti
type:  - behavior
Added file: http://bugs.python.org/file8584/py3k_profile_fix2.patches

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1302
__

py3k_profile_fix2.patches
Description: Binary data
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1267] Py3K cannot run as ``python -S``

2007-10-20 Thread Christian Heimes

Christian Heimes added the comment:

 I think find_module() should return a file descriptor (fd), not a
 FILE*, but most of the rest of the code should call fdopen() on that
 fd. Only call_find_module() should use the fd to turn it into a Python
 file object. Then the amount of change should be pretty minimal.

I'd have to touch most functions in import.c and related files to change
find_module() to use a file descriptor. It's a PITA and I don't think
it's worse the effort for now.

The new patch adds PyFile_FromFd and removes the other PyFile_FromFile*
functions. It also changes some methods to use a file descriptor and
some documentation. Two minor changes aren't related to the bug but they
nagged me.

Added file: http://bugs.python.org/file8585/py3k_filefromfd.patch

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1267
__Index: Python/pythonrun.c
===
--- Python/pythonrun.c	(revision 58574)
+++ Python/pythonrun.c	(working copy)
@@ -719,7 +719,7 @@
 	}
 
 	/* Set sys.stdin */
-	if (!(std = PyFile_FromFileEx(stdin, stdin, r, fclose, -1,
+	if (!(std = PyFile_FromFd(STDIN_FILENO, stdin, r, -1,
   NULL, \n))) {
 		goto error;
 	}
@@ -728,7 +728,7 @@
 	Py_DECREF(std);
 
 	/* Set sys.stdout */
-	if (!(std = PyFile_FromFileEx(stdout, stdout, w, fclose, -1,
+	if (!(std = PyFile_FromFd(STDOUT_FILENO, stdout, w, -1,
   NULL, \n))) {
 goto error;
 }
@@ -737,7 +737,7 @@
 	Py_DECREF(std);
 
 	/* Set sys.stderr */
-	if (!(std = PyFile_FromFileEx(stderr, stderr, w, fclose, -1,
+	if (!(std = PyFile_FromFd(STDERR_FILENO, stderr, w, -1,
   NULL, \n))) {
 goto error;
 }
Index: Python/import.c
===
--- Python/import.c	(revision 58574)
+++ Python/import.c	(working copy)
@@ -92,7 +92,7 @@
 extern struct _inittab _PyImport_Inittab[];
 
 /* Method from Parser/tokenizer.c */
-extern char * PyTokenizer_FindEncoding(FILE *fp);
+extern char * PyTokenizer_FindEncoding(int);
 
 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
 
@@ -2561,6 +2561,7 @@
 	struct filedescr *fdp;
 	char pathname[MAXPATHLEN+1];
 	FILE *fp = NULL;
+	int fd = -1;
 	char *found_encoding = NULL;
 	char *encoding = NULL;
 
@@ -2571,17 +2572,24 @@
 	if (fdp == NULL)
 		return NULL;
 	if (fp != NULL) {
+		fd = fileno(fp);
+		if (fd != -1)
+			fd = dup(fd);
+		fclose(fp);
+		fp = NULL;
+	}
+	if (fd != -1) {
 		if (strchr(fdp-mode, 'b') == NULL) {
 			/* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
 			   memory. */
-			found_encoding = PyTokenizer_FindEncoding(fp);
+			found_encoding = PyTokenizer_FindEncoding(fd);
 			encoding = (found_encoding != NULL) ? found_encoding :
    (char*)PyUnicode_GetDefaultEncoding();
 		}
-		fob = PyFile_FromFileEx(fp, pathname, fdp-mode, fclose, -1,
+		fob = PyFile_FromFd(fd, pathname, fdp-mode, -1,
 	(char*)encoding, NULL);
 		if (fob == NULL) {
-			fclose(fp);
+			close(fd);
 			PyMem_FREE(found_encoding);
 			return NULL;
 		}
Index: Include/fileobject.h
===
--- Include/fileobject.h	(revision 58574)
+++ Include/fileobject.h	(working copy)
@@ -8,10 +8,7 @@
 
 #define PY_STDIOTEXTMODE b
 
-PyAPI_FUNC(PyObject *) PyFile_FromFile(FILE *, char *, char *, int (*)(FILE*));
-PyAPI_FUNC(PyObject *) PyFile_FromFileEx(FILE *, char *, char *,
-	 int (*)(FILE *), int, char *,
-	 char *);
+PyAPI_FUNC(PyObject *) PyFile_FromFd(int, char *, char *, int, char *, char *);
 PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);
 PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
 PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
Index: Objects/fileobject.c
===
--- Objects/fileobject.c	(revision 58574)
+++ Objects/fileobject.c	(working copy)
@@ -26,21 +26,15 @@
 /* External C interface */
 
 PyObject *
-PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
+PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding,
+	  char *newline)
 {
-	return PyFile_FromFileEx(fp, name, mode, close, -1, NULL, NULL);
-}
-
-PyObject *
-PyFile_FromFileEx(FILE *fp, char *name, char *mode, int (*close)(FILE *),
-	   int buffering, char *encoding, char *newline)
-{
 	PyObject *io, *stream, *nameobj=NULL;
 
 	io = PyImport_ImportModule(io);
 	if (io == NULL)
 		return NULL;
-	stream = PyObject_CallMethod(io, open, isiss, fileno(fp), mode,
+	stream = PyObject_CallMethod(io, open, isiss, fd, mode,
 buffering, encoding, newline);
 	Py_DECREF(io);
 	if (stream == NULL)
Index: Objects/bytesobject.c
===
--- Objects/bytesobject.c	(revision 58574)
+++ Objects/bytesobject.c	(working copy)
@@ -1214,7 +1214,7 @@
 Py_ssize_t