Re: Is it possible to print different levels to different streams using the logging module?

2010-01-17 Thread Vinay Sajip
On Jan 16, 2:32 pm, Dotan Barak  wrote:
> Hi.
>
> I would like to use theloggingmodule and print the following levels to
> the mentioned streams:
>
> CRITICAL    -> stderr
> ERROR         -> stderr
> WARNING   -> stderr
> INFO             -> stdout
> DEBUG         -> stdout
>
> I would like that every message will be printed only once, and for the
> stream that i choose.
> (I failed to find a "maximum level" for the handlers in theloggingmodule).
>
> Thanks in advanced
> Dotan Barak

Peter's answer is good, and you can also look at a slightly different
take on it (for a slightly different requirement - printing INFO only
to stdout, and everything else to stderr).

http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams/1383365#1383365

Regards,

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


Re: Unicode and dictionaries

2010-01-17 Thread Martin v. Loewis
> This ought to be a bug; objects that compare equal and are hashable
> must have the same hash code.

It's not a bug. Changing the default encoding is not really supported,
let alone changing it to anything but latin-1, precisely for the reasons
you discuss.

If you do change the default encoding, Python *will* break. This has
been discussed many times, but some people still think they know better.

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


Re: Unicode and dictionaries

2010-01-17 Thread Martin v. Loewis
> Thanks to all of you. This once again proves how deep you can get
> yourself into a mess if you mix unicode and string objects in your
> code!

The specific issue is that you apparently changed the default encoding.
Don't do that, Python will break if you do.

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


Re: Unicode and dictionaries

2010-01-17 Thread Steven D'Aprano
On Sun, 17 Jan 2010 10:49:44 +0100, Martin v. Loewis wrote:

>> This ought to be a bug; objects that compare equal and are hashable
>> must have the same hash code.
> 
> It's not a bug. Changing the default encoding is not really supported,
> let alone changing it to anything but latin-1, precisely for the reasons
> you discuss.
> 
> If you do change the default encoding, Python *will* break. This has
> been discussed many times, but some people still think they know better.


That's specific to CPython though, isn't it? Other implementations may, 
or may not, cope with it better?





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


Adding a cookie

2010-01-17 Thread koranthala
Hi,
I am creating a webscraper for a specific web site for an
application.
Now, that website has a specific cookie which needs to be set in
the request. Otherwise, the website is redirected.
I have been trying for the last 6 hours to add a cookie to the
HTTP request, but to no avail.
I tried mechanize for some time, then found the cookielib module
which again is a copy of it.
For such a small thing, the whole setup seems to be too
complicated.

   The only way I could get any cookie in using the extract_cookies
from a cookiejar. But that will not help me because I want to add one
cookie - not get cookie from req and send it back.

Can anyone help me out?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusing, desparate MySQLdb problems...

2010-01-17 Thread stopchuckingstuff
On Jan 17, 4:01 am, Ned Deily  wrote:
> In article
> <5bc2641f-44fc-4324-b299-400ccbc79...@p8g2000yqb.googlegroups.com>, stopchuckingstuff
>   wrote:
>
> [...]
>
> > This just gets even more confusing!
>
> > I used a shebang line:
>
> > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python
>
> > which i got from which python in terminal, and now i get this error
> > when trying to import MySQLdb:
>
> > : No module named pkg_resources
>
> > How!? I don't get that error when using that same version of python in
> > IDLE...
>
> > What's going on?!
>
> Sounds like setuptools is not being found on sys.path.  And, judging
> from your earlier post, it appears that sys.path when running under
> Apache includes /Library/WebServer/.python-eggs.  Perhaps you need to
> ensure setuptools is installed there.  That wouldn't normally be on the
> python's sys.path when running from the terminal.
>
> But I realized after my last response that I should have asked how you
> were using Python with Apache: presumably with mod_wsgi or, possibly,
> mod_python.  In either case, the configurations are more complex and
> something I have little experience with so I should probably point you
> elsewhere.  For mod_wsgi, Graham Dumpleton offers exemplary thorough
> documentation here:
>
> http://code.google.com/p/modwsgi/http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSXhttp://code.google.com/p/modwsgi/wiki/WhereToGetHelp
>
> Good luck.
>
> --
>  Ned Deily,
>  n...@acm.org

I'm not using either mod_wsgi or mod_python, I just edited httpd.conf.

You're right about setuptools - imports in terminal, not in cgi.
however, the path to it (/Library/Frameworks/Python.framework/Versions/
2.6/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg)
is present in both sys.paths - as i said, both sys.paths are
identical.

And from printing the sys.paths, /Library/WebServer/.python-eggs
doesn't appear, I think it just uses it as a temporary folder to unzip
the python eggs into.

What I don't understand is if the path is there, why doesn't it find
the module?

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


Re: pyserial: Unexpected Local Echo

2010-01-17 Thread Steven Woody
2010/1/16 John Nagle :
> Grant Edwards wrote:
>>
>> On 2010-01-11, Steven Woody  wrote:
>>
>>> I am using pyserial.  But I always get the local echo after I
>>> write some characters onto serial port
>>
>> I really doubt you're getting a local echo.  Is the data coming
>> out the serial port?  Do you get the echo if you disconnect the
>> serial cable?
>>
>>> and I find no way to disable this behavior. When I say 'local
>>> echo', I mean the next read operation will get characters that
>>> was just write to the same port.
>>
>> The device to which you're connected is echoing them.  There's
>> also a chance that your rxd line is floating and there's enough
>> crosstalk in the cable to "echo" the data, but I'll bet money
>> it's not being done locally (in the serial driver or port).
>>
>>> I run my program on cygwin (pyserial was also built on the
>>> system from source code) and the serial port i am using is a
>>> USB adapter that simulates a port (COM4 on my XP) because my
>>> laptop don't have a real serial port.  But I checked my COM4
>>> settings, there is no any think like 'local echo'.
>
>    You're using what?  Some version of Python built on Cygwin
> running on a Windows XP system?   What if you just run a stock
> Python built for Windows on Windows XP?  Or run Linux?  That
> half-and-half environment may not work right.  pyserial has
> special cases in it for Windows and Linux, and it's not
> clear what it will do on Cygwin.
>
>    That said, if you're getting echo from output back to input,
> I'd look at the USB to serial device.  I've used devices with
> the Silicon Laboratories CP2102 part, and they work fine.
> ("http://www.aetherltd.com/connectingusb.html";)
>
>    Do you have something plugged into the serial port?  If
> so, what?
>
>                                John Nagle
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Now I tried run the same test code using pure Windows python +
pyserial, the result is same.

Actually, the USB device is a optic head, that read data from an
electric energy meter:

PC USB Port -> Optic Head -> Meter

I get the echo even when the meter itself is disconnected, that mean
the echo is not generated by firmware inside the meter. So, if the
echo is also not generated from my PC, that much be from the optic
head itself.  Is it possible?

Regards,
woody

-- 
Life is the only flaw in an otherwise perfect nonexistence
-- Schopenhauer

narke
public key at http://subkeys.pgp.net:11371 (narkewo...@gmail.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BaseHTTPServer get_request not called till first request

2010-01-17 Thread Adam Tauno Williams
On Sat, 2010-01-16 at 18:35 -0800, yousay wrote:
> On Jan 13, 1:38 am, Adam Tauno Williams 
> wrote:
> > Looking at  and
> >  as examples I've attempted
> > to create a BaseHTTPServer class that times-out accept() ever X seconds
> > to check some other work.  This seems to work well, but only once the
> > HTTPServer object has received its first request.  Up until the first
> > request get_request() is not invoked and not timeout occurs.
> > class HTTPServer(BaseHTTPServer.HTTPServer):
> > def server_bind(self):
> > BaseHTTPServer.HTTPServer.server_bind(self)
> > self.socket.settimeout(1)
> > self._shutdown = False
> > def get_request(self):
> > while not self._shutdown:
> > try:
> > print ' HTTP worker {0} waiting.'.format(self.pid)
> > self.log.debug('Waiting for connection...')
> > s, a = self.socket.accept()
> > s.settimeout(None)
> > return (s, a)
> > except socket.timeout:
> > /// do other work ///
> > return None, None
> > The "HTTP worker" message is not seen until the server has taken a
> > request, then it seems to dutifully do the timeout.
> your class Name is the same to the superClass,may be have influence

Nope, changed the name of the class (cleaned out all the *.pyc files),
and the initial wait still does not time out.


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


C-API: Get scope in function

2010-01-17 Thread moerchendiser2k3
Hi,

I have a small problem how to get the scope from a C-API function.
Check out this code snippet:

[code]
variable = 3

def test():
print variable #output: 3
print globals() # ... 'variable': 3, ...

test()
[/code


In my case I know there is a variable in the scope where this function
is called from, but I dont know how to get it.
Check out:

[code]
PyObject *MyFunction_Test(PyObject* self, PyObject *args, PyObject
*keywords)
{
 ... ?
}
[/code]

Is it possible to get the dictionary of the scope where this function
is called from?


Thanks a lot!!

Bye, googler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: r"string" vs R"string

2010-01-17 Thread Colin W.

On 17-Jan-10 02:16 AM, Terry Reedy wrote:

On 1/17/2010 1:55 AM, Brendan Miller wrote:

Is there any difference whatsoever between a raw string beginning with
the captical R or one with the lower case r e.g. r"string" vs
R"string"?


No. Nor is there and difference between the strings created with raw
literals and cooked literals.



"cooked" literal  ??
--
http://mail.python.org/mailman/listinfo/python-list


Problems with collision response

2010-01-17 Thread Joabos

I'm doing a project, and I need to insert collision detection and response on
it. Here's the code. What am I doing wrong?


   #Update all sprites, map
self.player.update(dt)

#Collide other sprites
collisions = rabbyt.collisions.aabb_collide_single(self.player,
self.spriteList)

for col in collisions:
pass

#Collide with map
collisions = rabbyt.collisions.aabb_collide_single(self.player,
self.map_manager.map_sprites())

for tile in collisions:
#Create a bounding line of all the tiles
self.player.collide(tile)
if len(collisions) > 0:
#Collide the sprite with the bounding line
pass
"""
if self.player.bottom < tile.top and self.player.top > tile.top:
self.player.collide(tile.attributes['col_type'],
DIRECTION.DOWN, tile.top)
elif self.player.top > tile.bottom and self.player.bottom <
tile.bottom:
self.player.collide(tile.attributes['col_type'],
DIRECTION.UP, tile.bottom)
elif self.player.left < tile.right and self.player.right >
tile.right:
self.player.collide(tile.attributes['col_type'],
DIRECTION.LEFT, tile.right)
elif self.player.right > tile.left and self.player.left <
tile.left:
self.player.collide(tile.attributes['col_type'],
DIRECTION.RIGHT, tile.left)
"""

#Collide with boundaries
"""if self.player.right > self.window_width:
self.player.collide(COL_TYPE.WALL, DIRECTION.RIGHT,
self.window_width)
elif self.player.left < 0:
self.player.collide(COL_TYPE.WALL, DIRECTION.LEFT, 0)

if self.player.bottom < 0:
self.player.collide(COL_TYPE.WALL, DIRECTION.DOWN, 0)
"""

-- 
View this message in context: 
http://old.nabble.com/Problems-with-collision-response-tp27199138p27199138.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: A simple-to-use sound file writer

2010-01-17 Thread Alf P. Steinbach

* Alf P. Steinbach:

* Steve Holden:

Alf P. Steinbach wrote:

* Steve Holden:

Alf P. Steinbach wrote:

* Grant Edwards:

On 2010-01-15, Steve Holden  wrote:


I will, however, observe that your definition of a square wave is
what I
would have to call a "'square' wave" (and would prefer to call a
"pulse
train"), as I envisage a square wave as a waveform having a 50% duty
cycle, as in

 ___ ___
|   |   |   |
|   |   |   |
|   |   |   |
+---+---+---+---+ and so on ad infinitum, (though I might allow you
|   |   |   |  to adjust the position
|   |   |   |  of y=0 if you want)
|___|   |___|

That is a square wave.


as opposed to your

 _
| |
| |
  __| |__   __
 | |
 | |
 |_|

That isn't.

Arguing to the contrary is just being Humpty Dumpty...

Neither I nor Steve has called that latter wave a square wave.

Steve, quoted above, has written that I defined a square wave that 
way.
I have not. So Steve's statement is a misrepresentation (I 
described it
as a sum of two square waves, which it is), whatever the reason for 
that

misrepresentation.





[snip]

So here you have an interesting example of a
piece of code that is pathological in Python2. All you have to change is
to add

  from __future__ import __division__

and bingo! It's a multi-language program. But try seeing what 2to3 says
about your Python3 code :)

I will forgive you the omission of the ".0" because I too would assume
that it would be slower.


I did not make any such assumption, no. The *1 just lingered from some 
testing.



[snip]

and so on, but I still get silence from the Quicktime player.


I don't know, sorry.

It might be that [simple_sound] also needs the "from __future__" treatment.

But anyway, with 2.x compatible code you can now see that the sample 
values produced are correct (just print them, or graph them).


