Re: Getting not derived members of a class

2005-08-01 Thread Jeff Epler
On 'y', Python has no way of recording where '_a' and '_b' were set, so
you can't tell whether it comes from class 'a' or 'b'.

You can find the attributes that are defined on 'b' only, though, by
using 'b.__dict__.keys()', or 'y.__class__.__dict__.__keys__()'.  This
gives
['__module__', 'who1', '__init__', '__doc__']

If you want to limit yourself to current versions of cpython (because the
bytecode used in cpython is only an implementation detail) and define a 'member
of class a' as one where a.__init__ has a statement like 'self.z = ...', you
can peer into the bytecodes.  Something like this:
from dis import HAVE_ARGUMENT, opname
LOAD_FAST = chr(opname.index('LOAD_FAST'))
STORE_ATTR = chr(opname.index('STORE_ATTR'))
HAVE_ARGUMENT = chr(HAVE_ARGUMENT)

def find(cls):
ns = cls.__dict__
result = ns.keys()
init = ns.get('__init__', None)
if not init: return ns
f = ns['__init__'].func_code.co_code
n = ns['__init__'].func_code.co_names
i = 0
while i < len(f) - 6:
if (f[i] == LOAD_FAST and f[i+1] == f[i+2] == '\0'
and f[i+3] == STORE_ATTR):
j = ord(f[i+4]) + 256 * ord(f[i+5])
result.append(n[j])
i += 6
elif f[i] > HAVE_ARGUMENT:
i += 3
else:
i += 1
return result

>>> import franz
>>> franz.find(y.__class__)
['__module__', 'who1', '__init__', '__doc__', '_b']

Jeff


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

Re: Newb: Telnet 'cooked data','EOF' queries.

2005-07-31 Thread Jeff Epler
On Sun, Jul 31, 2005 at 01:30:43PM +0100, glen wrote:
> Could someone explain what "cooked data" is.

The telnet protocol contains special sequences which are interpreted by
the telnet client or server program.  These are discussed in the telnet
RFC, which is RFC854 according to the telnetlib docstring.

"Cooked" data is data after these special sequences are removed.

> Also when trying read_all() the program seems to lock up, which I assume 
> is because it is waiting for an EOF, but 'when' is an EOF received.

As far as I know, the only EOF in telnet is when the other side closes
the socket.

Jeff


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

Re: A replacement for lambda

2005-07-30 Thread Jeff Epler
On Fri, Jul 29, 2005 at 10:14:12PM -0700, Tim Roberts wrote:
> C++ solves this exact problem quite reasonably by having a greedy
> tokenizer.  Thus, that would always be a left shift operator.  To make it
> less than and a function, insert a space:
> < 

Incidentally, I read in an article by Bjarne Stroustrup[1] that "C++0x" will 
parse
vector> v;
just like today's compilers parse
vector > v;

Another of the changes he discusses, letting 'auto i = ...' create i
with the type of the expression '...', will certainly be an improvement.
Even better if the keyword 'auto' could be made optional!  (Of course,
this is another break with C, where the declaration 
auto i;
makes 'i' an int)

And what's this got to do with Python?  I dunno.  Sorry.

Jeff
[1] 
http://www.informit.com/content/images/art_stroustrup_2005/elementLinks/rules.pdf


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

Re: poplib.POP3.list() returns extra value?

2005-07-28 Thread Jeff Epler
With a judicious bit of UTSL, that count seems to be the total number of
octets in the reply.  This information comes from any user of
_getlongresp(), which actually returns a tuple (resp, list, octets).
These methods would be:
list
retr
top
uidl

I'd consider it a doc bug too.  If you feel comfortable doing it, dive
in and improve the documentation of poplib.  Submitting a patch to the
patch tracker on sf.net/projects/python is probably the best way to do
this, if you have the necessary knowledge of cvs to produce a patch.

Jeff


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

Re: codecs.getencoder encodes entire string ?

2005-07-28 Thread Jeff Epler

On Thu, Jul 28, 2005 at 08:42:57AM -0700, nicolas_riesch wrote:
> And a last question: can I call this "enc" function from multiple
> threads ?

Yes.

Jeff


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

Re: Stripping C-style comments using a Python regexp

2005-07-27 Thread Jeff Epler
#
import re, sys

def q(c):
"""Returns a regular expression that matches a region delimited by c,
inside which c may be escaped with a backslash"""

return r"%s(\\.|[^%s])*%s" % (c, c, c)

single_quoted_string = q('"')
double_quoted_string = q("'")
c_comment = r"/\*.*?\*/"
cxx_comment = r"//[^\n]*[\n]"

rx = re.compile("|".join([single_quoted_string, double_quoted_string,
c_comment, cxx_comment]), re.DOTALL)

def replace(x):
x = x.group(0)
if x.startswith("/"): return ' '
return x

result = rx.sub(replace, sys.stdin.read())
sys.stdout.write(result)
#

The regular expression matches ""-strings, ''-character-constants,
c-comments, and c++-comments.  The replace function returns ' ' (space)
when the matched thing was a comment, or the original thing otherwise.
Depending on your use for this code, replace() should return as many
'\n's as are in the matched thing, or ' ' otherwise, so that line
numbers remain unchanged.

Basically, the regular expression is a tokenizer, and replace() chooses
what to do with each recognized token.  Things not recognized as tokens
by the regular expression are left unchanged.

Jeff
PS this is the test file I used:
/* ... */ xyzzy;
456 // 123
const char *mystr =  "This is /*trouble*/";
/* * */
/* /* */
// /* /* */
/* // /* */
/*
 * */


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

Re: Tkinter - Resizing a canvas with a window

2005-07-26 Thread Jeff Epler
You should just use 'pack' properly.  Namely, the fill= and expand=
parameters.  In this case, you want to pack(fill=BOTH, expand=YES).
For the button, you may want to use pack(anchor=E) or anchor=W to make
it stick to one side of the window.

The additional parameters for the button (both creation and packing)
give a geometry that is closer to the standard buttons in Windows 95
/ Windows 2000.  Use those or not, as you see fit.

Here's the new program:

from Tkinter import *

class testApp2:
 def __init__( self, master ):
 self.ma = master
 self.f = Frame( self.ma )
 self.f.pack(fill=BOTH, expand=YES)
 self.cv = Canvas(self.f, width=25, height=25, bg='red')
 self.cv.pack(fill=BOTH, expand=YES)
 self.b1 = Button( self.f, text='Hello', height=1, width=10,
padx=0, pady=1)
 self.b1.pack(side=BOTTOM, anchor=E, padx=4, pady=4)



root = Tk()
app = testApp2(root)
root.mainloop()

Jeff
PS thanks for including a full, runnable program in your post!


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

Re: How to realize ssh & scp in Python

2005-07-24 Thread Jeff Epler
Rather than doing anything with passwords, you should instead use public
key authentication.  This involves creating a keypair with ssh_keygen,
putting the private key on the machine opening the ssh connection
(~/.ssh/id_rsa), then listing the public key in the remote system's
~/.ssh/authorized_keys.

