Re: Nested dictionaries trouble

2007-04-18 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, IamIan wrote:

> years = ["199%s" % x for x in range(0,10)]
> years += ["200%s" % x for x in range(0,10)]
> 
> I haven't had any luck doing this in one line though. Is it possible?

In [48]: years = map(str, xrange(1999, 2011))

In [49]: years
Out[49]:
['1999',
 '2000',
 '2001',
 '2002',
 '2003',
 '2004',
 '2005',
 '2006',
 '2007',
 '2008',
 '2009',
 '2010']

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling python from soruce vs RPM ?

2007-04-18 Thread hlubenow
howa wrote:

> I have compiled python 2.5 from source
> 
> i.e.
> 
> ./configure
> make
> make install
> 
> 
> but when i try to install another package require python, seems it
> can't regonize python...
> 
> e.g..
> 
> 
> /usr/bin/python is needed by xyz

Does "/usr/bin/python" exist ?

Why haven't you installed via rpm ?

H.

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


Re: Future Python Gui?

2007-04-18 Thread hlubenow
[EMAIL PROTECTED] wrote:

> If this were just a tool for me, it wouldn't matter.  My concern is
> distribution.  If anybody who wants to run my software then they also
> have to go through all the trouble to install these extensions, none
> of which seem to have decent instructions.  I'm an old-time hack and I
> have trouble getting them to work.  A simple user won't have a chance!
> 
> If Python doesn't declare an official Gui system, then it'll be
> fragmented, inconsistent, and unsupportable.

I guess that's why Tkinter, despite its primitive look, has made its way
into the Python-distribution and I think, for the same reason it will stay
there, until it can be replaced by something similar consistent.

H.

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


Re: Help Understanding mx.ODBC Error

2007-04-18 Thread Greg Corradini

Steve,
As always, thanks for your consistent help on matters big and small.
I've managed to solve the problem, although I'm scared b/c the bug is still
elusive.
I dumped and deleted my seperate Access DBs, created new ones and tried
running the scripts on old data (that these scripts were able to digest
successfully before) and new data (that they errored on to begin with).
Everything works without me changing any code around. Hmm?

I don't know much about Access or the JetEngine. Is it possible that .mdbs
can go corrupt if overused? This seems unlikely, but I'm dumbfounded.

Thanks again
Greg Corradini

Steve Holden wrote:
> 
> Greg Corradini wrote:
>> Hello All,
>> A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among
>> other things, both scripts create new tables, perform a query and then
>> populate the tables with data in a dictionary that I've uploaded from
>> elsewhere. These scripts have run hundreds of times in the last few weeks
>> with no problems. 
>>  
>> But recently they continue to bail on the mycursor.execute('An SQL
>> Statement') after the table has been created. I get the following error
>> message: 
>> Traceback (most recent call last):
>> File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence
>> Script\DBF Checker\Access_SQL.py", line 35, in ?
>> curse.execute(sql)
>> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access
>> Driver] Too few parameters. Expected 4.', 4612) 
>>  
>> The real stinker, however, is that after it bails I can manually call
>> mycursor.execute('An SQL Statement'), then call my insert statement in
>> the
>> Python Shell and it works fine. 
>>  
>> I just can't figure out how to reconcile this problem. Has anybody run
>> into
>> this before? 
>>  
>> Thanks
>> Greg Corradini
> 
> I suspect what's happening here is that you are presenting statements 
> you have made up programmatically, and the values you are trying to 
> insert include apostrophes that break the syntax of your SQL. However 
> there isn't really enough evidence to decide unless you are prepared to 
> show us the error traceback, possibly with a dump of the SQL statement 
> you are actually trying to execute.
> 
> I apologize in advance if you are using parameterized queries (as you 
> should to avoid SQL injection vulnerabilities among other major 
> problems) but this message is typical of Access when it sees words it 
> can't parse.
> 
> regards
>   Steve
> -- 
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb http://del.icio.us/steve.holden
> Recent Ramblings   http://holdenweb.blogspot.com
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: 
http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html#a10065545
Sent from the Python - python-list mailing list archive at Nabble.com.

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


PY shutil on win xp home version

2007-04-18 Thread jim-on-linux
python help,

A client is using win xp home.

 my program contains;
   shutil.copyfile(n, 'prn')

This runs fine on win xp pro but they are getting 
the following traceback.

 File "LOP_PRT_10.pyc", line 170, in __init__
  File "LOP_PRT_10.pyc", line 188, in Fprint1
  File "shutil.pyc", line 47, in copyfile
IOError: [Errno 2] No such file or directory: 
'prn'

Since this runs ok on win xp pro, does this have 
something to do with the home version of xp.  

I'm thinking of changeing  'prn' to 'lpt1' and 
trying again but I don't want to  use the client 
as a testor.  Or is there some other explaination 
for the problem.

jim-on-linux
-- 
http://mail.python.org/mailman/listinfo/python-list


python-list@python.org

2007-04-18 Thread attn . steven . kuo
On Apr 18, 12:23 pm, Anton Vredegoor <[EMAIL PROTECTED]>
wrote:

(snipped)

> But still, the 'while True:' loop and the 'try-except' clause and the
> explicit StopIteration are not necessary ...
>
> from collections import deque
>
> def xsplitter(seq, pred):
>  Q = deque(),deque()
>  it = iter(seq)
>  def gen(p):
>  while Q[p]:  yield Q[p].popleft()
>  for x in it:
>  if pred(x) == p: yield x
>  else:
>  Q[~p].append(x)
>  for x in gen(p):  yield x
>  return gen(1),gen(0)
>
> def test():
>  L = 1, 'a', 3, 'a', 4, 5, 6, 'a'
>  it1, it2 = xsplitter(L, lambda x: x == 'a')
>  print it1.next()
>  print it2.next()
>  print it1.next()
>
> if __name__=='__main__':
>  test()
>
> A.



Try it with

def test():
L = 'a', 1, 2, 'a'
it1, it2 = xsplitter(L, lambda x: x == 'a')
print it1.next()
print it2.next()
print it1.next()
print it2.next()


The last print statement raises StopIteration...
We, however, expected each iterator to contain
two elements (one yielding 'a' then 'a', and
the other yielding 1 then 2).

--
Regards,
Steven

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


Re: unicode data - accessing codepoints > FFFF on narrow python builts

2007-04-18 Thread vbr
Hi, thanks for the answer,

> From: Gabriel Genellina <[EMAIL PROTECTED]>
> Subj: Re: unicode data - accessing codepoints >  on narrow python builts
> Datum: 18.4.2007 21:33:11
> 
> 
> py> x=u"\N{GOTHIC LETTER AHSA}"
> py> ord(x)
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: ord() expected a character, but string of length 2 found
> py> unicodedata.name(x)
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: need a single Unicode character as parameter
> py> len(x)
> 2
> py> list(x)
> [u'\ud800', u'\udf30']

> 
> That looks like UTF-16 (?) but seen as two characters instead of one.
> Probably in a 32bits build Python should refuse to use such character (and  
> limit Unicode support to the basic plane?) (or not?) (if not, what's the  
> point of sys.maxunicode?) (enough parenthesis for now).
> 

> -- 
> Gabriel Genellina
> 


Yes, this is a UTF-16 surrogate pair, which is, as far as I know the usual way 
the characters outside the basic plane are handled on narrow python builds. 
There are some problems with it, but most things (I need) with non-basic plane 
characters can be done this way (GUI display, utf-8 text saving) - thus I 
wouldn't be happy, if this support were removed.
The problem is the access to unicodedata, which requires "a string of length 
1"; I thought, it could also accept the codepoint number, but it doesn't seem 
to be possible.
Thanks again.


vbr - Vlastimil Brom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Python Gui?

2007-04-18 Thread Jarek Zgoda
[EMAIL PROTECTED] napisał(a):

> If this were just a tool for me, it wouldn't matter.  My concern is
> distribution.  If anybody who wants to run my software then they also
> have to go through all the trouble to install these extensions, none
> of which seem to have decent instructions.  I'm an old-time hack and I
> have trouble getting them to work.  A simple user won't have a chance!

I am not a hacker, just a software developer, but I'd have no problems
in either installing PyGTK on Ubuntu box (sudo apt-get install
python-gtk2, but it's installed by default anyway) or on Windows XP
machine (double click on installer icon). "Simple user" is not an idiot
either and if she can read English, she wouldn't have hard time too.

The rumours on "problems installing GUI toolkits" are greatly exagerated
IMO.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting currency using locals

2007-04-18 Thread Grzegorz Ślusarek
Dnia Wed, 18 Apr 2007 19:38:26 +0100, Michael Hoffman napisał(a):

> Grzegorz Ślusarek wrote:
>> Hi all. I have situation that I have value that holds price and I must show
>> this price using national specification(e.g. thousands_sep). Any idea how
>> this can be done under python 2.4.4? I saw that function format from module
>> locals can format value with national specification, but this could be done
>> only in python 2.5. Any solution for 2.4?
> 
> I think you mean locale, for anyone else who was puzzled by this.

Upss, I'm sorry ofcourse I was thinking about locale.
Grzegorz Ślusarek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python crash after using weave inline

2007-04-18 Thread Peter Wang
Soren,

For future reference, you might want to direct weave-related questions
to the [EMAIL PROTECTED] mailing list.

> def cartPolFast(xlen, ylen, x_c, y_c):
>
> res = zeros((xlen,ylen))
>
> code = """
> {
> int xlen, ylen, x_c, y_c;

This line is unnecessary, because weave exposes those variables inside
the local scope of your code.  This also makes the braces at the top
and bottom of the code block unnecessary.

> for( x = 0; x == xlen; x++)
>for( y = 0; y == ylen; y++)
> rel_x = x-x_c;
> rel_y = y_c-y;
>
> res(x,y) = rel_y*rel_y;
> }

Two things:
1. You need to put curly braces around the three lines of the inner
loop.
2. You need to change "x == xlen" and "y == ylen" to "x < xlen" and "y
< ylen".

I made these modifications to your code and it runs fine on my machine
(macbook pro, OS 10.4, scipy 0.5.2.dev2314).


-peter

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


Re: Future Python Gui?

2007-04-18 Thread Stef Mientki

> The rumours on "problems installing GUI toolkits" are greatly exagerated

Not at all !!
As an experienced computer user,
I yesterday installed a well known Python package on a clean winXP machine,
and it costed me be about 1.5 .. 2 hours !!
There are always unexpected situations,
I think  software developers call them "new features" ;-)

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Python Gui?

2007-04-18 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
>> Tile is available right now in Tk as an extension package, and a Tkinter
>> wrapper for it can be found here:
>>
>> http://tkinter.unpythonic.net/wiki/TileWrapper
> 
> That site seems to be down (500 Internal Server Error).
> 
> 
>> Tile will be integrated into Tk's core when 8.5 is released. It's
>> supposed to enter beta testing Real Soon Now. However, I imagine that
>> Python/Tkinter will depend on Tk 8.4 for the foreseeable
>> future--certainly 8.5 won't be supported officially before a full,
>> stable release is made. Perhaps in Python 2.6?
> 
> That is okay with me.  It'll be a long time before I get to a point
> where I'll need easy release.  But knowing that it will be part of a
> future release will also mean I don't have to worry about refactoring
> everything if the toolkit I'm using goes out of style and is replaced
> by something else.
> 
> Out of curiosity...  Did that page have install instructions for
> Tile?  Other pages I've seen talk about it but don't say how to
> integrate it in to a python installation (under Windows or Linux).
> 
> -- Brian
> 

On Windows, the easiest way to install Tile is to grab it from 
ActiveState's Tcl distribution 
(http://www.activestate.com/products/activetcl/) and then place it with 
the Tcl/Tk bits that come with Python. The Tcl/Tk build for Windows that 
python.org provides doesn't ship with Tile.  You'll also have to install 
the Tile wrapper at the site I referenced earlier in your site-packages 
directory.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python crash after using weave inline

2007-04-18 Thread Soren
On Apr 18, 10:07 pm, Peter  Wang <[EMAIL PROTECTED]> wrote:
> Soren,
>
> For future reference, you might want to direct weave-related questions
> to the [EMAIL PROTECTED] mailing list.
>
> > def cartPolFast(xlen, ylen, x_c, y_c):
>
> > res = zeros((xlen,ylen))
>
> > code = """
> > {
> > int xlen, ylen, x_c, y_c;
>
> This line is unnecessary, because weave exposes those variables inside
> the local scope of your code.  This also makes the braces at the top
> and bottom of the code block unnecessary.
>
> > for( x = 0; x == xlen; x++)
> >for( y = 0; y == ylen; y++)
> > rel_x = x-x_c;
> > rel_y = y_c-y;
>
> > res(x,y) = rel_y*rel_y;
> > }
>
> Two things:
> 1. You need to put curly braces around the three lines of the inner
> loop.
> 2. You need to change "x == xlen" and "y == ylen" to "x < xlen" and "y
> < ylen".
>
> I made these modifications to your code and it runs fine on my machine
> (macbook pro, OS 10.4, scipy 0.5.2.dev2314).
>
> -peter

Thanks alot Peter!

I'm a bit rusty on the C! :)

Soren


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


Re: Help Understanding mx.ODBC Error

2007-04-18 Thread Steve Holden
Greg Corradini wrote:
[actually, her wrote it here but I moved it to the bottom]
> Steve Holden wrote:
>> Greg Corradini wrote:
>>> Hello All,
>>> A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among
>>> other things, both scripts create new tables, perform a query and then
>>> populate the tables with data in a dictionary that I've uploaded from
>>> elsewhere. These scripts have run hundreds of times in the last few weeks
>>> with no problems. 
>>>  
>>> But recently they continue to bail on the mycursor.execute('An SQL
>>> Statement') after the table has been created. I get the following error
>>> message: 
>>> Traceback (most recent call last):
>>> File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence
>>> Script\DBF Checker\Access_SQL.py", line 35, in ?
>>> curse.execute(sql)
>>> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access
>>> Driver] Too few parameters. Expected 4.', 4612) 
>>>  
>>> The real stinker, however, is that after it bails I can manually call
>>> mycursor.execute('An SQL Statement'), then call my insert statement in
>>> the
>>> Python Shell and it works fine. 
>>>  
>>> I just can't figure out how to reconcile this problem. Has anybody run
>>> into
>>> this before? 
>>>  
>>> Thanks
>>> Greg Corradini
>> I suspect what's happening here is that you are presenting statements 
>> you have made up programmatically, and the values you are trying to 
>> insert include apostrophes that break the syntax of your SQL. However 
>> there isn't really enough evidence to decide unless you are prepared to 
>> show us the error traceback, possibly with a dump of the SQL statement 
>> you are actually trying to execute.
>>
>> I apologize in advance if you are using parameterized queries (as you 
>> should to avoid SQL injection vulnerabilities among other major 
>> problems) but this message is typical of Access when it sees words it 
>> can't parse.
>>
 > Steve,
 > As always, thanks for your consistent help on matters big and small.
 > I've managed to solve the problem, although I'm scared b/c the bug is 
still
 > elusive.
 > I dumped and deleted my separate Access DBs, created new ones and tried
 > running the scripts on old data (that these scripts were able to digest
 > successfully before) and new data (that they errored on to begin with).
 > Everything works without me changing any code around. Hmm?
 >
 > I don't know much about Access or the JetEngine. Is it possible that 
.mdbs
 > can go corrupt if overused? This seems unlikely, but I'm dumbfounded.

Greg:

No, there are no known cases of a database getting "tired" :-)

It sounds like a data dependency of some sort, but if the error has 
"gone away" then I guess we no longer have anything to work with. This 
is somewhat annoying, as I hate to see an error go untraced.

Take it from me, it does look like a SQL error - *are* you building your 
statements in the program, or are you using proper parameterization with 
"?" in your statements where a parameter would go?

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

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


Re: image sequence to Quicktime movie