I have now installed CPython 2.6.4 and the code presented upthread (the one with 
divisions fixed for 2.x compatibility) worked nicely with CPython 2.6.4, even 
though with a deprecation warning.


It produced the exact same sound file (bytes) as with CPython 3.1.1.

And the QuickTime 7.3 player played it with no problem, a base A pure sinewave, 
composed utterly of 50% duty cycle square waves, resounding in my headphones -- 
it also works with WinAmp 5.54, Windows Mediaplayer 10.00 and VLC 0.9.9, i.e. 
I'm unable to reproduce the problem.


So I suspect that you may lack a suitable codec, or it might be a PEBKAC 
problem?


Cheers & hth.,

- Alf

PS: I had expected some jaggies and such since I only divided the cycle into 100 
intervals, but graphing the data in Excel it showed a perfect sine. :-)

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


simple cgi program

2010-01-17 Thread superpollo

hi clp.

i would like to submit the following code for review. it is a simple 
common gateway interface program, which uses the least possible 
libraries for the sake of mechanism undertanding.


the third option in the firts conditional is for commandline testing.

bye.



code follows as:

#!/usr/bin/env python
import sys
import os
import urllib as url
me = os.path.basename(sys.argv[0])
env = os.environ
method = "POST"
data=None
if env.get("REQUEST_METHOD") == "GET":
data = env.get("QUERY_STRING")
elif env.get("REQUEST_METHOD") == "POST":
data = sys.stdin.read(int(env.get("CONTENT_LENGTH")))
elif not env.get("REQUEST_METHOD"):
data = sys.stdin.readline().rstrip("\n")
if not data:
sys.stdout.write("Content-type: text/html\n\n")
sys.stdout.write("\n" % (me , method))
sys.stdout.write("TYPE A DIGIT SEQUENCE AND HIT [ENTER]:\n")
sys.stdout.write("\n")
sys.stdout.write("\n")
else:
name = data.partition("=")[0]
encvalue = data.partition("=")[2]
decvalue = url.unquote_plus(encvalue)
sys.stdout.write("Content-type: text/plain\n\n")
sys.stdout.write("method: %s\n" % method)
sys.stdout.write("data: %s\n" % data)
sys.stdout.write("name: %s\n" % name)
sys.stdout.write("encvalue: %s\n" % encvalue)
sys.stdout.write("decvalue: %s\n" % decvalue)
if decvalue.isdigit():
sys.stdout.write("the sequence you typed is: %s\n" % decvalue)
else:
sys.stdout.write("what you typed is not a valid sequence\n")



criticism and advice are appreciated!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a cookie

2010-01-17 Thread Jens Müller

Hi,


   I am creating a webscraper for a specific web site for an
application.
   Now, that website has a specific cookie which needs to be set in
the request. Otherwise, the website is redirected.
   I have been trying for the last 6 hours to add a cookie to the
HTTP request, but to no avail.


You just need to send the cookie's value in the HTTP header.
E.g. urllib2 can do this like this:
request = urllib2.Request(url, None, {'Cookie': '$Version="1"; 
cookieName="CookieValue"; $Path=/cookiePath'})


Regards,
Jens 


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


Re: Problems with collision response

2010-01-17 Thread Diez B. Roggisch

Am 17.01.10 15:14, schrieb Joabos:


I'm doing a project, and I need to insert collision detection and response on
it. Here's the code. What am I doing wrong?


Not telling us what's happening, and what *should* happen, for starters.

What do you expect? The code you gave us isn't stand-alone, you don't 
give any context of what libraries you use, nor what error you see, if any.


The inevitable link to read:

 http://catb.org/~esr/faqs/smart-questions.html

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


Re: Problems with collision response

2010-01-17 Thread Diez B. Roggisch

Am 17.01.10 15:14, schrieb Joabos:


I'm doing a project, and I need to insert collision detection and response on
it. Here's the code. What am I doing wrong?


Not telling us what's happening, and what *should* happen, for starters.

What do you expect? The code you gave us isn't stand-alone, you don't 
give any context of what libraries you use, nor what error you see, if any.


The inevitable link to read:

 http://catb.org/~esr/faqs/smart-questions.html

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


Re: simple cgi program

2010-01-17 Thread D'Arcy J.M. Cain
On Sun, 17 Jan 2010 15:15:12 +0100
superpollo  wrote:
> hi clp.
> 
> i would like to submit the following code for review. it is a simple 
> common gateway interface program, which uses the least possible 
> libraries for the sake of mechanism undertanding.

Why not just use the cgi module?  It does all that for you.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with collision response

2010-01-17 Thread Joabos



Diez B. Roggisch-2 wrote:
> 
> Am 17.01.10 15:14, schrieb Joabos:
>>
>> I'm doing a project, and I need to insert collision detection and
>> response on
>> it. Here's the code. What am I doing wrong?
> 
> Not telling us what's happening, and what *should* happen, for starters.
> 
> What do you expect? The code you gave us isn't stand-alone, you don't 
> give any context of what libraries you use, nor what error you see, if
> any.
> 
> The inevitable link to read:
> 
>   http://catb.org/~esr/faqs/smart-questions.html
> 
> Diez
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Oh, sorry. Well, what's happenning is, whenever I boot the entire project,
there is *no* collision at all, when the player should stand on a tile. I
use Rabbyt and pyglet. There are no errors.
-- 
View this message in context: 
http://old.nabble.com/Problems-with-collision-response-tp27199138p27199336.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: chr(12) Form Feed in Notepad

2010-01-17 Thread bartc


"Dennis Lee Bieber"  wrote in message 
news:mailman.1021.1263702437.28905.python-l...@python.org...

On Sat, 16 Jan 2010 23:59:52 GMT, "bartc"  declaimed
the following in gmane.comp.python.general:


My point was these other control codes from over 30 years ago are still 
in

use today, so why not also make use of chr(12)?


 worked with old style text-only printers, where it triggered
the paper to move until a marker in a control tape matched. These
printers had known line spacing and column width (and did not wrap
text)...

Printing from Word/WordPad/NotePad doesn't follow that easy behavior
(in WordPad you can have text wrap to window, but it gets sent to a
printer as one long line which may or may not wrap depending on the
printer). A Text-only printer probably honors , but most all
printers in Windows are defined as graphical -- what is sent is a
bit-image of the data as rendered in a memory buffer at printer
resolution.

At that level, it is dependent upon what the printer driver and GDI
do when receiving a non-printable byte value...


Until recently at least printers were non-text-only but did not necessarily 
accept only bitmap images. For example they might use Postscript, HP/PCL or 
Epson Esc/p (or whatever the exact names were). I'm fairly certain the last 
two responded directly to chr(12) codes in the input stream.


Windows may or may not drive these in bitmap mode (which can be simpler for 
Windows, but then you lose any special processing available inside the 
printer), but given the task of sending a TXT file to such a printer, it is 
not unreasonable to expect it to honour codes such as CR, LF and FF, 
especially as most printers seem to be page-oriented now rather than use 
roll or fanfold paper.


It would just need to translate FF into the page-break command for the 
printer in question, eg. send the image so far and eject the page, just as 
it might do for EOF.


--
bartc 


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


Re: simple cgi program

2010-01-17 Thread superpollo

D'Arcy J.M. Cain ha scritto:

On Sun, 17 Jan 2010 15:15:12 +0100
superpollo  wrote:

hi clp.

i would like to submit the following code for review. it is a simple 
common gateway interface program, which uses the least possible 
libraries for the sake of mechanism undertanding.


Why not just use the cgi module?  It does all that for you.



yes, but i am trying to learn exactly the cgi mechanism internals, just 
for fun ;-)


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


Re: A simple-to-use sound file writer

2010-01-17 Thread Alf P. Steinbach

* Alf P. Steinbach:

Just as a contribution, ...


The original code I posted was only written for Python 3.1.1 (because the code 
was for my writings which assumes 3.x). In the simple_sound module this caused a 
deprecation warning with 2.x. And the example program didn't work with 2.x.


I've now installed CPython 2.6.4 and fixed the code so that it works nicely also 
with that version of Python.




"Generate simple mono (single-channel) [.wav], [.aiff] or [.aifc] files."

# Works with Python 2.6.4 and Python 3.1.1, but has not been extensively tested.
# Author: Alf P. Steinbach.
#
# Changes from original 3.1.1 version:
# * A deprecation warning suppressed by explicit cast to int.
# * The default sound library is now not imported until it's actually used.
# * Added exception handling (for the code's original purpose I couldn't).
#
# Notes:
# (1) It might be possible to optimize this by using array of 16-bit integers, 
then
# checking 'sys.byteorder' and doing a 'data.byteswap()' call as 
appropriate.
# (2) Data is kept in memory until 'close' due to a bug in the 'wave' module. 
That bug

# has now been fixed. But it may be present in any Python installation.

import collections
import array
import math

default_sample_rate = 44100 # Usual CD quality.

def sample_sawtooth( freq, t ):
linear = freq*t % 1.0
return 2*linear - 1.0

def sample_square( freq, t ):
linear = freq*t % 1.0
if linear < 0.5:
return -1.0
else:
return 1.0

def sample_triangle( freq, t ):
linear = freq*t % 1.0
if linear < 0.5:
return 4.0*linear - 1.0
else:
return 3.0 - 4.0*linear

def sample_sine( freq, t ):
return math.sin( 2*math.pi*freq*t )

DataFormat  = collections.namedtuple( "DataFormat",
"open_func, append_int16_func"
)

def _append_as_big_endian_int16_to( bytes_array, i ):
if i < 0:
i = i + 65536
assert( 0 <= i < 65536 )
bytes_array.append( i // 256 )
bytes_array.append( i % 256 )

def _append_as_little_endian_int16_to( bytes_array, i ):
if i < 0:
i = i + 65536
assert( 0 <= i < 65536 )
bytes_array.append( i % 256 )
bytes_array.append( i // 256 )

def aiff_format():
import aifc
return DataFormat( aifc.open, _append_as_big_endian_int16_to )

def wav_format():
import wave
return DataFormat( wave.open, _append_as_little_endian_int16_to )

class Writer:
"Writes normalized samples to a specified file or file-like object"
def __init__(
self,
filename,
sample_rate = default_sample_rate,
data_format = None
):

if data_format is None:
data_format = aiff_format()
self._sample_rate = sample_rate
self._append_int16_func = data_format.append_int16_func
self._writer = data_format.open_func( filename, "w" )
self._writer.setnchannels( 1 )
self._writer.setsampwidth( 2 )  # 2 bytes = 16 bits
self._writer.setframerate( sample_rate )
self._samples = []

def sample_rate( self ):
return self._sample_rate

def write( self, normalized_sample ):
assert( -1 <= normalized_sample <= +1 )
self._samples.append( normalized_sample )

def close( self ):
try:
data = array.array( "B" )   # B -> unsigned bytes.
append_int16_to = self._append_int16_func
for sample in self._samples:
level = int( round( 32767*sample ) )
append_int16_to( data, level )
self._writer.setnframes( len( self._samples ) )
self._writer.writeframes( data )
finally:
self._writer.close()

def example( filename = "ringtone.aiff" ):
global default_sample_rate

sample_rate = default_sample_rate
total_time  = 2
n_samples   = sample_rate*total_time

writer = Writer( filename )
for i in range( n_samples ):
t = 1.0*i/sample_rate
samples = (
sample_sine( 440, t ),
sample_sine( (5.0/4.0)*440, t ),
)
sample = sum( samples )/len( samples )
writer.write( sample )
writer.close()

if __name__ == "__main__":
example()



Cheers, & enjoy!,

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


Re: Is python not good enough?

2010-01-17 Thread Stefan Behnel
Paul Rubin, 17.01.2010 05:06:
> David Cournapeau writes:
> 
>> And certainly, one of the big reason for
>> the python success is easy interface with C. Maybe interfacing with C
>> is the real reason for holding back python implementations ?
> 
> The CPython/C API is not terrible but it's not all that easy to use.
> For example, it's very easy to make reference counting errors.  Other
> language FFI's that I've used avoid that problem to some extent.

Other languages don't have Cython.


> It's true that CPython has quite a few existing C modules that would require
> rework if the API were to change incompatibly.

"quite a few" sounds a bit too weak here. Some of the existing C extensions
have become reasons to use Python in the first place. Think of NumPy, for
example, and the whole scipy environment. Think of the
performance-to-usability ratio of cElementTree and lxml. Think of the huge
body of Cython code in Sage. Imagine what the set of dbm modules (or even
the entire standard library) would be without external C libraries and C
extensions.

The C-API and the ton of modules that use it are pretty vital for Python.
AFAICT, Py3 is pretty much a virgin platform when it comes to scientific
computing, mostly because NumPy still wasn't adapted to the changes in the
C-API. They even consider rewriting parts of it in Cython a simpler way to
solve this issue than trying to port the code itself. This shows that any
change to that API may have a tremendous effect on the usability of Python
as a whole.


> But I think a different
> (better) API wouldn't stop people from writing new modules.

"Writing new modules" may not be enough.

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


Re: r"string" vs R"string

2010-01-17 Thread Roy Smith
In article ,
 "Colin W."  wrote:

> On 17-Jan-10 02:16 AM, Terry Reedy wrote:
> > On 1/17/2010 1:55 AM, Brendan Miller wrote:
> >> Is there any difference whatsoever between a raw string beginning with
> >> the captical R or one with the lower case r e.g. r"string" vs
> >> R"string"?
> >
> > No. Nor is there and difference between the strings created with raw
> > literals and cooked literals.
> >
> >
> "cooked" literal  ??

I've never seen it referred to this way in the Python literature, but 
"cooked" is a well-known term meaning, "not raw".  The usage goes back 
decades.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: r"string" vs R"string

2010-01-17 Thread Aahz
In article ,
Colin W.  wrote:
>On 17-Jan-10 02:16 AM, Terry Reedy wrote:
>> On 1/17/2010 1:55 AM, Brendan Miller wrote:
>>>
>>> Is there any difference whatsoever between a raw string beginning with
>>> the captical R or one with the lower case r e.g. r"string" vs
>>> R"string"?
>>
>> No. Nor is there and difference between the strings created with raw
>> literals and cooked literals.
>
>"cooked" literal  ??

Consider '\n' vs r'\n' -- the first version is "cooked" (as cooking
alters the ingredients) to produce the newline character.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is python not good enough?

2010-01-17 Thread Blog

On 1/12/2010 9:09 PM, ikuta liu wrote:

I'm a little confused.
Is python not good enough?
for google, enhance python performance is the good way better then
choose build Go language?

Go language try to merge low level, hight level and browser language.

Those I'd like to see it on python..
Have you not heard about the "Unladen Swallow" project from google? 
There's a new PEP coming up which will propose google's codebase to be 
merged with Py3k, resulting in superior performance.


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


Re: Problem with wsgiref.headers.Headers

2010-01-17 Thread Gabriel Genellina

En Fri, 15 Jan 2010 18:41:29 -0300, Phil  escribió:


I am having an issue with wsgiref.headers.Headers.

For example, if I do this...

from wsgiref.headers import Headers
list = []
wrapper = Headers(list)
wrapper['content-type'] = "text/html"
print(list)
print(wrapper)

I get an empty list printed, and then the correct result for wrapper
printed.


You forgot to mention the Python version; the code works fine with 2.x,  
but fails in 3.1

r68205 [1] is the culprit, in response to issue #4718 [2]
The commit message says the changes were made to comply with  
http://www.wsgi.org/wsgi/Amendments_1.0 (basically, clarify  
str/unicode/bytes handling in Python 3.x). Either the documentation should  
be updated or the original behavior be maintained (meaning the original  
list contents could be altered); you probably should raise the question in  
the Web-SIG [3].


[1] http://svn.python.org/view?view=rev&revision=68205
[2] http://bugs.python.org/issue4718
[3] http://www.python.org/community/sigs/current/web-sig/

--
Gabriel Genellina

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


Re: Problem with wsgiref.headers.Headers

2010-01-17 Thread Gabriel Genellina

En Fri, 15 Jan 2010 18:41:29 -0300, Phil  escribió:


I am having an issue with wsgiref.headers.Headers.

For example, if I do this...

from wsgiref.headers import Headers
list = []
wrapper = Headers(list)
wrapper['content-type'] = "text/html"
print(list)
print(wrapper)

I get an empty list printed, and then the correct result for wrapper
printed.


You forgot to mention the Python version; the code works fine with 2.x,  
but fails in 3.1

r68205 [1] is the culprit, in response to issue #4718 [2]
The commit message says the changes were made to comply with  
http://www.wsgi.org/wsgi/Amendments_1.0 (basically, clarify  
str/unicode/bytes handling in Python 3.x). Either the documentation should  
be updated or the original behavior be maintained (meaning the original  
list contents could be altered); you probably should raise the question in  
the Web-SIG [3].


[1] http://svn.python.org/view?view=rev&revision=68205
[2] http://bugs.python.org/issue4718
[3] http://www.python.org/community/sigs/current/web-sig/

--
Gabriel Genellina

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


Re: Problem with wsgiref.headers.Headers

2010-01-17 Thread Gabriel Genellina

En Fri, 15 Jan 2010 18:41:29 -0300, Phil  escribió:


I am having an issue with wsgiref.headers.Headers.

For example, if I do this...

from wsgiref.headers import Headers
list = []
wrapper = Headers(list)
wrapper['content-type'] = "text/html"
print(list)
print(wrapper)

I get an empty list printed, and then the correct result for wrapper
printed.


You forgot to mention the Python version; the code works fine with 2.x,  
but fails in 3.1

r68205 [1] is the culprit, in response to issue #4718 [2]
The commit message says the changes were made to comply with  
http://www.wsgi.org/wsgi/Amendments_1.0 (basically, clarify  
str/unicode/bytes handling in Python 3.x). Either the documentation should  
be updated or the original behavior be maintained (meaning the original  
list contents could be altered); you probably should raise the question in  
the Web-SIG [3].