If you don't want to use this approach, `pexpect'[1] is supposed to be able
to perform this sort of tasks, and one of its examples is called
`sshls.py'.  I just downloaded it, and after changing the ssh
commandline to include
-o 'PreferredAuthentications password'
it worked for me.  In another recent thread, a different poster claimed
it didn't work, so your results may vary.

Jeff
[1] http://pexpect.sourceforge.net/


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

Re: Question about namespaces and import. How to avoid calling os.system

2005-07-22 Thread Jeff Epler
In main.py, execfile("gen.py")

or

In gen.py, have something like
from __main__ import env_params

or

In main.py, have something like
import __builtins__; __builtins__.env_params = env_params

or

call a function in the gen.py with env_params as a parameter
import gen
gen.do(env_params)

Jeff


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

Re: Getting TypeError in Changing file permissions

2005-07-22 Thread Jeff Epler
If you are using Unix, and all you have is the file object, you can use
os.fchmod(outfile.fileno(), 0700)

Jeff


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

Re: Mapping a drive to a network path

2005-07-22 Thread Jeff Epler
in fact, see this thread, it may have something useful for you:
http://mail.python.org/pipermail/python-win32/2003-April/000959.html

Jeff


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

Re: Mapping a drive to a network path

2005-07-22 Thread Jeff Epler
import os
os.system(r"net use z: \\computer\folder")

Something in the win32net module of win32all may be relevant if you
don't want to do it through os.system:

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32net__NetUseAdd_meth.html

Jeff


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

Re: time.time() under load between two machines

2005-07-22 Thread Jeff Epler
What makes you believe that the two machines' clocks are perfectly
synchronized?  If they're not, it easily explains the result.

I wrote a simple client/server program similar to what you described.
Running on two RedHat 9 machines on a local network, I generally
observed a time delta of 2ms (compared to typical 0.17ms latency
reported by "ping"), never in a negative direction.  These machines
times are synchronized by ntpd from the package ntp-4.1.2-0.rc1.2.

My program can be run like this:
rsh otherhost python timely.py -s | python timely.py -r
the values printed are the difference between the remote time before the
message is sent and the local time after the message is received.

You mention using Windows.  I don't know whether Windows machines by
default use anything as sophisticated as ntpd to keep their clocks
accurate.

Whatever is going on in your case, I suspect it is the operating system,
not Python.

Jeff

import os, sys, time

def serve():
while 1:
data = struct.pack("!d", time.time())
os.write(1, data)
time.sleep(1)

def recv(fileno):
while 1:
data = struct.unpack("!d", os.read(fileno, 8))[0]
now = time.time()
print now - data

if sys.argv[1] == "-s":
serve()
else:
recv(0)


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

Re: Filling up commands.getstatusoutput's buffer

2005-07-21 Thread Jeff Epler
On Wed, Jul 20, 2005 at 03:10:49PM -0700, [EMAIL PROTECTED] wrote:
> Hey,
> 
> Has anyone ever had commands.getstatusoutput's buffer fill up when
> executing a verbose command? [...]

How much output are you talking about?  I tried outputs as large as
about 260 megabytes without any problem. (RedHat 9, Python 2.2)

>>> len(commands.getoutput("dd if=/dev/zero bs=512 count=512000 2>/dev/null"))
262144000
>>> 512 * 512000
262144000

Jeff


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

Re: Image orientation and color information with PIL?

2005-07-18 Thread Jeff Epler
On Mon, Jul 18, 2005 at 10:55:42AM -0600, Ivan Van Laningham wrote:
> How are you going to determine the orientation of an image without
> sophisticated image analysis? There is research on automatic image
> orientation detection.
[...]
> If you write it I'll use it;-)

There's research going on in this area.  Here are a few papers:
http://www.dcs.shef.ac.uk/teaching/eproj/msc2004/abs/m3zs2.htm
http://research.microsoft.com/research/pubs/view.aspx?pubid=918
there are probably many others.

I considered implementing one of these algorithms back in 2003 or so,
but instead I bought a digital camera with an orientation sensor.

Jeff


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

Re: Image orientation and color information with PIL?

2005-07-18 Thread Jeff Epler
>>> i = Image.open("blue.jpg")
>>> i.size
(3008, 2000)
>>> i.mode
'RGB'

'RGB' is the value for color jpeg images.  I believe that for black&white
images, i.mode is 'L' (luminosity).

If you want to determine whether an existing image is landscape or portrait,
then just compare i.size[0] (width) and i.size[1] (height).

If by "determine if an image is horizontal/vertical", you want to find
the orientation data recorded by some digital cameras, you can do that
with PIL 1.1.4.  According to the release notes for 1.1.4,
+ Added experimental EXIF support for JPEG files.  To extract EXIF
  information from a JPEG file, open the file as usual, and call the
  "_getexif" method.  If successful, this method returns a dictionary
  mapping EXIF TIFF tags to values.  If the file does not contain EXIF
  data, the "_getexif" method returns None.

  The "ExifTags" module contains a dictionary mapping tags to tag
  names.

  This interface will most likely change in future versions.

The exif tag 274 is Orientation.  The values you'll see most often are 1
(Normal), 6 and 8 (90 and 270 degree rotations).  Orientation can also encode
180 degree rotation, as well as any of the four rotations combined with a
mirror operation.

>>> [k for (k,v) in ExifTags.TAGS.items() if v == 'Orientation']
[274]
>>> e = i._getexif()
>>> if e: print e[274]
1

I have written a standalone Python module that reads and changes the EXIF 
orientation data.  You can view it here:

http://unpy.net/cgi-bin/viewcvs.cgi/aethertool/disorient.py?rev=1.2&content-type=text/vnd.viewcvs-markup
It is available under the terms of the GNU GPL.

Here's another page about EXIF orientation data:
http://sylvana.net/jpegcrop/exif_orientation.html

Jeff


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

Re: Opinions on KYLIX 3 (Delphi 4 Linux)

2005-07-18 Thread Jeff Epler
I honestly don't know why anyone would spend money for a development
environment, no matter how fancy.  I don't know why anyone would develop
software in a language that doesn't have at least one open
implementation.

It's a great way to get screwed when Borland goes under or decides
they only want to sell a new, incompatible product.  What do you do with
your existing product when that happens?  Re-train on a new platform,
and re-write from scratch?

Just say no to proprietary software.

Jeff


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

Re: Windows command line problem

2005-07-18 Thread Jeff Epler
I don't exactly know what is going on, but '\x96' is the encoding for
u'\N{en dash}' (a character that looks like the ASCII dash,
u'\N{hyphen-minus}', u'\x45') in the following windows code pages:
cp1250 cp1251 cp1252 cp1253 cp1254
cp1255 cp1256 cp1257 cp1258 cp874

Windows is clearly doing something clever.

Jeff


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

Re: stdin/stdout fileno() always returning -1 from windows service

2005-07-18 Thread Jeff Epler
It seems to simply be common wisdom.  e.g.,
http://mail.python.org/pipermail/python-win32/2004-September/002332.html
http://mail.mems-exchange.org/pipermail/quixote-users/2004-March/002743.html
http://twistedmatrix.com/pipermail/twisted-python/2001-December/000644.html
etc

If you can find chapter and verse on MSDN, more power to you.  This page
implies that the "standard handles" are only available when there is a
console for the application.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getstdhandle.asp

Jeff


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

Re: stdin/stdout fileno() always returning -1 from windows service

2005-07-18 Thread Jeff Epler
On Sun, Jul 17, 2005 at 06:43:00PM -0700, chuck wrote:
> I have found that sys.stdin.fileno() and sys.stdout.fileno() always
> return -1 when executed from within a win32 service written using the
> win32 extensions for Python.
> 
> Anyone have experience with this or know why?

because there *is* no standard I/O for a windows service.

You should be able to execute code like
import sys
sys.stdout = sys.stderr = open("some.log", "w")
if you have code that expects the standard output files to be available.
You could also open sys.stdin in a similar way.

Jeff


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

Re: ssh popen stalling on password redirect output?

2005-07-15 Thread Jeff Epler
In your ssh configuration, specify something like
PreferredAuthentication "hostbased,publickey"
this will skip trying to use the methods called keyboard-interactive and
password.

You can give this flag on the ssh commandline, too.  read the ssh(1) and
ssh_config(5) manpages for more information.

Jeff


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

Re: Browser plug-in for Python?

2005-07-12 Thread Jeff Epler
Back in the day there was 'grail', which was a browser in its own right.
There may also have been a plug-in for other browsers, but I don't know
any real details about them.

Python itself has deprecated the 'restricted execution' environment it
had in previous versions, because ways to break out of the jail existed
or were thought to exist, and nobody stepped forward and offered to
spend the requisite time to create and validate (even in a hand-wavy
kind of way) a new security model.

If you want to write programs in Python and run them in today's
browsers, the shortest path from here to there is jython.  Several
applet demos are available at
http://www.jython.org/applets/index.html

I have used Jython a little bit, but never seriously and not in the past
few years.  Jython implements an older version of the Python
language, corresponding to cPython 2.1 if I remember correctly.

Jeff


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

Re: Parsing Data, Storing into an array, Infinite Backslashes

2005-07-11 Thread Jeff Epler
Your code is needlessly complicated.

Instead of this business
while 1:
try:
i = fetch.next()
except stopIteration:
break
simply write:
for i in fetch:
(if there's an explicit 'fetch = iter(somethingelse)' in code you did
not show, then get rid of that and just loop 'for i in somethingelse')

i[1] will never compare equal to count, because i[1] is always a string
and count is always an integer.  Integers and strings are never equal to
each other.

Wring code like
x = "a string " + 3
does not work in Python.  You can either convert to a string and then
use the + operator to concatenate:
x = "a string " + str(3)
or you can use %-formatting:
x = "a string %s" % 3
("%s" accepts any sort of object, not just strings)

Using repr(...) (`...` is just a shorthand for this) is what is really
introducing the backslashes.  When it outputs a string, it quotes the
string using backslashes.  But you pass the old part of the prepared
string through it each time, which leads to doubling backslashes.

Below is a program I wrote to process the data in your message.  It prints
out
Memory 2 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, 
Slot=DIMM2/J13, ConfigurationType=2
Memory 3 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, 
Slot=DIMM3/J14, ConfigurationType=2
Memory 0 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, 
Slot=DIMM0/J11, ConfigurationType=2
Memory 1 Summary=0, Speed=PC3200U-30330, Type=DDR SDRAM, Size=512, 
Slot=DIMM1/J12, ConfigurationType=2
the result is out of order because the result of calling .items() on a
dict is in an arbitrary order.

Jeff

s = [['Memory', '0', 'Summary', '0'], ['Memory', '0', 'Speed',
 'PC3200U-30330'], ['Memory', '0', 'Type', 'DDR SDRAM'], ['Memory', '0',
 'Size', '512'], ['Memory', '0', 'Slot', 'DIMM0/J11'], ['Memory', '0',
 'ConfigurationType', '2'], ['Memory', '1', 'Summary', '0'], ['Memory',
 '1', 'Speed', 'PC3200U-30330'], ['Memory', '1', 'Type', 'DDR SDRAM'],
 ['Memory', '1', 'Size', '512'], ['Memory', '1', 'Slot', 'DIMM1/J12'],
 ['Memory', '1', 'ConfigurationType', '2'], ['Memory', '2', 'Summary',
 '0'], ['Memory', '2', 'Speed', 'PC3200U-30330'], ['Memory', '2',
 'Type', 'DDR SDRAM'], ['Memory', '2', 'Size', '512'], ['Memory', '2',
 'Slot', 'DIMM2/J13'], ['Memory', '2', 'ConfigurationType', '2'],
 ['Memory', '3', 'Summary', '0'], ['Memory', '3', 'Speed',
 'PC3200U-30330'], ['Memory', '3', 'Type', 'DDR SDRAM'], ['Memory', '3',
 'Size', '512'], ['Memory', '3', 'Slot', 'DIMM3/J14'], ['Memory', '3',
 'ConfigurationType', '2']]

query = {}

for a, b, c, d in s:
if not query.has_key((a,b)): query[(a,b)] = []
query[(a,b)].append("%s=%s" % (c, d))

for (a,b), v in query.items():
print a, b, ", ".join(v)


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

Re: cursor positioning

2005-07-11 Thread Jeff Epler
Here's a simple module for doing progress reporting.  On systems without
curses, it simply uses "\r" to return the cursor to the first column.
On systems with curses, it also clears to the end of the line.  This
means that when the progress message gets shorter, there aren't droppings
left from the longer ones.

You have to take care that the progress message isn't wider than the
screen, but I don't know a nice way to *find* the width of the screen
that will work on windows and unix.  Hardcoding 80 ain't it either.

import sys

def progress(s):
sys.stderr.write(s + CLEAR_EOL + "\r"); sys.stderr.flush()

try:
import curses
except ImportError:
CLEAR_EOL = ''
else:
curses.setupterm()
CLEAR_EOL = curses.tigetstr("el") or ''

def test():
import time
for j in range(2):
for i in range(100):
progress("Doing item %d, %d%%" % (i * 100, i))
time.sleep(.01)
if __name__ == '__main__': test()


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

Re: About undisclosed recipient

2005-07-09 Thread Jeff Epler
You provided far too little information for us to be able to help.

If you are using smtplib, it doesn't even look at message's headers to
find the recipient list; you must use the rcpt() method to specify each
one.  If you are using the sendmail method, the "to_addrs" list has no
relationship to the headers of the actual message---it simply calls
rcpt() once for each address in to_addrs.  The example in the docstring
doesn't even *have* a To: header in the message!

Jeff


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

Re: Query

2005-07-08 Thread Jeff Epler
python-xlib includes an implementation of the xtest extension, which is
enabled on most users' X servers, and can be used to send arbitrary
keyboard or mouse events.

jeff


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

Re: Strange os.path.exists() behaviour

2005-07-06 Thread Jeff Epler
Pierre wrote:
> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
   ^^^
Here's the bug.  You're using Windows.  It's a filesystem, but not as we know 
it...

Anyway, You are getting exactly what the low-level Windows APIs return.

Here's a small "C" program.  It prints "0" next to the filename if the
file exists, -1 otherwise, as described at

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt__access.2c_._waccess.asp

int main(int argc, char **argv) {
int i;
for(i=1; idir
 Volume in drive C has no label.
 Volume Serial Number is 171D-4D2A

 Directory of C:\TMP\example

07/06/05  03:04p  .
07/06/05  03:04p  ..
07/06/05  03:05p 3 exist
   3 File(s)  3 bytes

C:\TMP\example>x:a.exe exist exist. exist nonexist nonexist. nonexist...
   exist: 0
  exist.: 0
   exist: 0
nonexist: -1
   nonexist.: -1
 nonexist...: -1

C:\TMP\example>type nonexist
The system cannot find the file specified.

C:\TMP\example>type exist


C:\TMP\example>

As you can see, not only does Windows think that "exist" exists, but it can
successfully "type" its contents too!

Jeff


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

Re: math.nroot [was Re: A brief question.]

2005-07-06 Thread Jeff Epler
On Tue, Jul 05, 2005 at 09:49:33PM +0100, Tom Anderson wrote:
> Are there any uses for NaN that aren't met by exceptions?

Sure.  If you can naturally calculate two things at once, but one might
turn out to be a NaN under current rules.

x, y = calculate_two_things()
if isnan(x):
perform_next_step_with_only_y(y)
else:
perform_next_step_with_both(x, y)

Under your scheme, you'd have to write
try:
x, y = calculate_two_things()
except NaNException:
y = calculate_one_thing()
perform_next_step_with_only_y(y)
else:
perform_next_step_with_both(x, y)
and at the very least duplicate the code for calculating 'y', possibly
re-doing a lot of work at runtime too.

Jeff


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

Re: resume upload

2005-07-05 Thread Jeff Epler
probably by using REST.  This stupid program puts a 200 line file by
sending 100 lines, then using REST to set a resume position and sending
the next 100 lines.

import getpass, StringIO, ftplib

lines = ["Line %d\n" % i for i in range(200)]
part1 = "".join(lines[:100])
part2 = "".join(lines[:100])

f = ftplib.FTP('server', 'username', 'password')
f.debugging = True
f.sendcmd('CWD /tmp')
f.storbinary("STOR example", StringIO.StringIO(part1))
f.putcmd('REST %d' % len(part1))
resp = f.getresp();
if resp[0] != '3': raise ftplib.error_reply, resp
f.storbinary("STOR example", StringIO.StringIO(part2))
f.quit()


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

Re: Tkinter + Tcl help

2005-07-05 Thread Jeff Epler
I think you need to write
root.tk.eval('load', '...\\libtcldot.so.0')

When you write
root.tk.eval("x y z")
it's like doing this at the wish/tclsh prompt:
# {x y z}
Not like this:
# x y z
Now, how useful it is to have a command called "x y z", I can't
guess... but tcl would let you do it.

I've also doubled the backslash in your library filename.  When using
windows-style paths in string literals, you must either double the
backslashes, or use r'' strings.  When you don't, it will often work,
but if the character after the un-doubled backslash is one with special
meaning (including the commonly-seen \r and \t, but also other letters)
then you'll get a pathname and an error that leave you scratching your
head.

Jeff


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

Re: importing pyc from memory?

2005-07-04 Thread Jeff Epler
This stupid code works for modules, but not for packages.  It probably has bugs.


import marshal, types

class StringImporter:
def __init__(self, old_import, modules):
self._import = old_import
self._modules = modules

def __call__(self, name, *args):
module = self._modules.get(name, None)
if module is None:
return self._import(name, *args)
code = marshal.loads(module)
mod = types.ModuleType(name)
exec code in mod.__dict__
return mod

def test():
import __builtin__
__builtin__.__import__ = StringImporter(__builtin__.__import__,
{ 'test_importer': open("/usr/lib/python2.3/os.pyc").read()[8:] })

import test_importer
print test_importer.path.join("a", "b")
print test_importer.__doc__

if __name__ == '__main__': test()


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

Re: Trapping user logins in python ( post #1)

2005-07-04 Thread Jeff Epler
I don't know of a portable way for an inetd-style daemon to "listen" for
user logins.

On some systems (including RedHat/Fedora and debian), you may be able to
use PAM to do this.  (pam modules don't just perform authentication,
they can take other actions.  As an example, pam_lastlog "prints the
last login on successful login".  I'm not sure what priviledge a pam
module has when it executes.

A more standard way to do this would be to place lines in /etc/profile
/etc/csh.login and so forth for any other shells used on your system.
RedHat-style systems have an /etc/profile.d where you can drop a file
that will be executed at login, too.  This will, of course, be executed
with the user's privilege level.  Another problem with this approach is
that /etc/profile is executed for a "login shell", but a graphical login
is not a login shell.

Jeff


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

Re: It seems that ZipFile().write() can only write files, how can empty directories be put into it?

2005-07-01 Thread Jeff Epler
This has been discussed before.  One thread I found was
http://mail.python.org/pipermail/python-list/2003-June/170526.html
The advice in that message might work for you.

Jeff


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

Re: Dictionary to tuple

2005-06-28 Thread Jeff Epler
It looks like you want tuple(d.iteritems())

>>> d = {1: 'one', 2: 'two', 3: 'three'}
>>> tuple(d.iteritems())
((1, 'one'), (2, 'two'), (3, 'three'))

You could also use tuple(d.items()).  The result is essentially the
same.  Only if the dictionary is extremely large does the difference
matter. (or if you're using an older version of Python without the
iteritems method)

Jeff


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

Re: Beginner question: Converting Single-Element tuples to list

2005-06-27 Thread Jeff Epler
On Mon, Jun 27, 2005 at 08:21:41AM -0600, John Roth wrote:
> Unfortunately, I've seen that behavior a number of times:
> no output is None, one output is the object, more than one
> is a list of objects. That forces you to have checks for None
> and list types all over the place.

maybe you can at least push this into a single convenience function...

def destupid(x, constructor=tuple, sequencetypes=(tuple, list)):
if x is None: return constructor()
if isinstance(x, sequencetypes): return x
return constructor((x,))

Jeff


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

Re: Frame widget (title and geometry)

2005-06-24 Thread Jeff Epler
Tkinter.Frame instances are not created with "geometry" or "title"
attributes.  Whatever 'classtitle' and 'classtitle2' are, they are not
written to work with Tkinter.Frame instances.

Jeff


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

Re: Frame widget (title and geometry)

2005-06-24 Thread Jeff Epler
It would help if you posted your code, as we're in the dark about
exactly what you tried to do and the error you received.

It sounds like you may be using the wrong type of widget for what you
want.  The terms used in Tk are different than in some other systems.

If you want a separate window with title bar etc, you want to create a
new instance of Tkinter.Toplevel.  It will have methods like wm_title
and wm_geometry.

Newer versions of Tk (8.4 and maybe 8.3) have a widget called
"labelframe" (called Tkinter.LabelFrame in python2.3 and newer) which is the
grooved-border-and-label container used to semantically group related
widgets.

"Frame" widgets are simply containers which are often useful for making
the screen layout work the way you want with pack and grid.

Jeff


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

Re: Is this a bug? I don't know where to start

2005-06-22 Thread Jeff Epler
Your list "targets" contains some values twice.

>>> targets=[97,101,139,41,37,31,29,89,23,19,8,13,131,19,73,97,19,139,79,67,61,17,113,127]
>>> for t in set(targets):
... if targets.count(t) > 1: print t
... 
97
139
19

It looks like the "duplicated" items in the output contain one of the
duplicated items from the input.

Jeff


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

Re: Loop until condition is true

2005-06-22 Thread Jeff Epler
def until(pred):
yield None
while True:
if pred(): break
yield None

def example():
i = 0
for _ in until(lambda: x==0):
x = 10 - i
i += 1
print x, i

example()


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

Re: PEP ? os.listdir enhancement

2005-06-22 Thread Jeff Epler
Why not just define the function yourself?  Not every 3-line function
needs to be built in.

def listdir_joined(path):
return [os.path.join(path, entry) for entry in os.listdir(path)]

dirs = [x for x in listdir_joined(path) if os.path.isdir(x)]

path_size = [(x, getsize(x)) for x in listdir_joined(path) if os.path.isfile(x)]


Jeff


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

Re: utf8 silly question

2005-06-21 Thread Jeff Epler
If you want to work with unicode, then write
us = u"\N{COPYRIGHT SIGN} some text"
You can also write this as
us = unichr(169) + u" some text"


When you have a Unicode string, you can convert it to a particular
encoding stored in a byte string with
bs = us.encode("utf-8")


It's generally a mistake to use the .encode() method on a byte string,
but that's what code like
bs = "\xa9 some text"
bs = bs.encode("utf-8")
does.  It can lull you into believing it works, if the test data only
has US ASCII contents, then break when you go into production and have
non-ASCII strings.

Jeff


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

Re: eval() in python

2005-06-21 Thread Jeff Epler
On Tue, Jun 21, 2005 at 08:13:47AM -0400, Peter Hansen wrote:
> Xah Lee wrote:
> > the doc seems to suggest that eval is only for expressions... it says
> > uses exec for statements, but i don't seem to see a exec function?
> 
> Because it's a statement: http://docs.python.org/ref/exec.html#l2h-563

but the documentation is sooo baaad that it makes babies cry and
maybe spreads herpes too.


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

Re: Embedding Python - Deleting a class instance

2005-06-21 Thread Jeff Epler
I wrote the following module to test the behavior of PyInstance_New.  I
called it something like this:
import vedel

class k:
def __del__(self): print "deleted"

vedel.g(k)

I get output like:
after creation, x->refcnt = 1
doing decref
deleted
after decref

Unless there's a cycle and GC gets involved, all there is to deleting
*anything* in Python is correctly managing the refcount.  On the other
hand, you can never free an object while it is still reachable.  Some
local name "x" may never spontaneously lose the thing it refers to.

/**/
#include 

static PyObject *g(PyObject *s, PyObject *o) {
PyObject *x = PyInstance_New( o, NULL, NULL);
if(x) {
printf("after creation, x->refcnt = %d\n", x->ob_refcnt);
printf("doing decref\n");
Py_DECREF(x);
printf("after decref\n");
} else {
printf("x == NULL\n");
}
Py_INCREF(Py_None);
return Py_None;
}

static PyMethodDef methods[] = {
{"g", (PyCFunction)g, METH_O, NULL},
{NULL},
};

void initvedel(void) {
Py_InitModule("vedel", methods);
}
/**/


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

Re: log in to a website

2005-06-16 Thread Jeff Epler
You may find the third-party modules "ClientForm" and "ClientCookie" to
be useful.

Using ClientForm, the following code uploads a file to a particular web form:
forms = ClientForm.ParseResponse(urllib2.urlopen(url))
f = forms[0]
f.add_file(open(local, "rb"), filename=remote, name="file")
u = f.click("attach")
urllib2.urlopen(u)

A web search should turn up the homepage for these modules.

Jeff


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

Re: Programmatic links in a TKinter TextBox

2005-06-15 Thread Jeff Epler
Based on the location where the user clicked, you can find the
associated tags.  Then you must loop through them to find the one that
gives the "href" value.

Jeff
:r /tmp/link.py

import Tkinter

app = Tkinter.Tk()
text = Tkinter.Text(app)
text.pack()

def click(event):
#this doesn't work
print event
w = event.widget
x, y = event.x, event.y
tags = w.tag_names("@%d,%d" % (x, y))
for t in tags:
if t.startswith("href:"):
print "clicked href %s" % t[5:]
break
else:
print "clicked without href"
return "break"

def show_hand_cursor(event):
event.widget.configure(cursor="hand1")
def show_arrow_cursor(event):
event.widget.configure(cursor="")

# configure text tag
text.tag_config("a", foreground="blue", underline=1)
text.tag_bind("a", "", show_hand_cursor)
text.tag_bind("a", "", show_arrow_cursor)
text.tag_bind("a", "", click)
text.config(cursor="arrow")

#add text
text.insert(Tkinter.INSERT, "click here!", "a")
text.insert(Tkinter.INSERT, "\n")

#add a link with data
href = "http://www.example.com";
text.insert(Tkinter.END, "this is a ")
text.insert(Tkinter.END, "link", ("a", "href:"+href))


app.mainloop()


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

Re: Strange socket problem

2005-06-15 Thread Jeff Epler
When using os.system(), files that are open in the parent are available
in the child, as you can see here in Linux' listing of the files open by
the child program:

[EMAIL PROTECTED] jepler]$ python -c 'f = open("/tmp/test", "w"); print 
f.fileno(); import os; os.system("ls -l /proc/self/fd")'
3
total 5
lrwx--  1 jepler jepler 64 Jun 15 07:25 0 -> /dev/pts/2
lrwx--  1 jepler jepler 64 Jun 15 07:25 1 -> /dev/pts/2
lrwx--  1 jepler jepler 64 Jun 15 07:25 2 -> /dev/pts/2
l-wx--  1 jepler jepler 64 Jun 15 07:25 3 -> /tmp/test
lr-x--  1 jepler jepler 64 Jun 15 07:25 4 -> /proc/3108/fd

You may be able to set the FD_CLOEXEC flag on the files that should not
be passed to children, something like this:
old = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
Refer to a real Unix reference for more information on what FD_CLOEXEC
does.

You may want to replace the use of os.system() with fork + close files
+ exec.  Then "myserver.py" will no longer have the listening socket
descriptor of your cherrypy server.

Python 2.4's 'subprocess' module may work better in this respect than
os.system.  It seems to include support for requesting that fds be
closed in the child (the close_fds parameter to subprocess.Popen)

Jeff


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

Re: [Python-Dev] A bug in pyconfig.h under Linux?

2005-06-14 Thread Jeff Epler
[sent to python-list and poster]

Did you follow the direction that Python.h be included before any system
header?

This is mentioned at least in
http://docs.python.org/ext/simpleExample.html

It's a crummy thing for Python to insist on, but if you can re-organize
your headers to do this it should make the warnings go away.

Jeff


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

Re: Get drives and partitions list (Linux)

2005-06-12 Thread Jeff Epler
Using /proc/partitions is probably preferable because any user can read
it, not just people who can be trusted with read access to drives, and
because the format of /proc/partitions is probably simpler and more
stable over time.

That said, what you do is
import commands
fdisk_output = commands.getoutput("fdisk -l %s" % partition)
followed by some specialized code to parse the output of 'fdisk -l'
The following code is not at all tested, but might do the trick.

# python parse_fdisk.py
/dev/hda4 blocks=1060290 bootable=False partition_id_string='Linux swap' 
partition_id=130 start=8451 end=8582
/dev/hda1 blocks=15634048 bootable=True partition_id_string='HPFS/NTFS' 
partition_id=7 start=1 end=1947
/dev/hda3 blocks=9213277 bootable=False partition_id_string='W95 FAT32 (LBA)' 
partition_id=12 start=8583 end=9729
/dev/hda2 blocks=52235347 bootable=False partition_id_string='Linux' 
partition_id=131 start=1948 end=8450

# This source code is placed in the public domain
def parse_fdisk(fdisk_output):
result = {}
for line in fdisk_output.split("\n"):
if not line.startswith("/"): continue
parts = line.split()

inf = {}
if parts[1] == "*":
inf['bootable'] = True
del parts[1]
else:
inf['bootable'] = False

inf['start'] = int(parts[1])
inf['end'] = int(parts[2])
inf['blocks'] = int(parts[3].rstrip("+"))
inf['partition_id'] = int(parts[4], 16)
inf['partition_id_string'] = " ".join(parts[5:])

result[parts[0]] = inf
return result

def main():
import commands
fdisk_output = commands.getoutput("fdisk -l /dev/hda")
for disk, info in parse_fdisk(fdisk_output).items():
print disk, " ".join(["%s=%r" % i for i in info.items()])

if __name__ == '__main__': main()


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

Re: count string replace occurances

2005-06-12 Thread Jeff Epler
On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote:
> if i have
> mytext.replace(a,b)
> how to find out many many occurances has been replaced?

The count isn't returned by the replace method.  You'll have to count
and then replace.

def count_replace(a, b, c):
count = a.count(b)
return count, s.replace(b, c)

>>> count_replace("a car and a carriage", "car", "bat")
(2, 'a bat and a batriage')



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

Re: TKinter -- '' event executing more than once?

2005-06-12 Thread Jeff Epler
For me, an 'is' test works to find out what widget the event is taking
place on.

#
import Tkinter

def display_event(e):
print "event received", e.widget, e.widget is t

t = Tkinter.Tk()
t.bind("", display_event)
w = Tkinter.Entry(t)
t.destroy()
#

This program prints:
event received .-1209415348 False
event received . True

if that fails, you could compare str(e.widget) and t._w, though this can
give a false positive if you have multiple Tk() instances---each Tk()
instance is called ".".

Jeff


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

Re: Hiding X windows

2005-06-11 Thread Jeff Epler
You may want to use a standalone program to do this.  "xwit" has the
ability to iconify a window which can be selected in a variety of ways.
http://hpux.connect.org.uk/hppd/hpux/X11/Misc/xwit-1.0/man.html

There's a direct Python interface to the X protocol in python-xlib.  You
could re-write the common function "Select_Window()" from dsimple.c in
the X source distribution.  One (old) copy is here:
http://ftp.rge.com/pub/X/X11R6.4/xc/programs/xwininfo/dsimple.c

Having done that, I'm not entirely sure how you proceed to hide the
window.  You might follow the directions in the ICCCM on how to iconify
or withdraw a window (http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4),
or you might follow the EWMH document
(http://standards.freedesktop.org/wm-spec/wm-spec-1.4.html#id2507242)

Jeff


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

Re: Socket Speed

2005-06-06 Thread Jeff Epler
The machines with the 100mbps ethernet link are slightly
different---Pentium 4, 2.8GHz, Python 2.2, RedHat 9.

File size: 87490278

Best of 4 runs: 7.50 MB/s reported by "wget".

There was other network activity and system load at the time.

Jeff


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

Re: PyArg_ParseTuple and dict

2005-06-05 Thread Jeff Epler
I tried to recreate the problem based on what you described in your
message.  I was unable to recreate the problem.

I wrote the following file "sjh.c":

#include 

PyObject *f(PyObject *self, PyObject *args) {
PyObject *ob = NULL;
if(!PyArg_ParseTuple(args, "O", &ob)) return NULL;
Py_INCREF(Py_None); 
return Py_None;
}

PyMethodDef methods[] = {
{"f", (PyCFunction)f, METH_VARARGS, "test function"},
{NULL}
};

void initsjh() {
Py_InitModule3("sjh", methods, "test module");
}

I compiled it for Python 2.3:
$ gcc sjh.c -I/usr/include/python2.3 -L/usr/lib/python2.3/config -lpython2.3 
-shared -o sjh.so

and I tested it:
$ python -c 'import sjh; print sjh.f(1)'
None
$ python -c 'import sjh; print sjh.f({})'
None
$ python -c 'import sjh; print sjh.f({None: None})'
None

Jeff


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

Re: GUI builders considered harmful (Was: anygui, anydb, any opinions?)

2005-06-05 Thread Jeff Epler
On Sun, Jun 05, 2005 at 02:38:16PM -0500, Mike Meyer wrote:
[...]
> The first, and most obvious, thing that GUI builders do is force the
> developer to specify an exact position - if not size - for the
> graphical elements of the UI.
[...]

Certainly some---or even most---builders work like this.  But there's no
reason that a GUI GUI builder can't work in terms of the more
sophisticated layout algorithms that are available in most modern GUI
toolkits.

I've written a GUI builder for Tcl/Tk (some old versions live at
http://unpy.net/~jepler/nf/ but they're very out of date).  The core of
the application is the part that can write Tcl source code to regenerate
the screen as it's currently displayed.

The user can either use graphical tools like "insert widget", "show
properties", "pack earlier/later", "automatically add accelerator keys",
or script the thing by typing in Tcl.  Want to use the grid manager?
Fine, go ahead.  The graphical interface to the grid command may be
poor, but the commandline interface works great.  When things are as you
want them, just "save", and you can trivially "source" the resulting Tcl
code from your Tcl/Tk app.

I'm not trying to evangelize Tcl/Tk above any other language/toolkit,
but I am saying that by pairing an interpreted language with a GUI
toolkit, you can get a powerful GUI builder that instantly has top-notch
scrptability and also the guarantee that you can use the powerful
features of the GUI toolkit.  

I didn't do a survey of existing software before writing mine, but I
don't know of another builder that takes this kind of approach.  I
wonder why not.

Jeff


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

Re: Socket Speed

2005-06-05 Thread Jeff Epler
300KB/s sounds dreadfully low.

I simply ran "python /usr/lib/python2.3/SimpleHTTPServer.py &", then
"wget -O /dev/null http://0.0.0.0:8000/70megfile";.  On the best of 4
runs (when the file was cached) wget measured 225.20MB/s.

The hardware is a Pentium-M laptop with 768MB RAM runnng at 1.5GHz.  The
OS is Fedora Core 2, kernel 2.6.12-rc5, Python 2.3.

Jeff


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

Re: method = Klass.othermethod considered PITA

2005-06-04 Thread Jeff Epler
On Sat, Jun 04, 2005 at 10:43:39PM +, John J. Lee wrote:
> 1. In derived classes, inheritance doesn't work right:

Did you expect it to print 'moo'?  I'd have been surprised, and expected
the behavior you got.

> 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do
>this.

In all the versions of Python I've used, classes are pickled by name.
This example you wrote doesn't pose any special problem when pickling.

>>> pickle.dumps(A)
'c__main__\nA\np0\n.'
>>> pickle.dumps(B)
'c__main__\nB\np0\n.'

Jeff


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

Re: thread vs GC

2005-06-02 Thread Jeff Epler
I suspect that getting the threads to die will be tricky, and as written
the thread holds a reference to the 'primegen' instance (this part can
be cured, but it still doesn't ever make the thread exit).

Instead of figuring out how to get this to clean itself up, why not make
sure you only make one 'primegen' instance, using one of the various
singleton patterns?  There may still be something "uncollectable", but
at least there will only be one.

Jeff


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

Re: Easy way to detect hard drives and partitions in Linux

2005-06-02 Thread Jeff Epler
You're not going to find a single portable "unix" way of doing this.
The format of /etc/fstab and /etc/mtab are pretty portable, but they
only list mountable/mounted partitions, not all partitions.

In addition to the linux possibilities mentioned in another reply, there
is also /proc/partitions.  Finally, if you only want to recognize
FDISK.EXE-type partitions (used by many types of Linux, though that
seems to be changing in Fedora Core 4), it shouldn't be hard to write a
Python program to read the partition table directly from the disk.  The
details will be readily available online.

Jeff


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

Re: TkInter Listbox Widget Formatting

2005-06-02 Thread Jeff Epler
This isn't an option in the stock Tk listbox or any of the alternatives
I know of offhand (bwidget ListBox, TixTList).  The TkTable widget,
which can also display multiple columns, can select different
justifications, either for the whole table, or for single cells.
I've never used TkTable with Python/Tkinter, however.

Jeff


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

Re: Unicode string in exec

2005-06-02 Thread Jeff Epler
First off, I just have to correct your terminology.  "exec" is a
statement, and doesn't require parentheses, so talking about "exec()"
invites confusion.

I'll answer your question in terms of eval(), which takes a string
representing a Python expression, interprets it, and returns the result.

In Python 2.3, the following works right:
>>> eval(u"u'\u0190'")
u'\u0190'
Here, the string passed to eval() contains the literal LATIN CAPITAL
LETTER OPEN E, and the expected unicode string is returned

The following behaves "surprisingly":
>>> eval(u"'\u0190'")
'\xc6\x90'
... you seem to get the UTF-8 encoding of the unicode.

This is related to PEP 263 (http://www.python.org/peps/pep-0263.html)
but the behavior of compile(), eval() and exec don't seem to be spelled
out.

Jeff


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

Re: scripting browsers from Python

2005-06-01 Thread Jeff Epler
I wanted to have a Python program make my browser do a POST.  I am using
Firefox on Linux.

Here's what I did:
* Prepare a HTML page on the local disk that looks like this:


http://www.example.com/cgi-bin/example.cgi";>






Submitting form...



* Point the webbrowser at it.  In my case, the webbrowser module didn't work 
immediately so I 
  just used os.system() with a hardcoded browser name for it

Jeff


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

Re: exit after process exit

2005-05-31 Thread Jeff Epler
You might want
os.spawnv(os.P_WAIT, "a.exe", ["a.exe"])

os.system("a.exe")

Jeff


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

Re: Strange behaviour of floating point constants in imported modules

2005-05-23 Thread Jeff Epler
This may be relevant to the problems you're seeing:

https://sourceforge.net/tracker/?func=detail&atid=305470&aid=774665&group_id=5470

The short story, as the tracker item paints it, is that setting
LC_NUMERIC to anything other than 'C' can give results like the ones you
describe---Python itself should never do this, but third parties code
may.

A web search for python LC_NUMERIC should turn up more about this topic,
probably even some past threads on this mailing list/newsgroup.

Jeff


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

Re: Shift-JIS to UTF-8 conversion

2005-05-23 Thread Jeff Epler
On Fri, May 20, 2005 at 12:16:15AM -0700, [EMAIL PROTECTED] wrote:
> Hello, I think the answer is basically correct but shift-jis is not a
> standard part of Python 2.3.

Ah, I was fooled --- I tested on Python 2.3, but my packager must have
included the codecs you went on to mention.

Jeff


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

Re: Shift-JIS to UTF-8 conversion

2005-05-19 Thread Jeff Epler
I think you do something like this (untested):

import codecs

def transcode(infile, outfile, incoding="shift-jis",
outcoding="utf-8"):
f = codecs.open(infile, "rb", incoding)
g = codecs.open(outfile, "wb", outcoding)

g.write(f.read())
# If the file is so large that it can't be read at once, do a loop which
# reads and writes smaller chunks
#while 1:
#block = f.read(4096000)
#if not block: break
#g.write(block)

f.close()
g.close()

Jeff


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

Re: Tkinter special math chars

2005-05-19 Thread Jeff Epler
On Thu, May 19, 2005 at 12:56:12PM -0500, phil wrote:
> Why is it so slow? (RH Linux, 2.4.20, 1.6Ghz AMD)
> 3/4 second slower to display widget w/unicode,
> even if I encode u'\u221e'

u'\u221e' vs u'\N{INFINITY}' should make no noticible run-time
difference--they both specify exactly the same string, and the decoding
takes place at the time the script or module is byte-compiled.

What Tk does at runtime is inspect a large number of fonts until it
finds one with the desired character---or all the fonts, if the
character doesn't exist.  Querying all the fonts on your
system can take quite a bit of time.  I believe that Tk caches this
information until program exit, or at least as long as the font is in
use, and characters that are nearby in their unicode values will be
resolved at the same time.

I'm not aware of a good explanation of the low-level font handling in
Tk; The information in the above paragraph was gleaned by reading the
source code (tkUnixFont.c and tkWinFont.c).

Jeff


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

Re: Tkinter special math chars

2005-05-19 Thread Jeff Epler
I wrote the following code:
import Tkinter
t = Tkinter.Label()
t.configure(
text=u"As the function approaches \N{INFINITY}, \N{HORIZONTAL 
ELLIPSIS}")
t.pack()
t.mainloop()
It worked for me on Windows NT 4.0 with Python 2.4, and on RedHat 9 with
a self-compiled Python 2.3, showing an infinity symbol and an ellipsis.

u'\N{...}' stands for the Unicode character named '...'.  Unicode.org
(and other sites) have lists of Unicode character names. 

Tk tries very hard to find the requested character in some font
available on the system, but when it fails it just displays a unicode
escape sequence like "\u220e" (instead of the END OF PROOF symbol, in
this case), and there's really no way for Python to find out and fall
back in some graceful way.

Relying on this behavior, here's a somewhat-falliable way to detect the
presence of a symbol in the font used in a given widget:
def symbol_exists(s, w, f = None):
if f is None:
f = w.cget("font")
width_symbol = w.tk.call("font", "measure", f, s)
width_bench = w.tk.call("font", "measure", f, "000")
return width_symbol < width_bench
This finds the width in pixels of the given symbol (s) and the string "000", in
the font f.  If the width of the symbol is smaller, then it's probably 
available.
If it's wider, then it's probably rendered as an escape sequence like "\u220e".
This is falliable because there's no guarantee that the symbol would not be as
wide as 000, but also it's possible for some escape code (say \u) to be
narrower than 000.  Neither of these seem very likely in practice.

Jeff


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

Re: Byte-operations.

2005-05-19 Thread Jeff Epler
In Python, "chr" gives a 1-byte string from a small integer, "ord" does
the reverse.  Strings are concatenated with "+" and substrings are taken
with the slice operator, s[pos1:pos2].

I'm not a visual basic expert, but it looks like these are the
operations the code below performs.

Jeff


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

Re: iso_8859_1 mystery/tkinter

2005-05-18 Thread Jeff Epler
this isn't about the "sign bit", it's about assumed encodings for byte
strings..

In iso_8859_1 and unicode, the character with value 0xb0 is DEGREE SIGN.
In other character sets, that may not be true---For instance, in the
Windows "code page 437", it is u'\u2591' aka LIGHT SHADE (a half-tone pattern).

When you write code like
x = '%c' % (0xb0)
and then pass x to a Tkinter call, Tkinter treats it as a string encoded
in some system-default encoding, which could give DEGREE SIGN, could
give LIGHT SHADE, or could give other characters (a thai user of Windows
might see THAI CHARACTER THO THAN, for instance, and I would see a
question mark because I use utf-8 and this is an invalid byte sequence).

By using
x = u'%c' % (0xb0)
you get a unicode string, and there is no confusion about the meaning of
the symbol---you always get DEGREE SIGN.

Jeff


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

Re: Interaction between TclTk editor with Python code

2005-05-17 Thread Jeff Epler
One way to get a handle on some Tcl variables from Python is to create
Tkinter.Variable instances with the names of the existing Tcl variables
(normally, the variable names are chosen arbitrarily).  Once you've done
this, you can do things like add variable traces (the trace_variable
method) on the Python side.  One thing to be aware of is that the Python
object's __del__ will unset the variable on the Tcl side.  Also, this
code sets an initial value for the variable which may or may not be
appropriate in your application.

The code below was ripped from a larger application, so it may or may
not work without modification.

Jeff

# This code is in the public domain
from Tkinter import *
def makevar(master, name, klass, *default):
self = newinstance(klass)
self._master = master
self._tk = master.tk
self._name = name
if default:
self.set(default[0])
else:
self.set(self._default)
return self

def makebool(master, name, *default):
return makevar(master, name, Tkinter.BooleanVar, *default)
def makeint(master, name, *default):
return makevar(master, name, Tkinter.IntVar, *default)
def makefloat(master, name, *default):
return makevar(master, name, Tkinter.DoubleVar, *default)
def makestring(master, name, *default):
return makevar(master, name, Tkinter.StringVar, *default)


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

Re: Recommended version of gcc for Python?

2005-05-16 Thread Jeff Epler
Most versions of gcc should be just fine to compile Python.  Python is
targeted at ANSI/ISO C compilers, but does not yet use any C99 features.

I don't think there was ever such a thing as "gcc 3.5";
http://gcc.gnu.org/ lists 4.0 as the "current release series" and 3.4.3
as the "previous release series".  I'd steer clear of this version.

I recommend using the default compiler of your distribution, unless you
know of a specific reason to use a different one.

Jeff


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

Re: Precision?

2005-05-15 Thread Jeff Epler
If you want to do decimal arithmetic, use the decimal module which is
new in Python 2.4.

Python 2.4 (#1, Jan 22 2005, 20:45:18) 
[GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal as D
>>> D("1.0") + D("3.0") + D("4.6")
Decimal("8.6")
>>> 

when you write '4.6', you get a binary floating-point number which is
not equal to the decimal number 4.6.
>>> 4.6
4.5996
>>> 4.6 == D("4.6")
False

Jeff


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

Re: How "return" no return ?

2005-05-13 Thread Jeff Epler
At the interactive prompt, a result is printed when both these things
are true:
* The entered code is an expression, not any other kind of statement
* The result of the expression is not 'None'
If an expression occurs, information about it will be printed instead.

So the interpreter won't print a result for
>>> a = 3# because it's an assignment statement
>>> def f(): return  # because it's a 'def' statement
>>> None # because the result of the expression is 'None'
>>> f()  # because the result of the expression is 'None'

Your example
>>> int a
is not Python, but if it was it would probably be a non-expression
statement, and thus never print a result in the interpreter.

Jeff


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

Re: Using TCL files in Python ?

2005-05-11 Thread Jeff Epler
While I've never used it, there *is* a Tix module in Python which
appears to wrap the widgets provided by Tix.  In Fedora Core 2, Python
doesn't seem to be configured to use Tix OOTB but a one-liner (that
should be harmless elsewhere) does make it work.

These classes are defined in the Tix module:
['Shell', 'Meter', 'TixSubWidget', 'ExFileSelectDialog',
'NoteBookFrame', 'DirSelectDialog', 'Control', 'LabelEntry',
'ButtonBox', 'ScrolledTList', 'Select', 'HList', 'Balloon', 'PopupMenu',
'DirSelectBox', 'ComboBox', 'ScrolledWindow', 'Grid', 'CheckList',
'DialogShell', 'Tree', 'DirList', 'ResizeHandle', 'NoteBook',
'ListNoteBook', 'ScrolledGrid', 'FileEntry', 'ScrolledHList', 'DirTree',
'OptionMenu', 'ScrolledText', 'LabelFrame', 'FileSelectBox',
'ScrolledListBox', 'InputOnly', 'PanedWindow', 'StdButtonBox',
'FileSelectDialog', 'CObjView', 'ExFileSelectBox', 'TList']

Here's what I did to get a simple Tix widget to work:
>>> import Tkinter, Tix
>>> t = Tkinter.Tk()
>>> t.tk.call("package", "require", "Tix")
'8.1.8.4'
>>> u = Tix.ComboBox(t)
>>> for i in range(30): u.insert("end", "Item %d" % i)
... 
>>> u.pack()

Jeff


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

Re: [HELP] Tkinter Application Minimized to System Tray :)

2005-05-06 Thread Jeff Epler
Tk, the library that Tkinter wraps, does not offer a way to "minimize to
the taskbar".

Jeff


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

Re: New Python regex Doc (was: Python documentation moronicities)

2005-05-06 Thread Jeff Epler
To add to what others have said:

* Typos and lack of spell-checking, such as "occurances" vs "occurrences"

* Poor grammar, such as "Other characters that has special meaning
  includes:"

* You dropped version-related notes like "New in version 2.4"

* You seem to love the use of s, while docs.python.org uses them
  sparingly

* The category names you created, "Wildcards", "Repetition Qualifiers",
  and so forth, don't help me understand regular expressions any better
  than the original document

* Your document dropped some basic explanations of how regular
  expressions work, without a replacement text:
Regular expressions can be concatenated to form new regular
expressions; if A and B are both regular expressions, then AB is
also a regular expression. In general, if a string p matches A and
another string q matches B, the string pq will match AB. [...] Thus,
complex expressions can easily be constructed from simpler primitive
expressions like the ones described here.
  Instead, you start off with one unclear example ("a+" matching
  "hh!") and one misleading example (a regular expression that
  matches some tiny subset of valid e-mail addresses)

* You write
Characters that have special meanings in regex do not have special
meanings when used inside []. For example, '[b+]' does not mean one
or more b; It just matches 'b' or '+'.
  and then go on to explain that backslash still has special meaning; I
  see that the original documentation has a similar problem, but this
  just goes to show that you aren't improving the accuracy or clarity of
  the documentation in most cases, just rewriting it to suit your own
  style.  Or maybe just as an excuse to write offensive things like "[a]
  fucking toy whose max use is as a simplest calculator"

I can't see anything to make me recommend this documentation over the
existing documentation.

Jeff


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

Re: Best way to convert a list into function call arguments?

2005-05-05 Thread Jeff Epler
Your question is answered in the tutorial:
http://docs.python.org/tut/node6.html#SECTION00674

4.7.4 Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or
tuple but need to be unpacked for a function call requiring separate
positional arguments. For instance, the built-in range() function
expects separate start and stop arguments. If they are not available
separately, write the function call with the *-operator to unpack the
arguments out of a list or tuple:

>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)# call with arguments unpacked from a list
[3, 4, 5]

Jeff


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

Re: descriptor dilemma

2005-05-04 Thread Jeff Epler
On Wed, May 04, 2005 at 09:14:18AM -0700, Sébastien Boisgérault wrote:
> 
> Yup ?!? Weird ... especially as:
> 
> >>> id(c.f) == id(C.__dict__['f'].__get__(c,C))
> True

Here, c.f is discarded by the time the right-hand-side of == is
executed.  So the object whose id() is being calculated on the
right-hand-side could turn out to be the same, since the two objects
have disjoint lifetimes.

Here are some more cases of the same thing:
>>> id([]) == id([])
1
>>> id([]) == id([1])
1

Jeff


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

Re: A faster method to generate a nested list from a template?

2005-05-04 Thread Jeff Epler
Are there only a few, unchanging templates?  If so, (dynamiclly) create
a function for each template.  This will be nearly the fastest you can
go in Python, excluding the time to create and byte-compile the nesting
function.

# This code is in the public domain
def make_nesting_expression(l, s):
result = []
for c in l:
if isinstance(c, list):
sub, s = make_nesting_expression(c, s)
result.append(sub)
else:
result.append("l[%d]" % s)
s += 1
print "make_nesting_expression", l, result
return "[" + ",".join(result) + "]", s

def make_nesting_function(l):
return eval("lambda l: %s" % make_nesting_expression(l, 0)[0])

t = [['a1','a2'],['b1'],['c1'],['d1']]
l = [1, 2, 3, 4, 5]
f = make_nesting_function(t)
print f(l)

Jeff


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

Re: How to read an integer value from a binary file?

2005-05-03 Thread Jeff Epler
As your 'for' loop shows, the number of items in the slice [2:5] is only
3, not 4.

Maybe you want the slice [2:6] instead.

>>> x = "xx\xb6/\0\0"
>>> struct.unpack('i', x[2:6])
(12214,)

Jeff


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

Re: cgi "print statement" in multithreaded enviroment?

2005-05-02 Thread Jeff Epler
You could write something like
class ThreadSpecificFile:
def set_stdout(f):
self.files[thread_id] = f
def write(data):
self.files[thread_id].write(data)
sys.stdout = ThreadSpecificFile()
where you'll have to fill out a few more things like thread_id,
__init__, and a way to clean up items from self.files when a thread
passes away.

Jeff


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

Re: How to track down all required shared libraries?

2005-04-30 Thread Jeff Epler
One poster suggests 'ldd' for executables.  You can also use this on shared
libraries:
$ ldd /usr/lib/python2.3/lib-dynload/_tkinter.so 
libtix8.1.8.4.so => /usr/lib/libtix8.1.8.4.so (0x009b6000)
libtk8.4.so => /usr/lib/libtk8.4.so (0x00111000)
libtcl8.4.so => /usr/lib/libtcl8.4.so (0x00539000)
libX11.so.6 => /usr/X11R6/lib/libX11.so.6 (0x00a48000)
libpthread.so.0 => /lib/tls/libpthread.so.0 (0x001de000)
libc.so.6 => /lib/tls/libc.so.6 (0x001f)
libdl.so.2 => /lib/libdl.so.2 (0x0052d000)
libm.so.6 => /lib/tls/libm.so.6 (0x00fcf000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x00656000)
If you know what shared modules your program uses, you can "ldd" them all and
find out the set of libraries they are linked to.

Jeff


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

Re: tkinter OptionMenu column break

2005-04-30 Thread Jeff Epler
I don't think that Tk's menus ever use more than one column.  They
certainly don't on Unix.

Jeff


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

Re: python equivalent of php implode

2005-04-27 Thread Jeff Epler
On Tue, Apr 26, 2005 at 09:59:29PM -0500, Mike Meyer wrote:
> Jeff Epler <[EMAIL PROTECTED]> writes:
> 
> > items = query_param.items()
> > keys = [item[0] for item in items]
> > values = [item[1] for item in items]
> 
> Is there some reason not to do:
> 
>keys = query_params.keys()
>values = query_params.values()
> 
> That would seem to be a lot more obvious as to what was going on.

I was afraid that .keys() and .values() might not "match up" (so that
the i'th key maps to the i'th value in query_param).  Now that I've
glanced at the documentation, I see that this *is* guaranteed[1], and
I should have written the code you proposed.

Jeff
[1] http://docs.python.org/lib/typesmapping.html note 3


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

Re: python equivalent of php implode

2005-04-26 Thread Jeff Epler
It looks like php's implode(sep, seq) is like sep.join(seq) in Python.

But this is a lousy way to write database queries.  You should use the
Python's DB-API interface's execute(statement, parameters) instead.
Assuming that paramstyle is 'qmark', I think it ends up looking
something like this:

items = query_param.items()
keys = [item[0] for item in items]
values = [item[1] for item in items]

# If the query parameters or the table are under
# user control you must take care to validate them
assert table in permitted_tables
for k in query_param.keys():
assert k in permitted_keys

sql = "INSERT INTO %s (%s) values %s" % (
table, ", ".join(keys),
", ".join(["?"] * len(keys))
)
conn.execute(sql, values)

now you don't have to worry that you get the quoting of the values
absolutely right, since db-api does it for you.

Jeff


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

Re: Why is Python not supporting full derivation of built-in file class?

2005-04-24 Thread Jeff Epler
This issue was discussed in another recent python-list thread, called
"Writing to stdout and a log file".

My second post includes a patch to Python's "fileobject.c" that made the
code that started that thread work, but for reasons I mentioned in that
post I didn't want to push for inclusion of my patch.  I didn't check,
but it will probably allow your code to work too.

If you feel differently, then the thing to do is probably to submit the
patch plus a test case to the sf.net patch tracker for python
(sf.net/projects/python, click on "patches".  you'll need a sourceforge
account to submit the patch)

Jeff
PS I did allow the Python test suite to run to completion after I wrote
that message.  It didn't produce any failures or unexpected skips on my
platform.


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

Re: Writing to stdout and a log file

2005-04-19 Thread Jeff Epler
In that case, it looks like you won't be able to get what you want
without modifying CPython.  PRINT_ITEM calls PyFile_SoftSpace,
PyFile_WriteString, and PyFile_WriteObject, which all use
PyFile_Check().  It might be as simple as changing these to
PyFile_CheckExact() calls in PyFile_WriteString / PyFile_WriteObject,
but I have no idea whether the test suite still works after this change
is made.  It does make this program work (it prints things from X.write):

class X(file):
def write(self, s):
print "X.write", `s`
return file.write(self, s)

import sys
x = X("/tmp/out.txt", "w")
print >>x, 42

I don't care to be the champion of this patch, or to submit it to
sourceforge; I suspect there should be a better review of PyFile_Check
vs PyFile_CheckExact uses in fileobject.c, instead of just picking the
few spots that make this usage work.  Before being submitted as a patch,
a testcase should be added too.  Feel free to run with this if you feel
strongly about it.

Jeff

Index: Objects/fileobject.c
===
RCS file: /cvsroot/python/python/dist/src/Objects/fileobject.c,v
retrieving revision 2.193
diff -u -u -r2.193 fileobject.c
--- Objects/fileobject.c7 Nov 2004 14:15:28 -   2.193
+++ Objects/fileobject.c20 Apr 2005 02:41:32 -
@@ -2012,7 +2012,7 @@
PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
return -1;
}
-   else if (PyFile_Check(f)) {
+   else if (PyFile_CheckExact(f)) {
FILE *fp = PyFile_AsFile(f);
 #ifdef Py_USING_UNICODE
PyObject *enc = ((PyFileObject*)f)->f_encoding;
@@ -2082,7 +2082,7 @@
"null file for PyFile_WriteString");
return -1;
}
-   else if (PyFile_Check(f)) {
+   else if (PyFile_CheckExact(f)) {
FILE *fp = PyFile_AsFile(f);
if (fp == NULL) {
err_closed();



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

Re: Writing to stdout and a log file

2005-04-19 Thread Jeff Epler
This variation works:
#
class Tee:
def __init__(self, *args):
self.files = args

def write(self, data):
for f in self.files:
result = f.write(data)
return result

def writelines(self, seq):
for i in seq: self.write(i)

import sys
sys.stdout = Tee(sys.stdout, open("/tmp/stdout.log", "w"))

print 'STDOUT', sys.stdout
#

It appears that the 'print' statement always uses file.write if
isinstance(sys.stdout, file).  I don't know whether this has been
reported as a bug before, or if there's a reason for the current
behavior.  It may be an accidental behavior that is left over from the
days when builtin types were not subclassable.

Jeff


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

Re: fpectl

2005-04-19 Thread Jeff Epler
On Tue, Apr 19, 2005 at 02:05:11AM -0700, Sébastien Boisgérault wrote:
> Thanks for this answer.
> 
> Did you forward this info to python-dev ?

I created a patch on the sf tracker.  It's been responded to by several
developers.  You can read what they said there.

http://python.org/sf/1185529

Jeff


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

Re: Tkinter Event Types

2005-04-18 Thread Jeff Epler
The "type" field is related to the definition of different events in
X11.  In Xlib, the event structure is a "C" union with the first
(common) field giving the type of the event so that the event-dependant
fields can be accessed through the proper union member.

Generally, you won't use this field in Tkinter programs.

jeff


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

Re: fpectl

2005-04-18 Thread Jeff Epler
It looks like the automatic build of the 'fpectl' module was broken
somewhere along the line, perhaps when the transition from Modules/Setup
to setup.py took place.

Once I made the change below and rebuilt, I got the fpectl module.
Furthermore, it appeared to "do something" on my Linux/x86 system:

$ ./python -c '1e200 ** 6'
OverflowError: (34, 'Numerical result out of range')
$ ./python -c 'import fpectl; print dir(fpectl); fpectl.turnon_sigfpe(); 1e200 
** 6'
['__doc__', '__file__', '__name__', 'error', 'turnoff_sigfpe', 'turnon_sigfpe']
Fatal Python error: Unprotected floating point exception
Aborted

Jeff


Index: setup.py
===
RCS file: /cvsroot/python/python/dist/src/setup.py,v
retrieving revision 1.217
diff -u -u -r1.217 setup.py
--- setup.py15 Apr 2005 20:32:39 -  1.217
+++ setup.py19 Apr 2005 00:13:15 -
@@ -400,6 +400,8 @@
 # select(2); not on ancient System V
 exts.append( Extension('select', ['selectmodule.c']) )
 
+exts.append( Extension('fpectl', ['fpectlmodule.c']) )
+
 # The md5 module implements the RSA Data Security, Inc. MD5
 # Message-Digest Algorithm, described in RFC 1321.  The
 # necessary files md5c.c and md5.h are included here.


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

Re: New Python regex Doc (was: Python documentation moronicities)

2005-04-18 Thread Jeff Epler
On Mon, Apr 18, 2005 at 01:40:43PM -0700, Xah Lee wrote:
> i have rewrote the Python's re module documentation.
> See it here for table of content page:
> http://xahlee.org/perl-python/python_re-write/lib/module-re.html

For those who have long ago consigned Mr. Lee to a killfile, it looks
like he's making an honest attempt to improve Python's documentation
here.

Mr Lee, I hope you will submit your documentation changes to python's
patch tracker on sourceforge.net.  I don't fully agree with some of what
you've written (e.g., you give top billing to the use of functions like
re.search while I would encourage use of the search method on compiled
RE objetcts, and I like examples to be given as though from interactive
sessions, complete with ">>>" and "..."), but nits can always be picked
and I'm not the gatekeeper to Python's documentation.

Jeff


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

Re: Get the entire file in a variable - error

2005-04-14 Thread Jeff Epler
It's not clear to me what you mean by "the first line" (gzip does not
output a file composed of lines, its output is byte-oriented).

Printing tst.getvalue() is probably not a very useful thing to do, since
it won't do anything useful when the output is a terminal, and it will
add an extra newline if you are redirecting to a file.

At least when close()ing the GzipFile before looking at the StringIO
instance's value, I get some bytes that gunzip just fine, giving the
original string.

Here's my interactive session:
>>> import gzip
>>> import StringIO
>>> io = StringIO.StringIO()
>>> z = gzip.GzipFile("test.gz", "w", 5, io)
>>> z.write("""\
... Python 2.2.2 (#1, Feb 24 2003, 19:13:11) 
... [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2
... Type "help", "copyright", "credits" or "license" for more information.
... """)
>>> z.close()
>>> from os import popen
>>> popen("gunzip -dc", "w").write(io.getvalue())
Python 2.2.2 (#1, Feb 24 2003, 19:13:11) 
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

I don't know anything about your database or its "LONG field".
Depending on the database software there could be additional problems
with embedded NULs, for instance.

Jeff


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

Re: Why won't someone step up and make use of the Free tools (was Re: Python 2.4 killing commercial Windows Python development ?)

2005-04-12 Thread Jeff Epler
On Tue, Apr 12, 2005 at 08:25:58PM +, Bengt Richter wrote:
> But credit where due. Someone has stepped up to a large chunk of the problem:
> 
>http://jove.prohosting.com/iwave/ipython/pyMinGW.html

Yay.  I'm glad somebody *is* doing this.  Maybe all that is needed is to
"get the word out".  Some prepackaged binaries would be nice, however.

Jeff


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

Re: Tkinter "withdraw" and "askstring" problem

2005-04-12 Thread Jeff Epler
The answer has to do with a concept Tk calls "transient".  
wm transient window ?master?
If master is specified, then the window manager is informed that
window  is  a  transient window (e.g. pull-down menu) working on
behalf of master (where master is the path name for a  top-level
window).   If master is specified as an empty string then window
is marked as not being a transient window any  more.   Otherwise
the command returns the path name of windowâs current master, or
an empty string if window isnât currently a transient window.  A
transient  window  will  mirror  state changes in the master and
inherit the state of the master when initially mapped. It is  an
error to attempt to make a window a transient of itself.

In tkSimpleDialog, the dialog window is unconditionally made transient
for the master.  Windows is simply following the documentation: The
askstring window "inherit[s] the state of the master [i.e., withdrawn]
when initially mapped".

The fix is to modify tkSimpleDialog.Dialog.__init__ to only make the
dialog transient for its master when the master is viewable.  This
mirrors what is done in dialog.tcl in Tk itself.  You can either change
tkSimpleDialog.py, or you can include a new definition of __init__ with 
these lines at the top, and the rest of the function the same:
def __init__(self, parent, title = None):
''' the docstring ... '''
Toplevel.__init__(self, parent)
if parent.winfo_viewable():
self.transient(parent)
...

# Thanks for being so dynamic, Python!
tkSimpleDialog.Dialog.__init__ = __init__; del __init__

Jeff


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

Why won't someone step up and make use of the Free tools (was Re: Python 2.4 killing commercial Windows Python development ?)

2005-04-12 Thread Jeff Epler
I'm sorry that this is going to come out sounding like a flame, but it
seems to me that there today only a few technical problems remaining
with Python when built with mingw32.

If one of the people who has expressed such deep concern about this
"msvcr71.dll" problem would simply install the Free tools and start
putting patches on sourceforge, it's quite possible that for the next
2.4.x release the mingw32 "port" could be a first-rate one, and suitable
for the uses that the posters in this thread have mentioned.

Since mingw32 is Free (gpl and other licenses for tools, public domain
libraries and copyrighted headers with "no restrictions for programs"
built using the headers) anyone can install and use these tools and
mingw creates no new problems with distribution of the resulting binary,
whether the final product is Free or proprietary.

(Admittedly I don't know anything about whether "win32all" builds under
mingw32, and it's not clear whether binary compatibility with extensions
built by microsoft compilers is an easy goal either)

http://www.mingw.org/

Jeff


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

Re: help: loading binary image data into memory

2005-04-11 Thread Jeff Epler
probably something like this: (untested)
def make_ftplib_callback(f):
def callback(block): f.write(block)
return callback
img = cStringIO.StringIO()
retrbinary( "get ???", make_ftplib_callback(img))

Jeff


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

Re: curious problem with large numbers

2005-04-07 Thread Jeff Epler
You may want to read
http://www.python.org/peps/pep-0754.html

Part of the text reads
The IEEE 754 standard defines a set of binary representations and
algorithmic rules for floating point arithmetic. Included in the
standard is a set of constants for representing special values,
including positive infinity, negative infinity, and indeterminate or
non-numeric results (NaN). Most modern CPUs implement the IEEE 754
standard, including the (Ultra)SPARC, PowerPC, and x86 processor
series.

Currently, the handling of IEEE 754 special values in Python depends
on the underlying C library. Unfortunately, there is little
consistency between C libraries in how or whether these values are
handled. For instance, on some systems "float('Inf')" will properly
return the IEEE 754 constant for positive infinity. On many systems,
however, this expression will instead generate an error message.

Jeff


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

Re: Read 16 bit integer complex data

2005-04-07 Thread Jeff Epler
You may want to use the 'numeric' or 'numarray' extensions for this.
The page on numarray is here:
http://www.stsci.edu/resources/software_hardware/numarray

numarray doesn't support "complex 16-bit integer" as a type, but you can
get a complex, floating-point valued array from your integer values.
Here's how, with a bit of explanation along the way:

I created a small example: a vector of 2 "complex 16-bit integers" 
in the native byte-order.
>>> s = struct.pack("", 1, 2, 3, 4)
>>> s
'\x01\x00\x02\x00\x03\x00\x04\x00'
I think this stands for the vector <1+2j, 3+4j> according to what you
wrote.

I can turn this into a 4-element numarray like so:
>>> numarray.fromstring(s, "s")
array([1, 2, 3, 4], type=Int16)
and extract the real and complex parts with extended slices:
>>> t[1::2] # take the items 1, 3, ..., 2*n+1 i.e., the complex parts
array([2, 4], type=Int16)

This expression forms the complex 64-bit floating point 2-element array
from 't':
>>> u = t[0::2] + t[1::2] * 1j
>>> u
array([ 1.+2.j,  3.+4.j])

If the byte-order of the file is different from the native byte order,
you can byte-swap it before forming the complex FP array:
>>> t.byteswap()
>>> t
array([ 256,  512,  768, 1024], type=Int16)


Jeff


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

Re: Resticted mode still active (error?)

2005-04-06 Thread Jeff Epler
Is there a script that causes this problem, without using mod_python or
jepp?  If so, please attach it to the sourceforge bug.
http://sourceforge.net/tracker/index.php?func=detail&aid=1163563&group_id=5470&atid=105470


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

  1   2   >