Re: How to request data from a lazily-created tree structure ?

2008-06-17 Thread Diez B. Roggisch


Yes, I need to make sure my requests are properly written so that the
generic XPath engine does not need all the structure in memory.

There are quite a few cases where you really don't need to load
everything at all. /a/b/*/c/d is an example. But even with an example
like /x/z[last()]/t, you don't need to load everything under the
every /x/z nodes. You just need to check for the latest one, and make
sure there is a t node under it.

Anyway, if I need to make requests that need all the data... that
means that the need for lazy instantiation of nodes disappears,
right ?



Yes. And unless you have memory-constraints I have to admit that I 
really doubt that the parsing overhead isn't by far exceeded by the 
network latency.


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


Re: print problem

2008-06-17 Thread Rich Healey
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Gabriel Genellina wrote:
> En Tue, 17 Jun 2008 03:15:11 -0300, pirata <[EMAIL PROTECTED]> escribió:
> 
>> I was trying to print a dot on console every second to indicates
>> running process, so I wrote, for example:
>>
>> for i in xrange(10):
>> print ".",
>> time.sleep(1)
>>
>> Idealy, a dot will be printed out each second. But there is nothing
>> print out until after 10 seconds, all 10 dots come out together.
>>
>> I've tried lose the comma in the print statement, and it works.
>>
>> Is that because of the print statement buffer the characters until
>> there is a new line character?
> 
> Very probably, altough I can't reproduce it on Windows. Try invoking the 
> script with python -u (unbuffered input/output):
> 
> python -u your_script.py
> 
Or just write to sys.stdout without the print wrapper..

- --
Rich Healey -  [EMAIL PROTECTED]
Developer / Systems Admin - OpenPGP: 0x8C8147807
MSN: [EMAIL PROTECTED] AIM: richohealey33
irc.psych0tik.net-> #hbh #admins richohealey
irc.freenode.org -> #hbh #debian PythonNinja
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIV2NxLeTfO4yBSAcRAkunAJ9w5lavHK4TIUbexX+pSYmPla9oOQCfT8tM
tzOhQgcpO7dEG7WhE6FNZ4w=
=IqJ1
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: String Concatenation O(n^2)

2008-06-17 Thread Hrvoje Niksic
"Ian Kelly" <[EMAIL PROTECTED]> writes:

> On Mon, Jun 16, 2008 at 11:09 AM, Jean-Paul Calderone
> <[EMAIL PROTECTED]> wrote:
>> It will depend what version of Python you're using and the *exact* details
>> of the code in question.  An optimization was introduced where, if the
>> string being concatenated to is not referred to anywhere else, it will be
>> re-sized in place.  This means you'll probably see sub-quadratic behavior,
>> but only with a version of Python where this optimization exists and only
>> if the code can manage to trigger it.
>
> AFAICT, PyString_Concat never calls _PyString_Resize.  Am I looking
> in the wrong place?

Take a look at ceval.c:string_concatenate.

As Jean-Paul says, note that the optimization doesn't work in many
circumstances.  For example, change local variable to instance
attribute, and it goes away.  Other python implementations don't have
it at all.
--
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeDecodeError: 'ascii' codec can't decode byte

2008-06-17 Thread Peter Otten
Gilles Ganault wrote:

> It seems like I have Unicode data in a CSV file but Python is using
> a different code page, so isn't happy when I'm trying to read and put
> this data into an SQLite database with APSW:

My guess is that you have non-ascii characters in a bytestring.
 
> What should I do so Python doesn't raise this error? Should I convert
> data in the CVS file, or is there some function that I should call
> before APSW's executemany()?

You cannot have unicode data in a file, only unicode converted to
bytestrings using some encoding. Assuming that encoding is UTF-8 and that
apsw can cope with unicode, try to convert your data to unicode before
feeding it to the database api:

> sql = "INSERT INTO mytable (col1,col2) VALUES (?,?)"

  rows = ([col.decode("utf-8") for col in row] for row in
records("test.tsv")) 
  cursor.executemany(sql, rows)

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


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Gabriel Genellina
En Tue, 17 Jun 2008 02:25:42 -0300, Lie <[EMAIL PROTECTED]> escribió:
> On Jun 17, 11:07 am, "Leo Jay" <[EMAIL PROTECTED]> wrote:
>> On Tue, Jun 17, 2008 at 11:29 AM, pirata <[EMAIL PROTECTED]> wrote:

>> > What's the difference between "is not" and "!=" or they are the same thing?
>>
>> The 'is' is used to test do they point to the exactly same object.
>> The '==' is used to test are their values equal.
>>
>> and be very careful to the dirty corner of python:

[example with "5 is 5" but "10 is not 10"]

> No you don't have to be careful, you should never rely on it in the
> first place.
>
> Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)'
> and 'not(id(a) == id(b))'

No.

> You use 'is' when you want to test whether two variable/names are
> actually the same thing (whether they actually refers to the same spot
> on memory). The '==' equality comparison just test whether two
> objects' values can be considered equal.

Yes, *that* is true. The above statement is not. A counterexample:

py> [] is []
False
py> id([])==id([])
True

Even dissimilar objects may have the same id:

py> class A: pass
...
py> class B: pass
...
py> A() is B()
False
py> A() == B()
False
py> id(A())==id(B())
True

Comparing id(a) with id(b) is only meaningful when a and b are both alive at 
the same time. If their lifetimes don't overlap, id(a) and id(b) are not 
related in any way. So I think that trying to explain object identity in terms 
of the id function is a mistake.

-- 
Gabriel Genellina

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


Re: newbie question: for loop within for loop confusion

2008-06-17 Thread Gabriel Genellina
En Mon, 16 Jun 2008 22:51:30 -0300, John Salerno <[EMAIL PROTECTED]> escribió:

> takayuki wrote:
>
>> I'm early on in my python adventure so I'm not there yet on the strip
>> command nuances.I'm reading "How to think like a python
>> programmer" first.  It's great.
>>
>> Then "Learning python".  I've read parts of Dive into Python and will
>> work through it fully when I'm a little farther along.
>
> Yeah, I really recommend Learning Python for getting the basics first.
> It's very thorough in that regard. Dive Into Python is *not* for
> beginners. I'm sorry if people disagree, but it's just not.

Sure, the author himself says so at the very beginning in 
http://www.diveintopython.org "Dive Into Python is a Python book for 
experienced programmers."

-- 
Gabriel Genellina

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


Re: Removing inheritance (decorator pattern ?)

2008-06-17 Thread Gerard flanagan

Maric Michaud wrote:

Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez écrit :

On Jun 16, 1:49 pm, Gerard flanagan <[EMAIL PROTECTED]> wrote:

[...]

variation of your toy code. I was thinking the Strategy pattern,
different classes have different initialisation strategies? But then you
could end up with as many Strategy classes as subclasses, I don't know.

[...]

This doesn't solve the original problem, the combinatorial explosion
of empty subclasses.

[...]


Yes, and it fails to implement the strategy pattern as well... which would 
have solved the problem as it is intended exactly for this purpose.




Ok, better would have been 'my made-up strategy pattern, any resemblance 
to other patterns, either living or dead, is purely coincidental' :-)


Non-canonically,

G.

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


Re: 'string'.strip(chars)-like function that removes from the middle?

2008-06-17 Thread Peter Otten
Terry Reedy wrote:

> Cédric Lucantis wrote:
> 
>> I don't see any string method to do that
> 
>  >>> 'abcde'.translate(str.maketrans('','','bcd'))
> 'ae'
> 
> I do not claim this to be better than all the other methods,
> but this pair can also translate while deleting, which others cannot.

You should mention that you are using Python 3.0 ;) 
The 2.5 equivalent would be

>>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd")))
u'ae'

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

Re: print problem

2008-06-17 Thread Gabriel Genellina
En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey <[EMAIL PROTECTED]> escribió:
> Gabriel Genellina wrote:
>> En Tue, 17 Jun 2008 03:15:11 -0300, pirata <[EMAIL PROTECTED]> escribió:
>>
>>> I was trying to print a dot on console every second to indicates
>>> running process, so I wrote, for example:
>>>
>>> for i in xrange(10):
>>> print ".",
>>> time.sleep(1)
>>>
>>> Idealy, a dot will be printed out each second. But there is nothing
>>> print out until after 10 seconds, all 10 dots come out together.
>>>
>>> I've tried lose the comma in the print statement, and it works.
>>>
>>> Is that because of the print statement buffer the characters until
>>> there is a new line character?
>>
>> Very probably, altough I can't reproduce it on Windows. Try invoking the 
>> script with python -u (unbuffered input/output):
>>
>> python -u your_script.py
>>
> Or just write to sys.stdout without the print wrapper..

I think the output is still buffered, even if you write directly to sys.stdout, 
but I don't have a Linux box to test right now.

-- 
Gabriel Genellina

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


Re: print problem

2008-06-17 Thread Chris
On Jun 17, 8:15 am, pirata <[EMAIL PROTECTED]> wrote:
> I was trying to print a dot on console every second to indicates
> running process, so I wrote, for example:
>
> for i in xrange(10):
>     print ".",
>     time.sleep(1)
>
> Idealy, a dot will be printed out each second. But there is nothing
> print out until after 10 seconds, all 10 dots come out together.
>
> I've tried lose the comma in the print statement, and it works.
>
> Is that because of the print statement buffer the characters until
> there is a new line character?
>
> Thanks

import sys
for i in xrange(10):
sys.stdout.write('.')
sys.stdout.flush()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Duncan Booth
"Leo Jay" <[EMAIL PROTECTED]> wrote:

> same objects are equal, but equal don't have to be the same object.

same objects are often equal, but not always:

>>> inf = 2e200*2e200
>>> ind = inf/inf
>>> ind==ind
False
>>> ind is ind
True

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: get keys with the same values

2008-06-17 Thread Wolfgang Grafen

You could use my mseqdict implementation of a sorted dict.

http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html

swap:
This method can only be applied when all values of the dictionary are 
immutable. The Python dictionary cannot hold mutable keys! So swap 
doesn't work if only one of the values has the type list or dictionary. 
Tuples and instances of classes are save as long as they don't emulate 
lists or dictionaries.


from 
http://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Mseqdict.html:


>>> x=seqdict.mseqdict(dict)
>>> x['Bild']='painting'
>>> x['Ziel']='goal'
>>> x['Tor'] ='goal'
>>> x # A small German - English dictionary
mseqdict(
['gewinnen', 'deshalb', 'Abend', 'aber', 'Bild', 'Erkennung', 
'Fl\366te', 'Ziel', 'Tor'],
{'Tor': ['goal'], 'Ziel': ['goal'], 'gewinnen': ['gain'], 'deshalb': 
['therefore'], 'Abend': ['evening'], 'aber': ['but'], 'Bild': 
['picture', 'painting'], 'Erkennung': ['recognition'], 'Fl\366te': 
['flute']})


>>> x.swap()
>>> x # A small English - German dictionary
mseqdict(
['gain', 'therefore', 'evening', 'but', 'picture', 'painting', 
'recognition', 'flute', 'goal'],
{'but': ['aber'], 'recognition': ['Erkennung'], 'painting': ['Bild'], 
'flute': ['Fl\366te'], 'gain': ['gewinnen'], 'goal': ['Ziel', 'Tor'], 
'evening': ['Abend'], 'therefore': ['deshalb'], 'picture': ['Bild']})


Best regards

Wolfgang


Nader schrieb:

Hello,

I have a dictionary and will get all keys which have the same values.

d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

I will something as :

d.keys(where their values are the same)

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']

Would somebody tell me how I can do it?

Regards,
Nader

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


Re: Showing a point in Gnuploy.py

2008-06-17 Thread A.T.Hofkamp
On 2008-06-16, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello. Could some1 tell me how i could "display" a specific point in
> gnuplot.py. Supposingly if i have a point of intersection (2,3). How
> can i show this on the graph? As in how can i write near the point of
> intersection the value :(2,3).
> Thnx

1. Find out in the Gnuplot manual what command to enter
2. Send the command to Gnuplot using g() function-call

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


gtk.gdk.Pixbuf.scale() unexpected behavior when offset != 0

2008-06-17 Thread Joel Hedlund

Hi!

I'm developing a pygtk application where I need to show images zoomed in 
so that the user can see individual pixels. gtk.gdk.Pixbuf.scale() 
seemed ideal for this, but if I set offset_x and offset_y to anything 
other than 0, the resulting image is heavily distorted and the offset is 
wrong. I've searched the internet for any snippet of code that uses this 
function with nonzero offset, but even after several hours of searching 
I've still come up blank. I think this may be a bug, but since it seems 
so fundamental I think it's way more likely that I've misunderstood 
something, so I thought I'd pass this by c.l.p first. Any help is 
greatly appreciated.


I wrote a test program to show off this behavior. Please find attached 
an image of David Hasselhoff with some puppies to help facilitate this 
demonstration. (feel free to use any image, but who doesn't like 
Hasselhoff and puppies?)


show_hasselhoff.py
#---
import gtk

original = gtk.gdk.pixbuf_new_from_file('hasselhoff.jpeg')
w = original.get_width()
h = original.get_height()
interp = gtk.gdk.INTERP_NEAREST

nice = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h)
ugly = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h)
original.scale(nice, 0, 0, w, h, 0, 0, 2, 2, interp)
original.scale(ugly, 0, 0, w, h, w/2, h/2, 2, 2, interp)

outtake = original.subpixbuf(w/4, h/4, w/2, w/2)
expected = outtake.scale_simple(w, h, interp)

w = gtk.Window()
hbox = gtk.HBox()
hbox.add(gtk.image_new_from_pixbuf(original))
hbox.add(gtk.image_new_from_pixbuf(nice))
hbox.add(gtk.image_new_from_pixbuf(ugly))
hbox.add(gtk.image_new_from_pixbuf(expected))
w.add(hbox)
w.show_all()
w.connect('destroy', gtk.main_quit)
gtk.main()
#---

When you run this, you should see 4 images in a window. From left to 
right: original, nice, ugly and expected. nice, ugly and expected are 
scaled/cropped copies of original, but ugly and expected are offset to 
show less mullet and more face. expected is what I expected ugly to turn 
out like judging from the pygtk docs.


Things to note about ugly:
* The topleft pixel of original has been stretched to the area of 
offset_x * offset_y.
* The first offset_x - 1 top pixels of original have been scaled by a 
factor 2 horizontally and then stretched vertically to the height of 
offset_y.

* Vice versa for the first offset_y - 1 leftmost pixels of original.
* The remaining area of ugly is a scaled version of 
original(1,1,width/2-1,height/2-1).


Things to note about the methods:
* This behavior is constant for all interpolation methods.
* This behavior is identical in gtk.gdk.Pixbuf.compose().

This can't possibly be how this is supposed to work! Have I 
misunderstood something, or is this a bug?


Cheers!
/Joel Hedlund
<>--
http://mail.python.org/mailman/listinfo/python-list

Re: 'string'.strip(chars)-like function that removes from the middle?

2008-06-17 Thread Sion Arrowsmith
In article <[EMAIL PROTECTED]>,
Peter Otten  <[EMAIL PROTECTED]> wrote:
>Terry Reedy wrote:
>>  >>> 'abcde'.translate(str.maketrans('','','bcd'))
>> 'ae'
>You should mention that you are using Python 3.0 ;) 
>The 2.5 equivalent would be
>
 u"abcde".translate(dict.fromkeys(map(ord, u"bcd")))
>u'ae'

Only if you're using Unicode:

>>> 'abcde'.translate(string.maketrans('',''), 'bcd')
'ae'
>>> sys.version_info
(2, 4, 4, 'final', 0)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
--
http://mail.python.org/mailman/listinfo/python-list

go to specific line in text file

2008-06-17 Thread Patrick David
Hello NG,

I am searching for a way to jump to a specific line in a text file, let's
say to line no. 9000.
Is there any method like file.seek() which leads me to a given line instead
of a given byte?

Hope for help
Patrick
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyinotify issue

2008-06-17 Thread AndreH
On Jun 13, 3:39 pm, AndreH <[EMAIL PROTECTED]> wrote:
> Good day,
>
> I just installed pyinotify on my gentoo box.
>
> When I test the library through "pyinotify.pv -v /tmp" under root,
> everything works great, but when I try the same thing under my local
> user account, I receive the following error:
> Error: cannot watch . (WD=-1)
>
> Not very helpful. I've tried VERBOSE=True mode, but it doens't provide
> any additional information.
>
> I also tried it for a directory in my home folder just to be sure it's
> not a permission problem, but no luck.
>
> Any ideas?
>
> Regards,
> Andre

Ok I ended up solving my problem.

pyinotify is just a wrapper for the c lib, inotif.h. Installing the
inotify-tools package allows one to do better troubleshooting.

First, my kernel version was too old and did not allow inotify to be
executed at user-level. I bumped my kernel up to 2.6.24 and enabled
the user-level execution flag.

Then pyinotify worked once and failed for all consecutive retries.
inotifwatch said that my "maximum number of user watches" was maxed
out and that I should increase it under /proc/sys/fs/inotify/
max_user_watches.

Something must be wrong, since the max_user_watches was set to 8192. I
played around with this setting (sysctl -w
fs.inotify.max_user_watches=16843), pyinotify.py and inotifywatch, and
finally came the conclusion that pyinotify 0.7.0 was buggy. I got hold
of 0.7.1 which seems to have fixed this problem. Hopefully, I'm not
speaking too soon.
--
http://mail.python.org/mailman/listinfo/python-list


New widget

2008-06-17 Thread Petertos
Hello, here's a new casual game that looks interesting. It's called
Smilies Invasion and you have to eat as much green smilies as you can:

http://www.dolmenent.com/smiliesinvasion/

Greetings from a newbie developer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: go to specific line in text file

2008-06-17 Thread John Machin
On Jun 17, 8:10 pm, Patrick David <[EMAIL PROTECTED]>
wrote:
> Hello NG,
>
> I am searching for a way to jump to a specific line in a text file, let's
> say to line no. 9000.
> Is there any method like file.seek() which leads me to a given line instead
> of a given byte?

If by "jump" you mean without reading the preceding 8999 lines, and by
"text file" you mean variable length records without a separate index
structure, that method hasn't been implemented yet. AFAIK it hasn't
been implemented in any other language either :-)

The linecache module may be what you want, depending on how closely
your access patterns match those the module was designed for.

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


Re: 'string'.strip(chars)-like function that removes from the middle?

2008-06-17 Thread Peter Otten
Sion Arrowsmith wrote:

> In article <[EMAIL PROTECTED]>,
> Peter Otten  <[EMAIL PROTECTED]> wrote:
>>Terry Reedy wrote:
>>>  >>> 'abcde'.translate(str.maketrans('','','bcd'))
>>> 'ae'
>>You should mention that you are using Python 3.0 ;)
>>The 2.5 equivalent would be
>>
> u"abcde".translate(dict.fromkeys(map(ord, u"bcd")))
>>u'ae'
> 
> Only if you're using Unicode:

... which is what you do if you are using the str type in 3.0.
 
Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 372 -- Adding an ordered directory to collections

2008-06-17 Thread bearophileHUGS
Martin v. L.:
> http://wiki.python.org/moin/TimeComplexity

Thank you, I think that's not a list of guarantees, while a list of
how things are now in CPython.


> If so, what's the advantage of using that method over d.items[n]?

I think I have lost the thread here, sorry. So I explain again what I
mean. I think for this data structure it's important to keep all the
normal dict operations at the same speed. If you use a C
implementation vaguely similar to my pure python recipe you can
perform the del in O(1) too, because pairs are joined in (double)
linked list. But such data structure is O(n) to find the n-th item
inserted into the sequence.

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


Numeric type conversions

2008-06-17 Thread John Dann
I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer.

I'm guess that there should be a function available whereby I can say
something like:

My2ByteInt = ConvertToInt(ByteStream[12:13])

to take a random example of the 2 bytes occurring at positions 12 and
13 in the byte stream.

Can anyone point me in the right direction towards a suitable function
please?

NB I don't know without further checking exactly how the bytes are
encoded, but I'm just transcribing some code across from a Windows
VB.Net program and these same bytes could be read straight into a
standard 2-byte signed short int, so I can be confident that it's a
fairly standard Windows-compatible encoding. 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric type conversions

2008-06-17 Thread Diez B. Roggisch
John Dann wrote:

> I'm new to Python and can't readily find the appropriate function for
> the following situation:
> 
> I'm reading in a byte stream from a serial port (which I've got
> working OK with pyserial) and which contains numeric data in a packed
> binary format. Much of the data content occurs as integers encoded as
> 2 consecutive bytes, ie a 2-byte integer.
> 
> I'm guess that there should be a function available whereby I can say
> something like:
> 
> My2ByteInt = ConvertToInt(ByteStream[12:13])
> 
> to take a random example of the 2 bytes occurring at positions 12 and
> 13 in the byte stream.
> 
> Can anyone point me in the right direction towards a suitable function
> please?

see the module struct in the standard-lib.

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


Re: Numeric type conversions

2008-06-17 Thread ershov . a_n
try struct.pack
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric type conversions

2008-06-17 Thread A.T.Hofkamp
On 2008-06-17, John Dann <[EMAIL PROTECTED]> wrote:
> I'm reading in a byte stream from a serial port (which I've got
> working OK with pyserial) and which contains numeric data in a packed
> binary format. Much of the data content occurs as integers encoded as
> 2 consecutive bytes, ie a 2-byte integer.

[snipperdesnip]

> Can anyone point me in the right direction towards a suitable function
> please?

The ctypes module should be helpful here

Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric type conversions

2008-06-17 Thread Gerhard Häring

John Dann wrote:

I'm new to Python and can't readily find the appropriate function for
the following situation:

I'm reading in a byte stream from a serial port (which I've got
working OK with pyserial) and which contains numeric data in a packed
binary format. Much of the data content occurs as integers encoded as
2 consecutive bytes, ie a 2-byte integer. [...]


Use the unpack() function from the struct module.

-- Gerhard

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


Re: How to request data from a lazily-created tree structure ?

2008-06-17 Thread méchoui
On Jun 17, 9:08 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Yes, I need to make sure my requests are properly written so that the
> > generic XPath engine does not need all the structure in memory.
>
> > There are quite a few cases where you really don't need to load
> > everything at all. /a/b/*/c/d is an example. But even with an example
> > like /x/z[last()]/t, you don't need to load everything under the
> > every /x/z nodes. You just need to check for the latest one, and make
> > sure there is a t node under it.
>
> > Anyway, if I need to make requests that need all the data... that
> > means that the need for lazy instantiation of nodes disappears,
> > right ?
>
> Yes. And unless you have memory-constraints I have to admit that I
> really doubt that the parsing overhead isn't by far exceeded by the
> network latency.
>
> Diez