[1] http://svn.python.org/view?view=rev&revision=68205
[2] http://bugs.python.org/issue4718
[3] http://www.python.org/community/sigs/current/web-sig/

--
Gabriel Genellina

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


Re: Problems with collision response

2010-01-17 Thread MRAB

Joabos wrote:

I'm doing a project, and I need to insert collision detection and response on
it. Here's the code. What am I doing wrong?


   #Update all sprites, map
self.player.update(dt)

#Collide other sprites

collisions = rabbyt.collisions.aabb_collide_single(self.player,
self.spriteList)

for col in collisions:

pass

#Collide with map

collisions = rabbyt.collisions.aabb_collide_single(self.player,
self.map_manager.map_sprites())

for tile in collisions:
#Create a bounding line of all the tiles
self.player.collide(tile)
if len(collisions) > 0:
#Collide the sprite with the bounding line
pass
"""
if self.player.bottom < tile.top and self.player.top > tile.top:
self.player.collide(tile.attributes['col_type'],
DIRECTION.DOWN, tile.top)
elif self.player.top > tile.bottom and self.player.bottom <
tile.bottom:
self.player.collide(tile.attributes['col_type'],
DIRECTION.UP, tile.bottom)
elif self.player.left < tile.right and self.player.right >
tile.right:
self.player.collide(tile.attributes['col_type'],
DIRECTION.LEFT, tile.right)
elif self.player.right > tile.left and self.player.left <
tile.left:
self.player.collide(tile.attributes['col_type'],
DIRECTION.RIGHT, tile.left)
"""

#Collide with boundaries

"""if self.player.right > self.window_width:
self.player.collide(COL_TYPE.WALL, DIRECTION.RIGHT,
self.window_width)
elif self.player.left < 0:
self.player.collide(COL_TYPE.WALL, DIRECTION.LEFT, 0)

if self.player.bottom < 0:

self.player.collide(COL_TYPE.WALL, DIRECTION.DOWN, 0)
"""


What are all those triple-quoted strings?
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] Spyder v1.0.3 released

2010-01-17 Thread Pierre Raybaut

Hi all,

I'm pleased to announce here that Spyder version 1.0.3 has been released:
http://packages.python.org/spyder