2007-04-18 Thread half . italian
I haven't experimented with it myself, but you'll probably find what
you need here. (Only works on original mac python distribution)

[sean:~] sean% python
Python 2.3.5 (#1, Aug 12 2006, 00:08:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from Carbon import Qt
>>> dir(Qt)
['AddSoundDescriptionExtension', 'AddTime', 'AlignWindow',
'CanQuickTimeOpenDataRef', 'CanQuickTimeOpenFile',
'ClearMoviesStickyError', 'CloseMovieFile', 'ConvertTime',
'ConvertTimeScale', 'CreateMovieFile', 'CreateShortcutMovieFile',
'DeleteMovieFile', 'DisposeMatte', 'DragAlignedWindow',
'EndFullScreen', 'EnterMovies', 'Error', 'ExitMovies',
'FlashMediaDoButtonActions', 'FlashMediaFrameLabelToMovieTime',
'FlashMediaFrameNumberToMovieTime',
'FlashMediaGetDisplayedFrameNumber', 'FlashMediaGetFlashVariable',
'FlashMediaGetRefConBounds', 'FlashMediaGetRefConID',
'FlashMediaGetSupportedSwfVersion', 'FlashMediaIDToRefCon',
'FlashMediaSetFlashVariable', 'FlashMediaSetPan', 'FlashMediaSetZoom',
'FlashMediaSetZoomRect', 'GetDataHandler',
'GetMovieImporterForDataRef', 'GetMoviesError',
'GetMoviesStickyError', 'GetSoundDescriptionExtension', 'Media',
'Media3DGetCameraAngleAspect', 'Media3DGetCameraData',
'Media3DGetCameraRange', 'Media3DGetCurrentGroup',
'Media3DRotateNamedObjectTo', 'Media3DScaleNamedObjectTo',
'Media3DSetCameraAngleAspect', 'Media3DSetCameraData',
'Media3DSetCameraRange', 'Media3DTranslateNamedObjectTo', 'MediaType',
'Movie', 'MovieController', 'MovieControllerType', 'MovieType',
'MoviesTask', 'MusicMediaGetIndexedTunePlayer', 'NewMovie',
'NewMovieFromDataFork', 'NewMovieFromDataFork64',
'NewMovieFromDataRef', 'NewMovieFromFile', 'NewMovieFromHandle',
'NewMovieFromScrap', 'NewTimeBase', 'NewUserData',
'NewUserDataFromHandle', 'OpenMovieFile', 'PasteHandleIntoMovie',
'QTDismissStandardParameterDialog', 'QTGetMIMETypeInfo',
'QTIsStandardParameterDialogEvent', 'QTNewAlias',
'QTRegisterAccessKey', 'QTStandardParameterDialogDoAction',
'QTTextToNativeText', 'QTUnregisterAccessKey', 'RemoveMovieResource',
'RemoveSoundDescriptionExtension', 'SpriteMediaCountImages',
'SpriteMediaCountSprites', 'SpriteMediaDisposeSprite',
'SpriteMediaGetActionVariable',
'SpriteMediaGetActionVariableAsString',
'SpriteMediaGetDisplayedSampleNumber', 'SpriteMediaGetImageName',
'SpriteMediaGetIndImageDescription', 'SpriteMediaGetProperty',
'SpriteMediaGetSpriteName', 'SpriteMediaGetSpriteProperty',
'SpriteMediaHitTestAllSprites', 'SpriteMediaHitTestOneSprite',
'SpriteMediaHitTestSprites', 'SpriteMediaSetActionVariable',
'SpriteMediaSetActionVariableToString', 'SpriteMediaSetProperty',
'SpriteMediaSetSpriteProperty', 'SpriteMediaSpriteIDToIndex',
'SpriteMediaSpriteIndexToID', 'SubtractTime',
'TextMediaAddHiliteSample', 'TextMediaAddTESample',
'TextMediaAddTextSample', 'TextMediaDrawRaw', 'TextMediaFindNextText',
'TextMediaGetTextProperty', 'TextMediaHiliteTextSample',
'TextMediaRawIdle', 'TextMediaRawSetup', 'TextMediaSetTextProperty',
'TextMediaSetTextSampleData', 'TimeBase', 'TimeBaseType', 'Track',
'TrackTimeToMediaTime', 'TrackType', 'UserData', 'UserDataType',
'VideoMediaGetCodecParameter', 'VideoMediaGetStallCount',
'VideoMediaGetStatistics', 'VideoMediaResetStatistics',
'VideoMediaSetCodecParameter', '__builtins__', '__doc__', '__file__',
'__name__']
>>>

~Sean

On Apr 18, 10:16 am, Simon Cassels <[EMAIL PROTECTED]> wrote:
> did u ever find anything out about this ?
>
> if so can you help me with some leads i am trying to figure an action  
> that can convert image files to quicktime automatically.
>
> cheers
> simon


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


Re: Martel Package from Biopython

2007-04-18 Thread Paul McGuire
On Apr 18, 12:28 pm, elventear <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I know this is not the best place to ask this but I haven't had luck
> in the Biopython forums with my questions, so I'll just try here.
>
> I want to use the Martel package to do some parsing. I've found it to
> be very powerful and convenient. Yet the documentation avaialble is
> less than complete. I have a few questions on how to use it, if you
> know the answers to my questions:
>
> - How does Bio.Std.record  affect the parsing of a Martel expression.
> - How does Bio.RecordReader work? How does it interact with
> Martel.HeaderFooter?
> - Many of the matching objects (ie. Martel.Digits) have an attrs
> argument. How does it work?
>
> Thanks!

Andrew Dalke says in his blog that he finds pyparsing to be similar in
concept to Martel.  I looked over the Martel presentations at his web
site, and I can see some similarities, but pyparsing has some of its
own peculiarities, too.  So if Martel remains a mystery, you could
give pyparsing a shot.  Pyparsing tries to make parser-writing a less
painful process, so it incorporates some conventions - most notably,
pyparsing assumes that whitespace is significant for the purposes of
word boundaries and such, but you grammar does not need to explicitly
spell out where whitespace would go.  Or try one of these other
parsing packages on Ned Batchelder's web page:
http://nedbatchelder.com/text/python-parsers.html.

-- Paul

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


tkinter canvas

2007-04-18 Thread Gigs_
how to write text on canvas. i know that i need to use canvas.create_text, but 
how to write text than when i create_text?
or how to access object ID in canvas and change some options?


thanks in advance!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Python Gui?

2007-04-18 Thread kirkjobsluder
On Apr 18, 11:24 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> > I'd say that the best bet is to learn swig and similar
> > bridging, expanding, and embedding mechanisms.
> > Python GUI programming is likely to involve either
> > python hooking into frameworks like Cocoa, Qt, or
> > wxWidgets, python embedded in frameworks
> > like Java or .NET, or flavors of python used
> > as domain-specific languages in applications such as
> > emacs, vim, and OpenOffice.org.
>
> If this were just a tool for me, it wouldn't matter.  My concern is
> distribution.  If anybody who wants to run my software then they also
> have to go through all the trouble to install these extensions, none
> of which seem to have decent instructions.  I'm an old-time hack and I
> have trouble getting them to work.  A simple user won't have a chance!

Deployment has improved a lot in recent years, PyObjC is a simple
double-click on a package.  Most windows libraries work the same way.
On the FOSS Unix world, you would add to a package system which will
install dependencies automatically.  When I used a FOSS Unix, I really
only got burned when I decided to live on the bleeding edge. And as
someone else pointed out, package tools should take much of the work
out of delivery.

Meanwhile, things could work the other way around. If Apple extends
their support to PyObjC for example, python developers would know that
every new OS X system would be able to run their PyObjC.

> If Python doesn't declare an official Gui system, then it'll be
> fragmented, inconsistent, and unsupportable.

I don't see that as the case because many other languages don't have
an "official" GUI system including C, C++, Ruby, lisp, Basic and
perl.  All of these have their active areas of deployment.  For that
matter, Java has three "official" GUI systems with most development on
the server side.

And didn't comp.long.python have this same argument in regards to
MySQL support which was dropped from php? In addition to license
issues, the php core library just wasn't used, and lagged behind the
MySQL library.

My personal opinion is that GUI development is such a moving target
that toolkits are a poor choice for inclusion into the core standard
libraries.  There does not appear to be a standards process involved,
and toolkits are expanding or changing parts of their API every few
years.  Anything that could be added, is going to be obsolete by the
time it is incorporated into the standard. My feeling is that python
is better served by encouraging GUI developers to include python-
friendly bindings.

> I wouldn't mind using just Tkinter, despite it's primative look,
> except that it doesn't support more advanced widgets like "notebook".

I wouldn't mind seeing tkgrid and tkhtml added to the standard
library.  But Tk is probably "good enough" for most simple
interfaces.

>
> -- Brian


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


Re: unicode data - accessing codepoints > FFFF on narrow python builts

2007-04-18 Thread vbr
Hi, thanks for your answer,
I'll try to check the source of unicodedata;
Using the wide Unicode build seems to be a kind of overkill for now, as for the 
vast majority of my uses, the BMP is enough. I was rather looking for some 
"lower-cost" alternatives for those rare cases, when I need higher multilingual 
planes.

Thanks again,

Vlastimil Brom
 - vbr

> From: "Martin v. Löwis" <[EMAIL PROTECTED]>
> Subj.: Re: unicode data - accessing codepoints >  on narrow python builts
> Datum: 18.4.2007 21:37:39
> 
> > Is it a bug in unicodedata, or is this the expected behaviour on a
> > narrow build?
> 
> It's a bug. It should either raise an exception, or return the correct
> result. If you know feel like submitting a bug report: please try to
> come up with a patch instead.
> 
> > Another problem I have is to access the "characters" and their
> > properties by the respective codepoints: under  it is possible,
> > to use unichr(), which isn't valid for higher valules on a narrow
> > build It is possible to derive the codepoint from the surrogate pair,
> > which would be usable also for wider codepoints.
> 
> See PEP 261. This is by design.
> 
> > Currently, I'm using a kind of parallel database for some unicode
> > ranges above , but I don't think, this is the most effective way.
> 
> Just use a wide Unicode build instead.
> 
> Regards,
> Martin
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PY shutil on win xp home version

2007-04-18 Thread Tim Golden
jim-on-linux wrote:
> python help,
> 
> A client is using win xp home.
> 
>  my program contains;
>shutil.copyfile(n, 'prn')
> 
> This runs fine on win xp pro but they are getting 
> the following traceback.
> 
>  File "LOP_PRT_10.pyc", line 170, in __init__
>   File "LOP_PRT_10.pyc", line 188, in Fprint1
>   File "shutil.pyc", line 47, in copyfile
> IOError: [Errno 2] No such file or directory: 
> 'prn'
> 
> Since this runs ok on win xp pro, does this have 
> something to do with the home version of xp.  
> 
> I'm thinking of changeing  'prn' to 'lpt1' and 
> trying again but I don't want to  use the client 
> as a testor.  Or is there some other explaination 
> for the problem.

Not that this is your question, but if you're
trying to print under Windows have you looked
at:

   http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html

for alternatives?

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


Re: Future Python Gui?

2007-04-18 Thread Kevin Walzer

>> I wouldn't mind using just Tkinter, despite it's primative look,
>> except that it doesn't support more advanced widgets like "notebook".

When Tile becomes part of the core Tk library, it should be accessible 
from Tkinter as well. Tile has a nice notebook widget. See 
http://tktable.sourceforge.net/tile/screenshots/windowsxp.html, 
http://tktable.sourceforge.net/tile/screenshots/macosx.html and 
http://tktable.sourceforge.net/tile/screenshots/unix.html.

> I wouldn't mind seeing tkgrid and tkhtml added to the standard
> library.  But Tk is probably "good enough" for most simple
> interfaces.

I'm not sure what tkgrid is: isn't that the standard Tk "grid" 
algorithm? If so, it's already accessible from Tkinter.

As for Tkhtml, it's undergoing *heavy* development: it's moving from a 
lightweight, basic HTML renderer into a full-featured browser widget 
with CSS support: see http://tkhtml.tcl.tk/ and 
http://tkhtml.tcl.tk/hv3.html and http://tkhtml.tcl.tk/screenshot1.gif. 
  The drawbacks are that it's currently at an alpha stage, and while the 
hv3 browser based on Tkhtml 3 is very impressive, it's overkill for the 
simple display of HTML--and the API for constructing a simpler widget 
seems to be very complex. As well, because it's still alpha, no one has 
wrapped it for Tkinter as of yet.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Python Gui?

2007-04-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
.
.
.
>I wouldn't mind using just Tkinter, despite it's primative look,
>except that it doesn't support more advanced widgets like "notebook".
.
.
.
"Tile" has already been mentioned in this thread, and I know
there'll be at least one more follow-up on the subject.  Tile
includes a ("native"!) notebook, as well as a combobox, tree-
view, ... http://wiki.tcl.tk/11075 >.

I recognize that Tile might not be widely installed until 2.6
or so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Installing Python on NT

2007-04-18 Thread Schwartz, Hillary


___
Hillary Schwartz
Applications Specialist, IT - Development
Lerner, Sampson & Rothfuss, LPA
Phone: (513) 241-3100 x3138
[EMAIL PROTECTED]

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

Python Threads -

2007-04-18 Thread S.Mohideen
Hi All,

Can you please suggest a technique in Python where we can spawn few number 
of worker threads and later map them to a function/s to execute individual 
Jobs.

Any references would be helpful..

Thanks
Moin
 

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


Antigen Notification: Antigen found a message matching a filter

2007-04-18 Thread Antigen_VITORIA
Microsoft Antigen for Exchange found a message matching a filter. The message 
is currently Detected.
Message: "Python_list Digest_ Vol 43_ Issue 299"
Filter name: "KEYWORD= spam: xxx "
Sent from: "[EMAIL PROTECTED]"
Folder: "SMTP Messages\Inbound And Outbound"
Location: "ITURAN/First Administrative Group/VITORIA"


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


Re: tkinter canvas

2007-04-18 Thread kyosohma
On Apr 18, 3:43 pm, Gigs_ <[EMAIL PROTECTED]> wrote:
> how to write text on canvas. i know that i need to use canvas.create_text, but
> how to write text than when i create_text?
> or how to access object ID in canvas and change some options?
>
> thanks in advance!

All you need to do is canvas.create_text(x, y, text='Hello World')
where x and y are coordinates on the canvas. You can also add fg and/
or bg to set foreground and background colors, respectively.

Mike

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


Do other Python GUI toolkits require this?

2007-04-18 Thread Kevin Walzer
 From the introduction to PyObjC, the Python-Objective-C bridge on Mac OS X:

"As described in Objective-C for PyObjC users the creation of 
Objective-C objects is a two-stage process. To initialize objects, first 
call a class method to allocate the memory (typically alloc), and then 
call an initializer (typically starts with init). Some classes have 
class methods which perform this behind the scenes, especially classes 
that create cached, immutable, or singleton instances."

An example:

myObject = NSObject.alloc().init()

I know Tkinter doesn't require any manual memory allocation of this 
sort. Does wxPython, PyQt, PyGtk require anything like this when 
creating objects?

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ???

2007-04-18 Thread mathedman
On 17 Apr 2007 06:56:05 -0700, [EMAIL PROTECTED] wrote:

 So many of the talking-head rants about VPI are idiotic.
  1) bomb scares should have ak\lerted officials --blah blah blah