Do you know if there is such XPath engine that can be applied to a DOM-
like structure ?

One way would be to take an XPath engine from an existing XML engine
(ElementTree, or any other), and see what APIs it calls... and see if
we cannot create a DOM-like structure that has the same API. Duck
typing, really...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Derek Martin
On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote:
> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)'
> > and 'not(id(a) == id(b))'
> 
> No.

Sure it is... he said "similar"... not identical.  They are not the
same, but they are similar.  

Saying a flat "no" alone, without qualifying your statement is
generally interpreted as rude in English...  It's kind of like how you
talk to children when they're too young to understand the explanation.
Yucky.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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

Re: Numeric type conversions

2008-06-17 Thread John Machin
On Jun 17, 9:28 pm, John Dann <[EMAIL PROTECTED]> wrote:
> I'm new to Python and can't readily find the appropriate function for
> the following situation:
>
> I'm reading in a byte stream from a serial port (which I've got
> working OK with pyserial) and which contains numeric data in a packed
> binary format. Much of the data content occurs as integers encoded as
> 2 consecutive bytes, ie a 2-byte integer.
>
> I'm guess that there should be a function available whereby I can say
> something like:
>
> My2ByteInt = ConvertToInt(ByteStream[12:13])
>
> to take a random example of the 2 bytes occurring at positions 12 and
> 13 in the byte stream.
>
> Can anyone point me in the right direction towards a suitable function
> please?
>
> NB I don't know without further checking exactly how the bytes are
> encoded, but I'm just transcribing some code across from a Windows
> VB.Net program and these same bytes could be read straight into a
> standard 2-byte signed short int, so I can be confident that it's a
> fairly standard Windows-compatible encoding.