__Important__
Spyder v1.0.3 is a *critical* bugfix release (bonus: new "Apply" button 
in matplotlib's figure options editor).



Previously known as Pydee, Spyder (Scientific PYthon Development
EnviRonment) is a free open-source Python development environment
providing MATLAB-like features in a simple and light-weighted
software, available for Windows XP/Vista/7, GNU/Linux and MacOS X:
   * advanced code editing features (code analysis, ...)
   * interactive console with MATLAB-like workpace (with GUI-based
list, dictionary, tuple, text and array editors -- screenshots:
http://packages.python.org/spyder/console.html#the-workspace) and
integrated matplotlib figures
   * external console to open an interpreter or run a script in a
separate process (with a global variable explorer providing the same
features as the interactive console's workspace)
   * code analysis with pyflakes and pylint
   * search in files features
   * documentation viewer: automatically retrieves docstrings or
source code of the function/class called in the interactive/external
console
   * integrated file/directories explorer
   * MATLAB-like path management
   ...and more!

Spyder is part of spyderlib, a Python module based on PyQt4 and
QScintilla2 which provides powerful console-related PyQt4 widgets.

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


Re: maintain 2 versions of python on my computer

2010-01-17 Thread Gabriel Genellina
En Sat, 16 Jan 2010 05:16:14 -0300, Gertjan Klein   
escribió:



Gabriel Genellina wrote:


En Thu, 14 Jan 2010 08:21:28 -0300, luis  escribió:


Is there any way to indicate the version of the python interpreter
must use a script?


See http://www.effbot.org/zone/exemaker.htm
It uses the #! line to determine which version to load, resembling the
Unix way.
(I've written a variant of the same idea but isn't ready yet)


I'd be interested to see what you've come up with, if you care to share.
I've been thinking about something like this as well. Exemaker, for me,
is the wrong solution, because it requires making an .exe file for every
script you want to run this way.


The advantage is that Task Manager shows the right program name, instead  
of always "python.exe". (You don't have to *make* an .exe for every  
script, just rename/copy it.)
If you don't care, the recipe posted by Duncan Booth is as close as a #!  
line as its gets.


--
Gabriel Genellina

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


Re: dict's as dict's key.

2010-01-17 Thread Lie Ryan
On 01/17/10 12:29, Ethan Furman wrote:
> Lie Ryan wrote:
>> On 01/14/10 05:33, Albert van der Horst wrote:
>>
>>> (I encountered this before. A dictionary is a natural for a
>>> boardgame position, i.e. chess. Now we want to look up chess
>>> positions.)
>>
>>
>> or use collections.namedtuple
> 
> Which is great until you want to make a move.  ;)

No problem, just create a new namedtuple.

The OP wanted fast attribute lookup and AFAICT doesn't mention anything
about fast construction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: maintain 2 versions of python on my computer

2010-01-17 Thread Sridhar Ratnakumar

On 1/14/2010 3:23 PM, Lie Ryan wrote:

On 01/14/10 22:21, luis wrote:

>
>  Hi
>
>  I am not an expert in programming and using Python for its simplicity
>
>  I have 2 versions of python installed on my computer (windos xp) to
>  begin the transition from version 2.4 to 2.6 or 3. maintaining the
>  operability of my old scripts
>
>  Is there any way to indicate the version of the python interpreter
>  must use a script?
>
>  thanks

On my Windows machine, I make a copy python.exe and rename it as
python25.exe, python26.exe, python3.exe, etc in their respective
directories. Then after setting up the PATH environment variable, you
can simply call python25, python3, etc from any directory in the command
prompt.


Lie, ActivePython does both of this during the installation -- 
pythonXY.exe and set PATH accordingly.


Luis, Distribute (a setuptools fork) has a feature called "entry points" 
that will create exe wrappers for the specified Python script. These exe 
wrappers use the #! line to determine the actual Python interpreter to 
invoke.



http://packages.python.org/distribute/setuptools.html#automatic-script-creation

If your script is foo-script.py, foo.exe will ultimately read the first 
line in foo-script.py which is #!C:\Python26\python.exe .. and that is 
used to run the script. Task manager will show "foo.exe" instead of 
"python.exe".


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


Re: Confusing, desparate MySQLdb problems...

2010-01-17 Thread Ned Deily
In article 
<94e8cfd8-d299-4c23-9e9e-d3f17d4c9...@e16g2000yqc.googlegroups.com>,
 stopchuckingstuff  wrote:
> I'm not using either mod_wsgi or mod_python, I just edited httpd.conf.
> 
> You're right about setuptools - imports in terminal, not in cgi.
> however, the path to it (/Library/Frameworks/Python.framework/Versions/
> 2.6/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg)
> is present in both sys.paths - as i said, both sys.paths are
> identical.
> 
> And from printing the sys.paths, /Library/WebServer/.python-eggs
> doesn't appear, I think it just uses it as a temporary folder to unzip
> the python eggs into.

>From your original post:
> When trying to import the module, it gives me this error:
> 
> : /Library/WebServer/.python-eggs/
> MySQL_python-1.2.3c1-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so: no
> appropriate 64-bit architecture (see "man python" for running in 32-
> bit mode)

so it appears that the .python-eggs directory is on sys.path.  But I 
don't know where that directory is coming from in the first place.  
Something you manually created?

> 
> What I don't understand is if the path is there, why doesn't it find
> the module?

Perhaps it is just a permissions problem since Apache is probably 
running under a different user name.  Check the owner/group and 
permissions of the various module directories and files. Make sure the 
directories and .so files have at least r-x and the python files at 
least r-- across the board.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Inheriting methods but over-riding docstrings

2010-01-17 Thread Gabriel Genellina
En Sat, 16 Jan 2010 14:55:11 -0300, Steven D'Aprano  
 escribió:



I have a series of subclasses that inherit methods from a base class, but
I'd like them to have their own individual docstrings. The obvious
solution (other than copy-and-paste) is this:


class Base(object):
colour = "Blue"
def parrot(self):
"""docstring for Base"""
return "Norwegian %s" % self.colour


class SubClass(Base):
colour = "Red"
def parrot(self):
"""docstring for Subclass"""
return super(Subclass, self).parrot()


but that adds an awful lot of boilerplate to my subclasses. Are there any
other good solutions to this problem?


Methods don't have docstrings; functions do. So one has to "clone" the  
function to set a new docstring.



def copy_function(fn, docstring):
fn = getattr(fn, "im_func", fn) # accomodate unbound methods in 2.x
function_type = type(lambda:0)
newfn = function_type(fn.__code__, fn.__globals__, fn.__name__,  
fn.__defaults__, fn.__closure__)

newfn.__doc__ = docstring
return newfn

class Base(object):
colour = "Blue"
def parrot(self):
"""docstring for Base"""
return "Norwegian %s" % self.colour

class SubClass(Base):
colour = "Red"
parrot = copy_function(Base.parrot, "docstring for Subclass")



py> x = Base()
py> print(x.parrot())
Norwegian Blue
py> print x.parrot.__doc__
docstring for Base
py> y = SubClass()
py> print(y.parrot())
Norwegian Red
py> print y.parrot.__doc__
docstring for Subclass

--
Gabriel Genellina

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


Re: Something More Elegant

2010-01-17 Thread Victor Subervi
On Sat, Jan 9, 2010 at 1:00 PM, Dennis Lee Bieber wrote:

>After the table design is complete you can move to business logic
> operations (SQL for standard/fixed actions), along with criteria to
> maintain the integrity of the data (foreign key constraints, etc.). This
> should result in a set of SQL statements that are parameterized so that
> only end-user data VALUES need to be supplied -- no ad hoc creation of
> SQL by plugging in table names or column names (and especially no such
> where the plugged in names were directly entered by the end-user -- I
> acknowledge that there are some situations where generating SQL is
> useful -- typically when you give the end user a dynamic search page*)
>

Can you please give me an example of what I *shouldn't* do in the above?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


py2exe and pydocs. Downloads?

2010-01-17 Thread W. eWatson
I'm using Python 2.5 under windows, and IDLE. Do py2exe and pydocs come 
with the package, or do I have to download them?

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


Re: Confusing, desparate MySQLdb problems...

2010-01-17 Thread stopchuckingstuff
On Jan 17, 5:52 pm, Ned Deily  wrote:
> In article
> <94e8cfd8-d299-4c23-9e9e-d3f17d4c9...@e16g2000yqc.googlegroups.com>,
>
>
>
>
>
>  stopchuckingstuff  wrote:
> > I'm not using either mod_wsgi or mod_python, I just edited httpd.conf.
>
> > You're right about setuptools - imports in terminal, not in cgi.
> > however, the path to it (/Library/Frameworks/Python.framework/Versions/
> > 2.6/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg)
> > is present in both sys.paths - as i said, both sys.paths are
> > identical.
>
> > And from printing the sys.paths, /Library/WebServer/.python-eggs
> > doesn't appear, I think it just uses it as a temporary folder to unzip
> > the python eggs into.
> >From your original post:
> > When trying to import the module, it gives me this error:
>
> > : /Library/WebServer/.python-eggs/
> > MySQL_python-1.2.3c1-py2.6-macosx-10.3-fat.egg-tmp/_mysql.so: no
> > appropriate 64-bit architecture (see "man python" for running in 32-
> > bit mode)
>
> so it appears that the .python-eggs directory is on sys.path.  But I
> don't know where that directory is coming from in the first place.  
> Something you manually created?
>
>
>
> > What I don't understand is if the path is there, why doesn't it find
> > the module?
>
> Perhaps it is just a permissions problem since Apache is probably
> running under a different user name.  Check the owner/group and
> permissions of the various module directories and files. Make sure the
> directories and .so files have at least r-x and the python files at
> least r-- across the board.
>
> --
>  Ned Deily,
>  n...@acm.org

Of course! how did i not realise that... it wasn't the python-eggs
directory, but the directory containing the modules (namely /Library/
Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages)
- i changed the permissions, and its all sorted!

Thank you so much!!
Sam
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode and dictionaries

2010-01-17 Thread Martin v. Loewis
>>> This ought to be a bug; objects that compare equal and are hashable
>>> must have the same hash code.
>> It's not a bug. Changing the default encoding is not really supported,
>> let alone changing it to anything but latin-1, precisely for the reasons
>> you discuss.
>>
>> If you do change the default encoding, Python *will* break. This has
>> been discussed many times, but some people still think they know better.
> 
> 
> That's specific to CPython though, isn't it? Other implementations may, 
> or may not, cope with it better?

No, that's fairly inherent to the problem. Only if that other
implementation doesn't use hashing for dictionaries, the problems
might go away. However, this is fairly unlikely - in particular,
since the language spec nearly mandates that dictionaries are hash-based
(rather than relying on comparability).

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


Re: Confusing, desparate MySQLdb problems...

2010-01-17 Thread Ned Deily
In article 
<109c960c-656b-4ea7-b69f-100e30804...@m16g2000yqc.googlegroups.com>,
 stopchuckingstuff  wrote:
> On Jan 17, 5:52 pm, Ned Deily  wrote:
> > In article
> > <94e8cfd8-d299-4c23-9e9e-d3f17d4c9...@e16g2000yqc.googlegroups.com>,
> > > What I don't understand is if the path is there, why doesn't it find
> > > the module?
> > Perhaps it is just a permissions problem since Apache is probably
> > running under a different user name.  Check the owner/group and
> > permissions of the various module directories and files. Make sure the
> > directories and .so files have at least r-x and the python files at
> > least r-- across the board.
> Of course! how did i not realise that... it wasn't the python-eggs
> directory, but the directory containing the modules (namely /Library/
> Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages)
> - i changed the permissions, and its all sorted!

Yay!  Sorry, I should have thought of permissions earlier: I've been 
bitten by that more than once.  It's an important thing to keep in mind 
when encountering missing imports: always check file system permissions 
first.

-- 
 Ned Deily,
 n...@acm.org

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


MySQLdb Confusion

2010-01-17 Thread Sam

To the powers that be,

I am running Apache 2 on Mac OSX 10.6.2.

I have, after many hours, managed to install MySQLdb, however I'm not  
sure if I installed it correctly as I had to fudge it a little.


I can import and use the module fine in IDLE or in python from  
Terminal (which would suggest it installed correctly), however when I  
try and import the module in a cgi script, I get the following error  
out of cgitb:


: No module named MySQLdb
  args = ('No module named MySQLdb',)
  message = 'No module named MySQLdb'

MySQLdb installed inside a .egg file in /Library/Frameworks/ 
Python.framework/Versions/2.6/lib/python2.6/site-packages, so I  
appended this to sys.path, and got a new error:

"
Traceback (most recent call last):
  File "/Users/Sam/Sites/Spoonful/cgi-bin/view.py", line 19, in  
<;module>;

import MySQLdb
  File "build/bdist.macosx-10.3-fat/egg/MySQLdb/__init__.py", line  
19, in <;module>;
  File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 7, in  
<;module>;
  File "build/bdist.macosx-10.3-fat/egg/_mysql.py", line 4, in  
__bootstrap__
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/ 
Extras/lib/python/pkg_resources.py", line 835, in resource_filename

self, resource_name
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/ 
Extras/lib/python/pkg_resources.py", line 1304, in get_resource_filename

self._extract_resource(manager, self._eager_to_zip(name))
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/ 
Extras/lib/python/pkg_resources.py", line 1326, in _extract_resource

self.egg_name, self._parts(zip_path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/ 
Extras/lib/python/pkg_resources.py", line 915, in get_cache_path

self.extraction_error()
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/ 
Extras/lib/python/pkg_resources.py", line 881, in extraction_error

raise err
ExtractionError: Can't extract file(s) to egg cache

The following error occurred while trying to extract file(s) to the  
Python egg

cache:

  [Errno 13] Permission denied: '/Library/WebServer/.python-eggs'

The Python egg cache directory is currently set to:

  /Library/WebServer/.python-eggs

Perhaps your account does not have write access to this directory?   
You can

change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
"

I have no idea what to from there?!

Apologies for the long question, but I've read many in which people  
complained about not enough detail, so...

Thanks very much, and I hope someone can help!

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


Re: BeautifulSoup

2010-01-17 Thread Phlip

John Nagle wrote:


   It's just somebody pirating movies.  Ineptly.  Ignore.


Anyone who leaves their movies hanging out in  tags, without a daily download 
limit or a daily hashtag, deserves to be taught a lesson!


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


Re: Unicode and dictionaries

2010-01-17 Thread Ben Finney
gizli  writes:

> >>> test_dict = {u'öğe':1}
> >>> u'öğe' in test_dict.keys()
> True
> >>> 'öğe' in test_dict.keys()
> True

I would call this a bug. The two objects are different, so the latter
expression should return ‘False’.

FYI, ‘foo in bar.keys()’ is easier to spell as ‘foo in bar’.

-- 
 \   “It is wrong to think that the task of physics is to find out |
  `\ how nature *is*. Physics concerns what we can *say* about |
_o__) nature…” —Niels Bohr |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Changing Lutz's mydir from Edition 2, Learning Python

2010-01-17 Thread W. eWatson
See Subject. The code is below with a few changes I made at the bottom 
by inserting

import string
import numpy

module = raw_input("Enter module name: ")
listing(module)

I thought I'd see if I could convert this to a program instead, which 
asks the user for the module.


As prompt entry, it was meant to do this, for example:

import math
import pynum
mydir.listing(numpy)

As below, it fails with:


Is it possible to get this to work?
Enter module name: numpy
--
name:
Traceback (most recent call last):
  File 
"C:/Sandia_Meteors/Sentinel_Development/Learn_Python/mydir_pgm.py", line 
31, in 

listing(module)
  File 
"C:/Sandia_Meteors/Sentinel_Development/Learn_Python/mydir_pgm.py", line 
8, in listing

print "name:", module.__name__, "file:", module.__file__
AttributeError: 'str' object has no attribute '__name__
mydir start===
# a module that lists the namespaces of other modules

verbose = 1

def listing(module):
if verbose:
print "-"*30
print "name:", module.__name__, "file:", module.__file__
print "-"*30

count = 0
for attr in module.__dict__.keys():  # scan namespace
print "%02d) %s" % (count, attr),
if attr[0:2] == "__":
print ""  # skip __file__, etc.
else:
print getattr(module, attr)  # same as .__dict__[attr]
count = count+1

if verbose:
print "-"*30
print module.__name__, "has %d names" % count
print "-"*30

if __name__ == "__main__":
import mydir
import string
import numpy

module = raw_input("Enter module name: ")
listing(module)
#listing(mydir)  # self-test code: list myself
===end==
--
http://mail.python.org/mailman/listinfo/python-list


Re: Changing Lutz's mydir from Edition 2, Learning Python

2010-01-17 Thread Arnaud Delobelle
"W. eWatson"  writes:

> See Subject. The code is below with a few changes I made at the bottom
> by inserting
> import string
> import numpy
>
> module = raw_input("Enter module name: ")

replace this line with:

   module_name = raw_input("Enter module name: ")
   module = __import__(module_name)

> listing(module)
>

HTH

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


Re: Changing Lutz's mydir from Edition 2, Learning Python

2010-01-17 Thread Chris Rebert
On Sun, Jan 17, 2010 at 12:11 PM, W. eWatson  wrote:
> See Subject. The code is below with a few changes I made at the bottom by
> inserting
>    import string
>    import numpy
>
>    module = raw_input("Enter module name: ")
>    listing(module)

As the error says, strings have no __name__ attribute; from this, one
can infer that listing() expects a module object, not a string which
is the name of a module.

Try instead:
    module = __import__(raw_input("Enter module name: "))
    listing(module)

Cheers,
Chris
--
http://blog.rebertia.com

> I thought I'd see if I could convert this to a program instead, which asks
> the user for the module.
>
> As prompt entry, it was meant to do this, for example:
>
> import math
> import pynum
> mydir.listing(numpy)
>
> As below, it fails with:
>
>
> Is it possible to get this to work?
> Enter module name: numpy
> --
> name:
> Traceback (most recent call last):
>  File "C:/Sandia_Meteors/Sentinel_Development/Learn_Python/mydir_pgm.py",
> line 31, in 
>    listing(module)
>  File "C:/Sandia_Meteors/Sentinel_Development/Learn_Python/mydir_pgm.py",
> line 8, in listing
>    print "name:", module.__name__, "file:", module.__file__
> AttributeError: 'str' object has no attribute '__name__
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-API: Get scope in function

2010-01-17 Thread Gabriel Genellina
En Sun, 17 Jan 2010 10:23:03 -0300, moerchendiser2k3  
 escribió:



I have a small problem how to get the scope from a C-API function.
Check out this code snippet:

[code]
variable = 3

def test():
print variable #output: 3
print globals() # ... 'variable': 3, ...

test()
[/code


In my case I know there is a variable in the scope where this function
is called from, but I dont know how to get it.


Note that in this case the relevant scope is the one where the Python  
function was *defined*, not where it is *called*.



Check out:

[code]
PyObject *MyFunction_Test(PyObject* self, PyObject *args, PyObject
*keywords)
{
 ... ?
}
[/code]

Is it possible to get the dictionary of the scope where this function
is called from?


Yes, you can obtain the global variables of the current execution frame  
using PyEval_GetGlobals()


--
Gabriel Genellina

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


Re: py2exe and pydocs. Downloads?

2010-01-17 Thread Gabriel Genellina
En Sun, 17 Jan 2010 15:16:17 -0300, W. eWatson   
escribió:


I'm using Python 2.5 under windows, and IDLE. Do py2exe and pydocs come  
with the package, or do I have to download them?


py2exe has to be downloaded from www.py2exe.org
I don't know pydocs, but pydoc comes with Python

--
Gabriel Genellina

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


Re: Problems with collision response

2010-01-17 Thread Steven D'Aprano
On Sun, 17 Jan 2010 06:14:59 -0800, Joabos wrote:

> I'm doing a project, and I need to insert collision detection and
> response on it. Here's the code. What am I doing wrong?
> 
> 
>#Update all sprites, map
> self.player.update(dt)
> 
> #Collide other sprites
> collisions = rabbyt.collisions.aabb_collide_single(self.player,
> self.spriteList)
> 
> for col in collisions:
> pass

Why are you looping over the collisions but do nothing?


[...]
>if len(collisions) > 0:
> #Collide the sprite with the bounding line pass

You have turned a great chunk of code into a string with triple quotes. 
That essentially is equivalent to commenting it out: it will not be 
executed. Then you did it again to a second chunk of code.

Removing all the code that doesn't do anything, you have FIVE lines left:


self.player.update(dt)
collisions = rabbyt.collisions.aabb_collide_single(self.player,
  self.spriteList)
collisions = rabbyt.collisions.aabb_collide_single(self.player,
  self.map_manager.map_sprites())
for tile in collisions:
self.player.collide(tile)


Notice that you generate collisions between the player and the sprite, do 
absolutely nothing with it, and immediately replace it with collisions 
between the player and the map.

Since you reported that there are no collisions between the player and 
the map, you need to check these three things:


(1) does player.collide actually do anything?

(2) does map_manager.map_sprites return the map sprites you expect?

(3) does rabbyt.collisions.aabb_collide_single detect the collisions?




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


Re: Changing Lutz's mydir from Edition 2, Learning Python

2010-01-17 Thread W. eWatson

Chris Rebert wrote:

On Sun, Jan 17, 2010 at 12:11 PM, W. eWatson  wrote:

See Subject. The code is below with a few changes I made at the bottom by
inserting
   import string
   import numpy

   module = raw_input("Enter module name: ")
   listing(module)


As the error says, strings have no __name__ attribute; from this, one
can infer that listing() expects a module object, not a string which
is the name of a module.

Try instead:
module = __import__(raw_input("Enter module name: "))
listing(module)

Cheers,
Chris
--
http://blog.rebertia.com


I thought I'd see if I could convert this to a program instead, which asks
the user for the module.


...



 File "C:/Sandia_Meteors/Sentinel_Development/Learn_Python/mydir_pgm.py",
line 31, in 
   listing(module)
 File "C:/Sandia_Meteors/Sentinel_Development/Learn_Python/mydir_pgm.py",
line 8, in listing
   print "name:", module.__name__, "file:", module.__file__
AttributeError: 'str' object has no attribute '__name__

Very cool. Thanks to both of you.
--
http://mail.python.org/mailman/listinfo/python-list


IDLE Namespace Toolbox? Windows.

2010-01-17 Thread W. eWatson
This is a follow up to my post "Changing Lutz's mydir.  It would seem 
there should be some sort of toolbox that allows one to do things like 
mydir, and perhaps a lot more. Maybe something like it exists in Linux. 
I'm a Windows user. I've found it a bit aggravating that using dir and 
help, for example, that the output just rolls on off the screen and I 
have to play around with the shell scroll bars to find what I'm looking 
for. A few simple changes to mydir should change that, but I would hope 
or think maybe there are even more tools to generally help.

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


enhancing 'list'

2010-01-17 Thread samwyse
Consider this a wish list.  I know I'm unlikely to get any of these in
time for for my birthday, but still I felt the need to toss it out and
see what happens.

Lately, I've slinging around a lot of lists, and there are some simple
things I'd like to do that just aren't there.

s.count(x[, cmp[, key]])
- return number of i‘s for which s[i] == x.  'cmp' specifies a custom
comparison function of two arguments, as in '.sort'.  'key' specifies
a custom key extraction function of one argument.
s.index(x[, i[, j[, cmp[, key)
- return smallest k such that s[k] == x and i <= k < j.  'cmp' and
'key' are as above.
s.rindex(x[, i[, j[, cmp[, key)
- return largest k such that s[k] == x and i <= k < j.  'cmp' and
'key' are as above.

There are two overlapping proposals here.  One is to add the .rindex
method, which strings already have.  The other is to extend the
optional arguments of .sort to all other methods that test for item
equality.

One last thing, the Python 2.6.2 spec says .count and .index only
apply to mutable sequence types.  I see no reason why they
(and .rindex) couldn't also apply to immutable sequences (tuples, in
particular).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe and pydocs. Downloads?

2010-01-17 Thread W. eWatson

Gabriel Genellina wrote:
En Sun, 17 Jan 2010 15:16:17 -0300, W. eWatson  
escribió:


I'm using Python 2.5 under windows, and IDLE. Do py2exe and pydocs 
come with the package, or do I have to download them?


py2exe has to be downloaded from www.py2exe.org
I don't know pydocs, but pydoc comes with Python

Thanks. I'll look at the link. Actually, I was close 
, but no banana (cigar).  Yep, 
right on your link, download from source forge.


According to Lutz's 4th edition (reading from Amazon), Pydoc is shipped 
with Python. I found this earlier in the Python Help under Global Index 
for modules.

==
The pydoc module automatically generates documentation from Python 
modules. The documentation can be presented as pages of text on the 
console, served to a Web browser, or saved to HTML files.


The built-in function help() invokes the online help system in the 
interactive interpreter, which uses pydoc to generate its documentation 
as text on the console. The same text documentation can also be viewed 
from outside the Python interpreter by running pydoc as a script at the 
operating system's command prompt. For example, running



pydoc sys

at a shell prompt
=
I get:
>>> import pydoc
>>> pydoc sys
SyntaxError: invalid syntax
>>>
The book says Help uses it, and there's some sort of html version, but 
I'm missing something here. Command line, Linux shell?

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


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread Chris Rebert
On Sun, Jan 17, 2010 at 2:22 PM, W. eWatson  wrote:
> This is a follow up to my post "Changing Lutz's mydir.  It would seem there
> should be some sort of toolbox that allows one to do things like mydir, and
> perhaps a lot more. Maybe something like it exists in Linux.

Indeed; on *nix, when in the terminal, python invokes the pager[1]
(which splits text into pages and lets you move between them, hence
the name) for documentation that is longer than one screen. Apparently
there are pagers available for Windows, but I don't know whether
Python tries to use them or not.

Perhaps try installing one, setting the PAGER environment variable,
and see what happens when run python from the terminal and invoke
help()? And/or file a bug if Python indeed doesn't try to invoke a
pager on Windows.

Of course, this won't do anything about IDLE's shell, which isn't a
proper terminal.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


basic Class in Python

2010-01-17 Thread BarryJOgorman
Working through Lutz's 'Learning Python'

Trying to run the following code (from file person.py - see below):

The file is held in Python31.

at the Python31 prompt am entering ''person.py'

Getting the following error:
Traceback (most recent call last)
File "C:python31\person.py", line 9, in (module)
bob=Person('Bob Smith', job='barman', pay =34000)
TypeError: object._new_() takes no parameters




#Add incremental self test code

class Person:
def _init_(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay

bob = Person('Bob Smith', job='barman', pay = 34000)
sue = Person('Sue Jones', job='dev', pay=10)
print(bob.name, bob.pay)
print(sue.name, sue.pay)

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


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread Chris Rebert
On Sun, Jan 17, 2010 at 3:09 PM, Chris Rebert  wrote:
> On Sun, Jan 17, 2010 at 2:22 PM, W. eWatson  wrote:
>> This is a follow up to my post "Changing Lutz's mydir.  It would seem there
>> should be some sort of toolbox that allows one to do things like mydir, and
>> perhaps a lot more. Maybe something like it exists in Linux.
>
> Indeed; on *nix, when in the terminal, python invokes the pager[1]

[1]: http://en.wikipedia.org/wiki/Terminal_pager

(postscript got clipped off accidentally)
- Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: basic Class in Python

2010-01-17 Thread John Bokma
BarryJOgorman  writes:

> class Person:
> def _init_(self, name, job=None, pay=0):

  def __init__(self, name, job=None, pay=0):

Note 2x _ before and after init.

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread John Bokma
"W. eWatson"  writes:

> This is a follow up to my post "Changing Lutz's mydir.  It would seem
> there should be some sort of toolbox that allows one to do things like
> mydir, and perhaps a lot more. Maybe something like it exists in
> Linux. I'm a Windows user. I've found it a bit aggravating that using
> dir and help, for example, that the output just rolls on off the
> screen and I have to play around with the shell scroll bars to find
> what I'm looking for. A few simple changes to mydir should change
> that, but I would hope or think maybe there are even more tools to
> generally help.

on the command prompt:

cmd | more

works 

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: basic Class in Python

2010-01-17 Thread Peter Otten
BarryJOgorman wrote:

> Working through Lutz's 'Learning Python'
> 
> Trying to run the following code (from file person.py - see below):
> 
> The file is held in Python31.
> 
> at the Python31 prompt am entering ''person.py'
> 
> Getting the following error:
> Traceback (most recent call last)
> File "C:python31\person.py", line 9, in (module)
> bob=Person('Bob Smith', job='barman', pay =34000)
> TypeError: object._new_() takes no parameters

In the future, please cut and paste the traceback -- don't retype. You may 
introduce errors that obscure the actual problem.

> #Add incremental self test code
> 
> class Person:
> def _init_(self, name, job=None, pay=0):

__init__() like all "special" method needs two leading and two trailing 
underscores, not one.

> self.name = name
> self.job = job
> self.pay = pay
> 
> bob = Person('Bob Smith', job='barman', pay = 34000)
> sue = Person('Sue Jones', job='dev', pay=10)
> print(bob.name, bob.pay)
> print(sue.name, sue.pay)

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


Re: basic Class in Python

2010-01-17 Thread Wolodja Wentland
On Sun, Jan 17, 2010 at 15:05 -0800, BarryJOgorman wrote:
 [...]
> class Person:
> def _init_(self, name, job=None, pay=0):
  ^^ --> __init__(self, ...

It's __init__() not _init_()!

Have fun learning Python!

-- 
  .''`. Wolodja Wentland 
 : :'  :
 `. `'` 4096R/CAF14EFC 
   `-   081C B7CD FF04 2BA9 94EA  36B2 8B7F 7D30 CAF1 4EFC


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


Re: basic Class in Python

2010-01-17 Thread BarryJOgorman
On Jan 17, 11:09 pm, John Bokma  wrote:
> BarryJOgorman  writes:
> > class Person:
> >     def _init_(self, name, job=None, pay=0):
>
>       def __init__(self, name, job=None, pay=0):
>
> Note 2x _ before and after init.
>
> --
> John Bokma                                                               j3b
>
> Hacking & Hiking in Mexico -  http://johnbokma.com/http://castleamber.com/- 
> Perl & Python Development

Many thanks - onward and upward!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: r"string" vs R"string

2010-01-17 Thread Steven D'Aprano
On Sun, 17 Jan 2010 11:13:48 -0500, Roy Smith wrote:

> In article ,
>  "Colin W."  wrote:
> 
>> On 17-Jan-10 02:16 AM, Terry Reedy wrote:
>> > On 1/17/2010 1:55 AM, Brendan Miller wrote:
>> >> Is there any difference whatsoever between a raw string beginning
>> >> with the captical R or one with the lower case r e.g. r"string" vs
>> >> R"string"?
>> >
>> > No. Nor is there and difference between the strings created with raw
>> > literals and cooked literals.
>> >
>> >
>> "cooked" literal  ??
> 
> I've never seen it referred to this way in the Python literature, but
> "cooked" is a well-known term meaning, "not raw".  The usage goes back
> decades.

I think the use of "cooked" meaning "not raw" goes back a little bit more 
than decades. The verb "to cook" dates from the late 14th century, and 
the adjective form "cooked" would follow soon after. The use of "cooked" 
to mean manipulated (as in "cooking the books") comes from the 1630s. 
Extending it to strings (as in raw versus cooked strings) is an obvious 
extension.




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


Re: basic Class in Python

2010-01-17 Thread Wolfgang Rohdewald
On Monday 18 January 2010, BarryJOgorman wrote:
> TypeError: object._new_() takes no parameters

> def _init_(self, name, job=None, pay=0):

__init__ needs two underscores left and right


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


Re: PyQT 4.6.2 question about radiobuttons

2010-01-17 Thread woooee
QT uses "toggled".  I do not use QT much but it would be something
like
self.radioButton_one.setCheckable(True)
QtCore.QObject.connect(self.radioButton_one, QtCore.SIGNAL("toggled
()"),self.button_one_function)

If this doesn't work, you can probably find more with a Google for
"toggled".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to duplicate array entries

2010-01-17 Thread Munir
On Jan 11, 12:56 am, Munir  wrote:
> > I have an array  x=[1,2,3]
>
> > Is there an operator which I can use to get the result
> > [1,1,1,2,2,2,3,3,3] ?
>
> > I tried x*3, which resulted in [1,2,3,1,2,3,1,2,3]
>
> Have you tried:
>
> y = x*3
> y.sort()
>
> Munir

A single line version of this:

sorted(x*3)

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


How to install local module other than in "site-packages"?

2010-01-17 Thread Jive Dadson
   (My apologies if this question shows up twice.  I posted it quite a 
while ago, and it's yet to show up.)


   This is no doubt a beginner's question, but I've searched for the 
answer for quite a while, to no avail.  I'm running Python 2.6 under 
Windows XP.


   How do I install a module that I wrote, without putting it in the 
site-packages directory for a specific release?  I have stuff that, to 
the best of my knowledge and belief, ought to work under any release.  I 
do not want to have multiple copies of it.  When I edit one of the 
modules, I want it to "take" for every release.  Is that clear?  Hope so.

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


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread W. eWatson

John Bokma wrote:

"W. eWatson"  writes:


This is a follow up to my post "Changing Lutz's mydir.  It would seem
there should be some sort of toolbox that allows one to do things like
mydir, and perhaps a lot more. Maybe something like it exists in
Linux. I'm a Windows user. I've found it a bit aggravating that using
dir and help, for example, that the output just rolls on off the
screen and I have to play around with the shell scroll bars to find
what I'm looking for. A few simple changes to mydir should change
that, but I would hope or think maybe there are even more tools to
generally help.


on the command prompt:

cmd | more

works 


Apparently, not in IDLE under Win.
>>> dir() | more
Traceback (most recent call last):
  File "", line 1, in 
dir() | more
NameError: name 'more' is not defined
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Diez B. Roggisch

Am 18.01.10 01:07, schrieb Jive Dadson:

  (My apologies if this question shows up twice.  I posted it quite a
while ago, and it's yet to show up.)

This is no doubt a beginner's question, but I've searched for the answer
for quite a while, to no avail. I'm running Python 2.6 under Windows XP.

How do I install a module that I wrote, without putting it in the
site-packages directory for a specific release? I have stuff that, to
the best of my knowledge and belief, ought to work under any release. I
do not want to have multiple copies of it. When I edit one of the
modules, I want it to "take" for every release. Is that clear? Hope so.


Setting the PYTHONPATH environment variable should work.

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


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread Chris Rebert
On Sun, Jan 17, 2010 at 4:11 PM, W. eWatson  wrote:
> John Bokma wrote:
>> "W. eWatson"  writes:
>>
>>> This is a follow up to my post "Changing Lutz's mydir.  It would seem
>>> there should be some sort of toolbox that allows one to do things like
>>> mydir, and perhaps a lot more. Maybe something like it exists in
>>> Linux. I'm a Windows user. I've found it a bit aggravating that using
>>> dir and help, for example, that the output just rolls on off the
>>> screen and I have to play around with the shell scroll bars to find
>>> what I'm looking for. A few simple changes to mydir should change
>>> that, but I would hope or think maybe there are even more tools to
>>> generally help.
>>
>> on the command prompt:
>>
>> cmd | more
>>
>> works
>
> Apparently, not in IDLE under Win.
 dir() | more
> Traceback (most recent call last):
>  File "", line 1, in 
>    dir() | more
> NameError: name 'more' is not defined

Er, that's supposed to be run in the terminal, not in IDLE. Presumably
you'd then run python.exe from the same terminal after issuing that
command.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Jive Dadson

Diez B. Roggisch wrote:

Am 18.01.10 01:07, schrieb Jive Dadson:

  (My apologies if this question shows up twice.  I posted it quite a
while ago, and it's yet to show up.)

This is no doubt a beginner's question, but I've searched for the answer
for quite a while, to no avail. I'm running Python 2.6 under Windows XP.

How do I install a module that I wrote, without putting it in the
site-packages directory for a specific release? I have stuff that, to
the best of my knowledge and belief, ought to work under any release. I
do not want to have multiple copies of it. When I edit one of the
modules, I want it to "take" for every release. Is that clear? Hope so.


Setting the PYTHONPATH environment variable should work.

Diez


I was trying that just now.  So far, no joy.  Can you type up a DUMMIES 
version?


There was no environment variable PYTHONPATH.  I added one to my "User 
Variables."  It's still not finding anything.  And yes, I closed and 
re-opened my Python shell before I tested it.

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


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Ben Finney
Jive Dadson  writes:

>How do I install a module that I wrote, without putting it in the
> site-packages directory for a specific release?  I have stuff that, to
> the best of my knowledge and belief, ought to work under any release.

Nevertheless, the compiled byte-code version will be specific to the
Python version that compiled it. You need to install the module to a
version-specific directory for that reason at least.

> I do not want to have multiple copies of it.  When I edit one of the
> modules, I want it to "take" for every release.  Is that clear?  Hope
> so.

You'll need (I'd love to be corrected on this) to come up with a
deployment discipline: a build process that deploys the module from its
(single, canonical) source location to the appropriate locations when
you decide to deploy it.

-- 
 \  “It is well to remember that the entire universe, with one |
  `\   trifling exception, is composed of others.” —John Andrew Holmes |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Diez B. Roggisch

Am 18.01.10 01:33, schrieb Jive Dadson:

Diez B. Roggisch wrote:

Am 18.01.10 01:07, schrieb Jive Dadson:

(My apologies if this question shows up twice. I posted it quite a
while ago, and it's yet to show up.)

This is no doubt a beginner's question, but I've searched for the answer
for quite a while, to no avail. I'm running Python 2.6 under Windows XP.

How do I install a module that I wrote, without putting it in the
site-packages directory for a specific release? I have stuff that, to
the best of my knowledge and belief, ought to work under any release. I
do not want to have multiple copies of it. When I edit one of the
modules, I want it to "take" for every release. Is that clear? Hope so.


Setting the PYTHONPATH environment variable should work.

Diez


I was trying that just now. So far, no joy. Can you type up a DUMMIES
version?

There was no environment variable PYTHONPATH. I added one to my "User
Variables." It's still not finding anything. And yes, I closed and
re-opened my Python shell before I tested it.


Did "echo %PYTHONPATH%" yield anything? Or is it part of

>>> import sys
>>> sys.path


?

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


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread MRAB

W. eWatson wrote:

John Bokma wrote:

"W. eWatson"  writes:


This is a follow up to my post "Changing Lutz's mydir.  It would seem
there should be some sort of toolbox that allows one to do things like
mydir, and perhaps a lot more. Maybe something like it exists in
Linux. I'm a Windows user. I've found it a bit aggravating that using
dir and help, for example, that the output just rolls on off the
screen and I have to play around with the shell scroll bars to find
what I'm looking for. A few simple changes to mydir should change
that, but I would hope or think maybe there are even more tools to
generally help.


on the command prompt:

cmd | more

works

Apparently, not in IDLE under Win.
 >>> dir() | more
Traceback (most recent call last):
  File "", line 1, in 
dir() | more
NameError: name 'more' is not defined


He said "command prompt", not Python prompt.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Inheriting methods but over-riding docstrings

2010-01-17 Thread Alf P. Steinbach

* Gabriel Genellina:
En Sat, 16 Jan 2010 14:55:11 -0300, Steven D'Aprano 
 escribió:



I have a series of subclasses that inherit methods from a base class, but
I'd like them to have their own individual docstrings. The obvious
solution (other than copy-and-paste) is this:


class Base(object):
colour = "Blue"
def parrot(self):
"""docstring for Base"""
return "Norwegian %s" % self.colour


class SubClass(Base):
colour = "Red"
def parrot(self):
"""docstring for Subclass"""
return super(Subclass, self).parrot()


but that adds an awful lot of boilerplate to my subclasses. Are there any
other good solutions to this problem?


Methods don't have docstrings; functions do. So one has to "clone" the 
function to set a new docstring.



def copy_function(fn, docstring):
fn = getattr(fn, "im_func", fn) # accomodate unbound methods in 2.x
function_type = type(lambda:0)
newfn = function_type(fn.__code__, fn.__globals__, fn.__name__, 
fn.__defaults__, fn.__closure__)

newfn.__doc__ = docstring
return newfn

class Base(object):
colour = "Blue"
def parrot(self):
"""docstring for Base"""
return "Norwegian %s" % self.colour

class SubClass(Base):
colour = "Red"
parrot = copy_function(Base.parrot, "docstring for Subclass")



py> x = Base()
py> print(x.parrot())
Norwegian Blue
py> print x.parrot.__doc__
docstring for Base
py> y = SubClass()
py> print(y.parrot())
Norwegian Red
py> print y.parrot.__doc__
docstring for Subclass


Since Steven says he has a series of subclasses, perhaps wrapping those function 
calls in a decorator?




def copy_function(fn, docstring):
# Gabriel Genellina's copy_function
fn = getattr(fn, "im_func", fn) # accomodate unbound methods in 2.x
function_type = type(lambda:0)
newfn = function_type(fn.__code__, fn.__globals__, fn.__name__, 
fn.__defaults__, fn.__closure__)

newfn.__doc__ = docstring
return newfn

def docstrings(**kwargs):
def with_altered_docstrings(cls, kwargs=kwargs):
for kwarg in kwargs.items():
func_name = kwarg[0]
docstring = kwarg[1]
original_func = getattr(cls, func_name)
new_func = copy_function(getattr(cls, func_name), docstring)
setattr(cls, func_name, new_func)
return cls
return with_altered_docstrings


class Base(object):
colour = "Blue"
def parrot(self):
"""docstring for Base"""
return "Norwegian %s" % self.colour

@docstrings( parrot = "docstring for Subclass" )
class SubClass(Base):
colour = "Red"



This is my first decorator ever so it might be Incorect and nonIdiomatic...

Also, neither 'copy_function' nor 'docstrings' seem to work with slots.


Steven: on a personal note, earlier when I saw you (I think it was you) using 
the "Norwegian Parrot" example I thought it referred to me because that was the 
only sense I could make of it, it followed right after some discussion we had. 
Thus my impression of you or or responses in this group was colored by a false 
interpretation. But, checking, which is often a good idea!, and *which I should 
have done then*, as far as I can see the term was first used in this group in 
April 2001, http://groups.google.com/group/comp.lang.python/browse_thread/thread/12a125ceddd401e2/c021547a1dc14a41>.


It's still a mystery to me what it refers to, though... :-)


Cheers & hth.,

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


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Jive Dadson

Ben Finney wrote:

Jive Dadson  writes:


   How do I install a module that I wrote, without putting it in the
site-packages directory for a specific release?  I have stuff that, to
the best of my knowledge and belief, ought to work under any release.


Nevertheless, the compiled byte-code version will be specific to the
Python version that compiled it. You need to install the module to a
version-specific directory for that reason at least.


I do not want to have multiple copies of it.  When I edit one of the
modules, I want it to "take" for every release.  Is that clear?  Hope
so.


You'll need (I'd love to be corrected on this) to come up with a
deployment discipline: a build process that deploys the module from its
(single, canonical) source location to the appropriate locations when
you decide to deploy it.



Thanks for your help.

Well that majorly sucks.  I was hoping the "foo.pth" thing would save 
me. There ought to be a way.  But even if they did invent one, it 
wouldn't help  me, because I am stuck at version 2.6.  Don't even get me 
started on that.  I really like Python, but the way every release breaks 
everything is a royal pain. The biggest problem is C-extensions of stuff 
that does not come with the Python release. I've complained about it 
before, but it didn't help.  I guess I got myself started on that. :-)


Since I cannot imagine facing the challenge of going to 3.0, I guess it 
doesn't matter if I have my stuff in a folder that's specific to 2.6.

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


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Jive Dadson

Diez B. Roggisch wrote:


Did "echo %PYTHONPATH%" yield anything? Or is it part of

 >>> import sys
 >>> sys.path


?

Diez


Yes and no in that order.  Never mind.  Ben Fenny talked me out of it 
anyway.  Gr.

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


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Jive Dadson

Diez B. Roggisch wrote:


Did "echo %PYTHONPATH%" yield anything? Or is it part of

 >>> import sys
 >>> sys.path


?

Diez


Update: It's working now.  I guess I hadn't reloaded something that I 
need to.  Thanks for your help.


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


Re: A simple-to-use sound file writer

2010-01-17 Thread TimmyGee
On Jan 15, 3:43 pm, Steve Holden  wrote:
> Alf P. Steinbach wrote:
>
> [...]> Perhaps you'd also admit to being wrong, and retract your innuoendo 
> etc.?
>
> Disregarding any matters of right or wrong (for this post, at least), I
> herebe retract anything I have said about you that you consider
> innuendo. Feel free to remind me what that was.
>
> regards
>  Steve
> --
> Steve Holden           +1 571 484 6266   +1 800 494 3119
> PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
> Holden Web LLC                http://www.holdenweb.com/
> UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

Now now children...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Jive Dadson

Okay, I might go this route anyway.  It's almost working.

I created a directory (folder in MS-speak) named Modules, and put its 
path in the PYTHONPATH env variable.


I can now put a file foo.py into the directory Modules, and it will load 
foo.py when I say "import foo."


Now I put a folder into Modules called myModule and in that I put 
bar.py.  It does not find bar.py when I say either import bar or import 
myModule.bar.  I tried the myModule.pth trick but it didn't help.  Maybe 
I did it wrong.

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


Arrrrgh! Another module broken

2010-01-17 Thread Jive Dadson
I just found another module that broke when I went to 2.6.  Gnuplot. 
Apparently one of its routines has a parameter named "with."  That used 
to be okay, and now it's not.


Once I get everything to work under 2.6, I am using it forever or until 
new releases no longer break working code, whichever comes first.

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


Re: Arrrrgh! Another module broken

2010-01-17 Thread Chris Rebert
On Sun, Jan 17, 2010 at 5:25 PM, Jive Dadson  wrote:
> I just found another module that broke when I went to 2.6.  Gnuplot.
> Apparently one of its routines has a parameter named "with."  That used to
> be okay, and now it's not.
>
> Once I get everything to work under 2.6, I am using it forever or until new
> releases no longer break working code, whichever comes first.

The latter ain't gonna happen. Going 2.x --> 3.x *will* break code,
and no future 3.x version will change that fact.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to install local module other than in "site-packages"?

2010-01-17 Thread Benjamin Kaplan
On Sun, Jan 17, 2010 at 8:09 PM, Jive Dadson  wrote:
> Okay, I might go this route anyway.  It's almost working.
>
> I created a directory (folder in MS-speak) named Modules, and put its path
> in the PYTHONPATH env variable.
>
> I can now put a file foo.py into the directory Modules, and it will load
> foo.py when I say "import foo."
>
> Now I put a folder into Modules called myModule and in that I put bar.py.
>  It does not find bar.py when I say either import bar or import
> myModule.bar.  I tried the myModule.pth trick but it didn't help.  Maybe I
> did it wrong.

Just put a blank file called __init__.py inside myModule

In Python, packages have to have an __init__.py file in them, even if
it's empty. Whatever you put in __init__.py gets imported when you
"import myModule".

http://docs.python.org/tutorial/modules.html#packages

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


Re: Inheriting methods but over-riding docstrings

2010-01-17 Thread Steve Holden
Gabriel Genellina wrote:
> En Sat, 16 Jan 2010 14:55:11 -0300, Steven D'Aprano
>  escribió:
> 
>> I have a series of subclasses that inherit methods from a base class, but
>> I'd like them to have their own individual docstrings. The obvious
>> solution (other than copy-and-paste) is this:
>>
>>
>> class Base(object):
>> colour = "Blue"
>> def parrot(self):
>> """docstring for Base"""
>> return "Norwegian %s" % self.colour
>>
>>
>> class SubClass(Base):
>> colour = "Red"
>> def parrot(self):
>> """docstring for Subclass"""
>> return super(Subclass, self).parrot()
>>
>>
>> but that adds an awful lot of boilerplate to my subclasses. Are there any
>> other good solutions to this problem?
> 
> Methods don't have docstrings; functions do. So one has to "clone" the
> function to set a new docstring.
> 
On behalf of all methods I would like to say "We demand the right to
docstrings".

>>> print abs.__doc__
abs(number) -> number

Return the absolute value of the argument.
>>>

Perhaps I am misunderstanding "don't have docstrings". This code:

>>> class TheHellOfIt:
... """Classes, of course, as first-class citizens and have
docstrings."""
... def method(self):
... """Discrimination against methods, I call it."""
... pass
...
>>> print TheHellOfIt.method.__doc__
Discrimination against methods, I call it.
>>> import sys
>>> help(sys.modules["__main__"])

Gives:

Help on built-in module __main__:

NAME
__main__

FILE
(built-in)

CLASSES
TheHellOfIt

class TheHellOfIt
 |  Classes, of course, as first-class citizens and have docstrings.
 |
 |  Methods defined here:
 |
 |  method(self)
 |  Discrimination against methods, I call it.

So, are the demands of the methods reasonable, or do they already have
what they are so loudly demanding?

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Arrrrgh! Another module broken

2010-01-17 Thread Matt Newville
On Jan 17, 7:25 pm, Jive Dadson  wrote:
> I just found another module that broke when I went to 2.6. > Gnuplot.  
> Apparently one of its routines has a parameter
> named "with."  That used to be okay, and now it's not.

This was fixed in version 1.8 of Gnuplot.py

> Once I get everything to work under 2.6, I am using it
> forever or until new releases no longer break working
> code, whichever comes first.

Hey, good luck with that forever plan.

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


Re: Inheriting methods but over-riding docstrings

2010-01-17 Thread J
On Sun, Jan 17, 2010 at 19:45, Alf P. Steinbach  wrote:
> Steven: on a personal note, earlier when I saw you (I think it was you)
> using the "Norwegian Parrot" example I thought it referred to me because
> that was the only sense I could make of it, it followed right after some
> discussion we had. Thus my impression of you or or responses in this group
> was colored by a false interpretation. But, checking, which is often a good
> idea!, and *which I should have done then*, as far as I can see the term was
> first used in this group in April 2001,  http://groups.google.com/group/comp.lang.python/browse_thread/thread/12a125ceddd401e2/c021547a1dc14a41>.
>
> It's still a mystery to me what it refers to, though... :-)

I can't really comment on decorators and subclassing yet (still a
newb) but I am finding this discussion very informative... and lo
there IS something I can comment on.

The Norwegian Blue is a remarkable bird.  Beautiful plumage!  Though
they do like to lie around on their backs a bit, and seem to spend
their time either resting, or pining for the fjords.  Yes lovely
plumage, indeed!

Google the remarkable Norwegian Blue Parrot and you'll fall in love as
I did so long ago :)

-- 

Marie von Ebner-Eschenbach  - "Even a stopped clock is right twice a
day." - 
http://www.brainyquote.com/quotes/authors/m/marie_von_ebnereschenbac.html
-- 
http://mail.python.org/mailman/listinfo/python-list


The answer

2010-01-17 Thread Jive Dadson
Okay, with your help I've figured it out.  Instructions are below, but 
read the caveat by Ben Fenny in this thread.  All this stuff is good for 
one default version of Python only.  The PYTHONPATH described below, for 
example, cannot specify a version number.  Yes, that's a pain in the 
butt, but there's no way around it.  If you switch versions, you may 
have to delete all the .pyc files that will show up in the module 
folders.  Python ought to check them to see if they are valid, but I do 
not know if it does so.


These instructions are for MS Windows.

1) Create your modules folder. Let's say it's named "Modules."  The 
documentation calls it a "package."