The fact is that on a large university campus bomb threats
are almost as common as exams! (there is a correlation!)
They are quietly checked out without emptying dorms or
CLASSROOMS.
  2)VPI is not a "schoolhouse: and the students are NOT kids.
 The stiudents are adults. In fact, it is a violation of federal 
  law for a university officials to discuss a student's
   performasnce with the parents!
  3) Lock-down-- INSANE  
  VPI is a small city.About 30,000 people, dozens of buildings (
some a mile apart) on 2600 acres (more than 3 times the size of
NY's Central Park. It is not fenced or walled. The grounds and  
 even the hallways of classroom buildings are coinsidered "public"
Select your favorite city of 30,000 people. Consider: police
 are called to an apartment building to investigate reported 
 gunshots. They find two dead and questioning leads to reports 
 that the killer left "town". Do they lock down the entire town?
Of course not --- it's not feasable ---
Nor would they notify all residents of danger -- there was no 
  reason to believe there was ---
   VPI of such a "city" --- and police already had a "person of 
 interest" for the two killings   --- a gun "enthusiast" ---the 
 boyfriend of the dead  girl.

   I  have spent many years on university campuses. But, I have 
  never had any association with VPI and ave never been there.
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do other Python GUI toolkits require this?

2007-04-18 Thread James Stroud
Kevin Walzer wrote:
>  From the introduction to PyObjC, the Python-Objective-C bridge on Mac 
> OS X:
> 
> "As described in Objective-C for PyObjC users the creation of 
> Objective-C objects is a two-stage process. To initialize objects, first 
> call a class method to allocate the memory (typically alloc), and then 
> call an initializer (typically starts with init). Some classes have 
> class methods which perform this behind the scenes, especially classes 
> that create cached, immutable, or singleton instances."
> 
> An example:
> 
> myObject = NSObject.alloc().init()
> 
> I know Tkinter doesn't require any manual memory allocation of this 
> sort. Does wxPython, PyQt, PyGtk require anything like this when 
> creating objects?
> 

This appears more or less unique to Objective C. It looks that with 
PyObjC, you have to interact with the Objective C runtime to manage 
memory. This is not required, thankfully, with any other GUI tookits 
I've seen.

I think the main difference is that PyObjC is not a GUI toolkit per se, 
but is simply a means to make the Objective C runtime (and hence Cocoa) 
available via a python layer.

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


comparison with None

2007-04-18 Thread Alan G Isaac
 >>> None >= 0
False
 >>> None <= 0
True

Explanation appreciated.

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


Re: Compiling python from soruce vs RPM ?

2007-04-18 Thread Paul Boddie
howa wrote:
> I have compiled python 2.5 from source
>
> i.e.
>
> ./configure
> make
> make install

By default, configure uses /usr/local as the "prefix", not /usr...

> but when i try to install another package require python, seems it
> can't regonize python...
>
> e.g..
>
>
> /usr/bin/python is needed by xyz

Consequently, by default, Python will be found at /usr/local/bin/
python, not /usr/bin/python as you seem to require. Try building from
source again:

make clean # probably needed if rebuilding in the same place
./configure --prefix=/usr
make
make install

Since /usr/bin/python isn't found, it doesn't look like there's an
existing version of Python that you might overwrite, but it's
important to verify such things when installing software. That's where
your distribution's packages have an advantage, and it's arguably a
better idea to install such packages instead, possibly building them
from source if no binary packages exist yet for Python 2.5. (If no
source packages exist, you have a bit more work to do.)

Paul

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


Re: Python Threads -

2007-04-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
S.Mohideen <[EMAIL PROTECTED]> wrote:
>
>Can you please suggest a technique in Python where we can spawn few number 
>of worker threads and later map them to a function/s to execute individual 
>Jobs.

You can see an example for a web spider on my Python website.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Help a hearing-impaired person: http://rule6.info/hearing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do other Python GUI toolkits require this?

2007-04-18 Thread Kevin Walzer
James Stroud wrote:

> This appears more or less unique to Objective C. It looks that with 
> PyObjC, you have to interact with the Objective C runtime to manage 
> memory. This is not required, thankfully, with any other GUI tookits 
> I've seen.
> 
> I think the main difference is that PyObjC is not a GUI toolkit per se, 
> but is simply a means to make the Objective C runtime (and hence Cocoa) 
> available via a python layer.
> 
> James

That's kind of what I thought. Memory management? In Python? *shudder*

I'm a Mac-only developer, and I keep telling myself I should drink the 
Mac-only Kool-aid of PyObjC. But Tk is burned into my brain, and 
anything else looks and feels weird to me. Tk is so flexible that it's 
fairly easy to tweak it to look Mac-like, and it's simpler to do that 
than learn a new tookit.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comparison with None

2007-04-18 Thread Terry Reedy

"Alan G Isaac" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| >>> None >= 0
| False
| >>> None <= 0
| True
|
| Explanation appreciated.

Should be in the reference manual section on comparisons.



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


Re: comparison with None

2007-04-18 Thread Steven Howe
Alan G Isaac wrote:
>  >>> None >= 0
> False
>  >>> None <= 0
> True
>
> Explanation appreciated.
>
> Thanks,
> Alan Isaac
>   
I've read and found that 'None' comparisons is not always a good idea.
Better to:
from types import NoneType

x = None
if type( x ) == NoneType:
# true
< code >
else:
# false; do something else.
< more code >

Steven Howe

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


Re: pycurl problem

2007-04-18 Thread Gabriel Genellina
En Wed, 18 Apr 2007 11:48:06 -0300, pabloski <[EMAIL PROTECTED]> escribió:

> I noted that if I define c.proxy and c.url as costants e.g. c.url =
> "http://www.google.com/search?blah blah" and c.proxy =
> "127.0.0.1:8080" it works
>
> However if I define them as described before pycurl raises the TypeError

Python -with its long "batteries included" tradition- comes with two  
powerful tools for diagnosing problems: print and repr

print "c.url", type(c.url), repr(c.url)
print "c.proxy", type(c.proxy), repr(c.proxy)

-- 
Gabriel Genellina

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


Re: comparison with None

2007-04-18 Thread Paul McGuire
On Apr 18, 5:19 pm, Steven Howe <[EMAIL PROTECTED]> wrote:
> Alan G Isaac wrote:
> >  >>> None >= 0
> > False
> >  >>> None <= 0
> > True
>
> > Explanation appreciated.
>
> > Thanks,
> > Alan Isaac
>
> I've read and found that 'None' comparisons is not always a good idea.
> Better to:
> from types import NoneType
>
> x = None
> if type( x ) == NoneType:
> # true
> < code >
> else:
> # false; do something else.
> < more code >
>
> Steven Howe

None is a singleton - there is but one None and no other.  The only
comparisons that make sense with None are "is" or "is not".  type(x)
== NoneType is unnecessary, x is None is sufficient.

>>> x = None
>>> x is None
True
>>> y = None
>>> x is y
True
>>> z = object()
>>> z is None
False
>>> z is not None
True
>>> x is not None
False
>>> y is not None
False

-- Paul


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


Re: comparison with None

2007-04-18 Thread brzrkr0
On Apr 18, 3:19 pm, Steven Howe <[EMAIL PROTECTED]> wrote:
> I've read and found that 'None' comparisons is not always a good idea.
> Better to:
> from types import NoneType
>
> x = None
> if type( x ) == NoneType:
> # true
> < code >
> else:
> # false; do something else.
> < more code >
>
> Steven Howe

Is that any better than this?

if x is None:
# do something
else:
# do something else

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


Re: Future Python Gui?

2007-04-18 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
>
> If Python doesn't declare an official Gui system, then it'll be
> fragmented, inconsistent, and unsupportable.

I don't agree. GUI frameworks are somewhat like Web frameworks, object-
relational mappers, and all the other things that work in different
ways, work better on various systems, appeal to different tastes and
so on. There are a number of cross-platform GUI frameworks which claim
some kind of native look and feel on every platform, but declaring one
the winner is not going to convince the satisfied users of the others
of its superiority. Meanwhile, some people don't care about more than
one platform and will quite happily target their chosen platform
intentionally, and it's worth remembering that anyone developing for,
say, a Free desktop environment will treat such an environment as the
means to provide "worthwhile" portability - targeting the Windows API,
for example, becomes an irrelevance.

There are a few technologies with an "official" GUI framework or APIs,
with Java being one of the more notorious at delivering either a
fairly weak set of features performing inconsistently across platforms
(AWT) or a more ambitious set of features wrapped up in a baroque
architecture, performing poorly and still managing to look alien on
most platforms (Swing). And before anyone mentions Delphi/Kylix, a
recent experience trying out a Kylix-based application on a Red Hat
system provided enough of an explanation as to why Borland dropped
that particular product.

As I've said often enough on the topic of Web frameworks, picking
winners gives only a temporary victory to those who want to avoid
making decisions. It's better to provide people with a means of making
an informed choice, and it should be realised that people will
approach this choice from rather different angles. It isn't always
going to be, "I want to write a Python application - what GUI should I
use?" Instead, it may be, "I want to write a KDE application - can I
do so in Python and what are my options?" Pretending that the answer
is always the same will frequently drive people to other technologies,
not attract them to a technology selling a vision that turns out to be
a mirage.

Paul

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


using the sysloghandler class

2007-04-18 Thread Nicholas Milkovits
Hello all,

I have a small script which attempts to write to the user.log syslog

import logging, logging.handlers

logger = logging.getLogger('bender')
handler = logging.handlers.SysLogHandler(('localhost',
logging.handlers.SYSLOG_UDP_PORT),
logging.handlers.SysLogHandler.LOG_USER)
formatter = logging.Formatter('%(filename)s: %(levelname)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.error('what')

but no log entries show up, however if I use the syslog module as such:

>>> import syslog
>>> syslog.syslog('testing syslog')

everything works fine. I am not sure what I am doing wrong. Any help
would be appreciated.

Thanks,

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


Re: What makes an iterator an iterator?

2007-04-18 Thread 7stud
On Apr 18, 8:50 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> The special methods need to be on the type -- having attributes of those
> names on the instance doesn't help (applies to all special methods in
> the normal, aka newstyle, object model; legacy, aka classic, classes,
> work by slightly different and not entirely self-consistent semantics).
>
> Alex

Can you explain some of the details of why this code fails:

---
class Parrot(object):
def __iter__(self):
return self
def __init__(self):
self.next = self.next().next
def next(self):
for word in "Norwegian Blue's have beautiful
plumage!".split():
yield word

P = Parrot()
for word in P:
print word
--

It causes an infinite loop that just prints out the iterator object
returned when you call the generator function.

If I try this:

-
class Parrot(object):
def __iter__(self):
return self
def __init__(self):
print self.next()
print self.next().next
#self.next = self.next().next
def next(self):
for word in "Norwegian Blue's have beautiful
plumage!".split():
yield word

P = Parrot()

'''
for word in P:
print word
'''
--

the output is:




Based on that output, self.next() is the iterator object that wraps
the generator function, and it has a next() method.  If 'i' is the
iterator object, then the statement:

self.next = self.next().next

is equivalent to:

self.next = i.next

and therefor calling P.next() is equivalent to i.next(), which appears
to be exactly what you want.   As I understand it, this is how the for
loop works:

1) The for loop causes the built in, global iter() function to be
called with P as an argument: iter(P).  That calls P's __iter__()
method, which just returns P.

2) The for loop repeatedly calls next() on whatever object is returned
by 1), so that results in calls to P.next().

3) P.next() is equivalent to i.next()

I don't understand at which step does the code fail.





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


Re: comparison with None

2007-04-18 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:
> On Apr 18, 3:19 pm, Steven Howe <[EMAIL PROTECTED]> wrote:
>> I've read and found that 'None' comparisons is not always a good idea.
>> Better to:
>> from types import NoneType
>>
>> x = None
>> if type( x ) == NoneType:
>> # true
>> < code >
>> else:
>> # false; do something else.
>> < more code >
>>
>> Steven Howe
> 
> Is that any better than this?
> 
> if x is None:
> # do something
> else:
> # do something else

To the contrary, it's not as good. "if x is None" is much clearer, and 
probably faster.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comparison with None

2007-04-18 Thread Gary Herron
Alan G Isaac wrote:
>  >>> None >= 0
> False
>  >>> None <= 0
> True
>
> Explanation appreciated.
>
> Thanks,
> Alan Isaac
>   
So that we can sort lists of objects, even when the objects of are
different types, Python guarantees to supply a unique and consistent
ordering of any two objects.   The definition of Python does not specify
what that ordering is -- that's implementation dependent --  but any two
objects of any two types *do* have an ordering and that ordering will
always be the same.

So in your implementation None is less than 0 (and probably less than
any integer).   Given that, your two observations above are consistent.

Gary Herron

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


Re: comparison with None

2007-04-18 Thread Gary Herron
[EMAIL PROTECTED] wrote:
> On Apr 18, 3:19 pm, Steven Howe <[EMAIL PROTECTED]> wrote:
>   
>> I've read and found that 'None' comparisons is not always a good idea.
>> Better to:
>> from types import NoneType
>>
>> x = None
>> if type( x ) == NoneType:
>> # true
>> < code >
>> else:
>> # false; do something else.
>> < more code >
>>
>> Steven Howe
>> 
>
> Is that any better than this?
>
> if x is None:
> # do something
> else:
> # do something else
>   
No.  using
  if x is None:
is the recommended way.

Gary Herron

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


python-list@python.org

2007-04-18 Thread Anton Vredegoor
[EMAIL PROTECTED] wrote:

> Try it with
> 
> def test():
> L = 'a', 1, 2, 'a'
> it1, it2 = xsplitter(L, lambda x: x == 'a')
> print it1.next()
> print it2.next()
> print it1.next()
> print it2.next()
> 
> 
> The last print statement raises StopIteration...
> We, however, expected each iterator to contain
> two elements (one yielding 'a' then 'a', and
> the other yielding 1 then 2).

Ouch! I never understood much about generators anyway.

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


Re: comparison with None

2007-04-18 Thread Robert Kern
Steven Howe wrote:
> Alan G Isaac wrote:
>>  >>> None >= 0
>> False
>>  >>> None <= 0
>> True
>>
>> Explanation appreciated.
>>
>> Thanks,
>> Alan Isaac
>>   
> I've read and found that 'None' comparisons is not always a good idea.
> Better to:
> from types import NoneType
> 
> x = None
> if type( x ) == NoneType:
> # true
> < code >
> else:
> # false; do something else.
> < more code >

The recommended idiom is to test for "x is None".

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Newbie: import

2007-04-18 Thread 7stud
On Apr 18, 10:34 am, [EMAIL PROTECTED] wrote:
> I thought import used relative paths from either the python executable
> or the script being executed.  I have a script pulling in code from an
> arbitrary directory.  How is this happening?
>
> It's a RHEL 4 environment by the way.  I couldn't find any relevant
> environment variables.
>
> Thanks from a newbie for any insight.

>From the online python tutorial here:

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

There is this:

--
6.1.1 The Module Search Path

When a module named spam is imported, the interpreter searches for a
file named spam.py in the current directory, and then in the list of
directories specified by the environment variable PYTHONPATH. This has
the same syntax as the shell variable PATH, that is, a list of
directory names. When PYTHONPATH is not set, or when the file is not
found there, the search continues in an installation-dependent default
path; on Unix, this is usually .:/usr/local/lib/python.

Actually, modules are searched in the list of directories given by the
variable sys.path which is initialized from the directory containing
the input script (or the current directory), PYTHONPATH and the
installation-dependent default. This allows Python programs that know
what they're doing to modify or replace the module search path. Note
that because the directory containing the script being run is on the
search path, it is important that the script not have the same name as
a standard module, or Python will attempt to load the script as a
module when that module is imported. This will generally be an error.
See section 6.2, ``Standard Modules,'' for more information.
--

You can use the following trick to import one of your own modules when
your module
 isn't in the current directory(and doesn't happen to be in PYTHONPATH
or the default path):