You need the unpack function of the struct module. Supposing you have
a four-byte string containing two such short ints, first + 1 then -1
then this will work:

>>> import struct
>>> two_shorts = '\x01\x00\xff\xff'
>>> struct.unpack('>>

In the format string, '<' means little-endian (almost universal on PCs
running Windows), and 'h' means a signed 'half-word'. See the struct
manual section for more options.

You can write a function called convert_to_int (take a hint on naming
conventions) and use it a slice at a time, or you can use
struct.unpack to grab a whole record at once. Here's a real live
example of that:

(
f.height, option_flags, f.colour_index, f.weight,
f.escapement_type, f.underline_type, f.family,
f.character_set,
) = unpack('http://mail.python.org/mailman/listinfo/python-list


Re: 32 bit or 64 bit?

2008-06-17 Thread Phil Hobbs

[EMAIL PROTECTED] wrote:

On Jun 15, 7:43 pm, Peter Otten <[EMAIL PROTECTED]> wrote:

[EMAIL PROTECTED] wrote:

On Jun 15, 6:58 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:

I do need speed. Is there an option?

Mind telling us what you *actually* want to achieve? (What do you want to
calculate?)
Christian

Physical simulations of objects with near-lightspeed velocity.

How did you determine that standard python floats are not good enough?


I have a physical system set up in which a body is supposed to
accelerate and to get very close to lightspeed, while never really
attaining it. After approx. 680 seconds, Python gets stuck and tells
me the object has passed lightspeed. I put the same equations in
Mathematica, again I get the same mistake around 680 seconds. So I
think, I have a problem with my model! Then I pump up the
WorkingPrecision in Mathematica to about 10. I run the same equations
again, and it works! At least for the first 10,000 seconds, the object
does not pass lightspeed.
I concluded that I need Python to work at a higher precision.


Everything beyond that is unlikely to be supported by the hardware and will
therefore introduce a speed penalty.



I have thought of that as well. However I have no choice. I must do
these calculations. If you know of any way that is supported by the
hardware, it will be terrific, but for now the slower things will have
to do.


You need to change your representation.  Try redoing the algebra using 
(c-v) as the independent variable, and calculate that.


Cheers,

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


Mapping a series of Dates to an array of Numbers

2008-06-17 Thread J-Burns
Hello. Got a problem here.

Ive got a set of points tht id be plotting. Those points would contain
the date on which the work was done against its frequency. Supposedly
if i did something on the 28th of March one of the points would be
(28, respective freq). The next time i did my work on the 1st of
April. So my next point would (1,freq).

Now how could i map all the dates to another array so that when im
plotting them i can plot the points as (day 1, freq), (day2,freq),
(day4 , freq)  and so on rather than having points like (28, freq),
(29,freq), (1,freq) and blah blah blah.

Id be needing some help on how to use the time class in python as
well. Thnx
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mapping a series of Dates to an array of Numbers

2008-06-17 Thread J-Burns
Btw dnt forget the solution should also cater to this problem:
Supposedly there is a day on which i did not do anything. Than that
particular spot in my graph should be left empty. Meaning that if i
did something on the 1st March and after it i did something on the 7th
March. Then essentially 1st march should be mapped to day1 and 7th
march to day 7(not day2)... :P
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mapping a series of Dates to an array of Numbers

2008-06-17 Thread Chris
On Jun 17, 2:15 pm, J-Burns <[EMAIL PROTECTED]> wrote:
> Hello. Got a problem here.
>
> Ive got a set of points tht id be plotting. Those points would contain
> the date on which the work was done against its frequency. Supposedly
> if i did something on the 28th of March one of the points would be
> (28, respective freq). The next time i did my work on the 1st of
> April. So my next point would (1,freq).
>
> Now how could i map all the dates to another array so that when im
> plotting them i can plot the points as (day 1, freq), (day2,freq),
> (day4 , freq)  and so on rather than having points like (28, freq),
> (29,freq), (1,freq) and blah blah blah.
>
> Id be needing some help on how to use the time class in python as
> well. Thnx

For every day you could build a timestamp and frequency pair, hell,
you don't even need to use the time module if you're capturing data
manually.  If you build your dataset as "(timestamp, frequency)" and
if frequency is nothing then use "None" when you extract data to plot
you could use a simple list comprehension to retrieve days that
actually had items "[(timestamp,frequency) for timestamp,frequency in
data_structure where frequency != None]".  Now you have your own list
that is composed just of data pairs where there is a frequency.
--
http://mail.python.org/mailman/listinfo/python-list


Re: go to specific line in text file

2008-06-17 Thread Hrvoje Niksic
Patrick David <[EMAIL PROTECTED]> writes:

> I am searching for a way to jump to a specific line in a text file,
> let's say to line no. 9000.  Is there any method like file.seek()
> which leads me to a given line instead of a given byte?

You can simulate it fairly easily, but it will internally read the
file line by line and will take the time roughly proportional to the
size of the file.

from itertools import islice
def seek_to_line(f, n):
for ignored_line in islice(f, n - 1):
pass   # skip n-1 lines

f = open('foo')
seek_to_line(f, 9000)# seek to line 9000

# print lines 9000 and later
for line in f:
print line
--
http://mail.python.org/mailman/listinfo/python-list


How do I avoid using HTTPRedirectHandler with urllib2?

2008-06-17 Thread Mukherjee, Pratip
Hi,
I am new to Python, trying it as an alternative to Perl. I am having
problem with python HTTP handling library, urllib2. How do I avoid using
the HTTPRedirectHandler while making a HTTP request? For those familiar
to Perl-LWP, this is done by using simple_request() on the UserAgent
object.
Thanks.

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

Re: Buffer size when receiving data through a socket?

2008-06-17 Thread John Salerno
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Both programs say recv(buffer_size) - buffer_size is the maximum number of 
> bytes to be RECEIVED, that is, READ. recv will return at most buffer_size 
> bytes. It may return less than that, even if the other side sent the data 
> in a single operation.
> Note that most of the time you want to use the sendall() method, because 
> send() doesn't guarantee that all the data was actually sent. 
> 

I was wondering about sendall(). The examples I've read in two different 
books are consistent in their use of send() and don't even mention 
sendall(), so I thought maybe it was for a more specialized situation.

> Yes, it is stored in an intermediate buffer until you read it. You typed 
> "hello" and sent it, the server replied with the string "You typed: 
> hello"; the OS stores it. You read only 10 bytes "You typed:", the 
> remaining are still in the buffer. Next round: you type something, the 
> server replies, you read the remaining bytes from the original reply, and 
> so on...

Oh I didn't even count "You typed:" as part of the 10 bytes! And what a 
coincidence that it happens to be exactly 10 characters! That really helped 
to hide the problem from me!

> (Note that in this particular configuration, the client will fill its 
> buffer at some time: because the server sends at least 11 bytes each 
> round, but the client reads at most 10 bytes, so the client is always 
> behind the server...)

How is the server sending back 11 bytes? Is it because it's sending at least 
the 10 characters, plus the extra space?

Thanks! 


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


Re: Buffer size when receiving data through a socket?

2008-06-17 Thread John Salerno
"John Salerno" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> from socket import *
>
> host = 'localhost'
> port = 51567
> address = (host, port)
> buffer_size = 1024
>
> client_socket = socket(AF_INET, SOCK_STREAM)
> client_socket.connect(address)
>
> while True:
>data = raw_input('> ')
>if not data:
>break
>client_socket.send(data)
>data = client_socket.recv(buffer_size)
>if not data:
>break
>print data
>
> client_socket.close()

Also, is that second "if not data: break" statement necessary? It seems like 
once you get past the first if, you don't need the second one. Of course, I 
guses it's possible that the server could return a False value, but even 
still, would it make sense to break out of the loop and close the connection 
because of that?

It runs fine without the if statement, but I'm wondering if I just haven't 
encountered the proper problem situation yet. 


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


Re: 32 bit or 64 bit?

2008-06-17 Thread [EMAIL PROTECTED]
On Jun 17, 3:13 pm, Phil Hobbs
<[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Jun 15, 7:43 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] wrote:
> >>> On Jun 15, 6:58 pm, Christian Meesters <[EMAIL PROTECTED]> wrote:
> > I do need speed. Is there an option?
>  Mind telling us what you *actually* want to achieve? (What do you want to
>  calculate?)
>  Christian
> >>> Physical simulations of objects with near-lightspeed velocity.
> >> How did you determine that standard python floats are not good enough?
>
> > I have a physical system set up in which a body is supposed to
> > accelerate and to get very close to lightspeed, while never really
> > attaining it. After approx. 680 seconds, Python gets stuck and tells
> > me the object has passed lightspeed. I put the same equations in
> > Mathematica, again I get the same mistake around 680 seconds. So I
> > think, I have a problem with my model! Then I pump up the
> > WorkingPrecision in Mathematica to about 10. I run the same equations
> > again, and it works! At least for the first 10,000 seconds, the object
> > does not pass lightspeed.
> > I concluded that I need Python to work at a higher precision.
>
> >> Everything beyond that is unlikely to be supported by the hardware and will
> >> therefore introduce a speed penalty.
>
> > I have thought of that as well. However I have no choice. I must do
> > these calculations. If you know of any way that is supported by the
> > hardware, it will be terrific, but for now the slower things will have
> > to do.
>
> You need to change your representation.  Try redoing the algebra using
> (c-v) as the independent variable, and calculate that.
>
> Cheers,
>
> Phil Hobbs

That was suggested. Problem is, that sometimes the velocities are near
zero. So this solution, by itself, is not general enough.
--
http://mail.python.org/mailman/listinfo/python-list


Re: go to specific line in text file

2008-06-17 Thread John Machin
On Jun 17, 10:46 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Patrick David <[EMAIL PROTECTED]> writes:
> > I am searching for a way to jump to a specific line in a text file,
> > let's say to line no. 9000.  Is there any method like file.seek()
> > which leads me to a given line instead of a given byte?
>
> You can simulate it fairly easily, but it will internally read the
> file line by line and will take the time roughly proportional to the
> size of the file.
>
> from itertools import islice
> def seek_to_line(f, n):

The OP gave no impression that he'd restrict himself to one
seek_to_line call per open. Perhaps you need
f.seek(0)
here otherwise
seek_to_line(f, 20)
seek_to_line(f, 10)
will give something unexpected (like jumping forwards instead of
backwards).

> for ignored_line in islice(f, n - 1):
> pass   # skip n-1 lines
>
> f = open('foo')
> seek_to_line(f, 9000)# seek to line 9000
>
> # print lines 9000 and later
> for line in f:
> print line

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


Re: 32 bit or 64 bit?

2008-06-17 Thread Richard Brodie

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

>That was suggested. Problem is, that sometimes the velocities are near
>zero. So this solution, by itself, is not general enough.

Maybe working in p, and delta-p would be more stable. 


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


Re: The best way to package a Python module?

2008-06-17 Thread js
Thanks everyone for details.
I'll try stealing some of the good bits of python-central of debian
for my purpose.

On Mon, Jun 16, 2008 at 10:43 AM, Ben Finney
<[EMAIL PROTECTED]> wrote:
> Jean-Paul Calderone <[EMAIL PROTECTED]> writes:
>
>> >What has changed is that the tools in common use for Debian
>> >packaging of Python libraries have taken on the role of generating
>> >those per-version copies at install time.
>>
>> [EMAIL PROTECTED]:~$ ls -l 
>> /usr/lib/python2.{4,5}/site-packages/sqlite/main.py
>> lrwxrwxrwx 1 root root 63 2007-12-27 15:29 
>> /usr/lib/python2.4/site-packages/sqlite/main.py -> 
>> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py
>> lrwxrwxrwx 1 root root 63 2007-12-27 15:29 
>> /usr/lib/python2.5/site-packages/sqlite/main.py -> 
>> /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py
>> [EMAIL PROTECTED]:~$
>>
>> That doesn't seem to agree with your statement.  Am I missing something?
>
> You are missing an inspection of the contents of the actual package
> file. The package file itself contains only a single copy of the
> Python module (at /usr/share/pycentral/site-packages/sqlite/main.py).
>
> What you see there on your filesystem was created at install time; the
> installation tool figures out, at install time, which Python versions
> need to be supported on this particular system, and creates those
> symlinks.
>
> Thus, the change that's occurred is that the user doesn't need to
> choose between "Python SQLite library for Python 2.4" and "Python
> SQLite library for Python 2.5".
>
> There is no longer a separation at the package level by Python
> version, so the user merely needs to choose (given your example) the
> single "Python SQLite library", and the install process takes care of
> setting it up for all supported versions of Python on the system.
>
> --
>  \   "[Freedom of speech] isn't something somebody else gives you. |
>  `\   That's something you give to yourself." —_Hocus Pocus_, |
> _o__)Kurt Vonnegut |
> Ben Finney
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Authentic Designer Handbags at www. yoyobag.com

2008-06-17 Thread kalra . shrut
Authentic Designer Handbags at www. yoyobag.com
--
http://mail.python.org/mailman/listinfo/python-list


Annoying message when interrupting python scripts

2008-06-17 Thread geoffbache
Hi all,

I find that I semi-frequently get the cryptic message

import site failed; use -v for traceback

printed on standard error when an arbitrary python script receives
SIGINT while the python interpreter
is still firing up. If I use -v for traceback I get something along
the lines of

'import site' failed; traceback:
Traceback (most recent call last):
  File "/usr/lib/python2.4/site.py", line 61, in ?
import os
  File "/usr/lib/python2.4/os.py", line 683, in ?
import copy_reg as _copy_reg
  File "/usr/lib/python2.4/copy_reg.py", line 5, in ?
"""
KeyboardInterrupt

Is this a bug? I couldn't find any code, but I imagine something like
try:
 import site
except:
 sys.stderr.write("import site failed; use -v for traceback\n")

which should surely allow a KeyboardInterrupt exception through?

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


Re: Annoying message when interrupting python scripts

2008-06-17 Thread geoffbache

To clarify: this is more serious than an incorrect error message, as
the intended interrupt gets swallowed and
script execution proceeds. Sometimes I seem to get half-imported
modules as well,
the script failing later with something like

AttributeError: 'module' object has no attribute 'getenv'

when trying to call os.getenv

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


Re: Pattern Matching Over Python Lists

2008-06-17 Thread Kirk Strauser
At 2008-06-17T05:55:52Z, Chris <[EMAIL PROTECTED]> writes:

> Is anyone aware of any prior work done with searching or matching a
> pattern over nested Python lists? I have this problem where I have a
> list like:
>
> [1, 2, [1, 2, [1, 7], 9, 9], 10]
>
> and I'd like to search for the pattern [1, 2, ANY] so that is returns:
>
> [1, 2, [1, 2, [6, 7], 9, 9], 10]
> [1, 2, [6, 7], 9, 9]

Hint: recursion.  Your general algorithm will be something like:

def compare(list, function):
if function(list):
print list
for item in list:
if item is a list:
compare(item, function)

def check(list):
if list starts with [1, 2] and length of the list > 2:
return True
else:
return False
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch StopIteration?

2008-06-17 Thread Nick Craig-Wood
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>  I'm writing to see calcuration process.
>  And so, I can't catch StopIteration...
> 
>  What is mistake?
> 
>  def collatz(n):
>r=[]
>while n>1:
>  r.append(n)
>  n = 3*n+1 if n%2 else n/2
>  yield r
> 
>  for i, x in enumerate(collatz(13)):
>try:
>  last = x[:i+1]
>  print x[:i+1]
>except StopIteration:
>  print last.appnd(1)
> 
>  Output:
>  [13]
>  [13, 40]
>  [13, 40, 20]
>  [13, 40, 20, 10]
>  [13, 40, 20, 10, 5]
>  [13, 40, 20, 10, 5, 16]
>  [13, 40, 20, 10, 5, 16, 8]
>  [13, 40, 20, 10, 5, 16, 8, 4]
>  [13, 40, 20, 10, 5, 16, 8, 4, 2]
>  last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1]  # i want this
>  list

I would have thought you want this...

>>> for i, x in enumerate(collatz(13)):
...   last = x[:i+1]
...   print x[:i+1]
... else:
...   last.append(1)
...   print last
...
[13]
[13, 40]
[13, 40, 20]
[13, 40, 20, 10]
[13, 40, 20, 10, 5]
[13, 40, 20, 10, 5, 16]
[13, 40, 20, 10, 5, 16, 8]
[13, 40, 20, 10, 5, 16, 8, 4]
[13, 40, 20, 10, 5, 16, 8, 4, 2]
[13, 40, 20, 10, 5, 16, 8, 4, 2, 1]

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2Q's: How to autocreate instance of class;How to check for membership in a class

2008-06-17 Thread Mark Wooding
asdf <[EMAIL PROTECTED]> wrote:

(Presumably nothing to do with the Common Lisp system-definition utility.)

> So for example if I know that var1=jsmith. Can I somehow do
> var1=User().

Something like this might work.

class User (object):
  def __init__(me, name):
me.name = name

class Users (object):
  def __getattr__(me, name):
try:
  return object.__getattr__(me, name)
except AttributeError:
  u = me.__dict__[name] = User(name)
  return u

>>> users = Users()
>>> alice = users.alice
>>> alice.name
'alice'
>>> alice is users.alice
True

Not very nice, though, and not particularly good at defending against
typos.

> My second question is how can I check if object is a member of a class.
> so let's say I create a=User(), b=User()...

The built-in isinstance function seems an obvious choice.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric type conversions

2008-06-17 Thread MRAB
On Jun 17, 12:28 pm, John Dann <[EMAIL PROTECTED]> wrote:
> I'm new to Python and can't readily find the appropriate function for
> the following situation:
>
> I'm reading in a byte stream from a serial port (which I've got
> working OK with pyserial) and which contains numeric data in a packed
> binary format. Much of the data content occurs as integers encoded as
> 2 consecutive bytes, ie a 2-byte integer.
>
> I'm guess that there should be a function available whereby I can say
> something like:
>
> My2ByteInt = ConvertToInt(ByteStream[12:13])
>
> to take a random example of the 2 bytes occurring at positions 12 and
> 13 in the byte stream.
>
[snip]
Please note that in slicing the start position is included and the end
position is excluded, so that should be ByteStream[12:14].
--
http://mail.python.org/mailman/listinfo/python-list


Re: Debuggers

2008-06-17 Thread R. Bernstein
TheSaint <[EMAIL PROTECTED]> writes:

> On 19:21, venerdì 13 giugno 2008 R. Bernstein wrote:
>
>> I'm not completely sure what you mean, but I gather that in
>> post-mortem debugging you'd like to inspect local variables defined at the
>> place of error.
>
> Yes, exactly. This can be seen with pdb, but not pydb.
> If I'm testing a piece of code and it breaks, then I'd like to see the
> variables and find which of them doesn't go as expected.
>  
>> Python as a language is a little different than say Ruby. In Python
>> the handler for the exception is called *after* the stack is unwound
>
> I'm not doing comparison with other languages. I'm simply curious to know why
> pydb don't keep variables like pdb.

If you are simply curious, then a guess is that the frame from the
traceback (t) isn't set by pydb's post_mortem method in calling the
Pdb interaction() method, whereas it does get set in the corresponding
pdb post_mortem code.

It's possible this is a bug -- it's all in the details. But if it is a
bug or a feature improvement, probably a better place to to request a
change would be in the tracker for the pydb project:

   http://sourceforge.net/tracker/?group_id=61395

Should you go this route, I'd suggest giving the smallest program and
scenario that exhibits the problem but also has a different behavior
in pdb. There are programming interfaces to post-mortem debugging in
pdb and pydb, namely post_mortem() and pm(); so best is a short self
contained program that when run sets up as much of this as possible.

And if the bug is accepted and fixed such a short-self contained
program would get turned into a test case and incluide to the set
regression tests normally run.

>
> Final, I agreed the idea to restart the debugger when an exception is trow.
> It could be feasible to let reload the file and restart. Some time I can
> re-run the program , as the error is fixed, but sometime pdb doesn't
> recognize the corrections applied.

The restart that I submitted as a patch to pdb two and a half years
ago is what I call a "warm" restart: no Python code is actually
reloaded. The reason ti was done way is that is a simple way to
maintain the debugger settings such as breakpoints; also it requires
saving less knowledge about how the program was initially run so it
might be applicable in more contexts.

The down side though, in addition to what you've noticed with regards
to files which have changed, is that global state may be different
going into the program when it is restarted.

In the last pydb release, 1.23 a "save" command was added to so that
breakpoints and other debugger state could be saved across debug
sessions which includes a "cold" or "exec" restart.

> I mean that after a post-mortem event, the debugger should forget all
> variables and reload the program, which meanwhile could be debugged.
>
> -- 
> Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


text alignment

2008-06-17 Thread Gandalf
Hi every one. What is the similar python WX style property for CSS
text-align?

I need this item text to start from the right direction:

aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60))
aaa.LoadPage('../../aa.html')


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


Trying to get pcap working

2008-06-17 Thread Michael Matthews
Hello,

I'm fairly new to Python, and have run into dead ends in trying to
figure out what is going on.  The basic thing I am trying to do is get
pylibpcap working on a Python installation.  More precisely, I want to
get it working on an ActiveState Python installation.

I have it working on cygwin (Windows XP). I was hoping to just be able
to copy the pcap.py and _pcapmodule.dll file to a directory in the
ActiveState install's sys.path (they are both in C:\Python25\Lib\site-
packages).  When I do this, it finds pcap.py just fine, but then
errors with:

C:\Python25\Lib\site-packages>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pcap
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\Lib\site-packages\pcap.py", line 7, in 
import _pcap
ImportError: No module named _pcap

(The build and initial install was done under cygwin because I could;
the goal is to "package" this up into a zip file and install it on
some more servers.)

Getting python to access the _pcapmodule.dll seems to be key; why does
the cygwin python installation work and ActiveState does not?  Is
there some sort of central known-DLL repository somewhere?

Thanks for any help you can give.

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


Re: text alignment

2008-06-17 Thread Gandalf
On Jun 17, 6:43 pm, Gandalf <[EMAIL PROTECTED]> wrote:
> Hi every one. What is the similar python WX style property for CSS
> text-align?
>
> I need this item text to start from the right direction:
>
> aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60))
>         aaa.LoadPage('../../aa.html')
>
> Thanks!

*right to the left direction...

And I'm using pythin 2.5 on XP (I forget to mention...)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pattern Matching Over Python Lists

2008-06-17 Thread bearophileHUGS
Kirk Strauser:
> Hint: recursion.  Your general algorithm will be something like:

Another solution is to use a better (different) language, that has
built-in pattern matching, or allows to create one.

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


Re: Context manager for files vs garbage collection

2008-06-17 Thread Sebastian "lunar" Wiesner
Floris Bruynooghe <[EMAIL PROTECTED]>:

> I was wondering when it was worthwil to use context managers for
> file.  Consider this example:
> 
> def foo():
> t = False
> for line in file('/tmp/foo'):
> if line.startswith('bar'):
> t = True
> break
> return t

Using this code inside a jthon web application might hit the resource limits
of the underlying operating system.

While CPython has a fairly deterministic garbage collector, the JVM gc is
non-deterministic, especially inside the server vm.  It keeps objects
around for quite a long time and only frees them, if available memory runs
low or the application is idle.  Since file objects don't consume much
memory, they might be hanging around for quite some time still claiming
resources,  which are a rare thing on many restricted server environments.

Relying on garbage collection on Python means relying on a non-portable
implementation detail.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric type conversions

2008-06-17 Thread John Dann
On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB
<[EMAIL PROTECTED]> wrote:

>[snip]
>Please note that in slicing the start position is included and the end
>position is excluded, so that should be ByteStream[12:14].

Yes, I just tripped over that, in fact, hence the error in my original
post. I suppose there must be some logic in including the start
position but excluding the end position, though it does escape me for
now. I can understand making a range inclusive or exclusive but not a
mixture of the two. Suppose it's just something you have to get used
to with Python and, no doubt, much commented on in the past.

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


Re: Buffer size when receiving data through a socket?

2008-06-17 Thread John Salerno
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Note that most of the time you want to use the sendall() method, because 
> send() doesn't guarantee that all the data was actually sent. 
> 

If I use sendall(), am I still recv'ing data with a given buffer size? What 
if I send more data than the buffer size. Is my code as written not prepared 
to handle that case? It seems like I might need to continue receiving data 
until there is no more to receive (in a loop?)...is that right? 


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


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Terry Reedy



pirata wrote:

I'm a bit confusing about whether "is not" equivelent to "!="


>>> 0 is not 0.0
True
>>> 0 != 0.0
False

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


Re: Numeric type conversions

2008-06-17 Thread Peter Otten
John Dann wrote:

> On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB
> <[EMAIL PROTECTED]> wrote:
> 
>>[snip]
>>Please note that in slicing the start position is included and the end
>>position is excluded, so that should be ByteStream[12:14].
> 
> Yes, I just tripped over that, in fact, hence the error in my original
> post. I suppose there must be some logic in including the start
> position but excluding the end position, though it does escape me for
> now. I can understand making a range inclusive or exclusive but not a
> mixture of the two. 

http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF

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


Re: Making wxPython a standard module?

2008-06-17 Thread TYR
>"  b = wx.Button(label="Click Me", action=myCallable)

>Instead you used to have to create a button and then call
>some utility function in some other object to bind that
>button to a callable (IIRC this was one place where Window
>IDs could be used).  Now, the button actually has a method
>you can use.  It's still an extra step...

That looks quite a lot like the behaviour of PythonForS60's appuifw
class. Frex, a menu:

appuifw.app.menu = [(u'Octopus', getfish(octopus)), (u'Cuttlefish',
getfish(cuttlefish)), (u'Squid', ((u'Humboldt', getfish(humboldt)),
(u'Giant', getfish(giantsquid)), (u'Colossal', getfish(colossal)))]

gives you a menu with three options, the last of which has three sub-
options, all of which call your getfish() function with their value.
--
http://mail.python.org/mailman/listinfo/python-list


Re: text alignment

2008-06-17 Thread Mike Driscoll
On Jun 17, 11:45 am, Gandalf <[EMAIL PROTECTED]> wrote:
> On Jun 17, 6:43 pm, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > Hi every one. What is the similar python WX style property for CSS
> > text-align?
>
> > I need this item text to start from the right direction:
>
> > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60))
> >         aaa.LoadPage('../../aa.html')
>
> > Thanks!
>
> *right to the left direction...
>
> And I'm using pythin 2.5 on XP (I forget to mention...)


The HtmlWindow widget can only display simple html. So, while you
cannot use CSS, you should be able to use the simple html alignment
directives. Check out the following site for pointers:

http://www.htmlite.com/lite008.php

If you want to be able to use CSS and javascript, you'll want to use
the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds
Internet Explorer.

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


Re: 'string'.strip(chars)-like function that removes from the middle?

2008-06-17 Thread Terry Reedy



Peter Otten wrote:

Terry Reedy wrote:


Cédric Lucantis wrote:


I don't see any string method to do that

 >>> 'abcde'.translate(str.maketrans('','','bcd'))
'ae'

I do not claim this to be better than all the other methods,
but this pair can also translate while deleting, which others cannot.


You should mention that you are using Python 3.0 ;) 
The 2.5 equivalent would be



u"abcde".translate(dict.fromkeys(map(ord, u"bcd")))

u'ae'


Sorry.  I did not realize that the maketrans function had not then been 
moved from the string module to the str class object, unlike nearly all 
other functions from string, including the translate function.  I also 
misremembered that maketrans did not have the new third delete param. 
What I did do once long ago was something like


>>> import string
>>> a = 'abcde'.translate(string.maketrans('bd','**'))
>>> a.replace('*','')
'ace'

which is not very nice.

tjr

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

Re: text alignment

2008-06-17 Thread Gandalf
On Jun 17, 7:49 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Jun 17, 11:45 am, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > On Jun 17, 6:43 pm, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > > Hi every one. What is the similar python WX style property for CSS
> > >text-align?
>
> > > I need this item text to start from the right direction:
>
> > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60))
> > >         aaa.LoadPage('../../aa.html')
>
> > > Thanks!
>
> > *right to the left direction...
>
> > And I'm using pythin 2.5 on XP (I forget to mention...)
>
> The HtmlWindow widget can only display simple html. So, while you
> cannot use CSS, you should be able to use the simple html alignment
> directives. Check out the following site for pointers:
>
> http://www.htmlite.com/lite008.php
>
> If you want to be able to use CSS and javascript, you'll want to use
> the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds
> Internet Explorer.
>
> Mike

well thanks it seems useful...
My question is about general items in WX and how to position them
inside an element without using CSS. It's only coincidence My item is
HtmlWindow
--
http://mail.python.org/mailman/listinfo/python-list


Re: text alignment

2008-06-17 Thread Gandalf
since you brought up this issue, please tell me where can I fine
menual for this library?
can i generate dynamic GUI from it?
If not, Is there any way to generate dynamic GUI (one that can change
according to the user input) with HTML-CSS- javascript similar
environment?
--
http://mail.python.org/mailman/listinfo/python-list


Static memory allocation in Python

2008-06-17 Thread Eduardo Henrique Tessarioli
Hi,

I am running a very simple python application and I noted that the memory
allocation is something like 4,5M.
This is a problem in my case, because I have to run 2 thousand process at
the same time.
The memory I need is 100k or less. Is there any way to set this for the
python process?

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

Re: 'string'.strip(chars)-like function that removes from the middle?

2008-06-17 Thread Ethan Furman

Ethan Furman wrote:

Greetings.

The strip() method of strings works from both ends towards the middle.
Is there a simple, built-in way to remove several characters from a 
string no matter their location? (besides .replace() ;)


For example:
.strip --> 'www.example.com'.strip('cmowz.')
'example'
.??? --> --- 'www.example.com'.strip('cmowz.')
'exaple'


Thanks for all the ideas!
--
Ethan
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'string'.strip(chars)-like function that removes from the middle?

2008-06-17 Thread Roel Schroeven

Peter Otten schreef:

Ethan Furman wrote:


The strip() method of strings works from both ends towards the middle.
Is there a simple, built-in way to remove several characters from a
string no matter their location? (besides .replace() ;)



identity = "".join(map(chr, range(256)))


Or

identity = string.maketrans('', '')


'www.example.com'.translate(identity, 'cmowz.')

'exaple'



--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

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


Re: text alignment

2008-06-17 Thread Mike Driscoll
On Jun 17, 12:59 pm, Gandalf <[EMAIL PROTECTED]> wrote:
> On Jun 17, 7:49 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 17, 11:45 am, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > > On Jun 17, 6:43 pm, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > > > Hi every one. What is the similar python WX style property for CSS
> > > >text-align?
>
> > > > I need this item text to start from the right direction:
>
> > > > aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60))
> > > >         aaa.LoadPage('../../aa.html')
>
> > > > Thanks!
>
> > > *right to the left direction...
>
> > > And I'm using pythin 2.5 on XP (I forget to mention...)
>
> > The HtmlWindow widget can only display simple html. So, while you
> > cannot use CSS, you should be able to use the simple html alignment
> > directives. Check out the following site for pointers:
>
> >http://www.htmlite.com/lite008.php
>
> > If you want to be able to use CSS and javascript, you'll want to use
> > the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds
> > Internet Explorer.
>
> > Mike
>
> well thanks it seems useful...
> My question is about general items in WX and how to position them
> inside an element without using CSS. It's only coincidence My item is
> HtmlWindow

Positioning the widgets within a container widgets (such as a
wx.Window, wx.Panel or wx.Frame) is usually done with sizers.
Something like this:

mySizer.Add(myWidget, 0, wx.ALIGN_RIGHT)

I've written a few tutorials on aligning widgets in various types of
sizers. You might find them helpful. There are located here:
http://www.blog.pythonlibrary.org

You might also find this site useful too: 
http://www.zetcode.com/wxpython/layout/

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


Re: text alignment

2008-06-17 Thread Mike Driscoll
On Jun 17, 1:20 pm, Gandalf <[EMAIL PROTECTED]> wrote:
> since you brought up this issue, please tell me where can I fine
> menual for this library?

You want the manual for wxPython? Go to the download page on the
Official wxPython page and get the Docs & Demos package:
http://wxpython.org/download.php

That include the wxWidgets Reference. Also see: 
http://wxpython.org/onlinedocs.php


> can i generate dynamic GUI from it?

Not sure what you mean by this. If you know how to create a "dynamic
GUI" with html/ajax or some such based on the user's interactions with
your website, than it should work in the embedded browser just as well
as it would in a non-embedded one.


> If not, Is there any way to generate dynamic GUI (one that can change
> according to the user input) with HTML-CSS- javascript similar
> environment?


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


Re: Removing inheritance (decorator pattern ?)

2008-06-17 Thread George Sakkis
On Jun 16, 11:10 pm, Maric Michaud <[EMAIL PROTECTED]> wrote:

> Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez écrit :
>
>
>
> > On Jun 16, 1:49 pm, Gerard flanagan <[EMAIL PROTECTED]> wrote:
> > > George Sakkis wrote:
> > > > I have a situation where one class can be customized with several
> > > > orthogonal options. Currently this is implemented with (multiple)
> > > > inheritance but this leads to combinatorial explosion of subclasses as
> > > > more orthogonal features are added. Naturally, the decorator pattern
> > > > [1] comes to mind (not to be confused with the the Python meaning of
> > > > the term "decorator").
>
> > > > However, there is a twist. In the standard decorator pattern, the
> > > > decorator accepts the object to be decorated and adds extra
> > > > functionality or modifies the object's behavior by overriding one or
> > > > more methods. It does not affect how the object is created, it takes
> > > > it as is. My multiple inheritance classes though play a double role:
> > > > not only they override one or more regular methods, but they may
> > > > override __init__ as well. Here's a toy example:
>
> > > I don't know if it will map to your actual problem, but here's a
> > > variation of your toy code. I was thinking the Strategy pattern,
> > > different classes have different initialisation strategies? But then you
> > > could end up with as many Strategy classes as subclasses, I don't know.
> > > (Also in vaguely similar territory
> > > -http://bazaar.launchpad.net/~grflanagan/python-rattlebag/trunk/annota...
> > > )
>
> > > class MetaBase(type):
>
> > >  def __init__(cls, name, bases, data):
> > >  cls.strategies = []
> > >  cls.prefixes = []
> > >  for base in bases:
> > >  print base
> > >  if hasattr(base, 'strategy'):
> > >  cls.strategies.append(base.strategy)
> > >  if hasattr(base, 'prefix'):
> > >  cls.prefixes.append(base.prefix)
> > >  super(MetaBase, cls).__init__(name, bases, data)
>
> > > class Joinable(object):
> > >  __metaclass__ = MetaBase
> > >  strategy = list
> > >  prefix = ''
>
> > >  def __init__(self, words):
> > >  self._words = words
> > >  for strategy in self.strategies:
> > >  self._words = strategy(self._words)
>
> > >  def join(self, delim=','):
> > >  return '%s %s' % (' '.join(self.prefixes),
> > > delim.join(self._words))
>
> > > class Sorted(Joinable):
> > >  strategy = sorted
> > >  prefix = '[sorted]'
>
> > > class Reversed(Joinable):
> > >  strategy = reversed
> > >  prefix = '[reversed]'
>
> > > class SortedReversed(Sorted, Reversed):
> > >  pass
>
> > > class ReversedSorted(Reversed, Sorted):
> > >  pass
>
> > > if __name__ == '__main__':
> > >  words = 'this is a test'.split()
> > >  print SortedReversed(words).join()
> > >  print ReversedSorted(words).join()
>
> > This doesn't solve the original problem, the combinatorial explosion
> > of empty subclasses. At the end of the day, I'd like a solution that
> > uses a (mostly) flat, single-inheritance, hierarchy, allowing the
> > client say:
>
> Yes, and it fails to implement the strategy pattern as well... which would
> have solved the problem as it is intended exactly for this purpose.

As someone in another newsgroup demonstrated, it can be solved with a
combination of strategy and decorator: http://tinyurl.com/5ulqh9

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


Re: Static memory allocation in Python

2008-06-17 Thread Calvin Spealman

On Jun 17, 2008, at 2:34 PM, Eduardo Henrique Tessarioli wrote:


Hi,

I am running a very simple python application and I noted that the  
memory allocation is something like 4,5M.
This is a problem in my case, because I have to run 2 thousand  
process at the same time.
The memory I need is 100k or less. Is there any way to set this for  
the python process?


The runtime itself isn't as light as, say, the C stdlib.

Now, there are a lot of shared libraries here, so you should measure  
not just a single instance, but how much it actually grows in overall  
system memory usage as you run more simultaneous python interpreters.



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


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


2d graphics - drawing a vescica piscis in Python

2008-06-17 Thread Terrence Brannon
Hello, I have written a program to draw a vescica piscis 

from turtle import *

def main():
setup(width=400, height=400)

r = 50
color("black")
circle(r)
color("white")
forward(r)
color("black")
circle(r)
x = raw_input('please enter a string:')

if __name__ == '__main__':
main()


... but I would like the following:

1 - I dont like how the bottom of the first circle is not complete
2 - I would like for the left circle to be filled with verticle lines
and the right circle to be filled with horizontal lines, so that the
vescica piscis is cross-hatched.

And finally, is turtle the "best" option for what I'm doing? pyCairo
looked a bit hard to get going with, but very powerful. sping looked a
bit alpha/beta.
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2d graphics - drawing a vescica piscis in Python

2008-06-17 Thread Mensanator
On Jun 17, 2:45 pm, Terrence Brannon <[EMAIL PROTECTED]> wrote:
> Hello, I have written a program to draw a vescica piscis  en.wikipedia.org/wiki/Vesica_piscis>
>
> from turtle import *
>
> def main():
>     setup(width=400, height=400)
>
>     r = 50
>     color("black")
>     circle(r)
>     color("white")
>     forward(r)
>     color("black")
>     circle(r)
>     x = raw_input('please enter a string:')
>
> if __name__ == '__main__':
>     main()
>
> ... but I would like the following:
>
> 1 - I dont like how the bottom of the first circle is not complete

Because you overwrote that portion of the circle when
you changed the color to white.

Instead, you should have done up() (which lifts the pen)
and then down() after you've moved to the start of the
second circle. No need to change the pen color.

> 2 - I would like for the left circle to be filled with verticle lines
> and the right circle to be filled with horizontal lines, so that the
> vescica piscis is cross-hatched.

That would be the fill() command, but it's not documented
how to fill with anything other than a solid color.

>
> And finally, is turtle the "best" option for what I'm doing? pyCairo
> looked a bit hard to get going with, but very powerful. sping looked a
> bit alpha/beta.

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


Is there a standard binary search with overridable comparisons?

2008-06-17 Thread markscottwright
I've got an ordered list of MyClasses that I want to be able to do
binary searches on, but against a tuple.  MyClass has valid
__lt__(self, rhs) and __eq__(self, rhs) member functions that work
when rhs is a tuple.

This works:
l = [MyClass(..), MyClass(..), ...]
l.find((a,b))

But this doesn't:
bisect.bisect(l, (a,b))

I'm assuming this is because inside bisect, it does 'key < list[x]'
rather than 'list[x] < key', so it's the tuple's __lt__ that is
called, rather than MyClass's tuple.

Is there a way around this?  Can I monkeypatch a new __lt__ into the
tuple class?

Here's some sample code that demonstrates the problem (it uses ints
rather than tuples, but the

import bisect
class MyC:
def __init__(self, v):
self.v = v

def __lt__(self, rhs):
return self.v < rhs

# cant search for int in a list of MyC's
l = sorted([MyC(x) for x in range(1000)])
bisect.bisect(l, 40)
1001 # AKA not found

# but, I can search for MyC in a list of ints
l = sorted(range(1000))
bisect.bisect(l, MyC(40))
41
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2d graphics - drawing a vescica piscis in Python

2008-06-17 Thread Matimus
On Jun 17, 12:45 pm, Terrence Brannon <[EMAIL PROTECTED]> wrote:
> Hello, I have written a program to draw a vescica piscis  en.wikipedia.org/wiki/Vesica_piscis>
>
> from turtle import *
>
> def main():
>     setup(width=400, height=400)
>
>     r = 50
>     color("black")
>     circle(r)
>     color("white")
>     forward(r)
>     color("black")
>     circle(r)
>     x = raw_input('please enter a string:')
>
> if __name__ == '__main__':
>     main()
>
> ... but I would like the following:
>
> 1 - I dont like how the bottom of the first circle is not complete
> 2 - I would like for the left circle to be filled with verticle lines
> and the right circle to be filled with horizontal lines, so that the
> vescica piscis is cross-hatched.
>
> And finally, is turtle the "best" option for what I'm doing? pyCairo
> looked a bit hard to get going with, but very powerful. sping looked a
> bit alpha/beta.

I would just draw on the tk canvas:

>>> import Tkinter as tk
>>> can = tk.Canvas()
>>> can.pack(fill=tk.BOTH, expand=True)
>>> c1 = can.create_oval(10,10,110,110)
>>> c2 = can.create_oval(60,10,170,110)

You can draw cross hatching using can.create_line(...).

Have fun,

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


Re: UnicodeDecodeError: 'ascii' codec can't decode byte

2008-06-17 Thread Gilles Ganault
On Tue, 17 Jun 2008 09:23:28 +0200, Peter Otten <[EMAIL PROTECTED]>
wrote:
> Assuming that encoding is UTF-8 and that apsw can cope
> with unicode, try to convert your data to unicode before
> feeding it to the database api:
>
>> sql = "INSERT INTO mytable (col1,col2) VALUES (?,?)"
>
>  rows = ([col.decode("utf-8") for col in row] for row in
>records("test.tsv")) 
>  cursor.executemany(sql, rows)

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


using the string functions (ex. find()) on a multi-symbol string

2008-06-17 Thread korean_dave
How can i use the find() function on a string that is composed of tons
of symbols that cause errors...

THis is my string:

find("p, li { white-space: pre-wrap; }Connected!","margin")

The tough part about this is that the string is dynamically produced.
So I can't manually go into the string and eliminate the quote-marks
or to "literal-character" them.


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


Re: 2d graphics - drawing a vescica piscis in Python

2008-06-17 Thread Lie
On Jun 18, 2:45 am, Terrence Brannon <[EMAIL PROTECTED]> wrote:
> Hello, I have written a program to draw a vescica piscis  en.wikipedia.org/wiki/Vesica_piscis>
>
> from turtle import *
>
> def main():
>     setup(width=400, height=400)
>
>     r = 50
>     color("black")
>     circle(r)
>     color("white")
>     forward(r)
>     color("black")
>     circle(r)
>     x = raw_input('please enter a string:')
>
> if __name__ == '__main__':
>     main()
>
> ... but I would like the following:
>
> 1 - I dont like how the bottom of the first circle is not complete
> 2 - I would like for the left circle to be filled with verticle lines
> and the right circle to be filled with horizontal lines, so that the
> vescica piscis is cross-hatched.
>
> And finally, is turtle the "best" option for what I'm doing? pyCairo
> looked a bit hard to get going with, but very powerful. sping looked a
> bit alpha/beta.

For an alternative to turtle, you might want to see PIL (Python
Imaging Library) or perhaps pygame.
--
http://mail.python.org/mailman/listinfo/python-list


Re: text alignment

2008-06-17 Thread Gandalf
On Jun 17, 8:43 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Jun 17, 1:20 pm, Gandalf <[EMAIL PROTECTED]> wrote:
>
> > since you brought up this issue, please tell me where can I fine
> > menual for this library?
>
> You want the manual for wxPython? Go to the download page on the
> Official wxPython page and get the Docs & Demos 
> package:http://wxpython.org/download.php
>
> That include the wxWidgets Reference. Also 
> see:http://wxpython.org/onlinedocs.php
>
> > can i generate dynamic GUI from it?
>
> Not sure what you mean by this. If you know how to create a "dynamic
> GUI" with html/ajax or some such based on the user's interactions with
> your website, than it should work in the embedded browser just as well
> as it would in a non-embedded one.
>
> > If not, Is there any way to generate dynamic GUI (one that can change
> > according to the user input) with HTML-CSS- javascript similar
> > environment?
>
> Mike

Hi Mike, I was referring to the ActiveX_IEHtmlWindow which you talked
about, when I asked you for a tutorial.
I have lots of experience on developing web application so if I could
implement some of my knowledge for developing none web application it
can save me trouble

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


Re: newbie question: for loop within for loop confusion

2008-06-17 Thread John Salerno

Gabriel Genellina wrote:

En Mon, 16 Jun 2008 22:51:30 -0300, John Salerno <[EMAIL PROTECTED]> escribió:


takayuki wrote:


I'm early on in my python adventure so I'm not there yet on the strip
command nuances.I'm reading "How to think like a python
programmer" first.  It's great.

Then "Learning python".  I've read parts of Dive into Python and will
work through it fully when I'm a little farther along.

Yeah, I really recommend Learning Python for getting the basics first.
It's very thorough in that regard. Dive Into Python is *not* for
beginners. I'm sorry if people disagree, but it's just not.


Sure, the author himself says so at the very beginning in http://www.diveintopython.org 
"Dive Into Python is a Python book for experienced programmers."



I know, but I just hear so many people recommend that book for people 
who want to learn the language.

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


Re: using the string functions (ex. find()) on a multi-symbol string

2008-06-17 Thread John Machin
On Jun 18, 7:12 am, korean_dave <[EMAIL PROTECTED]> wrote:
> How can i use the find() function on a string that is composed of tons
> of symbols that cause errors...
>
> THis is my string:
>
> find(" type="text/css">p, li { white-space: pre-wrap; } style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:
> 400; font-style:normal; text-decoration:none;">Connected!","margin")
>
> The tough part about this is that the string is dynamically produced.
> So I can't manually go into the string and eliminate the quote-marks
> or to "literal-character" them.

What are you trying to find? What error(s) do you get?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to request data from a lazily-created tree structure ?

2008-06-17 Thread Diez B. Roggisch



Do you know if there is such XPath engine that can be applied to a DOM-
like structure ?


No. But I toyed with the idea to write one :)


One way would be to take an XPath engine from an existing XML engine
(ElementTree, or any other), and see what APIs it calls... and see if
we cannot create a DOM-like structure that has the same API. Duck
typing, really...



Why can't you create a *real* DOM?

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


Re: [Twisted-Python] Re-working a synchronous iterator to use Twisted

2008-06-17 Thread Jean-Paul Calderone

On Tue, 17 Jun 2008 23:10:48 +0200, Terry Jones <[EMAIL PROTECTED]> wrote:

For the record, here's a followup to my own posting, with working code.
The earlier untested code was a bit of a mess. The below runs fine.

In case it wasn't clear before, you're pulling "results" (e.g., from a
search engine) in off the web. Each results pages comes with an indicator
to tell you whether there are more results. I wanted to write a function
(see processResults below) that, when called, would call the process
function below on each result, all done asynchronously.

This solution feels cumbersome, but it does work (aka prints the expected
output).

Comments welcome (just don't tell me to use version control :-))



I suspect the implementation could be slightly simplified, but it doesn't
look too bad as it is now (and I'm feeling slightly too lazy to back that
hunch up with code).  I did want to point out that you're missing one
tiny detail.


[snip]

# ASYNCHRONOUS calling
def processResults(uri):
   def cb((resultIterator, deferred)):
   for result in resultIterator:
   process(result)
   if deferred is not None:
   deferred.addCallback(cb)
   return getResults(uri).addCallback(cb)



Here, the returned Deferred will fire as soon as `cb´ has a result.  The
return value of `cb´ is always `None´ though, so `cb´ will have a result
synchronously in all cases.  This is incorrect for the case where there
are more results coming.  Your example produced the correct output anyway,
since all of your Deferreds are created already having results.  If you
had an "asynchronous" Deferred, you'd see your "finished" message before
process had been called on all results.

There are two possible solutions to this.  The simpler one is to return
`deferred´ from `cb´.  The problem this has is that it builds up a chain
of unbounded length which may ultimately encounter a limitation in the
implementation of Deferred, hitting the Python stack depth limit and then
failing with a RuntimeError.

The only slightly more complex one is to create a new Deferred in
`processResults´ and return it.  Then, fire it inside `cb´ when `deferred´
is None.  You also need to be slightly careful to hook up the errback
chain in this case, so that if there's some problem with getting an
iterator the app-facing Deferred gets errbacked.

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

Re: using the string functions (ex. find()) on a multi-symbol string

2008-06-17 Thread John Machin
On Jun 18, 7:12 am, korean_dave <[EMAIL PROTECTED]> wrote:
> How can i use the find() function on a string that is composed of tons
> of symbols that cause errors...
>
> THis is my string:
>
> find(" type="text/css">p, li { white-space: pre-wrap; } style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:
> 400; font-style:normal; text-decoration:none;">Connected!","margin")
>
> The tough part about this is that the string is dynamically produced.
> So I can't manually go into the string and eliminate the quote-marks
> or to "literal-character" them.

If as you say the string is dynamically created, your script should
have a variable name for it e.g. dynstr so all you have to do is:
   dynstr.find("margin")
Note: you should be using str methods (see 
http://docs.python.org/lib/string-methods.html);
almost all functionality in the string module is now deprecated and
redirected (slowly) e.g.
   def find(s, t):
  return s.find(t)

If you really want/need to put such a monster string containing both '
and " as a literal in your script, you can use triple quotes (""" or
''').

I.e.
find("", "margin")

See http://docs.python.org/tut/node5.html#SECTION00512

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Calling pcre with ctypes

2008-06-17 Thread moreati
Recently I discovered the re module doesn't support POSIX character
classes:

Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> r = re.compile('[:alnum:]+')
>>> print r.match('123')
None

So I thought I'd try out pcre through ctypes, to recreate pcredemo.c
in python. The c code is at:
http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup

Partial Python code is below

I'm stuck, from what I can tell a c array, such as:
int ovector[OVECCOUNT];

translates to
ovector = ctypes.c_int * OVECOUNT

but when I pass ovector to a function I get the traceback
$ python pcredemo.py [a-z] fred
Traceback (most recent call last):
  File "pcredemo.py", line 65, in 
compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT
ctypes.ArgumentError: argument 7: : Don't
know how to convert parameter 7

What is the correct way to construct and pass ovector?

With thanks, Alex

# PCRE through ctypes demonstration program

import ctypes
import getopt
import sys

import pcre_const

OVECOUNT = 30 # Should be a multiple of 3

pcre = ctypes.cdll.LoadLibrary('libpcre.so')

compiled_re = None
error   = ctypes.c_char_p()
pattern = ''
subject = ''
name_table  = ctypes.c_ubyte()
erroffset   = ctypes.c_int()
find_all= 0
namecount   = 0
name_entry_size = 0
ovector = ctypes.c_int * OVECOUNT
options = 0

# First, sort out the command line. There is only one possible option
at
# the moment, "-g" to request repeated matching to find all
occurrences,
# like Perl's /g option. We set the variable find_all to a non-zero
value
# if the -g option is present. Apart from that, there must be exactly
two
# arguments.

opts, args = getopt.getopt(sys.argv[1:], 'g')
for o, v in opts:
if o == '-g': find_all = 1

# After the options, we require exactly two arguments, which are the
# pattern, and the subject string.

if len(args) != 2:
print 'Two arguments required: a regex and a subject string'
sys.exit(1)

pattern = args[0]
subject = args[1]
subject_length = len(subject)

# Now we are going to compile the regular expression pattern, and
handle
# and errors that are detected.

compiled_re = pcre.pcre_compile(
pattern, options, ctypes.byref(error),
ctypes.byref(erroffset),
None
)

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


Execfile issue

2008-06-17 Thread Dan Yamins
I'm having (what I assume is) a simple problem regarding the way import and
execfile interact.  I apologize in advance for my naivete.

Lets say I have the function:

   def Func1():
   print dir()
   execfile('testfile')
   print dir()
   X

and the file

   #file: testfile
  X = 3


Then,  when I run Func1 , I get the output:

   >>> Func1()
   []
   ['X']
   Traceback (most recent call last):
 File "", line 1, in 
 File "", line 5, in Func1
   NameError: global name 'X' is not defined


SO, I have three questions:
1) Naively, I would think that the call to "execfile" in Func1 would act
as if the line was replaced with the lines of 'testfile'.  But obviously
not, in some way that has to do with the subtlety of the python compilation
process.   Can someone explain exactly what the problem is?
2) Why would something show up in the dir() call, but not be defined
(e.g. like 'X' did in the second dir() call in Func1()) ?
3) Is there any way to fix this that does not involved (essentially in
one way or another) importing "testfile" as a py module?   I would like to
avoid that scenario for a variety of reasons ...

Thanks!

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

Re: PEP 372 -- Adding an ordered directory to collections

2008-06-17 Thread Martin v. Löwis
> I think I have lost the thread here, sorry. So I explain again what I
> mean. I think for this data structure it's important to keep all the
> normal dict operations at the same speed. If you use a C
> implementation vaguely similar to my pure python recipe you can
> perform the del in O(1) too, because pairs are joined in (double)
> linked list. But such data structure is O(n) to find the n-th item
> inserted into the sequence.

Right. So byindex(n) would be O(n) then, right? If so, what's the
purpose of having that method in the first place?

The PEP doesn't give a rationale, but just proposes that the method
be there. My guess is that it includes it for performance reasons.
However, I think the PEP (author) is misguided in assuming that
making byindex() a method of odict, you get better performance than
directly doing .items()[n] - which, as you say, you won't.

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


Re: PEP 372 -- Adding an ordered directory to collections

2008-06-17 Thread Martin v. Löwis
> Well, this has become something of a rant, 

Indeed - and I was only asking about .byindex(n) :-)

I don't know why that method is included in the PEP. Speculating
myself, I assume that the PEP author wants it to be O(1). As
bearophile explains, that's not possible/not a good idea.

As for releasing the odict - that will likely have mostly the
same cost as releasing a regular dictionary, except that you
might have to look at each key twice (once in the regular dict,
once in the structure preserving the order). It might be
that the odict uses a linked-list style approach, which indeed
would nto be so good from a allocation/deallocation overhead
point of view. With the approach bearophile suggests (i.e.
each slot in the dict has a reference to the predecessor and
successor key also), a pure Python implementation would normally
allocate additional memory per key, whereas a pure C implementation
wouldn't (adding the space for the prev/next pointer right into
the slot's struct definition.

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


Re: Is there a standard binary search with overridable comparisons?

2008-06-17 Thread John Machin
On Jun 18, 6:55 am, markscottwright <[EMAIL PROTECTED]> wrote:
> I've got an ordered list of MyClasses that I want to be able to do
> binary searches on, but against a tuple.  MyClass has valid
> __lt__(self, rhs) and __eq__(self, rhs) member functions that work
> when rhs is a tuple.
>
> This works:
> l = [MyClass(..), MyClass(..), ...]
> l.find((a,b))
>
> But this doesn't:
> bisect.bisect(l, (a,b))
>
> I'm assuming

... Don't. It can be dangerous.

> this is because inside bisect, it does 'key < list[x]'
> rather than 'list[x] < key', so it's the tuple's __lt__ that is
> called, rather than MyClass's tuple.

Actually it appears (extremely gory details in Objects/object.c) that
it tries all rich comparison possibilities first:
tuple < myclass: not defined in tuple type
myclass > tuple: not defined in MyClass
before falling through to the default (which is based on addresses).

>
> Is there a way around this?  Can I monkeypatch a new __lt__ into the
> tuple class?

Looks like you need to implement MyClass.__gt__

I suspect someone will say that this section of the manual is trying
to tell us this:
"""
There are no reflected (swapped-argument) versions of these methods
(to be used when the left argument does not support the operation but
the right argument does); rather, __lt__() and __gt__() are each
other's reflection, __le__() and __ge__() are each other's reflection,
and __eq__() and __ne__() are their own reflection.
"""
... "trying" being the operative word :-)

Alternatively, do you really need rich comparison? Consider defining
__cmp__ instead of 2 to 6 of the __lt__ etc brigade.

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying message when interrupting python scripts

2008-06-17 Thread John Machin
On Jun 18, 12:51 am, geoffbache <[EMAIL PROTECTED]> wrote:
[snip]
> Is this a bug? I couldn't find any code, but I imagine something like
> try:
>  import site
> except:
>  sys.stderr.write("import site failed; use -v for traceback\n")
>
> which should surely allow a KeyboardInterrupt exception through?
>

Surely?? A bare "except" catches *all* remaining uncaught exceptions.
Allowing a KeyboardInterrupt exception through would require:
   except KeyboardInterrupt:
  pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: 32 bit or 64 bit?

2008-06-17 Thread Phil Hobbs

[EMAIL PROTECTED] wrote:


That was suggested. Problem is, that sometimes the velocities are near
zero. So this solution, by itself, is not general enough.


Are you sure?  I sort of doubt that you're spending zillions of 
iterations getting closer and closer to zero.   It would be worth 
actually doing the error analysis and finding out.


Cheers,

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


Multiprecision arithmetic library question.

2008-06-17 Thread Michael Press
I already compiled and installed the GNU multiprecision library
on Mac OS X, and link to it in C programs. 
How do I link to the library from Python? 
I do not want to download and install redundant material.
(I am new to Python)

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


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Gabriel Genellina
En Tue, 17 Jun 2008 09:09:41 -0300, Derek Martin <[EMAIL PROTECTED]>  
escribió:



On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote:

> Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)'
> and 'not(id(a) == id(b))'

No.


Sure it is... he said "similar"... not identical.  They are not the
same, but they are similar.


'equality' and 'identity' are similar too, so the whole answer would make  
no sense in that case. You can't explain identity based on things that  
aren't identical. A fine grained question for a fine grained difference  
requires a fine grained answer.



Saying a flat "no" alone, without qualifying your statement is
generally interpreted as rude in English...  It's kind of like how you
talk to children when they're too young to understand the explanation.
Yucky.


I didn't meant to be rude at all - and I apologize to Mr. Lie. The  
explanation for such strong "No" was in the paragraph below it (the idea  
was to say: "No to this, yes to that")


--
Gabriel Genellina

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


How do I create user-defined warnings?

2008-06-17 Thread Clay Hobbs
I already know how to make user-defined exceptions, like this one:

class MyException(Exception):
pass

But for a module I'm making, I would like to make a warning (so it just
prints the warning to stderr and doesn't crash the program).  I have
tried this:

class MyWarning(Warning):
pass

And it behaves like a normal error.  Please help me, I can't figure out
what I'm doing wrong.

-- 
Ratfink

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


Re: Decimals in python

2008-06-17 Thread Ethan Furman

[EMAIL PROTECTED] wrote:

Hello. New to using Python. Python automatically round off watver i
calculate using the floor function. How wud i make the exact value
appear?

Tried out fabs() in the math library but still confused. Cud some1
elaborate on it.


[python]
---help(math.floor):
Help on built-in function floor in module math:

floor(...)
floor(x)

Return the floor of x as a float.
This is the largest integral value <= x.
[/python]

The whole point of floor() is to round down.  If you want to see all the 
decimals, don't use floor(), and follow Aidan's advice to have at least 
one floating-point number in the calculation.

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


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Asun Friere
On Jun 17, 5:33 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 17 Jun 2008 02:25:42 -0300, Lie <[EMAIL PROTECTED]> escribió:

>
> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)'
> > and 'not(id(a) == id(b))'
>
> No.
...
> ... The above statement is not. A counterexample:
>
> py> [] is []
> False
> py> id([])==id([])
> True
>
But that's not what he said, he used 'a' and 'b' which are names, not
anonymous objects.
Fairer would be,
a = [];b = []
id(a) == id(b)

Morevover, Lie wrote "id(a)==id(b)".  Since there is no need for the
anonymous object to persist following id testing, you cannot guarantee
that you are comparing an id of two objects (as referred to by 'a' and
'b').  Haven't you, in effect, tested id(a) == id(a)?  While this
might be an interesting effect, I doubt that it clarifies the
difference between equivalence and identity testing, in the way Lie's
statement in fact does.

Also in considering what equivalence means in python reference ought
to be made to the __eq__ method.  The original querant may care to
look it up.




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


Re: Annoying message when interrupting python scripts

2008-06-17 Thread Ben Finney
John Machin <[EMAIL PROTECTED]> writes:

> On Jun 18, 12:51 am, geoffbache <[EMAIL PROTECTED]> wrote:
> [snip]
> > Is this a bug? I couldn't find any code, but I imagine something like
> > try:
> >  import site
> > except:
> >  sys.stderr.write("import site failed; use -v for traceback\n")
> >
> > which should surely allow a KeyboardInterrupt exception through?
> 
> Surely?? A bare "except" catches *all* remaining uncaught exceptions.

I parsed that "should" as "this should be changed".

> Allowing a KeyboardInterrupt exception through would require:
>except KeyboardInterrupt:
>   pass

Actually, to allow it through would require re-raising it:

except KeyboardInterrupt:
raise

Yes, I think that's what Geoff is saying "should" be done :-)

-- 
 \  "When I was born I was so surprised I couldn't talk for a year |
  `\ and a half."  -- Gracie Allen |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I create user-defined warnings?

2008-06-17 Thread Hans Nowak

Clay Hobbs wrote:

I already know how to make user-defined exceptions, like this one:

class MyException(Exception):
pass

But for a module I'm making, I would like to make a warning (so it just
prints the warning to stderr and doesn't crash the program).  I have
tried this:

class MyWarning(Warning):
pass

And it behaves like a normal error.  Please help me, I can't figure out
what I'm doing wrong.


Are you using the warning with 'raise'?  Don't do that, use warnings.warn 
instead:

In [1]: import warnings

In [2]: class MyWarning(Warning): pass
   ...:

In [3]: warnings.warn(MyWarning("bah humbug"))
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/IPython/FakeModule.py:1: 
MyWarning: bah humbug

  # -*- coding: utf-8 -*-

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
--
http://mail.python.org/mailman/listinfo/python-list


One more socket programming question

2008-06-17 Thread John Salerno
I'm now experimenting with the SocketServer class. Originally I 
subclassed the StreamRequestHandler to make my own custom handler, but a 
result of this seems to be that the client socket closes after it has 
been used, instead of staying open.


Just as a test, I decided to use BaseRequestHandler instead, because I 
know its methods aren't implemented. So this is what I have:


-
import SocketServer

host = ''
port = 51234
address = (host, port)
buffer_size = 1024

class MyRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
print '...connected from:', self.client_address
data = self.request.recv(buffer_size)
self.request.send('%s %s' % ('You typed:', data))

socket_server = SocketServer.TCPServer(address, MyRequestHandler)
print 'waiting for connection...'
socket_server.serve_forever()
--

--
from socket import *

host = 'localhost'
port = 51234
address = (host, port)
buffer_size = 1024

client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(address)

while True:
data = raw_input('> ')
if not data:
break
client_socket.send(data)
data = client_socket.recv(buffer_size)
print data

client_socket.close()
--

But this only seems to work one time, and then subsequent attempts 
return nothing, and then the client program seems to crash (or just 
close on its own).


What's happening here?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying message when interrupting python scripts

2008-06-17 Thread John Machin
On Jun 18, 12:26 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> John Machin <[EMAIL PROTECTED]> writes:
> > On Jun 18, 12:51 am, geoffbache <[EMAIL PROTECTED]> wrote:
> > [snip]
> > > Is this a bug? I couldn't find any code, but I imagine something like
> > > try:
> > >  import site
> > > except:
> > >  sys.stderr.write("import site failed; use -v for traceback\n")
>
> > > which should surely allow a KeyboardInterrupt exception through?
>
> > Surely?? A bare "except" catches *all* remaining uncaught exceptions.
>
> I parsed that "should" as "this should be changed".
>
> > Allowing a KeyboardInterrupt exception through would require:
> >except KeyboardInterrupt:
> >   pass
>
> Actually, to allow it through would require re-raising it:
>
> except KeyboardInterrupt:
> raise
>
> Yes, I think that's what Geoff is saying "should" be done :-)

And all of what he was saying or not saying or should have been saying
was prefaced by "I imagine" anyway :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiprecision arithmetic library question.

2008-06-17 Thread casevh
On Jun 17, 5:13 pm, Michael Press <[EMAIL PROTECTED]> wrote:
> I already compiled and installed the GNU multiprecision library
> on Mac OS X, and link to it in C programs.
> How do I link to the library from Python?
> I do not want to download and install redundant material.
> (I am new to Python)
>
> --
> Michael Press

GMPY provides the interface between Python and GMP. It is available at

http://code.google.com/p/gmpy/downloads/list

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


  1   2   >