2) In an explorer window or on the desktop, right click on My Computer, 
and select Properties.


3) Select the Advanced tab, and click on Environment Variables near the 
bottom.


4) Look for an environment variable named PYTHONPATH.

   a) If you do not find one, create one using the New button(s). I 
don't know if it has to be in User Variables or System Variables.  To 
save time experimenting, I just put one in both. For the value, put the 
full path of the folder Modules.


   b) If there's already a PYTHONPATH,  Edit it, adding a semi-colon 
and the full path of folder Module to the end.


5) Put your module folders into the folder Module.

6) (Here's a really arcane bit.) Into each module folder, put a file 
named __init__.py.  It will be executed when you load the module.  It 
can be empty, but it has to be there or else the module folder will be 
ignored.

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


Re: Arrrrgh! Another module broken

2010-01-17 Thread Jive Dadson

Matt Newville wrote:

Hey, good luck with that forever plan.

--Matt


Yeah, I know.  I'm just glad I don't have to get new executables and 
dll's from all my software vendors every Tuesday when the MS Window XP 
updates come out.


2.6 FOREVER!
--
http://mail.python.org/mailman/listinfo/python-list


The answer

2010-01-17 Thread Jive Dadson
Okay, with your help I've figured it out.  Instructions are below, but 
read the caveat by Ben Fenny in this thread.  All this stuff is good for 
one default version of Python only.  The PYTHONPATH described below, for 
example, cannot specify a version number.  Yes, that's a pain in the 
butt, but there's no way around it.  If you switch versions, you may 
have to delete all the .pyc files that will show up in the module 
folders.  Python ought to check them to see if they are valid, but I do 
not know if it does so.


These instructions are for MS Windows.

1) Create your modules folder. Let's say it's named "Modules."  The 
documentation calls it a "package."