import sys
sys.path.append("relative path or absolute path to dir with the
module")  # temporarily changes sys.path

import mymodule

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


Third party script debugging on remote server ...

2007-04-18 Thread dbee
Right. I've got a really, really annoying/difficult/time consuming
problem with my development environment. I'm using django to build a
web app with paypal integration. My server is hosted remotely, and it
is receiving IPN (payment notifications) POST requests from Paypal.
I've checked on google and irc and this is my last shot at solving
this before I go mad ... :-(

The problem is that I can't debug those POST requests. Browser
debugging is out of the question obviously cause I'm not at the
computer, ( and it doesn't have X ).

I've tried cgitb but that doesn't seem to work at all ...

import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain')
import cgitb; cgitb.enable()

... neither of those commands have any effect. Although I do log other
parts of the script to /tmp, so I know that it's reachable...

mod_python absolutely refuses to error_log to the apache error_log. I
have restarted it and it still won't flush whatever error buffer it
may ( or may not ) have stored.

I can re-constitute the requests in my browser using a GET request.
But frankly, that's kinda messy - there are lots of paypal IPN
combinations and I may have to integrate other applications with
paypal. So ideally speaking I'm looking for a proper debugging
environment for this kind of thing ...

Basically, I either want mod_python to start error_logging properly,
or I want some type of working traceback environment to be available.
Help !

Server version: Apache/2.0.52
Server built:   Aug 13 2006 03:29:43
CentOS4.x: (RedHat Clone)
mod_python.i386  3.1.3-5.1
installed

# httpd.conf



 ServerName mydomain.biz
 ServerAlias www.mydomain.biz
 SetHandler mod_python
 PythonPath "['/home/babo/django'] + sys.path"
 PythonHandler django.core.handlers.modpython
 SetEnv DJANGO_SETTINGS_MODULE mydomain.settings

  
   SetHandler None
   Options None
  




My python.conf: ( seems pretty normal )

#
# Mod_python is a module that embeds the Python language interpreter
# within the server, allowing Apache handlers to be written in Python.
#

LoadModule python_module modules/mod_python.so

# Override type-map handler for /var/www/manual


SetHandler default-handler



# This will cause files beneath /var/www/html with the extension .spam
# to be handled by the Python script /var/www/html/eggs.py
#
#
#AddHandler python-program .spam
#PythonHandler eggs
#

# This will cause all requests to the /python heirachy of your
# webserver to be handled by the python script /path/to/myhandler.py
#
#
#SetHandler python-program
#PythonPath "sys.path + ['/path/to']"
#PythonHandler myhandler
#

# This will cause all requests to the /python heirachy of your
# webserver to be handled by mod_python's Publisher handler
# (see http://localhost/manual/mod/mod_python/hand-pub.html)
#
# This will cause the output of all requests to files beneath
# /var/www/html with the extension .flt to be filtered through
# the Python script /var/www/html/filter.py
#
#
#PythonOutputFilter filter MYFILTER
#AddOutputFilter MYFILTER .flt
#

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


Beginner: Formatting text output (PyQt4)

2007-04-18 Thread Glen
Hello again,  I don't blame anyone for not answering my last post, since I
obviously hadn't spent much time researching, but I've come a little ways
and have another question.

How can I better format text output to a QTextEdit object?  I'm inserting
5 columns into each row.  When I write the info to a file, it looks like
the following:

42: 115 26: 114 35: 112 19: 108 16: 107 
45: 107 40: 106  5: 105 41: 104  2: 103 
 9: 102 48: 102 15: 101 22: 101 27: 101 
39: 101 43: 101 10: 100  6:  99 34:  99 
32:  98 49:  98 20:  97 30:  97  8:  96 
17:  96 38:  96 12:  95 14:  95 37:  95 
 4:  94 13:  94 44:  94 36:  93  3:  92 
24:  92 28:  92 31:  91 29:  89  7:  88 
 1:  87 18:  85 46:  85 33:  84 11:  83 
23:  83 47:  82 25:  80 21:  79 50:  56 
52:  39 51:  38 53:  36 54:  25 55:  18 

When I write the contents of the file to my TextEdit object it comes out
uneven, something like this:
42: 11526: 11435: 11219: 10816: 107
45: 10740: 1065: 10541: 104 2: 103
9: 10248: 10215: 10122: 10127: 101
39: 10143: 10110: 1006:  9934:  99
32:  9849:  9820:  9730:  978:  96
17:  9638:  9612:  9514:  9537:  95
4:  9413:  9444:  9436:  933:  92
24:  9228:  9231:  9129:  897:  88
 1:  8718:  8546:  8533:  8411:  83
23:  8347:  8225:  8021:  7950:  56
52:  3951:  3853:  3654:  2555:  18  

What seems to be happening is that the font that pyqt is using is not
fixed width, so I did this:
qTxtFormat = QTextCharFormat()
qTxtFormat.setFontFixedPitch(True)
ui.textEdit.setCurrentCharFormat(qTxtFormat)

Also, I tried using the pyqt formatting such as the following:

qStr = QtCore.QString( QtCore.QString( str(tL2[i][0]) 
).rightJustified(2)
+ ':' + QtCore.QString( str(tL2[i][1]) ).rightJustified(4) )
This still gives me uneven columns.

Any suggestions?

Thanks,

Glen

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


Re: Installing Python on NT

2007-04-18 Thread Gabriel Genellina
En Wed, 18 Apr 2007 18:09:03 -0300, Schwartz, Hillary  
<[EMAIL PROTECTED]> escribió:

?

-- 
Gabriel Genellina

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


Re: Third party script debugging on remote server ...

2007-04-18 Thread Graham Dumpleton
After calling whatever it is that is writing to standard output/error,
do:

  import sys
  sys.stdout.flush()
  sys.stderr.flush()

This should cause any buffered data to be immediately flushed to the
main Apache error log, ie., don't look in any virtual host logs, check
the main one.

Graham

On Apr 19, 9:15 am, dbee <[EMAIL PROTECTED]> wrote:
> Right. I've got a really, really annoying/difficult/time consuming
> problem with my development environment. I'm using django to build a
> web app with paypal integration. My server is hosted remotely, and it
> is receiving IPN (payment notifications) POST requests from Paypal.
> I've checked on google and irc and this is my last shot at solving
> this before I go mad ... :-(
>
> The problem is that I can't debug those POST requests. Browser
> debugging is out of the question obviously cause I'm not at the
> computer, ( and it doesn't have X ).
>
> I've tried cgitb but that doesn't seem to work at all ...
>
> import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain')
> import cgitb; cgitb.enable()
>
> ... neither of those commands have any effect. Although I do log other
> parts of the script to /tmp, so I know that it's reachable...
>
> mod_pythonabsolutely refuses to error_log to the apache error_log. I
> have restarted it and it still won't flush whatever error buffer it
> may ( or may not ) have stored.
>
> I can re-constitute the requests in my browser using a GET request.
> But frankly, that's kinda messy - there are lots of paypal IPN
> combinations and I may have to integrate other applications with
> paypal. So ideally speaking I'm looking for a proper debugging
> environment for this kind of thing ...
>
> Basically, I either wantmod_pythonto start error_logging properly,
> or I want some type of working traceback environment to be available.
> Help !
>
> Server version: Apache/2.0.52
> Server built:   Aug 13 2006 03:29:43
> CentOS4.x: (RedHat Clone)mod_python.i386  3.1.3-5.1
> installed
>
> # httpd.conf
>
> 
>
>  ServerName mydomain.biz
>  ServerAliaswww.mydomain.biz
>  SetHandlermod_python
>  PythonPath "['/home/babo/django'] + sys.path"
>  PythonHandler django.core.handlers.modpython
>  SetEnv DJANGO_SETTINGS_MODULE mydomain.settings
>
>   
>SetHandler None
>Options None
>   
>
> 
>
> My python.conf: ( seems pretty normal )
>
> #
> #Mod_pythonis a module that embeds the Python language interpreter
> # within the server, allowing Apache handlers to be written in Python.
> #
>
> LoadModule python_module modules/mod_python.so
>
> # Override type-map handler for /var/www/manual
> 
> 
> SetHandler default-handler
> 
> 
>
> # This will cause files beneath /var/www/html with the extension .spam
> # to be handled by the Python script /var/www/html/eggs.py
> #
> #
> #AddHandler python-program .spam
> #PythonHandler eggs
> #
>
> # This will cause all requests to the /python heirachy of your
> # webserver to be handled by the python script /path/to/myhandler.py
> #
> #
> #SetHandler python-program
> #PythonPath "sys.path + ['/path/to']"
> #PythonHandler myhandler
> #
>
> # This will cause all requests to the /python heirachy of your
> # webserver to be handled bymod_python'sPublisher handler
> # (seehttp://localhost/manual/mod/mod_python/hand-pub.html)
> #
> # This will cause the output of all requests to files beneath
> # /var/www/html with the extension .flt to be filtered through
> # the Python script /var/www/html/filter.py
> #
> #
> #PythonOutputFilter filter MYFILTER
> #AddOutputFilter MYFILTER .flt
> #


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


Re: Newbie: import

2007-04-18 Thread 7stud
Here's an example where you are trying to import a function in one of
your .py files--when that .py file is not in the current directory:


import sys
sys.path.append("/Users/me/2testing/dir1/")
#directory that contains the file

import test1  #name of file without .py extension
test1.greet()

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


Re: Python COM iterator

2007-04-18 Thread Larry Bates
Carsten Haese wrote:
> On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote:
>> Does anyone know if there is a way to make a Python COM object
>> act like a proper iterator in VB/Delphi?
> 
> I don't use COM, VB, or Delphi, but Google turned up these two
> references:
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vaconUsingForEach.asp
>   http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-1.html
> 
> Judging from those links, an object is iterable in VB and Delphi (or as
> they call it, it is enumerable) if it exposes a GetEnumerator method
> that returns an enumerator. The enumerator in turn needs to expose a
> MoveNext method and a Current property.
> 
> Assuming that the Enumerable and the Enumerator are allowed to be the
> same object, you'll probably need code that looks something like this:
> 
>   class foo:
> _public_methods_=['GetEnumerator','MoveNext']
> # You'll need to figure out how to expose "self.Current"
> 
> def __init__(self):
> self.numbers=[1,2,3,4,5,6,7,8]
> self.Current = None
> 
> def MoveNext(self):
> try:
> self.Current = self.numbers.pop(0)
> return True
> except IndexError:
> return False
> 
> def GetEnumerator(self):
> return self
> 
> Good luck,
> 
> Carsten.
> 
> 

I looked over the links and what you have proposed seems to make sense, but
I can't make it work.  I have the following class defined and registered.

class foo:

_public_methods_=['GetEnumerator','MoveNext']
_public_attrs_=['Current']
_reg_clsid_='{FC2A0E7B-E428-4414-B1C4-60373BB12102}'
_reg_progid_="Syscon.foo"

def __init__(self):
self.numbers=[1,2,3,4,5,6,7,8]
self.Current = None

def MoveNext(self):
try:
self.Current = self.numbers.pop(0)
rtnval=True

except IndexError:
self.Current=None
rtnval=False

def GetEnumerator(self):
return self


Then I do:

>>> import win32com.client
>>> typelib='Syscon.foo'
>>> F=win32com.client.Dispatch(typelib)
>>> for x in F:
... print x
... 
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 228, in
__getitem__
raise TypeError, "This object does not support enumeration"
TypeError: This object does not support enumeration
>>>

but this works fine:

>>> F.MoveNext()
>>> F.Current
1
>>> F.MoveNext()
>>> F.Current
2
>>>


I'm stumped.

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


Re: converting currency using locals

2007-04-18 Thread Gabriel Genellina
En Wed, 18 Apr 2007 15:08:24 -0300, Grzegorz Ślusarek <[EMAIL PROTECTED]>  
escribió:

> Hi all. I have situation that I have value that holds price and I must  
> show
> this price using national specification(e.g. thousands_sep). Any idea how
> this can be done under python 2.4.4? I saw that function format from  
> module
> locals can format value with national specification, but this could be  
> done
> only in python 2.5. Any solution for 2.4?
> example what I want achieve:
> value 24500.50
> Hungarian Price 24 500.50
> Romaniam Price 24.500.50
> Thanks for any help
> Gregor

Python 2.4.4 can handle thousands separator and grouping but not  
*specific* settings for monetary values. That is, when  
thousands_sep==mon_thousands_sep and grouping==mon_grouping and  
decimal_point==mon_decimal_point the following code works also for  
monetary values:
(I've checked the 'hu' and 'ro' locales on my system and both have that  
property)

Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on  
win32
Type "help", "copyright", "credits" or "license" for more information.
py> import locale
py> locale.setlocale(locale.LC_ALL, '')
'Spanish_Argentina.1252'
py> help(locale.format)
Help on function format in module locale:

format(f, val, grouping=0)
 Formats a value in the same way that the % formatting would use,
 but takes the current locale into account.
 Grouping is applied if the third parameter is true.

py> locale.format('%.2f', 1234567.1234, True)
'1.234.567,12'

-- 
Gabriel Genellina

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

Re: Future Python Gui?

2007-04-18 Thread [EMAIL PROTECTED]
> On Windows, the easiest way to install Tile is to grab it from
> ActiveState's Tcl distribution
> (http://www.activestate.com/products/activetcl/) and then place it with
> the Tcl/Tk bits that come with Python. The Tcl/Tk build for Windows that
> python.org provides doesn't ship with Tile.  You'll also have to install
> the Tile wrapper at the site I referenced earlier in your site-packages
> directory.

For posterity's sake, here's what I did...

- install python http://www.python.org/download/
  (use the Windows MSI install package)
- go to http://bruno.thoorens.free.fr/ and do the download
- instructions say to copy "tty.py" to "Tkinter" folder, but that
doesn't exist
- copy instead to C:\Python25\Lib
- copy folders as directed (to C:\Python25\Tcl)

This should also work with the ActivePython download at
http://www.activestate.com/products/activepython/ .

Within your program, you need:

# Import "Tile" theming engine
tkroot.tk.call('package', 'require', 'tile')
tkroot.tk.call('namespace', 'import', '-force', 'ttk::*')
tkroot.tk.call('tile::setTheme', 'xpnative')

after your call to "tkroot = Tk()" (or "tkroot = Tkinter.Tk()" if you
just "import Tkinter").

The frustrating part is that the main reason I wanted this is because
it says it wraps a "Notebook" widget.  If it does, I can't find it!


-- Brian

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


Re: Future Python Gui?

2007-04-18 Thread [EMAIL PROTECTED]
> "Tile" has already been mentioned in this thread, and I know
> there'll be at least one more follow-up on the subject.  Tile
> includes a ("native"!) notebook, as well as a combobox, tree-
> view, ... http://wiki.tcl.tk/11075>.

It seems that Tile does include a "notebook" widget but it's pure Tcl
code and so isn't available via the Python wrapper.

-- Brian

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


Re: Future Python Gui?

2007-04-18 Thread [EMAIL PROTECTED]
> As I've said often enough on the topic of Web frameworks, picking
> winners gives only a temporary victory to those who want to avoid
> making decisions. It's better to provide people with a means of making
> an informed choice, and it should be realised that people will
> approach this choice from rather different angles. It isn't always
> going to be, "I want to write a Python application - what GUI should I
> use?" Instead, it may be, "I want to write a KDE application - can I
> do so in Python and what are my options?" Pretending that the answer
> is always the same will frequently drive people to other technologies,
> not attract them to a technology selling a vision that turns out to be
> a mirage.

This is getting off-topic, I guess, so I'll only comment once because
I don't want to get wrapped up in a flame war.  This is the argument
used by people who think that having both KDE and GNOME is a good
thing because it promotes competition, etc.  Personally, I believe
it's a bad thing because it duplicates effort and delivers an
inconsistent look & feel.  Developers are forced to choose a
framework, not knowing if it will go away in favor of another choice
and rendering their own hard work obsolete.  I don't want my work
dependent upon the framework.  I'd rather have less good if it meant
longer-term stability and greater consistency.

But that's just me.

-- Brian

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


Re: Future Python Gui?

2007-04-18 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
>> "Tile" has already been mentioned in this thread, and I know
>> there'll be at least one more follow-up on the subject.  Tile
>> includes a ("native"!) notebook, as well as a combobox, tree-
>> view, ... http://wiki.tcl.tk/11075>.
> 
> It seems that Tile does include a "notebook" widget but it's pure Tcl
> code and so isn't available via the Python wrapper.
> 
> -- Brian
> 
That's not correct. When the Tkinter wiki is back up, see the page I 
referred to.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Python Gui?

2007-04-18 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
>> On Windows, the easiest way to install Tile is to grab it from
>> ActiveState's Tcl distribution
>> (http://www.activestate.com/products/activetcl/) and then place it with
>> the Tcl/Tk bits that come with Python. The Tcl/Tk build for Windows that
>> python.org provides doesn't ship with Tile.  You'll also have to install
>> the Tile wrapper at the site I referenced earlier in your site-packages
>> directory.
> 
> For posterity's sake, here's what I did...
> 
> - install python http://www.python.org/download/
>   (use the Windows MSI install package)
> - go to http://bruno.thoorens.free.fr/ and do the download
> - instructions say to copy "tty.py" to "Tkinter" folder, but that
> doesn't exist
> - copy instead to C:\Python25\Lib
> - copy folders as directed (to C:\Python25\Tcl)
> 
> This should also work with the ActivePython download at
> http://www.activestate.com/products/activepython/ .
> 
> Within your program, you need:
> 
> # Import "Tile" theming engine
> tkroot.tk.call('package', 'require', 'tile')
> tkroot.tk.call('namespace', 'import', '-force', 'ttk::*')
> tkroot.tk.call('tile::setTheme', 'xpnative')
> 
> after your call to "tkroot = Tk()" (or "tkroot = Tkinter.Tk()" if you
> just "import Tkinter").
> 
> The frustrating part is that the main reason I wanted this is because
> it says it wraps a "Notebook" widget.  If it does, I can't find it!
> 
> 
> -- Brian
> 

The wrapper I maintain works differently, and includes the notebook widget.

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Python Gui?

2007-04-18 Thread Kevin Walzer
Since the Tkinter wiki is still down, here is the Tile wrapper I maintain:


###

November 2006: Posted by Kevin Walzer, [EMAIL PROTECTED] Based on 
Tile wrapper by Martin Franklin. This version updates the wrapper to 
reflect changes in Tile commands, and adds support for Tile-based frames 
(ttk::frame). Freely reusable.

import Tkinter
from Tkconstants import *


class Style:
 def default(self, style, **kw):
 """Sets the default value of the specified option(s) in style"""
 pass

 def map_style(self, **kw):
 """Sets dynamic values of the specified option(s) in style. See
 "STATE MAPS", below."""
 pass

 def layout(self, style, layoutSpec):
 """Define the widget layout for style style. See "LAYOUTS" below
 for the format of layoutSpec. If layoutSpec is omitted, return the
 layout specification for style style. """
 pass

 def element_create(self, name, type, *args):
 """Creates a new element in the current theme of type type. The
 only built-in element type is image (see image(n)), although
 themes may define other element types (see
 Ttk_RegisterElementFactory).
 """
 pass

 def element_names(self):
 """Returns a list of all elements defined in the current theme. """
 pass

 def theme_create(self, name, parent=None, basedon=None):
 """Creates a new theme. It is an error if themeName already 
exists.
 If -parent is specified, the new theme will inherit styles, 
elements,
 and layouts from the parent theme basedon. If -settings is 
present,
 script is evaluated in the context of the new theme as per 
style theme
 settings.
 """
 pass

 def theme_settings(self, name, script):
 """Temporarily sets the current theme to themeName, evaluate 
script,
 then restore the previous theme. Typically script simply 
defines styles
 and elements, though arbitrary Tcl code may appear.
 """
 pass

 def theme_names(self):
 """Returns a list of the available themes. """
 return self.tk.call("style", "theme", "names")

 def theme_use(self, theme):
 """Sets the current theme to themeName, and refreshes all 
widgets."""
 return self.tk.call("style", "theme", "use", theme)

class Widget(Tkinter.Widget, Style):
 def __init__(self, master, widgetName=None, cnf={}, kw={}, extra=()):
 if not widgetName:
 ## why you would ever want to create a Tile Widget is 
behond me!
 widgetName="ttk::widget"
 Tkinter.Widget.__init__(self, master, widgetName, cnf, kw)

 def instate(self,  spec=None, script=None):
 """Test the widget's state. If script is not specified, returns 1
 if the widget state matches statespec and 0 otherwise. If script
 is specified, equivalent to if {[pathName instate stateSpec]}
 script.
 """
 return self.tk.call(self._w, "instate", spec, script)

 def state(self, spec=None):
 """Modify or inquire widget state. If stateSpec is present, sets
 the widget state: for each flag in stateSpec, sets the 
corresponding
 flag or clears it if prefixed by an exclamation point. Returns 
a new
 state spec indicating which flags were changed: ''set changes
 [pathName state spec] ; pathName state $changes'' will restore
 pathName to the original state. If stateSpec is not specified,
 returns a list of the currently-enabled state flags.
 """
 return self.tk.call(self._w, "state", spec)

class Button(Widget, Tkinter.Button):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::button", cnf, kw)

###add frame support here--KWs
class Frame(Widget, Tkinter.Frame):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::frame", cnf, kw)

class Checkbutton(Widget, Tkinter.Checkbutton):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::checkbutton", cnf, kw)

class Combobox(Widget, Tkinter.Entry):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::combobox", cnf, kw)

 def current(self, index=None):
 """If index is supplied, sets the combobox value to the element
 at position newIndex in the list of -values. Otherwise, returns
 the index of the current value in the list of -values or -1 if
 the current value does not appear in the list.
 """
 return self.tk.call(self._w, "current", index)

class Entry(Widget, Tkinter.Entry):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::entry", cnf, kw)

 def validate(self):
 """Force revalidation, independent of the conditions specified by
 the

Spawn/Exec with asterisk in argument

2007-04-18 Thread jeremyfee
The spawn* and exec* functions appear to escape asterisks, I'm
guessing all shell characters too, before the spawn/exec'ed process
sees them.  Is there a way around this?

Not sure if this is a bug or a "feature".

user$ touch test.txt
user$ ls -l *
-rw-r--r--   1 user  user  0 Apr 18 18:30 test.txt
user$ ls -l \*
ls: *: No such file or directory
user$ python
Python 2.3.5 (#1, Aug 12 2006, 00:08:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("ls -l *")
-rw-r--r--   1 user  user  0 Apr 18 18:30 test.txt
0
>>> os.spawnvp(os.P_WAIT, "ls", ("ls", "-l", "*"))
ls: *: No such file or directory
1

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


Re: Future Python Gui?

2007-04-18 Thread Kevin Walzer
This should be saved as "Tile.py." Sorry.


###

November 2006: Posted by Kevin Walzer, [EMAIL PROTECTED] Based on 
Tile wrapper by Martin Franklin. This version updates the wrapper to 
reflect changes in Tile commands, and adds support for Tile-based frames 
(ttk::frame). Freely reusable.

import Tkinter
from Tkconstants import *


class Style:
 def default(self, style, **kw):
 """Sets the default value of the specified option(s) in style"""
 pass

 def map_style(self, **kw):
 """Sets dynamic values of the specified option(s) in style. See
 "STATE MAPS", below."""
 pass

 def layout(self, style, layoutSpec):
 """Define the widget layout for style style. See "LAYOUTS" below
 for the format of layoutSpec. If layoutSpec is omitted, return the
 layout specification for style style. """
 pass

 def element_create(self, name, type, *args):
 """Creates a new element in the current theme of type type. The
 only built-in element type is image (see image(n)), although
 themes may define other element types (see
 Ttk_RegisterElementFactory).
 """
 pass

 def element_names(self):
 """Returns a list of all elements defined in the current theme. """
 pass

 def theme_create(self, name, parent=None, basedon=None):
 """Creates a new theme. It is an error if themeName already 
exists.
 If -parent is specified, the new theme will inherit styles, 
elements,
 and layouts from the parent theme basedon. If -settings is 
present,
 script is evaluated in the context of the new theme as per 
style theme
 settings.
 """
 pass

 def theme_settings(self, name, script):
 """Temporarily sets the current theme to themeName, evaluate 
script,
 then restore the previous theme. Typically script simply 
defines styles
 and elements, though arbitrary Tcl code may appear.
 """
 pass

 def theme_names(self):
 """Returns a list of the available themes. """
 return self.tk.call("style", "theme", "names")

 def theme_use(self, theme):
 """Sets the current theme to themeName, and refreshes all 
widgets."""
 return self.tk.call("style", "theme", "use", theme)

class Widget(Tkinter.Widget, Style):
 def __init__(self, master, widgetName=None, cnf={}, kw={}, extra=()):
 if not widgetName:
 ## why you would ever want to create a Tile Widget is 
behond me!
 widgetName="ttk::widget"
 Tkinter.Widget.__init__(self, master, widgetName, cnf, kw)

 def instate(self,  spec=None, script=None):
 """Test the widget's state. If script is not specified, returns 1
 if the widget state matches statespec and 0 otherwise. If script
 is specified, equivalent to if {[pathName instate stateSpec]}
 script.
 """
 return self.tk.call(self._w, "instate", spec, script)

 def state(self, spec=None):
 """Modify or inquire widget state. If stateSpec is present, sets
 the widget state: for each flag in stateSpec, sets the 
corresponding
 flag or clears it if prefixed by an exclamation point. Returns 
a new
 state spec indicating which flags were changed: ''set changes
 [pathName state spec] ; pathName state $changes'' will restore
 pathName to the original state. If stateSpec is not specified,
 returns a list of the currently-enabled state flags.
 """
 return self.tk.call(self._w, "state", spec)

class Button(Widget, Tkinter.Button):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::button", cnf, kw)

###add frame support here--KWs
class Frame(Widget, Tkinter.Frame):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::frame", cnf, kw)

class Checkbutton(Widget, Tkinter.Checkbutton):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::checkbutton", cnf, kw)

class Combobox(Widget, Tkinter.Entry):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::combobox", cnf, kw)

 def current(self, index=None):
 """If index is supplied, sets the combobox value to the element
 at position newIndex in the list of -values. Otherwise, returns
 the index of the current value in the list of -values or -1 if
 the current value does not appear in the list.
 """
 return self.tk.call(self._w, "current", index)

class Entry(Widget, Tkinter.Entry):
 def __init__(self, master=None, cnf={}, **kw):
 Widget.__init__(self, master, "ttk::entry", cnf, kw)

 def validate(self):
 """Force revalidation, independent of the conditions specified by
 the -validate option. Returns 0 if t

Using the Python interpreter

2007-04-18 Thread tkpmep
Instead of starting IDLE as I normally do, I started the Python
interpreter and tried to run a program. I got a Python prompt (>>>),
and then tried unsuccessfully to run a Python script named Script1.py
that runs perfectly well in IDLE. Here's what I did:

>>>Script1.py
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name Script1 is not defined

>>>python Script1.py
  File "", line 1
   python Script1.py
SyntaxError: invalid syntax

I can load it (and have it execute) by typing

>>>import Script1
0
1
2
3
4

and if I edit it, I can then execute it by reloading it

>>>import Script1
0
1
2
3
4


But this seems contrived - is there no way to repeatedly run Script1
from the interpreter without reloading it?

Thomas Philips

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


Re: Third party script debugging on remote server ...

2007-04-18 Thread dbee
On Apr 19, 12:31 am, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> After calling whatever it is that is writing to standard output/error,
> do:
>
>   import sys
>   sys.stdout.flush()
>   sys.stderr.flush()
>
> This should cause any buffered data to be immediately flushed to the
> main Apache error log, ie., don't look in any virtual host logs, check
> the main one.
>
> Graham
>
> On Apr 19, 9:15 am, dbee <[EMAIL PROTECTED]> wrote:
>
> > Right. I've got a really, really annoying/difficult/time consuming
> > problem with my development environment. I'm using django to build a
> > web app with paypal integration. My server is hosted remotely, and it
> > is receiving IPN (payment notifications) POST requests from Paypal.
> > I've checked on google and irc and this is my last shot at solving
> > this before I go mad ... :-(
>
> > The problem is that I can't debug those POST requests. Browser
> > debugging is out of the question obviously cause I'm not at the
> > computer, ( and it doesn't have X ).
>
> > I've tried cgitb but that doesn't seem to work at all ...
>
> > import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain')
> > import cgitb; cgitb.enable()
>
> > ... neither of those commands have any effect. Although I do log other
> > parts of the script to /tmp, so I know that it's reachable...
>
> > mod_pythonabsolutely refuses to error_log to the apache error_log. I
> > have restarted it and it still won't flush whatever error buffer it
> > may ( or may not ) have stored.
>
> > I can re-constitute the requests in my browser using a GET request.
> > But frankly, that's kinda messy - there are lots of paypal IPN
> > combinations and I may have to integrate other applications with
> > paypal. So ideally speaking I'm looking for a proper debugging
> > environment for this kind of thing ...
>
> > Basically, I either wantmod_pythonto start error_logging properly,
> > or I want some type of working traceback environment to be available.
> > Help !
>
> > Server version: Apache/2.0.52
> > Server built:   Aug 13 2006 03:29:43
> > CentOS4.x: (RedHat Clone)mod_python.i386  3.1.3-5.1
> > installed
>
> > # httpd.conf
>
> > 
>
> >  ServerName mydomain.biz
> >  ServerAliaswww.mydomain.biz
> >  SetHandlermod_python
> >  PythonPath "['/home/babo/django'] + sys.path"
> >  PythonHandler django.core.handlers.modpython
> >  SetEnv DJANGO_SETTINGS_MODULE mydomain.settings
>
> >   
> >SetHandler None
> >Options None
> >   
>
> > 
>
> > My python.conf: ( seems pretty normal )
>
> > #
> > #Mod_pythonis a module that embeds the Python language interpreter
> > # within the server, allowing Apache handlers to be written in Python.
> > #
>
> > LoadModule python_module modules/mod_python.so
>
> > # Override type-map handler for /var/www/manual
> > 
> > 
> > SetHandler default-handler
> > 
> > 
>
> > # This will cause files beneath /var/www/html with the extension .spam
> > # to be handled by the Python script /var/www/html/eggs.py
> > #
> > #
> > #AddHandler python-program .spam
> > #PythonHandler eggs
> > #
>
> > # This will cause all requests to the /python heirachy of your
> > # webserver to be handled by the python script /path/to/myhandler.py
> > #
> > #
> > #SetHandler python-program
> > #PythonPath "sys.path + ['/path/to']"
> > #PythonHandler myhandler
> > #
>
> > # This will cause all requests to the /python heirachy of your
> > # webserver to be handled bymod_python'sPublisher handler
> > # (seehttp://localhost/manual/mod/mod_python/hand-pub.html)
> > #
> > # This will cause the output of all requests to files beneath
> > # /var/www/html with the extension .flt to be filtered through
> > # the Python script /var/www/html/filter.py
> > #
> > #
> > #PythonOutputFilter filter MYFILTER
> > #AddOutputFilter MYFILTER .flt
> > #

Hi Graeme,

Thanks for the suggestion. Unluckily for me, it doesn't seem to be
working though ...

I've tried it a number of different ways. I guess if I put the code
after an exception, then the code won't be called.
So I ran an error in the python script and then I called the
sys.stderr.flush() from the python shell. No luck though.

I called on it's own, still no luck,

Then I tried ...

try:

raise Exception('Please log this error')

except:

import sys

sys.stderr.flush()
sys.stdout.flush()

The error log still has no error info in it :-(  

Is this problem unique to me ?

This is startup message that gets posted to error_log on apache
restart ... (The IIS string is a mod_sec Security Signature)
[Wed Apr 18 19:58:25 2007] [notice] mod_python: (Re)importing module
'django.core.handlers.modpython'
[Wed Apr 18 19:58:32 2007] [notice] mod_python: (Re)importing module
'django.core.handlers.modpython'
DEBUG:  InitPostgres
DEBUG:  InitPostgres
[Wed Apr 18 19:59:56 2007] [notice] caught SIGTERM, shutting down
[Wed Apr 18 19:59:57 2007] [notice] suEXEC mechanism enabled

Re: Using the Python interpreter

2007-04-18 Thread Stevie
On Thu, 19 Apr 2007 01:32:36 +0100, [EMAIL PROTECTED] wrote
(in article <[EMAIL PROTECTED]>):

> Instead of starting IDLE as I normally do, I started the Python
> interpreter and tried to run a program. I got a Python prompt (>>>),
> and then tried unsuccessfully to run a Python script named Script1.py
> that runs perfectly well in IDLE. Here's what I did:
> 
 Script1.py
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name Script1 is not defined
> 
 python Script1.py
>   File "", line 1
>python Script1.py
> SyntaxError: invalid syntax
> 
> I can load it (and have it execute) by typing
> 
 import Script1
> 0
> 1
> 2
> 3
> 4
> 
> and if I edit it, I can then execute it by reloading it
> 
 import Script1
> 0
> 1
> 2
> 3
> 4
> 
> 
> But this seems contrived - is there no way to repeatedly run Script1
> from the interpreter without reloading it?
> 
> Thomas Philips
> 

Why dont you wrap the code into a procedure (a def statement) in your script1 
file import it using the from xxx import yyy statement. Then you can use it 
over and over.

By the sounds of it your script is full of inline code that is executed when 
its imported and therefore only runs once. To get it to re-run you have to 
repeatedly import it. Your really should only need to do this under very 
specific circumstances.

Steve

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


indexing web pages - in python?

2007-04-18 Thread Dan Stromberg

Are there any open source search engines written in python for indexing a
given collection of (internal only) html pages?  Right now I'm talking
about dozens, but hopefully it'll be hundreds or thousands at some point.

I'm thinking some sort of CGI script, with perhaps a cron job that updates
the indexes.

I'm not particularly looking for something that has a full RDBMS behind
it - just a file that stores indexes.  I'll go with an RDBMS-based
solution if I must, but I don't think that's really needed at this point.

TIA

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


Re: comparison with None

2007-04-18 Thread Alan Isaac
"Terry Reedy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Should be in the reference manual section on comparisons.

Only to this extent:
http://www.python.org/doc/2.4/ref/comparisons.html

objects of different types always compare unequal, and are ordered
consistently but arbitrarily.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in
operators.
In the future, the comparison rules for objects of different types
are
likely to change.)

...  Most other types compare unequal unless they are the same
object;
the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one
execution
of a program.

This does not provide a direct answer to "why" None comparisons.
(As far as I can tell, None is less than any object.)

However, Gary Herron's explanation makes sense: this provides a stable
sort when None is involved, and meets the criterion that objects of
different types must always compare unequal.  However this would also
be true if None always compared greater than any object, and the current
behavior does not seem to be guaranteed.

Is that about right?

Cheers,
Alan Isaac


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


Re: Spawn/Exec with asterisk in argument

2007-04-18 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:
> The spawn* and exec* functions appear to escape asterisks, I'm
> guessing all shell characters too, before the spawn/exec'ed process
> sees them.

No. It is the shell that ordinarily processes these characters and gives 
them a special meaning. On most systems, ls does not give any special 
meaning to asterisk.

> Is there a way around this?

If you want to process asterisk the way the shell does, you can pass 
things through the shell. os.system is one way of doing that. Probably 
better is:

subprocess.check_call("ls -l *", shell=True)

Another way is using the glob module (and optionally 
os.path.expanduser() for tilde expansion and os.path.expandvars() for 
variable expansion, other things that are normally taken care of by the 
shell).
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using the Python interpreter

2007-04-18 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:
> Instead of starting IDLE as I normally do, I started the Python
> interpreter and tried to run a program. I got a Python prompt (>>>),
> and then tried unsuccessfully to run a Python script named Script1.py
> that runs perfectly well in IDLE. Here's what I did:
> 
 Script1.py
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name Script1 is not defined
> 
 python Script1.py

You need to do this from a Windows command line, not from Python.

C:\Python25>python Script1.py
Hello, world!
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Third party script debugging on remote server ...

2007-04-18 Thread dbee
On Apr 19, 1:52 am, dbee <[EMAIL PROTECTED]> wrote:
> On Apr 19, 12:31 am, Graham Dumpleton <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > After calling whatever it is that is writing to standard output/error,
> > do:
>
> >   import sys
> >   sys.stdout.flush()
> >   sys.stderr.flush()
>
> > This should cause any buffered data to be immediately flushed to the
> > main Apache error log, ie., don't look in any virtual host logs, check
> > the main one.
>
> > Graham
>
> > On Apr 19, 9:15 am, dbee <[EMAIL PROTECTED]> wrote:
>
> > > Right. I've got a really, really annoying/difficult/time consuming
> > > problem with my development environment. I'm using django to build a
> > > web app with paypal integration. My server is hosted remotely, and it
> > > is receiving IPN (payment notifications) POST requests from Paypal.
> > > I've checked on google and irc and this is my last shot at solving
> > > this before I go mad ... :-(
>
> > > The problem is that I can't debug those POST requests. Browser
> > > debugging is out of the question obviously cause I'm not at the
> > > computer, ( and it doesn't have X ).
>
> > > I've tried cgitb but that doesn't seem to work at all ...
>
> > > import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain')
> > > import cgitb; cgitb.enable()
>
> > > ... neither of those commands have any effect. Although I do log other
> > > parts of the script to /tmp, so I know that it's reachable...
>
> > > mod_pythonabsolutely refuses to error_log to the apache error_log. I
> > > have restarted it and it still won't flush whatever error buffer it
> > > may ( or may not ) have stored.
>
> > > I can re-constitute the requests in my browser using a GET request.
> > > But frankly, that's kinda messy - there are lots of paypal IPN
> > > combinations and I may have to integrate other applications with
> > > paypal. So ideally speaking I'm looking for a proper debugging
> > > environment for this kind of thing ...
>
> > > Basically, I either wantmod_pythonto start error_logging properly,
> > > or I want some type of working traceback environment to be available.
> > > Help !
>
> > > Server version: Apache/2.0.52
> > > Server built:   Aug 13 2006 03:29:43
> > > CentOS4.x: (RedHat Clone)mod_python.i386  
> > > 3.1.3-5.1
> > > installed
>
> > > # httpd.conf
>
> > > 
>
> > >  ServerName mydomain.biz
> > >  ServerAliaswww.mydomain.biz
> > >  SetHandlermod_python
> > >  PythonPath "['/home/babo/django'] + sys.path"
> > >  PythonHandler django.core.handlers.modpython
> > >  SetEnv DJANGO_SETTINGS_MODULE mydomain.settings
>
> > >   
> > >SetHandler None
> > >Options None
> > >   
>
> > > 
>
> > > My python.conf: ( seems pretty normal )
>
> > > #
> > > #Mod_pythonis a module that embeds the Python language interpreter
> > > # within the server, allowing Apache handlers to be written in Python.
> > > #
>
> > > LoadModule python_module modules/mod_python.so
>
> > > # Override type-map handler for /var/www/manual
> > > 
> > > 
> > > SetHandler default-handler
> > > 
> > > 
>
> > > # This will cause files beneath /var/www/html with the extension .spam
> > > # to be handled by the Python script /var/www/html/eggs.py
> > > #
> > > #
> > > #AddHandler python-program .spam
> > > #PythonHandler eggs
> > > #
>
> > > # This will cause all requests to the /python heirachy of your
> > > # webserver to be handled by the python script /path/to/myhandler.py
> > > #
> > > #
> > > #SetHandler python-program
> > > #PythonPath "sys.path + ['/path/to']"
> > > #PythonHandler myhandler
> > > #
>
> > > # This will cause all requests to the /python heirachy of your
> > > # webserver to be handled bymod_python'sPublisher handler
> > > # (seehttp://localhost/manual/mod/mod_python/hand-pub.html)
> > > #
> > > # This will cause the output of all requests to files beneath
> > > # /var/www/html with the extension .flt to be filtered through
> > > # the Python script /var/www/html/filter.py
> > > #
> > > #
> > > #PythonOutputFilter filter MYFILTER
> > > #AddOutputFilter MYFILTER .flt
> > > #
>
> Hi Graeme,
>
> Thanks for the suggestion. Unluckily for me, it doesn't seem to be
> working though ...
>
> I've tried it a number of different ways. I guess if I put the code
> after an exception, then the code won't be called.
> So I ran an error in the python script and then I called the
> sys.stderr.flush() from the python shell. No luck though.
>
> I called on it's own, still no luck,
>
> Then I tried ...
>
> try:
>
> raise Exception('Please log this error')
>
> except:
>
> import sys
>
> sys.stderr.flush()
> sys.stdout.flush()
>
> The error log still has no error info in it :-(  
>
> Is this problem unique to me ?
>
> This is startup message that gets posted to error_log on apache
> restart ... (The IIS string is a mod_sec Security Signature)
> [Wed Apr 18 19:58:25 2007] [notice] mod_python: (Re)importing module

Re: indexing web pages - in python?

2007-04-18 Thread Kevin T. Ryan
On Apr 18, 8:55 pm, Dan Stromberg <[EMAIL PROTECTED]> wrote:
> Are there any open source search engines written in python for indexing a
> given collection of (internal only) html pages?  Right now I'm talking
> about dozens, but hopefully it'll be hundreds or thousands at some point.
>
> I'm thinking some sort of CGI script, with perhaps a cron job that updates
> the indexes.
>
> I'm not particularly looking for something that has a full RDBMS behind
> it - just a file that stores indexes.  I'll go with an RDBMS-based
> solution if I must, but I don't think that's really needed at this point.
>
> TIA

You could try:

http://gnosis.cx/download/indexer.py

There is an extensive write-up by the author at:

http://gnosis.cx/publish/programming/charming_python_15.txt

Might be something you'd be interested in ...

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


Re: What makes an iterator an iterator?

2007-04-18 Thread Terry Reedy
An iterator is an object with a .__iter__  method that returns self and a 
.next method that either returns an object or raises StopIteration.

One very good way to get an iterator from an iterable is for .__iter__ to 
be a generator function.  When called, it returns an generator with 
.__iter__ and .next methods that work as specified.

words = "Norwegian Blues have beautiful plumage!".split()
print words

prints
['Norwegian', 'Blues', 'have', 'beautiful', 'plumage!']

class Parrot(object):
def __init__(self, words):
self.words = words
def __iter__(self):
for word in words:
yield word

for word in Parrot(words):
print word

prints

Norwegian
Blues
have
beautiful
plumage!

One can also make an iterable an (self) iterator by correctly writing the 
two needed methods.

class Parrot2(object):
def __init__(self, words):
self.words = words
def __iter__(self):
self.it = -1
return self
def next(self):
self.it += 1
try:
return self.words[self.it]
except IndexError:
raise StopIteration

for word in Parrot2(words):
print word

which prints the same 5 lines.  However, when an object is its own 
iterator, it can only be one iterator at a time (here, pointing at one 
place in the word list), whereas the first method allows multiple iterators 
(here, possibly pointing to different places in the list.

| Can you explain some of the details of why this code fails:

[snip all examples of bad code that violate the iterator rule by improperly 
writing .next as a generator function]

I think most people should learn how to write iterators correctly, as I 
gave examples of above, rather than worry about the details of how and why 
mis-written code fails with a particular version of a particular 
implementation.  So I won't go down that road.

Terry Jan Reedy



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


Re: Compiling python from soruce vs RPM ?

2007-04-18 Thread howa
On Apr 19, 6:10 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
>
> Since /usr/bin/python isn't found, it doesn't look like there's an
> existing version of Python that you might overwrite, but it's
> important to verify such things when installing software. That's where
> your distribution's packages have an advantage, and it's arguably a
> better idea to install such packages instead, possibly building them
> from source if no binary packages exist yet for Python 2.5. (If no
> source packages exist, you have a bit more work to do.)
>
> Paul


Thanks.


One more question:

How to uninstall using the source package?

the source package doesn't come with `make uninstall`?




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


Re: Strange terminal behavior after quitting Tkinter application

2007-04-18 Thread Charles Sanders
Chris wrote:
> 
> But does anyone know why the Tkinter program is doing this to the
> terminal in the first place? I don't want to have to tell users of my
> program that they must recover their terminal's sanity each time after
> running my program.
> 

I don't know about Tkinter, but my guess would be that
it has to change the terminal settings to do what it does, and
you are quitting without restoring the settings.

Is there some Tkinter clean up that you have omitted ?

Have you ensured that the clean up runs on both normal
exit and abnormal exit (eg ^C) ?

For example, the curses library (in C) requires an
endwin() call before exit to restore settings. If this
is omitted, a "stty sane" is needed to set the terminal to
a semi-sensible default. On Unix and similar systems, signal
handlers are normally installed to ensure (as far as possible)
that the cleanup occurs if the process is killed. This also
applies to vi and similar programs that take total control of
the terminal.


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


Re: python - dll access (ctypes or swig)

2007-04-18 Thread Alex Martelli
Thomas Heller <[EMAIL PROTECTED]> wrote:
   ...
> > and some technical issues such as threading (if COM client and server
   ...
> I think that the latter problem (incompatible threading models in the same
> process) are solved by COM apartments - aren't they?

"apartment" is one threading model, but it still means that your
application and your in-process server must be compatible with it
(again, we're discussing the fact that out-of-process servers, at a
performance price, can do away with these minor limitations).


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


Re: What makes an iterator an iterator?

2007-04-18 Thread Alex Martelli
7stud <[EMAIL PROTECTED]> wrote:
   ...
> Can you explain some of the details of why this code fails:
   ...
> def next(self):
> for word in "Norwegian Blue's have beautiful
> plumage!".split():
> yield word

Sure, easily: a loop like "for x in y:" binds an unnamed temporary
variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to
be pedantic type(_t).next(t)] until that raises StopIteration.

Calling a generator, such as this next method, returns an iterator
object; calling it repeatedly returns many such iterator objects, and
never raises StopIteration, thus obviously producing an unending loop.


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


Re: comparison with None

2007-04-18 Thread Alan Isaac
"Terry Reedy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Should be in the reference manual section on comparisons.

Only to this extent:
http://www.python.org/doc/2.4/ref/comparisons.html

objects of different types always compare unequal, and are ordered
consistently but arbitrarily.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in
operators.
In the future, the comparison rules for objects of different types
are
likely to change.)

...  Most other types compare unequal unless they are the same
object;
the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one
execution
of a program.

This does not provide a direct answer to "why" None comparisons.
(As far as I can tell, None is less than any object.)

However, Gary Herron's explanation makes sense: this provides a stable
sort when None is involved, and meets the criterion that objects of
different types must always compare unequal.  However this would also
be true if None always compared greater than any object, and the current
behavior does not seem to be guaranteed.

Is that about right?

Cheers,
Alan Isaac


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


Re: Future Python Gui?

2007-04-18 Thread [EMAIL PROTECTED]
> The wrapper I maintain works differently, and includes the notebook widget.

I've seen the page.  You can get to it via Google's cache; just put
the url in the box and the one search result returned usually has a
"cached" link.

However, that file is completely useless without instructions on how
to use it, and there are no instructions within the page or file.

That is:
 - exactly where does it get installed
 - what else needs to get installed (eg. some dll)
 - where do you find these other things
 - where does that something else get installed
 - how do you import this module
 - how does use of Tkinter change (if at all) once imported

I know all this stuff is obvious to those that have been working with
it for a while, but for those of us just getting started with Python,
it's immensely frustrating that we're assumed to know all these steps.

-- Brian

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


Re: Python COM iterator

2007-04-18 Thread Carsten Haese
>[...]
> > On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote:
> >> Does anyone know if there is a way to make a Python COM object
> >> act like a proper iterator in VB/Delphi?
>[...]

After more googling, staring at win32com's code, and a fair bit of trial
and error, I've come up with the following working example:

# server.py
import pythoncom

class HelloWorld:
_reg_clsid_ = "{CAB8BED1-9174-4AAD-ABC5-F377951CB71B}"
_reg_desc_ = "Python Test COM Server"
_reg_progid_ = "Python.TestServer"
_public_methods_ = ['Next']
_com_interfaces_ = [pythoncom.IID_IEnumVARIANT]

def __init__(self):
self.numbers=[1,2,3,4,5,6,7,8]

def Next(self, count):
assert count==1
try:
return (self.numbers.pop(0),)
except IndexError:
return ()

def _NewEnum(self):
import win32com.server.util
return win32com.server.util.wrap(self)

if __name__=='__main__':
  import win32com.server.register 
  win32com.server.register.UseCommandLine(HelloWorld)
  
# client.py
import win32com.client
comobj = win32com.client.Dispatch("Python.TestServer")
for x in comobj:
print x

This works for me on Python 2.5 and pywin32 Build 210, but I don't know
whether clients in VB or Delphi are able to use this iterator.

-Carsten


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


Re: Python Threads -

2007-04-18 Thread Alex Martelli
S.Mohideen <[EMAIL PROTECTED]> wrote:

> Hi All,
> 
> Can you please suggest a technique in Python where we can spawn few number
> of worker threads and later map them to a function/s to execute individual
> Jobs.
> 
> Any references would be helpful..

I believe I give some examples in the Nutshell, but the basic idea is
very simple: start the N worker threads you want in your pool -- they
all use .get on the same Queue.Queue instance qI which contains "work
requests" (WRs).  A WR could e.g. be a tuple with a Queue qO (or None to
indicate that the result is not interesting), a callable, and 0+
arguments (or an empty tuple to request thread termination); the worker
thread just calls the callable on the arguments and puts the result to
qO (if qO is not None).  Many other similar arrangements are possible,
depending on your application's exact needs, but I hope the general idea
is clear.


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


Question about Tkinter MenuOption variable

2007-04-18 Thread Chad
Is there anyway to set the individual options in Tkinter to a
particular variable.  For example, I have a menu option(code is below)
which has January, February, March and so on, which I would like to
have corresponding values of 01, 02, 03 and so on.  Can someone please
tell me how to do that within the context of the code I have below -
or even totally modify it if you must.

 Label(self,
  text = "Month"
  ).grid(row = 5, column = 1, sticky = W)
   OPTIONS = [
   "Jan",
   "Feb",
   "Mar",
   "Apr",
   "May",
   "June",
   "July",
   "Aug",
   "Sep",
   "Oct",
   "Nov",
   "Dec"]
   default_option = StringVar(self)
   default_option.set(OPTIONS[0])
   self.month_option = OptionMenu(self, default_option, *OPTIONS)
   self.month_option.grid(row = 5, column = 2, sticky = W)

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


Re: Beginner: Formatting text output (PyQt4)

2007-04-18 Thread Glen
On Wed, 18 Apr 2007 22:50:14 +, Glen wrote:

Ok, obviously, my post didn't come out the way I wanted it to.  In the
first example from my text file below, the dictionary pairs, constructed
from sorted tuples were in straight columns.  When I write them to my
QTextEdit, however, the columns are no longer straight.  Some of the
padding inserted by my call to rightJustified() are not equal to the
actual size of the text, so some rows are longer than others in the text
browser.  I know I've encountered this before, perhaps with Java, but I
can't remember the solution.  How do I get the formatting of my output to
the gui to reflect the output I would get to a file using the builtin
write() function?  Any help is appreciated.  Sorry about the confusion. 

Thanks,
G

> Hello again,  I don't blame anyone for not answering my last post,
since
> I obviously hadn't spent much time researching, but I've come a little
> ways and have another question.
> 
> How can I better format text output to a QTextEdit object?  I'm
> inserting 5 columns into each row.  When I write the info to a file, it
> looks like the following:
> 
> 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40:
> 106  5: 105 41: 104  2: 103
>  9: 102 48: 102 15: 101 22: 101 27: 101
> 39: 101 43: 101 10: 100  6:  99 34:  99 32:  98 49:
> 98 20:  97 30:  97  8:  96 17:  96 38:  96 12:  95
> 14:  95 37:  95
>  4:  94 13:  94 44:  94 36:  93  3:  92
> 24:  92 28:  92 31:  91 29:  89  7:  88
>  1:  87 18:  85 46:  85 33:  84 11:  83
> 23:  83 47:  82 25:  80 21:  79 50:  56 52:  39 51:
> 38 53:  36 54:  25 55:  18
> 
> When I write the contents of the file to my TextEdit object it comes out
> uneven, something like this:
> 42: 11526: 11435: 11219: 10816: 107 45: 10740: 106
> 5: 10541: 104 2: 103 9: 10248: 10215: 10122: 101 27:
> 101 39: 10143: 10110: 1006:  9934:  99 32:  9849: 98
>20:  9730:  978:  96 17:  9638:  9612:  9514: 95
>   37:  95 4:  9413:  9444:  9436:  933:  92 24:  92 28:
> 9231:  9129:  897:  88
>  1:  8718:  8546:  8533:  8411:  83
> 23:  8347:  8225:  8021:  7950:  56 52:  3951:  38
> 53:  3654:  2555:  18
> 
> What seems to be happening is that the font that pyqt is using is not
> fixed width, so I did this:
>   qTxtFormat = QTextCharFormat()
>   qTxtFormat.setFontFixedPitch(True)
>   ui.textEdit.setCurrentCharFormat(qTxtFormat)
> 
> Also, I tried using the pyqt formatting such as the following:
> 
>   qStr = QtCore.QString( QtCore.QString( str(tL2[i][0])
>   ).rightJustified(2) + ':' + QtCore.QString( str(tL2[i][1])
>   ).rightJustified(4) )
> This still gives me uneven columns.
> 
> Any suggestions?
> 
> Thanks,
> 
> Glen

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


Weekly Python Patch/Bug Summary

2007-04-18 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  357 open ( +8) /  3745 closed ( +8) /  4102 total (+16)
Bugs:  958 open (+19) /  6657 closed ( +9) /  7615 total (+28)
RFE :  251 open ( +2) /   280 closed ( +2) /   531 total ( +4)

New / Reopened Patches
__

Help with Python codebase  (2007-04-11)
CLOSED http://python.org/sf/1698723  opened by  Munawar

Update to Macintosh library documentation  (2007-04-11)
   http://python.org/sf/1698768  opened by  Kevin Walzer

ZipFile.printdir fix (2.5)  (2007-04-11)
   http://python.org/sf/1698915  opened by  Alan McIntyre

ZipFile.printdir fix (2.6)  (2007-04-11)
   http://python.org/sf/1698917  opened by  Alan McIntyre

Bastion and rexec message out-of-date  (2007-04-12)
   http://python.org/sf/1698951  opened by  Gabriel Genellina

getstate/setstate for incremental codecs  (2007-04-12)
CLOSED http://python.org/sf/1698994  opened by  Walter Dörwald

replacing char* with const char* in sysmodule.c/.h  (2007-04-12)
   http://python.org/sf/1699259  opened by  sebastinas

Armin's method cache optimization updated for Python 2.6  (2007-04-13)
   http://python.org/sf/1700288  opened by  Kevin Jacobs

VC6 build patch for trunk  (2007-04-14)
   http://python.org/sf/1700463  opened by  Hirokazu Yamamoto

stack size of python_d.exe on VC6  (2007-04-14)
   http://python.org/sf/1700467  opened by  Hirokazu Yamamoto

link_objects in setup.cfg crashes build  (2007-04-18)
   http://python.org/sf/1703178  opened by  Markus Schatten

silenced a compiler warning  (2007-04-18)
   http://python.org/sf/1703268  opened by  Alexander Belopolsky

missing declaration in readline.c  (2007-04-18)
   http://python.org/sf/1703270  opened by  Alexander Belopolsky

bug fix: ctypes truncates 64-bit pointers  (2007-04-18)
   http://python.org/sf/1703286  opened by  Alexander Belopolsky

fixes non ansi c declarations in libffi  (2007-04-18)
   http://python.org/sf/1703300  opened by  Alexander Belopolsky

Refactor test_frozen.py to use unittest.  (2007-04-18)
   http://python.org/sf/1703379  opened by  Jerry Seutter

Patches Closed
__

Fix test_urllib on Windows buildbots  (2007-04-07)
   http://python.org/sf/1695862  closed by  zseil

Don't block on Queue get/put when time is moved back  (2007-03-29)
   http://python.org/sf/1690578  closed by  loewis

struct.pack() on 64bit architectures  (2004-03-30)
   http://python.org/sf/925932  closed by  zseil

bug# 1607041: Condition.wait timeout fails on clock change  (2006-12-01)
   http://python.org/sf/1607149  closed by  loewis

Add IllegalStateError  (2007-03-21)
   http://python.org/sf/1685642  closed by  gvanrossum

Help with Python codebase  (2007-04-11)
   http://python.org/sf/1698723  closed by  gbrandl

getstate/setstate for incremental codecs  (2007-04-12)
   http://python.org/sf/1698994  closed by  doerwalter

Change *args from a tuple to list  (2006-05-31)
   http://python.org/sf/1498441  closed by  collinwinter

New / Reopened Bugs
___

README is referencing obsolete? http://starship.python.net  (2007-04-09)
   http://python.org/sf/1696740  opened by  Jiri Navratil

package.pth file name not used as described.   (2007-04-09)
   http://python.org/sf/1697169  opened by  cfk

winreg module for cygwin?  (2007-04-09)
   http://python.org/sf/1697175  opened by  Zooko O'Whielacronx

Property with -> annotation triggers assert  (2007-04-09)
   http://python.org/sf/1697248  opened by  Guido van Rossum

types.InstanceType is missing but used by pydoc  (2007-04-10)
   http://python.org/sf/1697782  reopened by  gbrandl

types.InstanceType is missing but used by pydoc  (2007-04-10)
   http://python.org/sf/1697782  opened by  Christian Heimes

__getslice__ still used in built-in types  (2007-04-10)
   http://python.org/sf/1697820  opened by  Torsten Bronger

Segfaults on memory error  (2007-04-10)
   http://python.org/sf/1697916  reopened by  gbrandl

Segfaults on memory error  (2007-04-10)
   http://python.org/sf/1697916  opened by  STINNER Victor

msgfmt cannot cope with BOM  (2007-04-10)
   http://python.org/sf/1697943  opened by  Christoph Zwerschke

xml.etree document element.tag  (2007-04-11)
   http://python.org/sf/1698167  opened by  paul rubin

wrong % of params for format string in ZipFile.printdir()  (2007-04-11)
   http://python.org/sf/1698398  opened by  Szabolcs Berecz

dtdparser discards last line  (2007-04-11)
CLOSED http://python.org/sf/1698944  opened by  L. Peter Deutsch

shlex fails to parse strings correctly  (2007-04-12)
   http://python.org/sf/1699594  opened by  Collin Winter

pickle example contains errors  (2007-04-13)
   http://python.org/sf/1699759  opened by  Mark Edgington

locale.getlocale() output fails as setlocale() input   (2007-04-13)
   http://python.org/sf/1699853  opened by  Bernhard Reiter

import and capital lett

Text Suffix to Prefix Conversion

2007-04-18 Thread EMC ROY
Dear all,

I'm a postgraduate student in Hong Kong, studying english language. I
wanna seek help from all of you about some plain text manipulation.

I have already add part-of-speech (POS) tags with angle bracket by
software tagger, right after every word in my file, as attribute. How
could I change the tag suffix to tag prefix?

Original Sentence:   An apple for you.
Present: An apple for
you .<.>
Desire:   An apple for you
<.>.

My file includes several hundred thousands of words. Manual editing is
not possible.

All suggestion are welcome!!

EMC ROY
19/04/2007

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

Re: Text Suffix to Prefix Conversion

2007-04-18 Thread Steven Bethard
EMC ROY wrote:
> Original Sentence: An apple for you.
> Present:   An apple for you .<.>
> Desire:An apple for you <.>.

>>> text = 'An apple for you .<.>'
>>> import re
>>> re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text)
'An apple for you <.>.'
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: What makes an iterator an iterator?

2007-04-18 Thread 7stud
Hi,

Thanks for the responses.

> 7stud <[EMAIL PROTECTED]> wrote:
> > Can you explain some of the details of why this code fails:
> ---
> class Parrot(object):
> def __iter__(self):
> return self
> def __init__(self):
> self.next = self.next().next
> def next(self):
> for word in "Norwegian Blue's have beautiful
> plumage!".split():
> yield word
>
> P = Parrot()
> for word in P:
> print word
> --

On Apr 18, 8:45 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
>
> ...a loop like "for x in y:" binds an unnamed temporary
> variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to
> be pedantic type(_t).next(t)] until that raises StopIteration.


A.  Isn't this the crux:

> repeatedly calls[type(_t).next(t)]

 As far as I can tell, if the call was actually _t.next(), the code I
asked about would work.  However, the name look up for 'next' when you
call:

P.next()

is entirely different from the name look up for 'next' when you call:

type(P).next().

In the first lookup, the instance attribute "next" hides the class
attribute "next".  In the second lookup, the "next" attribute of the
class is returned, i.e. the next() method.  Yet, a generator-function-
call returns an iterator object that wraps the generator function, so
when the for loop makes repeated calls to type(P).next(), an iterator
object is repeatedly returned--what you want is i.next() to be
returned.

I suspected next() might be called through the class, but after
carefully parsing the section on iterators (Python in a Nutshell, p.
65) where it says iter() returns an object i, and then the for loop
repeatedly calls i.next(), I dismissed that idea.  I have to admit I'm
still a little confused by why you only parenthetically noted that
information and called it pedantic.


On Apr 18, 8:38 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
> One very good way to get an iterator from an iterable is for .__iter__ to
> be a generator function.

Ahhh.  That eliminates having to deal with next().next constructs.
Nice.

> snip all examples of bad code that violate the iterator rule
> by improperly writing .next as a generator function

What iterator rule states that .next can't be a generator function?
My book says an iterator is any object with a .next method that is
callable without arguments (Python in a Nutshell(p.65) says the same
thing).   Also, my boos says an iterable is any object with an
__iter__ method.As a result,  next() and __iter__() don't have to
be in the same object:

lass MyIterator(object):
def __init__(self, obj):
self.toIterateOver = obj
def next(self):
for x in range(self.toIterateOver.age):
print x
raise StopIteration

class Dog(object):
def __init__(self, age):
self.age = age
def __iter__(self):
return MyIterator(self)

d = Dog(5)
for year in d:
print year


I've read recommendations that an iterator should additionally contain
an __iter__() method, but I'm not sure why that is.  In particular PEP
234 says:

--
Classes can define how they are iterated over by defining an
__iter__() method; this should take no additional arguments and
return a valid iterator object.  A class that wants to be an
iterator should implement two methods: a next() method that
behaves
as described above, and an __iter__() method that returns self.

The two methods correspond to two distinct protocols:

1. An object can be iterated over with "for" if it implements
   __iter__() or __getitem__().

2. An object can function as an iterator if it implements next().

Container-like objects usually support protocol 1.  Iterators are
currently required to support both protocols.  The semantics of
iteration come only from protocol 2; protocol 1 is present to make
iterators behave like sequences; in particular so that code
receiving an iterator can use a for-loop over the iterator.

Classes can define how they are iterated over by defining an
__iter__() method; this should take no additional arguments and
return a valid iterator object.  A class that wants to be an
iterator should implement two methods: a next() method that
behaves
as described above, and an __iter__() method that returns self.

The two methods correspond to two distinct protocols:

1. An object can be iterated over with "for" if it implements
   __iter__() or __getitem__().

2. An object can function as an iterator if it implements next().

Container-like objects usually support protocol 1.  Iterators are
currently required to support both protocols.  The semantics of
iteration come only from protocol 2; protocol 1 is present to make
iterators behave like sequences; in particular so that code
receiving an iterator can use a for-loop over the iterator.



>The semantics of
>iteration come only from protocol 2

My example demonstrate

Re: Third party script debugging on remote server ...

2007-04-18 Thread Graham Dumpleton

> Hi Graeme,
>
> Thanks for the suggestion. Unluckily for me, it doesn't seem to be
> working though ...
>
> I've tried it a number of different ways. I guess if I put the code
> after an exception, then the code won't be called.
> So I ran an error in the python script and then I called the
> sys.stderr.flush() from the python shell. No luck though.
>
> I called on it's own, still no luck,
>
> Then I tried ...
>
> try:
>
> raise Exception('Please log this error')
>
> except:
>
> import sys
>
> sys.stderr.flush()
> sys.stdout.flush()
>
> The error log still has no error info in it :-(  
>
> Is this problem unique to me ?

Those calls don't generate output themselves and exception details
don't get output at the point of a try/except block. If you want to
generate to Apache error log details of exception from try/except,
use:

  import traceback
  import sys

  try:
 xxx
  except:
 traceback.print_exc()
 sys.stderr.flush()

Using these flush functions from interactive debugger isn't going to
show you anything as this trick is only needed with mod_python. All
the functions do is force the output of any buffered data that was
written out previously.

Graham

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


unicode and __repr__()

2007-04-18 Thread Martin Drautzburg
I am using repr() to pass arrays, dicts and combinations therof to
javascript as it already returns a valid javascript expression (a
string) right away. But for some reason it does not handle Umlaute
correctly and those characters finally appear as two strange characters
on the browser. I am using UTF-8 and assembling the string expression
manually works okay and the umlaute appear correctly in the browser (so
I could probably write my own serializer and it would work).

The commandline shows a difference too:

>>> print "["+"'ö'"+"]"
['ö'] <-- this is openbracket quote oumlaut quote closebracket

>>> print ["ö"].__repr__()
['\xf6'] 

It works okay for all other chars, just the umlaute seem to be a
problem.

How can I get __repr__() to handle the umlauter correctly, or is there
an easy way to postprocess the output ?

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


Re: Beginner: Formatting text output (PyQt4)

2007-04-18 Thread Tina I
Glen wrote:


>> Hello again,  I don't blame anyone for not answering my last post,
> since
>> I obviously hadn't spent much time researching, but I've come a little
>> ways and have another question.
>>
>> How can I better format text output to a QTextEdit object?  I'm
>> inserting 5 columns into each row.  When I write the info to a file, it
>> looks like the following:
>>
>> 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40:
>> 106  5: 105 41: 104  2: 103
>>  9: 102 48: 102 15: 101 22: 101 27: 101
>> 39: 101 43: 101 10: 100  6:  99 34:  99 32:  98 49:
>> 98 20:  97 30:  97  8:  96 17:  96 38:  96 12:  95
>> 14:  95 37:  95
>>  4:  94 13:  94 44:  94 36:  93  3:  92
>> 24:  92 28:  92 31:  91 29:  89  7:  88
>>  1:  87 18:  85 46:  85 33:  84 11:  83
>> 23:  83 47:  82 25:  80 21:  79 50:  56 52:  39 51:
>> 38 53:  36 54:  25 55:  18
>>
>> When I write the contents of the file to my TextEdit object it comes out
>> uneven, something like this:
>> 42: 11526: 11435: 11219: 10816: 107 45: 10740: 106
>> 5: 10541: 104 2: 103 9: 10248: 10215: 10122: 101 27:
>> 101 39: 10143: 10110: 1006:  9934:  99 32:  9849: 98
>>20:  9730:  978:  96 17:  9638:  9612:  9514: 95
>>   37:  95 4:  9413:  9444:  9436:  933:  92 24:  92 28:
>> 9231:  9129:  897:  88
>>  1:  8718:  8546:  8533:  8411:  83
>> 23:  8347:  8225:  8021:  7950:  56 52:  3951:  38
>> 53:  3654:  2555:  18
>>
>> What seems to be happening is that the font that pyqt is using is not
>> fixed width, so I did this:
>>  qTxtFormat = QTextCharFormat()
>>  qTxtFormat.setFontFixedPitch(True)
>>  ui.textEdit.setCurrentCharFormat(qTxtFormat)
>>
>> Also, I tried using the pyqt formatting such as the following:
>>
>>  qStr = QtCore.QString( QtCore.QString( str(tL2[i][0])
>>  ).rightJustified(2) + ':' + QtCore.QString( str(tL2[i][1])
>>  ).rightJustified(4) )
>> This still gives me uneven columns.
>>
>> Any suggestions?
>>
>> Thanks,
>>
>> Glen
> 
Do you need to use QTextEdit for the output? Sounds like maybe you 
should look at for example the QTableWidget or maybe the QTreeWidget?

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


Re: comparison with None

2007-04-18 Thread Steven Howe

Alan Isaac wrote:

"Terry Reedy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
  

Should be in the reference manual section on comparisons.



Only to this extent:
http://www.python.org/doc/2.4/ref/comparisons.html

objects of different types always compare unequal, and are ordered
consistently but arbitrarily.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in
operators.
In the future, the comparison rules for objects of different types
are
likely to change.)

...  Most other types compare unequal unless they are the same
object;
the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one
execution
of a program.

This does not provide a direct answer to "why" None comparisons.
(As far as I can tell, None is less than any object.)

However, Gary Herron's explanation makes sense: this provides a stable
sort when None is involved, and meets the criterion that objects of
different types must always compare unequal.  However this would also
be true if None always compared greater than any object, and the current
behavior does not seem to be guaranteed.

Is that about right?

Cheers,
Alan Isaac


  
I love scripting languages ... but sometimes an explicit evaluation that 
one would find in

a compiled language is better.
Which is why I suggested using the explicit type(x) == types.NoneType as 
opposed to

x is None


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

Re: How to communicate via USB "port"

2007-04-18 Thread Tim Roberts
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>Can someone explain how I would read the data from the USB "port"? I
>don't know if it matters, but I am trying to read the data from a GPS
>plugged in to the USB port.

USB is a "protocol" bus.  It isn't like a serial port, where you can just
start reading bits.  Each device has one or more "interfaces", and each
interface has one or more "pipe" for transmitting data.  You have to know
which "pipe" to talk to, what kind of pipe it is, and how to force the
device to send before you can talk to it.

On the other hand, as someone else pointed out, many types of USB devices
fall into standard device classes, and the operating system supplies
drivers for those classes.  If your GPS device is in the communication
class, you might be able to pretend it is a serial device.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Text Suffix to Prefix Conversion

2007-04-18 Thread 7stud
On Apr 18, 11:08 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> EMC ROY wrote:
> > Original Sentence: An apple for you.
> > Present:   An apple for you .<.>
> > Desire:An apple for you <.>.
> >>> text = 'An apple for you .<.>'
> >>> import re
> >>> re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text)
>
> 'An apple for you <.>.'

If you end up calling re.sub() repeatedly, e.g. for each line in your
file, then you should "compile" the regular expression so that python
doesn't have to recompile it for every call:

import re

text = 'An apple for you .<.>'
myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3')
re.sub(myR, r'\2\1\3', text)


Unfortunately, I must be doing something wrong because I can't get
that code to work.  When I run it, I get the error:

Traceback (most recent call last):
  File "2pythontest.py", line 3, in ?
myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3')
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/sre.py", line 180, in compile
return _compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/sre.py", line 225, in _compile
p = sre_compile.compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/sre_compile.py", line 496, in compile
p = sre_parse.parse(p, flags)
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/sre_parse.py", line 668, in parse
p = _parse_sub(source, pattern, 0)
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/sre_parse.py", line 308, in _parse_sub
itemsappend(_parse(source, state))
  File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
python2.4/sre_parse.py", line 396, in _parse
if state.flags & SRE_FLAG_VERBOSE:
TypeError: unsupported operand type(s) for &: 'str' and 'int'


Yet, these two examples work without error:

--
import re

text = 'An apple for you .<.>'
#myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3')
print re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text)

myR = re.compile(r'(hello)')
text = "hello world"
print re.sub(myR, r"\1XXX", text)

-output:
An apple for you <.>.
helloXXX world


Can anyone help?




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


Re: Nested dictionaries trouble

2007-04-18 Thread Steven D'Aprano
On Wed, 18 Apr 2007 12:16:12 -0700, IamIan wrote:

> I am using the suggested approach to make a years list:
> 
> years = ["199%s" % x for x in range(0,10)]
> years += ["200%s" % x for x in range(0,10)]
> 
> I haven't had any luck doing this in one line though. Is it possible?

years = ["199%s" % x for x in range(0,10)] + \
["200%s" % x for x in range(0,10)]

Sorry for the line continuation, my news reader insists on breaking the
line. In your editor, just delete the "\" and line break to make it a
single line.


If you don't like that solution, here's a better one:

years = [str(1990 + n) for n in range(20)]

Or there's this:

years = [str(n) for n in range(1990, 2010)]

Or this one:

years = map(str, range(1990, 2010))


-- 
Steven.

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


Re: What makes an iterator an iterator?

2007-04-18 Thread Ben Finney
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> class Parrot(object):
> def __iter__(self):
> return self
> def __init__(self):
> self.next = self._next()
> def _next(self):
> for word in "Norwegian Blue's have beautiful plumage!".split():
> yield word

Clearly the problem is you've misused an apostrophe. Python doesn't
like the plural getting an apostrophe.

http://www.angryflower.com/bobsqu.gif>

-- 
 \  "Speech is conveniently located midway between thought and |
  `\ action, where it often substitutes for both."  -- John Andrew |
_o__)  Holmes, _Wisdom in Small Doses_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Strange terminal behavior after quitting Tkinter application

2007-04-18 Thread Chris
Hi,

I'm puzzled by some strange behavior when my Python/Tkinter
application quits (on linux): the terminal from which I started Python
is messed up.

If start up python, then import the code below, then start the program
with Application(), then click the Quit button, my terminal never
prints anything again (such as commands I type).



import Tkinter
import sys

class Application(Tkinter.Tk):

def __init__(self,**config):
Tkinter.Tk.__init__(self,**config)
 
Tkinter.Button(self,text="Quit",command=self.quit_application).pack()

def quit_application(self):
sys.exit()




Can anyone tell me what I'm doing wrong?

Thanks for your help.

Chris

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


Re: Strange terminal behavior after quitting Tkinter application

2007-04-18 Thread Chris
(I'm not sure what happened to the formatting in my post: the
"Tkinter.Button" line should be at the same level of indentation as
the "Tkinter.Tk.__init__" line.)

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


Win32com, and Excel issues.

2007-04-18 Thread Ant
Hi all,

I'm doing some Excel automation work for a friend, and am developing
on a machine running Office 2000. My friends machine is running Excel
2003. The code I've written works like a charm on my machine (in fact
all three of my machines), but falls over early on on Excel 2003.

The code snippet it falls over on is code to copy one worksheet after
another:

app = wincl.Dispatch("Excel.Application")
app.Visible = True
app.Workbooks.Open(self.filename)
sheet = app.Worksheets(1)
sheet.Copy(None, sheet)

and this last line throws the following exception:

pywintypes.com_error: (-2147417851, 'the server threw an exception.'
, None, None)

which isn't too helpful.

I'm wondering if something has changed in the Excel API that doesn't
allow a null parameter to Copy or some similar issue. I tried using
the keyword argument format, but that simply refused to work.

Other relevant information:

* The program is packaged using py2exe, so I know that the same
version of Python, and the same libraries are on each machine.
* One of the test machines running Excel 2000 does not have Python
installed.
* The machines are all of a similar spec.

Any ideas are welcome!

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


Re: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ???

2007-04-18 Thread Muhammad
On Apr 17, 12:18 pm, utabintarbo <[EMAIL PROTECTED]> wrote:
> On Apr 17, 10:32 am, Muhammad <[EMAIL PROTECTED]> wrote:
>
> > On Apr 17, 7:56 am, [EMAIL PROTECTED] wrote:
> >> - 
> > You mentioned "Korean Al-Qaeda Terrorist" in the title! Honesty
> > demands that you establish it as a fact that the person was connected
> > to Al-Qaeda and that he was a terrorist and not some mentally sick
> > fellow.
> > Muhammad
>
> Just do it in a more appropriate forum, mmmkay?

Sorry about that. But I only post when I feel it necessary. And I
thought that if I let this person be, it might get to: But Al-Qaeda is
a Muslim terrorist organization, let us go get Muslims. Precisely like
Wafa Sultan and Co. who want to eradicate "Radical Islam" for a start,
but end up saying "There is no moderate Muslim". In other words, "Get
all the Muslims". Not that it frightens me, I have seen much worse,
but it is a bother.
Muhammad

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


Signals

2007-04-18 Thread Robert Rawlins - Think Blue
Hello Chaps,

 

I posted about this the other day but I'm still struggling to get any form
of result from it. Basically I have the following piece of code, and
according to its API is produces singals when particular events occur, but i
have no idea how to list for events, I've tried all sorts of combinations
using the signal module but haven't been able to get it working.

 

#!/usr/bin/python

 

import dbus, signal

 

bus = dbus.SystemBus()

obj = bus.get_object('org.bluez', '/org/bluez')

obj = bus.get_object('org.bluez', '/org/bluez/hci0')

adapter = dbus.Interface(obj, 'org.bluez.Adapter')

 

adapter.DiscoverDevices()

 

Now here is a copy of the API documentation that lists the signals thrown by
the API, this is the one I'm trying to listen for.

 

void RemoteDeviceFound(string address, uint32 class, int16 rssi)

 

   This signal will be send every time an inquiry result

   has been found by the service daemon. In general they

   only appear during a device discovery.

 

Basically I'm just looking to run a function that will print those details
to screen. Can anyone help with working out how to listen for this signal?
I'd also like to know how i can keep the application running until I decided
to stop it manually, as the DiscoverDevices() can take a while to complete
and send out several RemoteDeviceFound() signals in that period.

 

Thanks guys

 

Rob

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

Re: Queue enhancement suggestion

2007-04-18 Thread Antoon Pardon
On 2007-04-17, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On 17 Apr 2007 14:32:01 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>>On 2007-04-17, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>>> On 17 Apr 2007 13:32:52 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
On 2007-04-17, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
 [snip]
>>>
> Not sure I understand this -  it sounds vaguely incestous to me.
> I normally use a GUI with two queues,  one for input, one for
> output, to two threads that front end two named pipes to
> the next process - I try to avoid more than one thing reading or
> writing to one end of a queue or a pipe, so the dataflow diagram
> for my stuff always looks like a TinkerToy...

The problem is that sometimes the gui thread has something to show
too. With the added problem that the code wanting to show something
doesn't know when it is executing the gui thread or an other. So
it is very difficult to avoid the gui thread putting things on the
queue. But since the gui thread is the single reader, it will dead
lock if the queue happens to be full at the moment the gui thread
want to add another item.

>>>
>>> This is pretty easily solved:
>>>
>>> def sendToGUI(event):
>>> if isInGUIThread():
>>> gui.scheduleCall(event)
>>> else:
>>> guiQueue.put(event)
>>
>>No that is not a solution for the simple reason that now things
>>can be shown out of order. Suppose I have a thread that shows
>>the value of a certain variable. Now I have a button that can
>>stop this thread and zero the variable. If I go for your
>>solution a value may still be in the queue and my window
>>ends up showing this last value instead of zero.
>>
>
> Addressing that is up to the application code.  Threading is tough,
> there are no magic bullets.  The above is a very standard tool for
> addressing the concern raised earlier in this thread.  It's only
> *part* of a solution though, the rest of the application has to play
> along.

My solution is a more complete implementation of Queues, which allow
a thread to register as reader, writer or reader-writer. Reader-writers
are always allowed to put an element in the queue even if it is "full".

Since the Reader-writer will typically only put things on the queue
as a result of user interaction, the queue wont grow too large
anyway.

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


  1   2   3   >