2) In an explorer window or on the desktop, right click on My Computer, 
and select Properties.


3) Select the Advanced tab, and click on Environment Variables near the 
bottom.


4) Look for an environment variable named PYTHONPATH.

   a) If you do not find one, create one using the New button(s). I 
don't know if it has to be in User Variables or System Variables.  To 
save time experimenting, I just put one in both. For the value, put the 
full path of the folder Modules.


   b) If there's already a PYTHONPATH,  Edit it, adding a semi-colon 
and the full path of folder Module to the end.


5) Put your module folders into the folder Module.

6) (Here's a really arcane bit.) Into each module folder, put a file 
named __init__.py.  It will be executed when you load the module.  It 
can be empty, but it has to be there or else the module folder will be 
ignored.

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


Re: Arrrrgh! Another module broken

2010-01-17 Thread Jive Dadson

Matt Newville wrote:

On Jan 17, 7:25 pm, Jive Dadson  wrote:

I just found another module that broke when I went to 2.6. > Gnuplot.  
Apparently one of its routines has a parameter
named "with."  That used to be okay, and now it's not.


This was fixed in version 1.8 of Gnuplot.py


Once I get everything to work under 2.6, I am using it
forever or until new releases no longer break working
code, whichever comes first.


Hey, good luck with that forever plan.

--Matt



Thanks. I also had to install a new version of numpy.  Have I kvetched 
enough about have to track down new versions of all my third party stuff 
every time I up-rev Python?  I guess so.  :-)


2.6 FOREVER!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Arrrrgh! Another module broken

2010-01-17 Thread Stephen Hansen
On Sun, Jan 17, 2010 at 5:25 PM, Jive Dadson  wrote:

> I just found another module that broke when I went to 2.6.  Gnuplot.
> Apparently one of its routines has a parameter named "with."  That used to
> be okay, and now it's not.
>
> Once I get everything to work under 2.6, I am using it forever or until new
> releases no longer break working code, whichever comes first.
>

Yeaaah, this is slightly crazy as an expectation.

Python is -very- conservative with adding new keywords, but we do it
sometimes. Yeah, 'with' became a keyword in 2.6... which we've been saying
it would for 4 or so years, and Python 2.5 was nice enough to give a
deprecation warning for if you tried to use it.

Major Python releases-- 2.x to 2.6-- are ... major. They aren't like little
patches which MS releases for WinXP on tuesdays, that comparison doesn't
even vaguely make sense. Its more like Win2k to WinXP to Vista to Win7. And
each of those, y'know, broke quite a few programs before the developers
fixed them up.

Its impossible to evolve a product with 100% backwards compatibility. Python
attempts to be as backwards compatible as possible, but depending on how
long often you do upgrades (2.4->2.5->2.6 is much less painful then 2.3->2.6
for example) and how much you know what you're doing (what packages are and
how they work for instance), it will vary how much effort it takes for you
to support a new version. Maybe none: I'm upgrading our core system at work
with a total of about 400k lines of python code including third-party
libraries and some autogenerated stuff, and about 110k of just
people-written code, from Python 2.4 to 2.6... and it all just works so
far.

Yeah... if you use a lot of third-party libraries, you have to wait until
they upgrade before you can, especially if they're C libraries. Its really,
really, really not that big of a deal. Major releases happen only every
couple of years.

But feel free to stay on 2.6. Its a perfectly nice platform.

I'm looking forward to 2.7, myself.

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


Re: Inheriting methods but over-riding docstrings

2010-01-17 Thread Stephen Hansen
On Sun, Jan 17, 2010 at 4:45 PM, Alf P. Steinbach  wrote:

> Steven: on a personal note, earlier when I saw you (I think it was you)
> using the "Norwegian Parrot" example I thought it referred to me because
> that was the only sense I could make of it, it followed right after some
> discussion we had. Thus my impression of you or or responses in this group
> was colored by a false interpretation. But, checking, which is often a good
> idea!, and *which I should have done then*, as far as I can see the term was
> first used in this group in April 2001,  http://groups.google.com/group/comp.lang.python/browse_thread/thread/12a125ceddd401e2/c021547a1dc14a41
> >.
>

Parrot was a fairly elaborate april fools joke between the Python and Perl
developers; the two languages were going to merge! Somehow that joke
actually turned into a real generic VM, though I'm not sure if its used for
anything but Perl6 even if it has such capability.

That post is referring to that, with someone then referencing the Dead
Parrot sketch by Monty Python-- http://en.wikipedia.org/wiki/Dead_Parrot

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


Re: py2exe and pydocs. Downloads?

2010-01-17 Thread Gabriel Genellina
En Sun, 17 Jan 2010 19:43:25 -0300, W. eWatson   
escribió:


According to Lutz's 4th edition (reading from Amazon), Pydoc is shipped  
with Python. I found this earlier in the Python Help under Global Index  
for modules.

==
The pydoc module automatically generates documentation from Python  
modules. The documentation can be presented as pages of text on the  
console, served to a Web browser, or saved to HTML files.


The built-in function help() invokes the online help system in the  
interactive interpreter, which uses pydoc to generate its documentation  
as text on the console. The same text documentation can also be viewed  
from outside the Python interpreter by running pydoc as a script at the  
operating system's command prompt. For example, running



pydoc sys

at a shell prompt
=
I get:
 >>> import pydoc
 >>> pydoc sys
SyntaxError: invalid syntax
 >>>
The book says Help uses it, and there's some sort of html version, but  
I'm missing something here. Command line, Linux shell?


From *inside* the Python interpreter:

py> import sys
py> help(sys)
Help on built-in module sys:

NAME
sys

FILE
(built-in)
[...lots of info...]

py> help("sys")
Help on built-in module sys:
[...same info...]


From the system command line (shell, command prompt, DOS box...), assuming  
you're using 2.5 or later:


c:\temp>python -m pydoc sys
Help on built-in module sys:
[...same info...]


C:\TEMP>python -m pydoc
pydoc - the Python documentation tool

pydoc.py  ...
Show text documentation on something.   may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package.  If  contains a '\', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.

pydoc.py -k 
Search for a keyword in the synopsis lines of all available modules.

pydoc.py -p 
Start an HTTP server on the given port on the local machine.

pydoc.py -g
Pop up a graphical interface for finding and serving documentation.

pydoc.py -w  ...
Write out the HTML documentation for a module to a file in the current
directory.  If  contains a '\', it is treated as a filename; if
it names a directory, documentation is written for all the contents.


Try the -g option; it lets you search for the relevant documentation and  
show it on your favorite web browser (locally).


Depending on how you installed Python, you may find a 'pydoc' or  
'pydocgui' script somewhere in your Python directory.


--
Gabriel Genellina

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


Re: Is python not good enough?

2010-01-17 Thread alex23
Blog  wrote:
> Have you not heard about the "Unladen Swallow" project from google?
> There's a new PEP coming up which will propose google's codebase to be
> merged with Py3k, resulting in superior performance.

This kind of worries me for a number of reasons:
 * unladen is _way_ too immature and unproven a project to replace the
current implementation,
 * Google themselves have stressed they're only concerned with
improvements that benefit their use cases, such that
 * other benchmarks appear to perform _worse_ under unladen, and
 * has the project even posted substantive enough gains to warrant
this change? that didn't seem to be the situation when I last checked
 * so far, the speed improvements have come at a cost of significantly
higher memory use (i believe it was ~10 times that of CPython at one
point)

I dunno, I kinda feel about Unladen Swallow the exact same way I do
about Go: if it wasn't a Google project, I really doubt it would be
getting the attention it is (over the other performance enhancement
projects: cython, psyco2, pypi et al)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The answer

2010-01-17 Thread Alf P. Steinbach

* Jive Dadson:
Okay, with your help I've figured it out.  Instructions are below, but 
read the caveat by Ben Fenny in this thread.  All this stuff is good for 
one default version of Python only.  The PYTHONPATH described below, for 
example, cannot specify a version number.  Yes, that's a pain in the 
butt, but there's no way around it.  If you switch versions, you may 
have to delete all the .pyc files that will show up in the module 
folders.  Python ought to check them to see if they are valid, but I do 
not know if it does so.


These instructions are for MS Windows.

1) Create your modules folder. Let's say it's named "Modules."  The 
documentation calls it a "package."


2) In an explorer window or on the desktop, right click on My Computer, 
and select Properties.


3) Select the Advanced tab, and click on Environment Variables near the 
bottom.


4) Look for an environment variable named PYTHONPATH.

   a) If you do not find one, create one using the New button(s). I 
don't know if it has to be in User Variables or System Variables.  To 
save time experimenting, I just put one in both. For the value, put the 
full path of the folder Modules.


The User variables /override/ the System variables for a given user. The System 
variables provide defaults for all users. One notable exception is PATH, where 
the User PATH items are appended to the System PATH.


Anyways, with many items in a variable like PATH it can be impractical to use 
Windows' functionality, which presents it all on one line, which for a PATH with 
many items can be exceeding long  --  like a many thousand characters[1] line.


So for your convenience, below is a little Windows app (as an HTML application, 
it's just some HTML and VBScript and CSS) that presents the user PATH items one 
per line in a Notepad-like window. It should be no problem modifying it to 
instead edit PYTHONPATH, or even a choice of environment variable. As my late 
father used to say, when you don't have a tool, you make it.


Maybe now I should recode this in Python. But on the other hand, one shouldn't 
spend time fixing what works.  So  ... enjoy! :-)


Note: it's crucial to use [.HTA] filename extension.
Also, it's quite possible that this doesn't work in Windows Vista (at least not 
without configuration of Windows), but it works in XP and earlier.








content="http://schemas.microsoft.com/intellisense/ie5";>





Simple user-environment %path% editor


body{ margin: 0px; padding: 0px; }

#menuArea
{
width: 100%; height: 1.8em; white-space: nowrap; padding-top: 
2px;
background: #E0E0E0;
}

#clientArea
{
width: 100%; position: absolute; top: 1.8em; bottom: 0;
}

#pathEditor
{
display: inline-block;
width: 100%; height: 100%;
border: 0;
position: absolute; top: 0;
overflow: scroll;
}



option explicit
dim wshShell
dim wshUserEnv
dim originalText

sub loadText
pathEditor.innerText = replace( wshUserEnv( "PATH" ), ";", vbNewline)
end sub

sub saveText
dim text
dim button

text = pathEditor.innerText
text = replace( text, vbNewLine, ";" )
button = MsgBox( _
text, vbYesNo + vbQuestion, "Save this as new %path% 
value?" _
)
if button = vbYes then wshUserEnv( "PATH" ) = text
end sub

sub onBtnLoad
loadText
end sub

sub onBtnLoadOriginal
pathEditor.innerText = originalText
end sub

sub onBtnSave
saveText
end sub

sub onLoaded
set wshShell = createObject( "WScript.Shell" )
set wshUserEnv = wshShell.environment( "USER" )
loadText
originalText = pathEditor.innerText
MsgBox _
"Type one path per line (no semicolons)", _
vbInformation, _
"How to use:"
end sub





  Load current
  Reload original
  Save as current ...











   b) If there's already a PYTHONPATH,  Edit it, adding a semi-colon and 
the full path of folder Module to the end.


5) Put your module folders into the folder Module.

6) (Here's a really arcane bit.) Into each module folder, put a file 
named __init__.py.  It will be executed when you load the module.  It 
can be empty, but it has t

Re: The answer

2010-01-17 Thread alex23
On Jan 18, 12:30 pm, Jive Dadson  wrote:
> These instructions are for MS Windows.
>
> 1) Create your modules folder. Let's say it's named "Modules."  The
> documentation calls it a "package."
>
> 2) In an explorer window or on the desktop, right click on My Computer,
> and select Properties.
>
> 3) Select the Advanced tab, and click on Environment Variables near the
> bottom.
>
> 4) Look for an environment variable named PYTHONPATH.
>
>     a) If you do not find one, create one using the New button(s). I
> don't know if it has to be in User Variables or System Variables.  To
> save time experimenting, I just put one in both. For the value, put the
> full path of the folder Modules.
>
>     b) If there's already a PYTHONPATH,  Edit it, adding a semi-colon
> and the full path of folder Module to the end.
>
> 5) Put your module folders into the folder Module.
>
> 6) (Here's a really arcane bit.) Into each module folder, put a file
> named __init__.py.  It will be executed when you load the module.  It
> can be empty, but it has to be there or else the module folder will be
> ignored.

Actually, if you're using Python 2.6+/3.x, you can effectively skip
steps 1-5, as these versions now support user site-packages.

Rather than create a Module folder and modify your PYTHONPATH, add (if
it doesn't exist already) the following folder:
%APPDATA%/Python/Python26/site-packages

Modules can sit directly in the folder, or within packages.

For more details: http://www.python.org/dev/peps/pep-0370/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Namespace Toolbox? Windows.

2010-01-17 Thread alex23
On Jan 18, 8:22 am, "W. eWatson"  wrote:
> I've found it a bit aggravating that using dir and
> help, for example, that the output just rolls on off the screen and I
> have to play around with the shell scroll bars to find what I'm looking
> for. A few simple changes to mydir should change that, but I would hope
> or think maybe there are even more tools to generally help.

If you haven't already, you really should check out IPython:
http://ipython.scipy.org

It's an enhanced interactive shell packed full of convenience
features. For example, output is by default paged, so you'll get the
behaviour you want from help() and dir() straight away. However,
you'll probably end up using IPython's help instead: ? will
not only display the docstring, it'll provide metadata about the
object, such as its base class, the file it was defined in and even
the namespace it exists in.

%page  will pretty print the object and run it through the
pager.
%timeit  is an _exceptionally_ handy wrapper
around the timeit module.
%bg  runs in a separate, background thread

There's a directory stack, macros, code in history can be edited,
profiling & debugging, functions can be called without parenthesis
(nice if you use IPython as a shell replacement), and you can easily
capture the results of a command line call to a variable.

But yes, along with all that, it pages object printing :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The answer

2010-01-17 Thread Jive Dadson

alex23 wrote:
>
> Actually, if you're using Python 2.6+/3.x, you can effectively skip
> steps 1-5, as these versions now support user site-packages.
>
> Rather than create a Module folder and modify your PYTHONPATH, add (if
> it doesn't exist already) the following folder:
> %APPDATA%/Python/Python26/site-packages
>
> Modules can sit directly in the folder, or within packages.
>
> For more details: http://www.python.org/dev/peps/pep-0370/

That requires a directory whose name embeds the Python version number, 
which is the evil from which I flee, or rather sought to flee.  Imagine 
if all your C++ code had to go into directories that were named for some 
specific C++ compiler.  It's just WRONG.  It's a maintenance nightmare 
to have a bunch of different source files that all have to be updated 
whenever you fix a bug or add a feature.

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


Re: The answer

2010-01-17 Thread alex23
Jive Dadson  wrote:
> That requires a directory whose name embeds the Python version number,
> which is the evil from which I flee, or rather sought to flee.  Imagine
> if all your C++ code had to go into directories that were named for some
> specific C++ compiler.  It's just WRONG.  It's a maintenance nightmare
> to have a bunch of different source files that all have to be updated
> whenever you fix a bug or add a feature.

With the PEP 370 approach, you can just designate a folder the core
one and symlink all other versions to it. Or better yet, use version
control to push updates to each folder.

With all of the versions sharing one folder, as you'd prefer, it would
be a lot more difficult to actually achieve version-level granularity
if and when you need it. It's not WRONG, it's just providing a level
of control that you don't need at this point.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: enhancing 'list'

2010-01-17 Thread Asun Friere
On Jan 18, 9:37 am, samwyse  wrote:
> Consider this a wish list.  I know I'm unlikely to get any of these in
> time for for my birthday, but still I felt the need to toss it out and
> see what happens.
>
> Lately, I've slinging around a lot of lists, and there are some simple
> things I'd like to do that just aren't there.
>

If memory serves me correctly, it has been possible to subclass 'built-
in' types since Py2.2 or thereabouts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheriting methods but over-riding docstrings

2010-01-17 Thread Steven D'Aprano
On Mon, 18 Jan 2010 01:45:17 +0100, Alf P. Steinbach wrote:

> Steven: on a personal note, earlier when I saw you (I think it was you)
> using the "Norwegian Parrot" example I thought it referred to me because
> that was the only sense I could make of it, it followed right after some
> discussion we had. Thus my impression of you or or responses in this
> group was colored by a false interpretation. But, checking, which is
> often a good idea!, and *which I should have done then*, as far as I can
> see the term was first used in this group in April 2001,  http://groups.google.com/group/comp.lang.python/browse_thread/
thread/12a125ceddd401e2/c021547a1dc14a41>.
> 
> It's still a mystery to me what it refers to, though... :-)


It refers to the famous Monty Python "Dead Parrot Sketch", involving a 
Norwegian Blue parrot that definitely isn't dead but merely pining for 
the fjords.

http://www.mtholyoke.edu/~ebarnes/python/dead-parrot.htm

http://en.wikipedia.org/wiki/Dead_Parrot


No doubt you'll be able to find it on Youtube.


A little-known FAQ is that Python is named for Monty Python, not the 
snake, and that traditionally metasyntactic variables such as foo, bar 
etc. are frequently named after Monty Python sketches. E.g. I will 
frequently reference the Cheeseshop sketch, the Spanish Inquisition, 
Ethel the Aardvark, Spam (the lunch meat, not the email), and similar.

E.g. instead of foo, bar, baz, we frequently use spam, ham, eggs.


http://www.python.org/doc/faq/general/#why-is-it-called-python




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


  1   2   >