Re: Help beautify ugly heuristic code

2004-12-09 Thread Lonnie Princehouse
Doh!  I misread "a" as host instead of ip in your first post.   I'm
sorry about that; I really must slow down.  Anyhow,

I believe you can still do this with only compiling a regex once and
then performing a few substitutions on the hostname.

Substitutions:

1st byte of IP => (0)
2nd byte of IP => (1)
3rd byte of IP => (2)
4th  byte of IP => (3)
and likewise for hex => (x0)  (x1)  (x2)  (x3)

Each host string will possibly map into multiple expansions, esp. if a
number repeats itself in the IP, or if an IP byte is less than 10 (such
that the decimal and hex representations are the same).  Zero-padded
and unpadded will both have to be substituted, and it's probably best
to not to alter the last two fields in the host name since ISPs can't
change those.

With this scheme, here are a few expansions of (ip,host) tuples:

172.182.240.186  ACB6F0BA.ipt.aol.com
becomes
(x0)(x1)(x2)(x3).ipt.aol.com

67.119.55.77 adsl-67-119-55-77.dsl.lsan03.pacbell.net
becomes
adsl-(0)-(1)-(2)-(3).dsl.lsan03.pacbell.net
adsl-(0)-(1)-(2)-(x1).dsl.lsan03.pacbell.net


81.220.220.143   ip-143.net-81-220-220.henin.rev.numericable.fr
becomes
ip-(3).net-(0)-(1)-(1).henin.rev.numericable.fr
ip-(3).net-(0)-(1)-(2).henin.rev.numericable.fr
ip-(3).net-(0)-(2)-(1).henin.rev.numericable.fr
ip-(3).net-(0)-(2)-(2).henin.rev.numericable.fr

etcetera.

Now you can run a precompiled regular expression against these hostname
permutations, i.e.  ".*\(0\).*\(1\).*\(2\).*\(3\).*" would match any
host in which the IP address numbers appeared in the correct order.

There are only a handful dynamic addresses in your sample data that
don't match a decimal or hexadecimal IP-based pattern, e.g.

68.53.109.99 pcp03902856pcs.nash01.tn.comcast.net
68.147.136.167   s01060050bf91c1e4.cg.shawcable.net

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


Re: How do I do this? (eval() on the left hand side)

2004-12-09 Thread Peter Otten
Caleb Hattingh wrote:

> I am convinced now that locals() doesn't work as (I) expected.  Steven
> says there was some or other reason why locals() as used in this context
> is not writable - Do you know why this is?  I really do not like
> guidelines like "may not work", "is unreliable" and so on.  Perhaps this
> is a character flaw, but I really do like to know what works, when it
> works, and when it doesn't work.

I think Peter Hansen has answered that. Your expectations were just wrong.
 
> In this scenario, we can see it doesn't work.  To my eyes, it doesn't work
> *in the way I expect* (which is highly subjective, no argument there).
> Would this be a situation where it would be nice to have an exception
> thrown if locals() is assigned to in a scope where it is not writable?

If python were to throw an exception, it should always be thrown. But I'm
the wrong one to worry about that as I didn't even find a single 

globals()[name] = value 

assignment in my scripts. I want to know a variable's name, or I put it in a
dictionary.

> It would also be nice if globals and locals behaved the same, differing
> only in scope (which is what I expected originally anyway).  But we can't
> have everything, I guess :)

That would mean that both would become read-only, I guess, but I don't see
that happen.

Peter

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


newbie question: starting external application(win)?

2004-12-09 Thread Frank Esselbach
Hello,

I'am new in python. I need informations, how its possible run another
(non-python) exe file from python without terminate the python system.

I have googeled, but could not find informations that I can understand.
The most informations comes from unix/linux butIneed this for win32.

Thanks a lot, Frank
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I do this? (eval() on the left hand side)

2004-12-09 Thread Nick Coghlan
Peter Hansen wrote:
Nick Coghlan wrote:
Generally, altering the contents of the dicts returned by locals() and 
globals() is unreliable at best.

Nick, could you please comment on why you say this about globals()?
I've never heard of any possibility of "unreliability" in updating
globals() and, as far as I know, a large body of code exists which
does in fact rely on this -- much of mine included. ;-)
As Steve pointed out, I was, well, flat out wrong. You're quite correct - it's 
only locals() that can cause a problem.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree and XPATH

2004-12-09 Thread Fredrik Lundh
<[EMAIL PROTECTED]> wrote:

> I'm using ElementTree from effbot (http://effbot.org/zone/element.htm)
> and I'm having some problems finding nodes that have the same name. I
> know in XPATH, we can use an index to identify which node we need, but
> it seems to be invalid syntax if I give "/a/b[0]" to the findall()
> method. Does anyone know the correct syntax?

the XPath subset supported by ElementTree is documented here:

http://effbot.org/zone/element-xpath.htm

for more extensive support, see Ken Rimey's PDIS toolkit:

http://pdis.hiit.fi/pdis/download/

 



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


Re: new comp.lang.python mirror at lampfroums.org--any Linux, Apache, MYSQL, Python Apps?

2004-12-09 Thread Fredrik Lundh
Terry Reedy wrote:

> Whereas this is my second or third exposure, with the first that made an 
> impression coming earlier 
> this year.  A list of those books might help some people, and would establish 
> that LAMP is an 
> established concept.

the LAMP concept has been pushed by O'Reilly and others since
early 2001:

http://www.onlamp.com/pub/a/onlamp/2001/01/25/lamp.html

I'm not sure how you've managed to miss it...

 



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


Re: a newbie question

2004-12-09 Thread Nick Coghlan
Peter Hansen wrote:
If that's not what you wanted, try specifying what you mean
by "preinstalled python libraries".  I can think of at least
two things that this phrase might refer to...
For the "where's the standard library" interpretation, the following works on 
any platform:

 python -c "import pdb; print pdb.__file__"
The rest of the standard library will be in the same directory as pdb.pyc.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: deferred decorator

2004-12-09 Thread Nick Coghlan
Bryan wrote:
Nick Coghlan wrote:
Bryan wrote:
i'm also curious if it's possible to write this recipe using the new 
class style for the Deffered class.it appears you can nolonger 
delegate all attributes including special methods to the contained 
object by using the __getattr__ or the new __getattribute__ methods.  
does anyone know how to port this recipe to the new class style?

Override __getattribute__. I don't know why you think it doesn't let 
you override all attribute accesses, as that's exactly what it is for.

Cheers,
Nick.
here's an example. __getattribute__ gets called for x but not for the 
special method __add__.  and the __str__ method was found in the base 
class object which printed the memory location, but didn't call 
__getattribute__.  so __getattribute__ cannot be used to capture special 
methods and delegate them to an encapsulated object.   this is why i'm 
asking what the technique using new classes would be for this recipe.
Hmm, good point. I now have a vague idea why it happens that way, too 
(essentially, it appears the setting of the magic methods causes the interpreter 
to be notified that the object has a Python-defined method to call. With only 
__getattribute__ defined, that notification doesn't happen for all of the other 
magic methods).

This actually makes sense - otherwise how would the method which implements 
__getattribute__ be retrieved?

Similarly, in the existing recipe, none of __init__, __call__, __coerce__ or 
__getattr__ are delegated - the behaviour is actually consistent for all magic 
methods (I'm curious how the existing recipe actually works - it seems the use 
of "self.runfunc" in __call__ should get delegated. It obviously isn't, though).

Something like the following might work (I haven't tested it though):
  class Deferred(object):
...
  def lookup_magic(f_name):
def new_f(self, *args, **kwargs):
  return getattr(self, f_name)(*args, **kwargs)
return new_f
  func_list = ['__add__', '__radd__', ...]
  for f_name in func_list:
setattr(Deferred, f_name) = lookup_magic(f_name)
A metaclass may actually provide a cleaner solution, but I'm not quite sure 
where to start with that.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse XML using Python

2004-12-09 Thread Thomas Guettler
Am Wed, 08 Dec 2004 23:25:49 -0800 schrieb anilby:

> Hi,
> 
> I wanted to write a script that will read the below file:

Hi,

Here is an example how to use sax:

http://pyxml.sourceforge.net/topics/howto/node12.html

 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: wxPython bug

2004-12-09 Thread Dennis Benzinger
Jive wrote:
> [...]
> What to do?

Ask in comp.soft-sys.wxwindows
-- 
http://mail.python.org/mailman/listinfo/python-list


Psycopg 1.1.17 compiled binaries for windows, postgre 8.0.0-beta4 and python 2.3

2004-12-09 Thread Eino Mäkitalo
I had Visual C++ 6.0, so I compiled those
libpq.dll and psycopg.pyd.
if there are anyone to play with
Windows, Python 2.3 and Postgre-8.0.0-beta4 for windows like me.
You cat get those from: http://eino.net/html/python.html
Original psycopg source code is available in: 
http://initd.org/projects/psycopg1

I looking forward to see how much easier it will be with python 2.4
(free compiler), and psycopg2 (supporting python datetime etc).
Eino
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.islink()

2004-12-09 Thread Peter Maas
JanC schrieb:
There are no ntfs links.

You're wrong, NTFS supports symlinks for directories and hard links for 
files:



Thanks for the update and my apologies to Egor. I was using Win2k for
two years and never saw a link, neither at system nor at application
locations. How nasty of Microsoft to add this feature so silently :)
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ideas for projects

2004-12-09 Thread Fuzzyman

Phillip Bowden wrote:
> I feel that I've learned the language pretty well, but I'm having
> trouble thinking of a medium to large project to start.  What are
some
> projects that you have written in the past with Python?

I'm the maintainer of several python projects. Most of them have
their current homepage at
http://www.voidspace.org.uk/atlantibots/pythonutils.html

(soon to move though)



My *main* current interest is writing python CGIs - online tools.
There are a couple of projects I really want to do, but haven't had
the time. If you are interested I could support you in working on
these.



The first one is an online bookmarks manager. There are various of
these around - but none in python and none as straightforward as I
would like. It would be easy to get something working and then expand
it to do more things (like import bookmarks from IE/mozilla/firefox,
check links, organise folders etc).  I could give you a section on
voidspace - complete with FTP login and python 2.3.4  - if you
wanted.



An alternative project (not online) is a 'simple version control'
program. I've written a set of libraries and a GUI tool that do
directory syncing. The libraries are called FSDM and the GUI tool is
called DirWatcher. It can snapshot directories and then work out any
changes. I use it for keeping directories in sync in the three
different computers I use.



It would be relatively simple for turning this into a tool that
monitored projects for you. You could 'snapshot' a set of folders
and label that as  version 0.1. You could track changes and allow the
rolling back of individual files, or even a whole project to a previous
version. Again I could offer you every support (work with you
effectively). I would also like to  change the data format of saved
files from my own text markup to XML. There is a very nice library
called XMLobject that will read & write XML - so it should be simple,
but I don't have the time. It would make an excellent little version
control system for small projects with individual developers.
Anyway, whatever you do, good luck.

 

Regards,

 

 

Fuzzyman

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


Re: PIL for Windows for Python 2.4

2004-12-09 Thread Fuzzyman
So you've built PIL for windows, Python 2.4 ?

Any chance of sharing it ? What compiler have you configured distutils
to use ?

Regards,

Fuzzyman

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


Re: ANNOUNCE: Ice 2.0 released

2004-12-09 Thread Duncan Grisby
In article <[EMAIL PROTECTED]>,
 Michi Henning <[EMAIL PROTECTED]> wrote:

[...]
>Instead of compiling the definition, you can write:
>
>Ice.loadSlice("Color.ice")
>import M
>
>print "My favourite color is ", M.Color.blue

Just like this then?

omniORB.importIDL("Color.idl")
import M

print "My favourite color is ", M.blue

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Upgrading Python Article

2004-12-09 Thread Fuzzyman
Sure - I don't really *blame* windoze for the problem. It's just more
of a pain upgrading python version on windows. As I said it's given me
an opportunity to work out which extension modules I'm really using !

In actual fact I admire windows, there's an awful lot that goes on
beneath the hood. Microsofts dubious business practises mean that they
get a lot of stick - but windows is very sophisticated.

It is produced with a different ethos though, not *just* the fact that
it is closed source. It is designed for users, whereas Lunix is
designed for programmers. This means that setting up a compiler isn't a
straightforward process (See the references in the article).

Microsoft do now give away their .NET optimising compiler - but
distutils can't be configured to use it without hacking into it. This
means it's more tricky than configuring distutils to use gcc from
mingw. I'm still not sure whether that will work for python 2.4 - I had
got the impression it wouldn't. On the other hand the microsoft
compiler is *better* than gcc anyway :-)

Regards,
Fuzzyman
http://www.voidspace.org.uk/atlantibots/pythonutils.html

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


Re: Sorting in huge files

2004-12-09 Thread Paul
The reason I am not telling you much about the data is not because I am
afraid anyone would steal my ideas, or because I have a non-disclosure
agreement or that I don't want to end up pumping gas.
It is just that it is pretty freaking damn hard to even explain what is
going on. Probably a bit harder than your usual database.

If you really want to know, my entries are elliptic curves and my
hashing function is an attempt at mapping them to their Serre resdual
representation modulo a given prime p.

Now, for you to tell me something relevant about the data that I don't
already know from some big-shot conjecture/theorem would probably
require that you read a few grad school books on number theory. Happy?

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


Re: Psycopg 1.1.17 compiled binaries for windows, postgre 8.0.0-beta4 and python 2.3

2004-12-09 Thread Max M
Eino Mäkitalo wrote:
I had Visual C++ 6.0, so I compiled those
libpq.dll and psycopg.pyd.
if there are anyone to play with
Windows, Python 2.3 and Postgre-8.0.0-beta4 for windows like me.
You cat get those from: http://eino.net/html/python.html
Original psycopg source code is available in: 
http://initd.org/projects/psycopg1
Postgres runs fine on Windows now in a native version. And pgAdmin is a 
pretty nice tool.

A precompiled psycopg is the missing link. Thanks. I will try it out.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Docs. Hardcopy 2.4 Library Reference, interested?

2004-12-09 Thread Richie Hindle

[Brad]
> Is anyone interested in purchasing a hardcopy version of the Python 2.4
> Library reference?

Have you seen http://www.network-theory.co.uk/python/ ?  (I don't know
anything about it beyond what's on that page.)

For what it's worth, I wouldn't want a hardcopy manual - I find the
electronic one easier to use.

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: Ideas for projects

2004-12-09 Thread Paul Rubin
Phillip Bowden <[EMAIL PROTECTED]> writes:
> I feel that I've learned the language pretty well, but I'm having
> trouble thinking of a medium to large project to start.  What are some
> projects that you have written in the past with Python?

Why don't you say what areas interest you, and how much experience you
have with programming in general.  That will help choose a response.
Most programmers who have been at it for a while, don't have trouble
thinking of projects.  They have far more ideas than they can ever
possibly get around to working on.

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


Re: Sorting in huge files

2004-12-09 Thread Paul Rubin
"Paul" <[EMAIL PROTECTED]> writes:
> If you really want to know, my entries are elliptic curves and my
> hashing function is an attempt at mapping them to their Serre resdual
> representation modulo a given prime p.
> 
> Now, for you to tell me something relevant about the data that I don't
> already know from some big-shot conjecture/theorem would probably
> require that you read a few grad school books on number theory. Happy?

If you know that much math, you shouldn't have any trouble reading
Knuth "The Art Of Computer Programming" vol 3 "Sorting and Searching",
for info on how to do external sorts.  External sorting means sorting
files that are too large to fit in memory.  Basically you read in
chunks of the file that will fit in memory, sort the chunks in memory
and write the sorted chunks to disk.  Then you merge the sorted
chunks.  Since in the old days a huge amount of computer resources
went into doing these operations, whole books (like Knuth's) have been
written about how to handle all the details efficiently.

If you only want to do this sort once, your simplest approach (if
you're using Unix/Linux) is to use the Unix/Linux "sort" command,
which does an external sort.  You'll have to first crunch your data
into a format that the "sort" command can handle, then run "sort",
then uncrunch if appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


High level SNMP

2004-12-09 Thread Jeremy Sanders
Hi -

I'd like to write a program which basically does a few snmpgets. I haven't
been able to find a python package which gives you a nice high-level and
simple way of doing this (like PHP has). Everything appears to be
extremely low level. All I need is SNMPv1.

Does anyone know of a simple python package for doing this? I'd rather
have something written in pure python, so that it is easily cross-platform.

Jeremy

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


Re: Help beautify ugly heuristic code

2004-12-09 Thread Mitja
On Wed, 08 Dec 2004 16:09:43 -0500, Stuart D. Gathman <[EMAIL PROTECTED]>  
wrote:

I have a function that recognizes PTR records for dynamic IPs.  There is
no hard and fast rule for this - every ISP does it differently, and may
change their policy at any time, and use different conventions in
different places.  Nevertheless, it is useful to apply stricter
authentication standards to incoming email when the PTR for the IP
indicates a dynamic IP (namely, the PTR record is ignored since it  
doesn't
mean anything except to the ISP).  This is because Windoze Zombies are  
the
favorite platform of spammers.
This is roughly it you'll have to experiment and find the right  
numbers for different pattern matches, maybe even add some extra criteria  
etc. I don't have the time for it right now, but I'd be interested to know  
how much my code and yours differ in the detection process (i.e. where are  
the return values different).

Hope the indentation makes it through alright.
#!/usr/bin/python
import re
reNum = re.compile(r'\d+')
reWord = re.compile(r'(?<=[^a-z])[a-z]+(?=[^a-z])|^[a-z]+(?=[^a-z])')
#words that imply a dynamic ip
dynWords = ('dial','dialup','dialin','adsl','dsl','dyn','dynamic')
#words that imply a static ip
staticWords = ('cable','static')
def isDynamic(host, ip):
  """
Heuristically checks whether hostname is likely to represent
a dynamic ip.
Returns True or False.
  """
  #for easier matching
  ip=[int(p) for p in ip.split('.')]
  host=host.lower()
  #since it's heuristic, we'll give the hostname
  #(de)merits for every pattern it matches further on.
  #based on the value of these points, we'll decide whether
  #it's dynamic or not
  points=0;
  #the ip numbers; finding those in the hostname speaks
  #for itself; also include hex and oct representations
  #lowest ip byte is even more suggestive, give extra points
  #for matching that
  for p in ip[:3]:
#bytes 0, 1, 2
if (host.find(`p`) != -1) or (host.find(oct(p)[1:]) != -1): points+=20
  #byte 3
  if (host.find(`ip[3]`) != -1) or (host.find(oct(ip[3])[1:]) != -1):  
points+=60
  #it's hard to distinguish hex numbers from "normal"
  #chars, so we simplify it a bit and only search for
  #last two bytes of ip concatenated
  if host.find(hex(ip[3])[2:]+hex(ip[3])[2:]) != -1: points+=60

  #long, seemingly random serial numbers in the hostname are also a hint
  #search for all numbers and "award" points for longer ones
  for num in reNum.findall(host):
points += min(len(num)**2,60);
  #substrings that are more than just a hint of a dynamic ip
  for word in reWord.findall(host):
if word in dynWords: points+=30
if word in staticWords: points-=30
  print '[[',points,']]'
  return points>80
if __name__=='__main__':
  for line in open('dynip.samp').readlines()[:50]:
(ip,host) = line.rstrip('DYN').split()[:2]
if host.find('.') != -1:
  print host, ip, ['','DYNAMIC'][isDynamic(host,ip)]
--
Mitja
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.3.5 ?

2004-12-09 Thread Fuzzyman
Fuzzy

Regards,
What's that phrase that includes 'hobgoblin of little minds' ?

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


Re: cookie lib policy how-tp?

2004-12-09 Thread Fuzzyman
I think your question has already been answered - but just to clarify a
couple of issues.

Setting a cookie policy will only *restrict* the situations in which
cookies are returned. The default is to *always* return them.

Also using an MSIE instance is useful for creating a CookieJar instance
with your current set of IE cookies in it, but it doesn't make
cookielib behave any more like IE.

(take all that with the usual pinch of salt, but I'm pretty sure it's
correct).

Regards,

Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html

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


Re: ANN: GallerPy 0.5.0

2004-12-09 Thread Fuzzyman
It's very nice looking and emminently 'hackable'.

Nice one.

Regards,

Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html

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


Python 2.4 Tix failing on Windows XP

2004-12-09 Thread j vickroy
Hello,

I've just installed (accepted all installation defaults) Python 2.4 (final) 
on my Microsoft Windows XP (home edition - service pack 2) computer, and I 
am experiencing the following behavior regarding Tix:

>>> import sys
>>> sys.version
'2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)]'
>>> import Tix
>>> root = Tix.Tk()
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\lib\lib-tk\Tix.py", line 210, in __init__
self.tk.eval('package require Tix')
TclError: couldn't load library "tix8184.dll": this library or a dependent 
library could not be found in library path
>>> import os
>>> os.environ['TIX_LIBRARY']
'C:\\Python24\\tcl\\tix8.1'
>>>


"tix8184.dll" is definitely not in the 'C:\Python24\tcl\tix8.1' folder; its 
in the 'C:\Python24\DLLs' folder.  I placed a copy of "tix8184.dll" in  the 
'C:\Python24\tcl\tix8.1' folder, but I still get the same error.

 I next tried:

>>> os.environ['TIX_LIBRARY'] = 'C:\\Python24\\DLLs'

but I still get the same error.

Could someone tell me what I am doing incorrectly?

Thanks.


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


Re: newbie question: starting external application(win)?

2004-12-09 Thread Diez B. Roggisch
> I have googeled, but could not find informations that I can understand.
> The most informations comes from unix/linux butIneed this for win32.

The module popen2 is your friend. Or the os.spawn* methods in module os. 
-- 
Regards,

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


Re: Python Docs. Hardcopy 2.4 Library Reference, interested?

2004-12-09 Thread Jacek Generowicz
"Brad Clements" <[EMAIL PROTECTED]> writes:

> Is anyone interested in purchasing a hardcopy version of the Python 2.4
> Library reference?
> 
> That is, assuming it was NOT  a direct print of current html/pdf versions.
> 
> So, nicely formatted for a printed book (spiral bound probably), with
> several indexes as appropriate, or perhaps a permutted index.
> 
> I'm thinking about doing this through lulu.com or cafepress, but it's going
> to take a lot of work to make a really nice printed version of the library
> reference from the LaTex source files (even via sgmlconv). Also wondering if
> I can get bleeds from either of these sites.
> 
> So, before I waste my time. Is anyone interested in such a beast? And if so,
> how much would you be willing to spend?
> 
> On demand printing still looks expensive to me. :-(

Brian Gough (Network Theory Ltd.) publishes Python manuals:

  http://www.network-theory.co.uk/python/

He sometimes reads this group; I've CCd him to give him a heads-up.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I do this? (eval() on the left hand side)

2004-12-09 Thread caleb . hattingh
Both Peters :)

Sure, I must concede that the problem here was my expectation of how
things should work.

Thanks for the explanations.  I still don't really know whether this
behaviour of locals() is the result of a design decision, or an
implementation artifact of CPython, but at least I have a clear idea of
how to play nice with locals().

thx
Caleb


Peter Otten wrote:
> Caleb Hattingh wrote:
>
> > I am convinced now that locals() doesn't work as (I) expected.
Steven
> > says there was some or other reason why locals() as used in this
context
> > is not writable - Do you know why this is?  I really do not like
> > guidelines like "may not work", "is unreliable" and so on.  Perhaps
this
> > is a character flaw, but I really do like to know what works, when
it
> > works, and when it doesn't work.
>
> I think Peter Hansen has answered that. Your expectations were just
wrong.
>
> > In this scenario, we can see it doesn't work.  To my eyes, it
doesn't work
> > *in the way I expect* (which is highly subjective, no argument
there).
> > Would this be a situation where it would be nice to have an
exception
> > thrown if locals() is assigned to in a scope where it is not
writable?
>
> If python were to throw an exception, it should always be thrown. But
I'm
> the wrong one to worry about that as I didn't even find a single
>
> globals()[name] = value
>
> assignment in my scripts. I want to know a variable's name, or I put
it in a
> dictionary.
>
> > It would also be nice if globals and locals behaved the same,
differing
> > only in scope (which is what I expected originally anyway).  But we
can't
> > have everything, I guess :)
>
> That would mean that both would become read-only, I guess, but I
don't see
> that happen.
> 
> Peter

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


Re: dictionary initialization

2004-12-09 Thread caleb . hattingh
Hi Dan

I must confess that upon rereading my words, there is some irony there
(but not really sarcasm, is there?).  However, I *really* tried to keep
my tone, well, professional.  I realise I didn't do a good job and
apologise.  I hope that's ok.

Keep well
Caleb

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


Re: Pictograms and Python

2004-12-09 Thread caleb . hattingh
Diez

Ya got me there!

"""
I have a sript that downloads a webpage. According to the picture  on
this webpage I need to pass a parameter to this , running script a few
lines later.
"""

Err, ya, I guess I would be suspicious too.Sorry about that!
Keep well
Caleb

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


Questions about file object and close()

2004-12-09 Thread John Marshall
Hi,

Does anyone see a problem with doing:
data = file("tata").read()

Each time this is done, I see a new file
descriptor allocated (Linux) but not
released.

1) Will there ever be a point where I
   will have a problem with file
   descriptors because the garbage
   collector has _not_ yet collected the
   file objects?

2) When I subclassed the file object as
   follows:
-
class MyFile(file):
def close(self):
print "MyFile.close()"
file.close(self)
-
   and did a simple 'MyFile("tata")' I did not see
   a call to MyFile.close(). Am I wrong to have
   expected MyFile.close() to have been called?

3) There is no file.__del__() as far as I
   can tell at the Python level. Are files
   opened by the calls above properly
   closed when the objects are destroyed
   and collected?

Thanks,
John

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


Re: wxPython bug

2004-12-09 Thread Johan Lindberg
> [...]
> What to do?

Open up wxProject.py and fix the problem. The traceback is pretty
clear:
On line 137 in wxProject.py, the method GetFirstChild expects 2
arguments, but was given 3.

Unfortunately the wx documentation is not very clear about the
GetFirstChild method. It
only says:
wxPython note: In wxPython the returned wxTreeItemId and the new
cookie value are both returned as a tuple containing the two values.
It should also mention that it (GetFirstChild) only takes one parameter
(item)

For future reference: keep the wxPython api docs
(http://www.wxpython.org/docs/api/) close.

/Johan Lindberg

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


Re: os.path.islink()

2004-12-09 Thread JanC
Peter Maas schreef:

> Thanks for the update and my apologies to Egor. I was using Win2k for
> two years and never saw a link, neither at system nor at application
> locations. How nasty of Microsoft to add this feature so silently :)

IIRC this is something they had to add for the US government (probably 
something to do with posix compliancy?), but that they don't want people 
to use...   ;-)


-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about file object and close()

2004-12-09 Thread Peter Hansen
John Marshall wrote:
Hi,
Does anyone see a problem with doing:
data = file("tata").read()
Each time this is done, I see a new file
descriptor allocated (Linux) but not
released.
1) Will there ever be a point where I
   will have a problem with file
   descriptors because the garbage
   collector has _not_ yet collected the
   file objects?
Should be easy to check.  Write a loop which
does that many times.  There are a finite
number of file descriptors available, so if
it's going to fail, it will fail fairly
quickly.
3) There is no file.__del__() as far as I
   can tell at the Python level. Are files
   opened by the calls above properly
   closed when the objects are destroyed
   and collected?
Yes, but you can only count on this happening
in the CPython implementation.  Nevertheless,
it's still widely considered more than just good style
to explicitly close your files within a finally
clause, even in CPython where technically you don't
have to in most cases:
f = file("tata")
try:
data = f.read()
finally:
f.close()
The above is quite robust and should be your model
for all file access, at least until you're much more
experienced with Python.
One should use the open().read() idiom only in small
utility scripts and other such short-running applications.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.3.5 ?

2004-12-09 Thread Peter Hansen
Fuzzyman wrote:
What's that phrase that includes 'hobgoblin of little minds' ?
It's about "foolish consistency", but I don't see the relevance
to the current thread.
Are you suggesting that back-porting bug fixes to older
versions of Python is foolish?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: High level SNMP

2004-12-09 Thread Petri Laakso
On Thu, 09 Dec 2004 11:15:27 +, Jeremy Sanders wrote:

> Hi -
> 
> I'd like to write a program which basically does a few snmpgets. I haven't
> been able to find a python package which gives you a nice high-level and
> simple way of doing this (like PHP has). Everything appears to be
> extremely low level. All I need is SNMPv1.
> 
> Does anyone know of a simple python package for doing this? I'd rather
> have something written in pure python, so that it is easily cross-platform.
>

Hi, Jeremy

have you tested twistedsnmp?
http://twistedsnmp.sourceforge.net/

Petri

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


Re: newbie question: starting external application(win)?

2004-12-09 Thread Peter Hansen
Frank Esselbach wrote:
Hello,
I'am new in python. I need informations, how its possible run another
(non-python) exe file from python without terminate the python system.
I have googeled, but could not find informations that I can understand.
The most informations comes from unix/linux butIneed this for win32.
There's a variety of options, ranging from os.popen and os.system
through spawn, the new in 2.4 subprocess module, and os.startfile.
Which one is best for you might depend on specifics.  You can
either read the docs for the "os" module or "subprocess", or
tell us more detail.  What exe are you trying to run, and how
are you doing it now which is "terminating the python system"?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question: starting external application(win)?

2004-12-09 Thread Johan Lindberg
>The module popen2 is your friend. Or the os.spawn* methods in module
os.

Another (simpler IMO) way to do it is to use os.startfile.

To start Notepad:
>>> import os
>>> os.startfile("notepad.exe")

also, you can start an application from an associated file.

Start MS Word with:
>>> os.startfile("MyDocument.doc")

/Johan Lindberg

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


Re: Parse XML using Python

2004-12-09 Thread Anil

Thomas Guettler wrote:
> Am Wed, 08 Dec 2004 23:25:49 -0800 schrieb anilby:
>
> > Hi,
> >
> > I wanted to write a script that will read the below file:
>
> Hi,
>
> Here is an example how to use sax:
>
> http://pyxml.sourceforge.net/topics/howto/node12.html
>
>  Thomas
>
> --
> Thomas Güttler, http://www.thomas-guettler.de/


Could you please tell me how to achieve the below.
I am interested in  getting the output like:

ABC
EFGA   --> child of ABC
ABDG   --> child of AEFGA
MON   --> child of ABC
A1
 FGA   --> child of A1
 BG--> child of FGA

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


Re: PIL for Windows for Python 2.4

2004-12-09 Thread Scott F
"Fuzzyman" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> So you've built PIL for windows, Python 2.4 ?
> 
> Any chance of sharing it ? What compiler have you configured
> distutils to use ?


I'm very sorry I spoke too soon.  After making the initial change, the 
setup.py took off on a run.  But it soon quit, informing me that I 
needed the Visual Studio 7 tools.  So, I have no PIL either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Wrapper objects

2004-12-09 Thread Egil M?ller
Is there any way to create transparent wrapper objects in Python?

I thought implementing __getattribute__ on either the wrapper class or
its metaclass would do the trick, but it does not work for the built
in operators:

class Foo(object):
class __metaclass__(type):
def __getattribute__(self, name):
print "Klass", name
return type.__getattribute__(self, name)
def __getattribute__(self, name):
print "Objekt", name
return object.__getattribute__(self, name)


>>> Foo() + 1
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'Foo' and 'int'
>>> Foo().__add__(1)
Objekt __add__
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 8, in __getattribute__
AttributeError: 'Foo' object has no attribute '__add__'


Thus, note that a + b does not do

try:
return a.__add__(b)
except:
return b.__radd__(a)

and neither, as I first thought

try:
return type(a).__add__(a, b)
...

but something along the lines of

try:
return type.__getattribute__(type(a), '__add__')(a, b)
...


So my naive implementation of a wrapper class,


class wrapper(object):
def __init__(self, value, otherdata):
self.value = value
self.otherdata = otherdata
def __getattribute__(self, name):
return getattr(self.value, name)


does not work. Any ideas for a solution?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing wxPython on Linux and Windows

2004-12-09 Thread Ed Leafe
On Dec 2, 2004, at 4:19 AM, Peter Maas wrote:
Recently I replaced Win2k with Linux on my desktop computer. Using 
mostly
multi-platform software I thought this would be easy. It was not as
easy as expected getting wxPython to work. There seemed to be no SuSE 
RPM
so I installed from source. Here are my steps (gtk 2.4 was already
installed):
	You could have saved yourself some grief with 
http://wxpython.org/builddoc.php

 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about file object and close()

2004-12-09 Thread John Marshall
On Thu, 2004-12-09 at 08:41 -0500, Peter Hansen wrote: 
> John Marshall wrote:
> > Hi,
> > 
> > Does anyone see a problem with doing:
> > data = file("tata").read()
> > 
> > Each time this is done, I see a new file
> > descriptor allocated (Linux) but not
> > released.
> > 
> > 1) Will there ever be a point where I
> >will have a problem with file
> >descriptors because the garbage
> >collector has _not_ yet collected the
> >file objects?
> 
> Should be easy to check.  Write a loop which
> does that many times.  There are a finite
> number of file descriptors available, so if
> it's going to fail, it will fail fairly
> quickly.
> 

I did do this and it did not fail. My concern
was since the close() is not done explicitly
by me, and does not seem to be called in
a file.__del__() or otherwise, I was not
sure. I want to be sure! Given your comment
below about the CPython implementation, there
is no guarantee which seems unreasonable for
such an operation.

It seems to me that a file.__del__() _should_
call a file.close() to make sure that the file
is closed as a clean up procedure before
releasing the object. I cannot see why this
would not be the prescribed behavior and thus
my question. Isn't that what __del__
(destructors) are supposed to handle--cleaning
up?

> > 3) There is no file.__del__() as far as I
> >can tell at the Python level. Are files
> >opened by the calls above properly
> >closed when the objects are destroyed
> >and collected?
> 
> Yes, but you can only count on this happening
> in the CPython implementation.  Nevertheless,
> it's still widely considered more than just good style
> to explicitly close your files within a finally
> clause, even in CPython where technically you don't
> have to in most cases:
> 
> f = file("tata")
> try:
>  data = f.read()
> finally:
>  f.close()
> 
> The above is quite robust and should be your model
> for all file access, at least until you're much more
> experienced with Python.

How would more experience change this? Assuming I
am catching any exceptions I am interested in, why
wouldn't the following be just as good?
try:
data = file("tata").read()
except:
...


> One should use the open().read() idiom only in small
> utility scripts and other such short-running applications.

I don't see why this is so only for small scripts. As
I question above, why doesn't the file object clean up
after itself as a guaranteed course of action?

Of course, I could implement my own file object to
guarantee the clean up and be on my way. But I am
still surprised at what I am seeing.

Thanks,
John

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


Re: Python Docs. Hardcopy 2.4 Library Reference, interested?

2004-12-09 Thread Brian Gough
"Brad Clements" <[EMAIL PROTECTED]> writes:

> Is anyone interested in purchasing a hardcopy version of the Python 2.4
> Library reference?

I have one in the pipeline but I'm waiting for sales of the Python
Tutorial and Python Language Reference to justify bringing it out.

The amount of text in the library manual is huge (it requires two
volumes), which makes it more costly.

-- 
best regards,

Brian Gough

Network Theory Ltd,
Publishing the Python Manuals --- http://www.network-theory.co.uk/python/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parse XML using Python

2004-12-09 Thread Diez B. Roggisch
Anil wrote:

> Could you please tell me how to achieve the below.
> I am interested in  getting the output like:
> 
> ABC
> EFGA   --> child of ABC
> ABDG   --> child of AEFGA
> MON   --> child of ABC
> A1
>  FGA   --> child of A1
>  BG--> child of FGA

print """
ABC
EFGA   --> child of ABC
ABDG   --> child of AEFGA
MON   --> child of ABC
A1
 FGA   --> child of A1
 BG--> child of FGA
"""

Unless you don't tell us what _input_ shall be processed to yield that
output, I doubt anybody can be of more help

-- 
Regards,

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


MDaemon Warning - virus found: Returned mail: see transcript for details

2004-12-09 Thread MAILER-DAEMON

*** WARNING **
Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado 
un fichero anexo(s) infectado(s).  Por favor revise el reporte de abajo.

AttachmentVirus name   Action taken
--
transcript.zipI-Worm.Mydoom.m  Removed


**


The original message was received at Thu, 9 Dec 2004 15:37:21 +0100
from python.org [116.192.12.107]

- The following addresses had permanent fatal errors -
<[EMAIL PROTECTED]>



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

Re: dictionary initialization

2004-12-09 Thread Dan Perl
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi Dan
>
> I must confess that upon rereading my words, there is some irony there
> (but not really sarcasm, is there?).  However, I *really* tried to keep
> my tone, well, professional.  I realise I didn't do a good job and
> apologise.  I hope that's ok.
>
> Keep well
> Caleb
>

It's water under the bridge.  I admire though the fact that you sent this 
message.

Dan 


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


results of division

2004-12-09 Thread Brad Tilley
Hello,
What is the proper way to limit the results of division to only a few 
spaces after the decimal? I don't need rocket-science like precision. 
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.
Thank you,
Brad
--
http://mail.python.org/mailman/listinfo/python-list


Re: High level SNMP

2004-12-09 Thread Jeremy Sanders
On Thu, 09 Dec 2004 15:34:14 +0200, Petri Laakso wrote:

>> have you tested twistedsnmp?
> http://twistedsnmp.sourceforge.net/

I looked at it, but it needs Twisted compiled and installed, which is a
pain.

The old versions of PySNMP (version 2.XX), seem to be a lot simpler to
use than later ones, so I might do that. That's if I can work out how to
convert the random string it produces to a floating point number. Somehow
it manages to gain 3 bytes over a float...

Jeremy

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


Re: new comp.lang.python mirror at lampfroums.org--any Linux, Apache, MYSQL, Python Apps?

2004-12-09 Thread astro

Thanks for the feedback.

I linked to Oreilly's onlamp.com article at: 

http://lampforums.org/forumdisplay.php?f=36

What is LAMP?

LAMP is an acronym for Linux, Apache, MYSQL/Postgres, and
PHP/Perl/Python/Ruby.

These open-source efforts offer ever-increasing power and versatility.

In 2001, Dale Dougherty wrote at Oreilly's a
href=http://www.onlamp.com/pub/a/onlamp/2001/01/25/lamp.html :

"Several months ago, David Axmark and Monty Widenius of the MySQL team
visited us in Sebastopol and they dropped a new term in our laps: LAMP.
This term was popular in Germany, they said, to define how MySQL was
used in conjunction with Linux, Apache, and either Perl, Python, or
PHP. Their explanation of LAMP made a lightbulb go off in my head."

"The lightbulb that went off in my head was that LAMP represents the
open source web platform. Most importantly, LAMP is the platform of
choice for the development and deployment of high performance web
applications. It is solid and reliable, and if Apache is any indicator,
then LAMP sites predominate."

Best,

Elliot


-- 
astro

astro's Profile: http://lampforums.org/member.php?userid=1
View this thread: http://lampforums.org/showthread.php?t=92951

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


Re: Wrapper objects

2004-12-09 Thread Simon Brunning
On 9 Dec 2004 06:11:41 -0800, Egil M?ller <[EMAIL PROTECTED]> wrote:
> Is there any way to create transparent wrapper objects in Python?

This work - ?

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


samba/windows shares

2004-12-09 Thread I.V. Aprameya Rao
hi

does anybody know how to access samba/windows shares on a network? is 
there any module that does this?

i am running linux and i thought of using the mount command to mount that 
remote share and then access it, but i was wondering whether that is the 
right way?

Aprameya

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


Re: results of division

2004-12-09 Thread Simon Brunning
On Thu, 09 Dec 2004 09:38:55 -0500, Brad Tilley <[EMAIL PROTECTED]> wrote:
> What is the proper way to limit the results of division to only a few
> spaces after the decimal? I don't need rocket-science like precision.
> Here's an example:
> 
> 1.775 is as exact as I need to be and normally, 1.70 will do.
 
Use the new decimal type - .

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: results of division

2004-12-09 Thread Paul Rubin
Brad Tilley <[EMAIL PROTECTED]> writes:
> What is the proper way to limit the results of division to only a few
> spaces after the decimal? I don't need rocket-science like
> precision. Here's an example:
> 
> 1.775 is as exact as I need to be and normally, 1.70 will do.

"%.2f"% 1.775
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: results of division

2004-12-09 Thread Aahz
In article <[EMAIL PROTECTED]>,
Brad Tilley  <[EMAIL PROTECTED]> wrote:
>
>What is the proper way to limit the results of division to only a few 
>spaces after the decimal? I don't need rocket-science like precision. 
>Here's an example:
>
>1.775 is as exact as I need to be and normally, 1.70 will do.

You have two options: use floating point and round manually or use the
new Decimal class and specify your precision.  However, if you restrict
your calculations, you will have errors after chaining more than one or
two operations.  Your best bet is to perform rounding only at the end of
your calculations, at which point you can either round the result
directly or round for display only (by using appropriate % formatting).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL for Windows for Python 2.4

2004-12-09 Thread Fuzzyman
If you're determined enough there are instructions here :
http://www.vrplumber.com/programming/mstoolkit/

These will get you the Visual Studio 7 tools (free releases of) and
tell you how to configure distutils to use it.

Hefty downloads though, do not attempt this without broadband !

Regards,

Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html

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


Re: Help beautify ugly heuristic code

2004-12-09 Thread Jeremy Sanders
On Wed, 08 Dec 2004 18:38:14 -0500, Stuart D. Gathman wrote:

>> Here are the last 20 (which my subjective judgement says are correct):
> 
> 65.112.76.15usfshlxmx01.myreg.net 201.128.108.41 
[snip]
> 80.143.79.97p508F4F61.dip0.t-ipconnect.de DYN

Looks like you could do something like look for a part of the dns name
which is over a certain length with a high fraction of numbers and
punctuation characters.

Of course, you could build up a probability tree of the chance of a
character being followed by another character in a dynamic name and a
static name.

This might work well, as many are sequences of numbers (high chance of
number followed by number), and mixed characters and numbers, which are
unusual in normal dns names.

Jeremy

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


How to install tile (or any other tcl module)

2004-12-09 Thread Stephen Kennedy

I've been trying to get Tile to work with python.
It can make your tkinter apps look like
http://tktable.sourceforge.net/tile/screenshots/demo-alt-unix.png
See http://tktable.sourceforge.net/tile/

Under linux I built tile from source, installed and it just works.

import Tkinter
root = Tkinter.Tk()
root.tk.call('package', 'require', 'tile')
root.tk.call('namespace', 'import', '-force', 'ttk::*')
root.tk.call('tile::setTheme', 'alt')
### Widgets are now pretty!

Under win32, I installed the binary package into python/tcl
(i.e. python/tcl/tile0.5) with all the other tcl packages, but tcl
can't find it. Any ideas?

Traceback (most recent call last):
  File "Script1.py", line 5, in ?
root.tk.call('package', 'require', 'tile')
_tkinter.TclError: can't find package tile

Stephen.


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


Re: PIL for Windows for Python 2.4

2004-12-09 Thread Simon Brunning
On 9 Dec 2004 06:58:05 -0800, Fuzzyman <[EMAIL PROTECTED]> wrote:
> If you're determined enough there are instructions here :
> http://www.vrplumber.com/programming/mstoolkit/
> 
> These will get you the Visual Studio 7 tools (free releases of) and
> tell you how to configure distutils to use it.

Also useful: .

> Hefty downloads though, do not attempt this without broadband !

380 Mb approximately.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about file object and close()

2004-12-09 Thread Peter Hansen
John Marshall wrote:
It seems to me that a file.__del__() _should_
call a file.close() to make sure that the file
is closed as a clean up procedure before
releasing the object. 
I believe it does, but I tried your experiment
with subclassing file and didn't ever see a
call to close, so I can only assume that the
built-in __del__() is actually just calling the
builtin close() and bypassing my overridden close(),
although there could also be some other magic about
how files behave that explains this.
I don't see why this is so only for small scripts. As
I question above, why doesn't the file object clean up
after itself as a guaranteed course of action?
The issue is that although __del__ is calling
close, there is no guarantee in Python about when
__del__ is run, nor in fact that it will ever be
run.  (If nothing else, a call to os._exit() will
always bypass normal shutdown.)  In Jython, for
example, there is no reference counting the way CPython
does it, so __del__ methods are called only when the
object is garbage collected.  When does that happen?
There's no guarantee: if you haven't explicitly closed
the file, it might not get closed until the interpreter
is shutting down (if then).
In CPython, you at least (currently) have sort of a
guarantee that the file will be closed when the object
is destroyed, which because of reference counting will
happen as soon as you "del file" or rebind the name
to another object, or whatever.
So in CPython, it is working properly (and you shouldn't
run out of file descriptors unless you are into
complicated code where the file objects are being kept
in cyclical data structures that cannot be reclaimed
through simple reference counting) but I cannot explain
why we don't see a subclass's close() method get called
when __del__ does, as it must, get called.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Docs. Hardcopy 2.4 Library Reference, interested?

2004-12-09 Thread Richie Hindle

[Brian]
> I have one in the pipeline but I'm waiting for sales of the Python
> Tutorial and Python Language Reference to justify bringing it out.

I'd be interested to know how many of these manuals you sell...?  This is
only idle curiosity, and if you don't want to say then that's no problem.
(I'd briefly considered doing this myself, until I found your site.)

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: results of division

2004-12-09 Thread Peter Hansen
Brad Tilley wrote:
What is the proper way to limit the results of division to only a few 
spaces after the decimal? I don't need rocket-science like precision. 
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.
The answer is "what are you trying to do?".  The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing.  Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Directory structure inside a ZipFile object

2004-12-09 Thread Scott David Daniels
Bulba! wrote:
tried to  read file, zip it, and put in the target directory
It works nice, except the zipfile created contains the directory path
of the source file -- which I do NOT want to recreate. 
Look into the two-argument form of the write command:
import zipfile
archive = zipfile.ZipFile('box.zip', 'w', zipfile.ZIP_DEFLATED)
archive.write('source/somewhere/one.txt', 'name.txt')
archive.write('two.txt', 'another.txt')
archive.close()
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: results of division

2004-12-09 Thread Paul McGuire
"Paul Rubin"  wrote in message
news:[EMAIL PROTECTED]
> Brad Tilley <[EMAIL PROTECTED]> writes:
> > What is the proper way to limit the results of division to only a few
> > spaces after the decimal? I don't need rocket-science like
> > precision. Here's an example:
> >
> > 1.775 is as exact as I need to be and normally, 1.70 will do.
>
> "%.2f"% 1.775

At the risk of kicking off *another* floating-point representation thread,
here is some odd string interp behavior (Python 2.3.4).

I seemed to recall in the past finding that the above syntax would not
round, but would instead truncate (old C runtime perhaps), so that even
printing 1.779 to 2 decimal places would print only "1.77".  So I tried a
few things at the Python prompt, and got some odd behavior.

>>> print "%.2f" % 1.776
1.78
>>> print "%.2f" % 1.774
1.77

Good so far, now let's try the borderline case:

>>> print "%.2f" % 1.775
1.77

Hmmm, if we rounded, I would have expected 1.775 to round up to 1.78.
Perhaps this is a floating point rep issue, that we are really rounding
1.774 or something.  Sure enough, repr shows us:

>>> repr(1.775)
'1.7749'

So I added a wee bit to 1.775:

>>> print "%.2f" % 1.7751
1.78

Ok, that looks better.  What if I round explicitly?

>>> print "%.2f" % round(1.775,2)
1.78

Errr?  How come round() is able to understand 1.775 correctly, whereas
string interp is not?  I'm guessing that round() adds some small epsilon to
the value to be rounded, or perhaps even does the brute force rounding I
learned in FORTRAN back in the 70's:  add 0.5 and truncate.  But this would
still truncate 1.77999 to two places, so this theory fails also.  What
magic is round() doing, and should this same be done in the string interp
code?

-- Paul



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


Re: results of division

2004-12-09 Thread Brad Tilley
Simon Brunning wrote:
On Thu, 09 Dec 2004 09:38:55 -0500, Brad Tilley <[EMAIL PROTECTED]> wrote:
What is the proper way to limit the results of division to only a few
spaces after the decimal? I don't need rocket-science like precision.
Here's an example:
1.775 is as exact as I need to be and normally, 1.70 will do.
 
Use the new decimal type - .
Ah, quantize() works great. Thank you for the tip.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Class Variable Inheritance

2004-12-09 Thread Scott David Daniels
Brian Jones wrote:
class a(object):
mastervar = []
def __init__(self):
print 'called a'
class b(a):
def __init__(self):
print 'called b'
self.mapvar()
def mapvar(self):
self.mastervar.append(['b'])
class c(b):
  mastervar = []   # Adding this should make things clearer
def __init__(self):
print 'called c'
self.mapvar()
def mapvar(self):
super(c, self).mapvar()
self.mastervar.append(['c'])
if __name__ == '__main__':
a1 = a()
b1 = b()
c1 = c()
d1 = c() # Call C again
  for object in a1, b1, c1, d1:
  print id(object.mastervar), object.mastervar
What I don't understand is why mastervar gets modified by each _seperate 
instance_ of classes that happen to extend the base class 'a'. Shouldn't 
mastervar be contained within the scope of the inheriting classes?  Why 
is it being treated like a global variable and being modified by the 
other instances?
By over-riding mastervar in class c, I hope I've shown that a class 
variable is shared by all of its instances, but can be over-ridden by
a subclass's class variable.

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


Re: jython and swing

2004-12-09 Thread Rick Holbert
Could it have something to do with your PATH or CLASSPATH settings?

Here's a test script that works for me:

#!/usr/bin/env jython

from java import lang
from javax import swing

print "lang attributes: "

for attr in dir(lang):
print "\t%s" % attr

print
print "swing attributes: "

for attr in dir(swing):
print "\t%s" % attr

print
print "Good Bye!"

Note: both #!/usr/bin/env jython and #!/bin/env jython seem to work on the
OSU stdsun system...

Nandan wrote:

> hello, can I ask a jython question here?
> 
> when I use the jython interpreter I have no problem with the statement:
> 
> from java import lang
> from javax import swing
> 
> but when I put this in a script, I get a package not found error.
> what am I doing wrong?
> 
> the script header is #!/bin/env jython
>  
> --
> Nandan Bagchee
> Ohio State University
> [EMAIL PROTECTED]

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


Re: results of division

2004-12-09 Thread Brad Tilley
Peter Hansen wrote:
Brad Tilley wrote:
What is the proper way to limit the results of division to only a few 
spaces after the decimal? I don't need rocket-science like precision. 
Here's an example:

1.775 is as exact as I need to be and normally, 1.70 will do.

The answer is "what are you trying to do?".  The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing.  Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?
-Peter
I'm summing up the bytes in use on a hard disk drive and generating a 
report that's emailed based on the percentage of the drive in use. I 
know there are other ways to do this, but I like Python and I like to 
write my own code. I always find comp.lang.python a very helpful place.

Thank you,
Brad
--
http://mail.python.org/mailman/listinfo/python-list


How can I change the timestamps of directories? (os.utime(), WinXP)

2004-12-09 Thread Martin Bless
I'm working on a backup scheme that looks at modification times. To
run some tests I'd like to be able to set the modification time of
directories (WinXPsp2, Python-2.3.4)

os.utime() works well with files but throws a permission error with
directories. See code below.

Q: Can this be done via the os-module?
Q: Is it possible at all? Somebody knows?

Thanks,

mb - Martin Bless


"""
Trying to the timestamps of a directory
"""
import sys, os, stat, datetime, time
today = datetime.datetime.now()
pastday = today - datetime.timedelta(days=11)
atime = int(time.mktime(pastday.timetuple()))
mtime = atime
times = (atime,mtime)
path = os.path.normpath(r'c:/dummydir')
os.utime(path,times)

""" throws error:
OSError: [Errno 13] Permission denied: 'c:\\dummydir'
"""


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


Re: Questions about file object and close()

2004-12-09 Thread Scott David Daniels
John Marshall wrote:
On Thu, 2004-12-09 at 08:41 -0500, Peter Hansen wrote: 

John Marshall wrote:
Does anyone see a problem with doing:
   data = file("tata").read()
 ... a perfectly good explanation
It seems to me that a file.__del__() _should_
>  how he wishes it were designed 
Isn't that what __del__ (destructors) are supposed to handle
> --cleaning up?
Just in case you are actually asking, and not simply complaining:
The existence of a __del__ method affects when a garbage collect
may remove an object (and may in some cases delay it).  In Jython
(and on top of any system doing its own garbage collection),
there may be no control over when an object is deallocated.
A close on an output file may finalize I/O that has been considered
a mistake, and it might cause an I/O error that will prevent the rest
of the program from executing.
One should use the open().read() idiom only in small
utility scripts and other such short-running applications.
I don't see why this is so only for small scripts. As
I question above, why doesn't the file object clean up
after itself as a guaranteed course of action?
If you really want, define a function like:
def contents(filename):
source = open(filename)
try:
return source.read()
finally:
source.close()
and then you can make your small uses clear.
-Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: results of division

2004-12-09 Thread Tim Peters
[Paul McGuire]
...
> >>> print "%.2f" % 1.775
> 1.77
>
> Hmmm, if we rounded, I would have expected 1.775 to round up
> to 1.78.

Platform-dependent.  1.775 isn't exactly representable regardless, but
whether exactly-half-way numbers that are exactly representable round
up or truncate varies across platform C libraries.  For example, 1.25
is exactly representable in binary fp, but '%.1f' % 1.25 produces 1.3
on Windows but 1.2 on most other platforms (most non-Microsoft C
runtimes use the IEEE "round to nearest or even" rule).

> Perhaps this is a floating point rep issue, that we are really
> rounding 1.774 or something.  Sure enough,
> repr shows us:
> 
> >>> repr(1.775)
> '1.7749'
> 
> So I added a wee bit to 1.775:
> 
> >>> print "%.2f" % 1.7751
> 1.78
> 
> Ok, that looks better.  What if I round explicitly?
> 
> >>> print "%.2f" % round(1.775,2)
> 1.78
> 
> Errr?  How come round() is able to understand 1.775 correctly,
> whereas string interp is not?  I'm guessing that round() adds
> some small epsilon to the value to be rounded,

No way -- that would be insane.

> or perhaps even does the brute force rounding I learned in
> FORTRAN back in the 70's:  add 0.5 and truncate.

Yes, that's what Python's round() does.

>  But this would still truncate 1.77999 to two places, so this
> theory fails also.

No:

>>> 1.775
1.7749
>>> 1.775 * 100.0
177.5
>>> 1.775*100 + 0.5
178.0
>>>

That is, before adding 0.5, it multiplies by 100.0.  The vagaries of
binary fp are such that machine_value_for(1.755) * 100 is exactly
175.5, and adding 0.5 to that gives 178 exactly.

> What magic is round() doing, and should this same be done in the
> string interp code?

Python implements round() itself.  Float string formatting is done by
the platform C sprintf().  If you care about decimal representations
so much that you can't tolerate vagaries due to differences in the
53rd significant bit, use the new decimal module instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


OT: Re: PDF count pages

2004-12-09 Thread Andreas Lobinger
Aloha,
[EMAIL PROTECTED] wrote:
Andreas Lobinger wrote:
>>> import pdffile
I browsed the code in CVS and it looks like a pretty comprehensive
implementation. Maybe we should join forces.
I have problems contacting you via the given e-mail adress.
Wishing a happy day
LOBI
--
http://mail.python.org/mailman/listinfo/python-list


Re: results of division

2004-12-09 Thread Peter Hansen
Brad Tilley wrote:
Peter Hansen wrote:
The answer is "what are you trying to do?".  The others have
given options and good advice, but the "right" approach
depends on what exactly you are doing.  Is this just for
display purposes, or is there more significant (though
perhaps not "precision-critical") calculation going on?
I'm summing up the bytes in use on a hard disk drive and generating a 
report that's emailed based on the percentage of the drive in use. I 
know there are other ways to do this, but I like Python and I like to 
write my own code. I always find comp.lang.python a very helpful place.
So, from the sounds of it, you really care about this
rounding operation in the displayed values, in which
case the "'%.2f' % value" approach ought to be fine.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse XML using Python

2004-12-09 Thread Jeremy Bowers
On Thu, 09 Dec 2004 06:00:27 -0800, Anil wrote:

> 
> Thomas Guettler wrote:
>> Hi,
>>
>> Here is an example how to use sax:
>>
>> http://pyxml.sourceforge.net/topics/howto/node12.html
>>
>>  Thomas
>>
>> --
>> Thomas GÃttler, http://www.thomas-guettler.de/
> 
> 
> Could you please tell me how to achieve the below.
> I am interested in  getting the output like:

Anil, "use sax" is all you are likely to get as a starting point. If
someone just hands you a solution, what have you learned?

Start using sax (or some other parser, personally I think I'd recommend
ElementTree for this use (google it)), and if you have trouble, post a
the exact code you have, the exact input you are using, what happens, and
what you expected to happen.

It is unlikely that repeated appeals, in the absence of evidence that you
tried to solve it yourself, will get you anywhere.

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


Re: Loading a file only once into an object and being able to access it from other modules - still have a problem

2004-12-09 Thread Philippe C. Martin
Hi,

After all of you answers, I though I had it straight, yet .

This is what  I am doing:

class SC_ISO_7816:

__m_loaded = None

..
def __init__(self):
"""
"""
if SC_ISO_7816.__m_loaded == None:
SC_ISO_7816.__m_loaded = True
print 'LOADING'
self.__Load()
print self.SW1_DICT
else:
print 'DICT ALREADY LOADED!',
print self.SW1_DICT
pass

...




if I import and/or create more than one instance of SC_ISO_7816, when I see

'LOADING' then I also see a fully populated dictionary.

But when I see (second or more time)

'DICT ALREADY LOADED', then my dict is emtpy


What else am I not understanding  ?

Regards,

Philippe










-- 
*
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
*
-- 
http://mail.python.org/mailman/listinfo/python-list


mapping function to vars

2004-12-09 Thread jahurt
I need to map a function to several variables.  I'm trying to use map
and lambda to do this.  Here's my attempt...

#!/usr/bin/env python
from random import *

[fee, fye, foe, fum] = map(lambda n: random(), range(4))

print fee
print fye
print foe
print fum

...I'm essentially trying to map a function that takes no parameters to
a group of variables.  This works, but pychecker complains about the
'n' parameter.  Is there a better way to do this?  TIA

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


Re: Sorting in huge files

2004-12-09 Thread Paul
Thanks! I definitely didn't want to go into any elaborate programming
for this, and the Unix sort is perfect for this.
It sorted a tenth of my data in about 8 min, which is entirely
satisfactory to me (assuming it will take ~ 20 times more to do the
whole thing).
Your answer greatly helped!
Paul

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


Re: Upgrading Python Article

2004-12-09 Thread JanC
Fuzzyman schreef:

> On the other hand the microsoft
> compiler is *better* than gcc anyway :-)

It's better at optimising, but it doesn't support standard C & C++.  ;-)

-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I do this? (eval() on the left hand side)

2004-12-09 Thread Bengt Richter
On Tue, 07 Dec 2004 21:12:24 GMT, "It's me" <[EMAIL PROTECTED]> wrote:

>
>"Caleb Hattingh" <[EMAIL PROTECTED]> wrote in message
>news:[EMAIL PROTECTED]
>> Hi It's me
>>
>> >
>> > a = 3
>> > y = "a"
>> > print eval(y)
>> >
>>
>> To get 'a' to be 4 here, you would say
>>
>> a = 4
>>
>
>Obviously but that's not what I wish to do.
>
>> I am not sure why you would want to do otherwise?  Perhaps you could
>> sketch out a little more about what you are trying to do?  That would help
>> a lot.  Are you aiming for something like pointer emulation with simple
>> datatypes?
>>
>
>In REXX, for instance, one can do a:
>
>interpret y' = 4'
>
>Since y contains a, then the above statement amongs to:
>
>a = 4
>
>There are many situations where this is useful.   For instance, you might be
>getting an input which is a string representing the name of a variable and
>you wish to evaluate the expression (like a calculator application, for
>instance).
>
If you want to make a calculator, why not define a calculator class that
behaves the way you like, giving it methods for interaction according to any
syntax you like?

What would you like to be able to type for your calculator to interpret?
assignment statements and expressions? There is a difference between the
statements your calculator interprets and the statements you use to implement
your calculator, unless you are hoping just to pass input through for Python
to interpret (which will be risky if you don't control what's entered!).

But, to pursue your REXX example a bit, the question IMO is how important the
spelling is to you vs the functionality. Python lets you create custom objects
that behave pretty much any way you like. You can (ab)use the way python 
compiles
various operators operating on or with instances of your custom objects so you 
can
spell things in various ways, e.g., instead of
a = 3
y = "a"
print eval(y)

you could have a magic class instance o and write
o.a = 3
o.y = "a"
print o().y

and instead of 

interpret y' = 4'

write
o().y = 4 

Let's try it (untested beyond what you see here ;-)

 >>> class Magic(object):
 ... def __call__(self):
 ... return DerefName(self)
 ...
 >>> class DerefName(object):
 ... def __init__(self, wrapped):
 ... object.__setattr__(self, 'wrapped', wrapped)
 ... def __getattr__(self, name):
 ... wrapped = object.__getattribute__(self, 'wrapped')
 ... return getattr(wrapped, getattr(wrapped, name))
 ... def __setattr__(self, name, value):
 ... wrapped = object.__getattribute__(self, 'wrapped')
 ... setattr(wrapped, getattr(wrapped, name), value)
 ...
 >>> o = Magic()
 >>> o.a = 3
 >>> o.y = "a"
 >>> print o().y
 3
 >>> o().y = 4
 >>> print o().y
 4
 >>> o.y
 'a'
 >>> o.a
 4
 >>> o().z
 Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 6, in __getattr__
 AttributeError: 'Magic' object has no attribute 'z'
 >>> o.z = "y"
 >>> o().z
 'a'
 >>> o.z
 'y'

Anyway, getattr/setattr functionality provides the primal cauldron for python 
magic,
if you want to cook something up, and incantations usually involve prefixing 
the name of
a magic instance to your spell(ing)s ;-) Add descriptors for extra spice ...

Double, double, toil and trouble... oh, wait, that's for floating point ;-)

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


Re: mapping function to vars

2004-12-09 Thread Brian Quinlan
[EMAIL PROTECTED] wrote:
I need to map a function to several variables.  I'm trying to use map
and lambda to do this.  Here's my attempt...
#!/usr/bin/env python
from random import *
[fee, fye, foe, fum] = map(lambda n: random(), range(4))
from random import random
fee = random()
fye = random()
foe = random(),
fum = random()
print fee
print fye
print foe
print fum

...I'm essentially trying to map a function that takes no parameters to
a group of variables.  This works, but pychecker complains about the
'n' parameter.  Is there a better way to do this?  TIA
--
http://mail.python.org/mailman/listinfo/python-list


Re: mapping function to vars

2004-12-09 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
I need to map a function to several variables.  I'm trying to use map
and lambda to do this.  Here's my attempt...
#!/usr/bin/env python
from random import *
[fee, fye, foe, fum] = map(lambda n: random(), range(4))
print fee
print fye
print foe
print fum
...I'm essentially trying to map a function that takes no parameters to
a group of variables.  This works, but pychecker complains about the
'n' parameter.  Is there a better way to do this?  TIA
>>> import random
>>> fee, fye, foe, fum = [random.random() for _ in range(4)]
>>> fee, fye, foe, fum
(0.39415235335694276, 0.43533547827112462, 0.47106288849970501, 
0.87920678036897715)

I don't know pychecker well enough, but I think it ignores variables 
named _, so I think you could also just switch your n with _. 
Personally, I find the list comprehension much more readable.

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


Re: Loading a file only once into an object and being able to access it from other modules - still have a problem

2004-12-09 Thread Peter Hansen
Philippe C. Martin wrote:
class SC_ISO_7816:
__m_loaded = None
Please don't use tabs in code you post here.  Many newsreaders
have trouble displaying them, and make the code look like it
does above (i.e. no indentation at all) which makes it hard to
understand.
..
def __init__(self):
"""
"""
if SC_ISO_7816.__m_loaded == None:
SC_ISO_7816.__m_loaded = True
Here you are directly accessing a "class attribute",
which all instances will see.  You knew that.
print 'LOADING'
self.__Load()
What does this do?  You don't show the code, but from
the other stuff I infer it is creating an attribute
named self.SW1_DICT.  Is that right?
print self.SW1_DICT
And here you print it.
if I import and/or create more than one instance of SC_ISO_7816, when I see
'LOADING' then I also see a fully populated dictionary.
But when I see (second or more time)
'DICT ALREADY LOADED', then my dict is emtpy
What else am I not understanding  ?
Well, from the looks of things, you don't seem to understand the
basic idea of instances and instance attributes.  There is a key
difference between SC_ISO_67816.__m_loaded and self.SW1_DICT,
and that is that the former one is seen by *all instances*, while
the latter is an attribute in *only a single instance*.
Given that, you shouldn't expect multiple instances of
the class to be able to see the SW1_DICT attribute that
you set in self.__Load().
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I do this? (eval() on the left hand side)

2004-12-09 Thread Jeff Shannon
Nick Coghlan wrote:
Peter Hansen wrote:
Nick, could you please comment on why you say this about globals()?
I've never heard of any possibility of "unreliability" in updating
globals() and, as far as I know, a large body of code exists which
does in fact rely on this -- much of mine included. ;-)

As Steve pointed out, I was, well, flat out wrong. You're quite 
correct - it's only locals() that can cause a problem.

Of course, just because modifications of the dict returned by globals() 
*do* reliably result in modifications to the global namespace, doesn't 
mean it's a good idea. ;)

Personally, I don't *want* to create variables by "magic" like that.  
I'd rather pass a few extra parameters around, and explicitly create any 
global names I need.  If I really need to store objects under arbitrary 
names, then I probably should be using a regular dict (and passing it 
around as need be) instead of dumping stuff into globals().  (But then, 
I'm a devoted follower of the Pythonic principle of 'explicit is better 
than implicit' -- heck, even before I knew Python existed, I typically 
used this->name to reference C++ members despite the fact that 'this' 
was not required, just because I wanted to be able to *see* which 
variables were members and which weren't...)

Jeff Shannon
Technician/Programmer
Credit International
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse XML using Python

2004-12-09 Thread Fredrik Lundh
<[EMAIL PROTECTED]> wrote:

> 

> 
> .
> .
> 

> 
>
> ..
> and so on

an XML document can only have a single root element, but your example
has at least two top-level elements (abcd and xyz).

here is some elementtree code that handles this by wrapping your data in
a "root" element.

from elementtree import ElementTree

p = ElementTree.XMLTreeBuilder()

p.feed("")
p.feed(open("mydocument.xml").read())
p.feed("")

root = p.close()

def printelem(elem, prefix=""):
label = elem.get("label")
if label:
if not prefix:
print
print prefix + label
for elem in elem:
printelem(elem, prefix + "..")

for elem in root:
printelem(elem)

# end

the elementtree library can be found here:

http://effbot.org/zone/element-index.htm

 



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


Re: mapping function to vars

2004-12-09 Thread jahurt

Steven Bethard wrote:
> [EMAIL PROTECTED] wrote:
> > I need to map a function to several variables.  I'm trying to use
map
> > and lambda to do this.  Here's my attempt...
> >
> > #!/usr/bin/env python
> > from random import *
> >
> > [fee, fye, foe, fum] = map(lambda n: random(), range(4))
> >
> > print fee
> > print fye
> > print foe
> > print fum
> >
> > ...I'm essentially trying to map a function that takes no
parameters to
> > a group of variables.  This works, but pychecker complains about
the
> > 'n' parameter.  Is there a better way to do this?  TIA
> >
>
>  >>> import random
>  >>> fee, fye, foe, fum = [random.random() for _ in range(4)]
>  >>> fee, fye, foe, fum
> (0.39415235335694276, 0.43533547827112462, 0.47106288849970501,
> 0.87920678036897715)
>
> I don't know pychecker well enough, but I think it ignores variables
> named _, so I think you could also just switch your n with _.
> Personally, I find the list comprehension much more readable.
> 
> Steve

Thanks! This is exactly what I was after :)

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


Re: results of division

2004-12-09 Thread Christopher A. Craig
"Paul McGuire" <[EMAIL PROTECTED]> writes:

> Errr?  How come round() is able to understand 1.775 correctly, whereas
> string interp is not?  I'm guessing that round() adds some small epsilon to
> the value to be rounded, or perhaps even does the brute force rounding I
> learned in FORTRAN back in the 70's:  add 0.5 and truncate.  But this would
> still truncate 1.77999 to two places, so this theory fails also.  What
> magic is round() doing, and should this same be done in the string interp
> code?

Consulting bltinmodule.c would tell you.  round(x,n) in (Python 2.4):

multiplies x by 10**n
adds .5
truncates
divides by 10**n.

Don't confuse this trick with giving us the correct result though,
it's still floating point:

>>> round(1.77499, 2)
1.78

-- 
Christopher A. Craig <[EMAIL PROTECTED]>
"[Windows NT is] not about 'Where do you want to go today?'; it's more like
'Where am I allowed to go today?'" -- Mike Mitchell, NT Systems Administrator

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


Re: Creating Fixed Length Records

2004-12-09 Thread Andrew James
Greg,
Absolutely *perfect* case for a dose of Python string concatenation
performance theory or, How To Join Strings Together Fast:

http://www.skymind.com/~ocrow/python_string/

HTH,
Andrew

On Wed, 2004-12-08 at 17:29 -0600, Greg Lindstrom wrote:
> Hello-
> 
> I'm creating fixed-length record layouts for various record translations 
> I need to perform.  I have been using a home-grown object, 
> "FixedLengthRecord" for about 4 years now and am very happy with it.  
> Almost.  The burr under my saddle occurs when I serialize the record.  
> Currently, I create an empty text field and for each record in my 
> database (all record layouts, data types, lengths, defaults, etc. are 
> held in an SQL server) I concatenate the field to the text segment.  I 
> have been led to believe this is bad form because Python will copy the 
> entire segment each time I add a field.  Up until now, it was not a big 
> deal because the segments had at most 20 fields.  I have just been 
> handed a record layout that is almost 5000 bytes long with 350 fields in 
> it.  Gulp!!  Although I could let my object churn away on this bad boy, 
> I'd like to know if there is a more pythonic way to serialize the record.
> 
> One thought I had, which might lead to an addition to the language, was 
> to use the struct module.  If I could feed the pack method a format 
> string then a tuple of values (instead of individual values), then I 
> could create the format string once, then pass it a tuple with the 
> values for that record.  Just a thought. 
> 
> So, gurus, what are your suggestions to tame this record?  Are there 
> easier ways that I'm just not seeing?
> 
> Thanks,
> --greg
-- 
Andrew James <[EMAIL PROTECTED]>

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


Calling a C program from a Python Script

2004-12-09 Thread Brad Tilley
Is it possible to write a file open, then read program in C and then 
call the C program from a Python script like this:

for root, files, dirs in os.walk(path)
for f in files:
try:
EXECUTE_C_PROGRAM
If possible, how much faster would this be over a pure Python solution?
Thank you,
Brad
--
http://mail.python.org/mailman/listinfo/python-list


Re: Loading a file only once into an object and being able to access it from other modules - still have a problem

2004-12-09 Thread Philippe C. Martin
>Well, from the looks of things, you don't seem to understand the
>basic idea of instances and instance attributes.  There is a key
>difference between SC_ISO_67816.__m_loaded and self.SW1_DICT,
>and that is that the former one is seen by *all instances*, while
>the latter is an attribute in *only a single instance*.


Sorry for the tabs !


Indeed I had not grasped the concept has from my many years in C++, I would 
have had to use a private constructor + a static create method to keep users 
from instanciating more than one object.


You are correct, my __Load method "loads" self.DICTIONNARIES.

So now my understanding is that __Load needs to load 
SC_ISO_7816.DICTIONNARIES, and children classes will have to refer to 
SC_ISO_7816.DICTIONNARIES if they want to see something.


I'll give it a shot right now.

Thank you!

Philippe



-- 
*
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
*
--
http://mail.python.org/mailman/listinfo/python-list


Users

2004-12-09 Thread python1
Do you know of a way to list the users on a Win2K machine? I can't seem 
to find a module for this.

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


Re: ElementTree and XPATH

2004-12-09 Thread Istvan Albert
[EMAIL PROTECTED] wrote:
it seems to be invalid syntax if I give "/a/b[0]" to the findall()
method. Does anyone know the correct syntax?
I think the proper mindset going in should be that
elementtree does not support xpath but that
there are some handy constructs that resemble
the location steps of xpath.
Sometimes it takes very little work to achieve what
you want directly with python. In your case you could
probably use:
findall("/a/b")[0]
to the same effect.
Istvan.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a C program from a Python Script

2004-12-09 Thread Grant Edwards
On 2004-12-09, Brad Tilley <[EMAIL PROTECTED]> wrote:

> Is it possible to write a file open, then read program in C and then 
> call the C program from a Python script like this:

Huh?  What do you mean "write a file open"?  You want to read a
C source file and execute the C source?  If you have access to
a C interpreter, I guess you could invoke the interpreter from
python using popen, and feed the C source to it.  Alternatively
you could invoke a compiler and linker from C to generate an
executable and then execute the resulting file.

> for root, files, dirs in os.walk(path)
>  for f in files:
>  try:
>  EXECUTE_C_PROGRAM

You're going to have to explain clearly what you mean by
"EXECUTE_C_PROGRAM".  If you want to, you can certainly run a
binary executable that was generated from C source, (e.g. an
ELF file under Linux or whatever a .exe file is under Windows).

> If possible, how much faster would this be over a pure Python
> solution?

Solution to what?

-- 
Grant Edwards   grante Yow!  And furthermore,
  at   my bowling average is
   visi.comunimpeachable!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Users

2004-12-09 Thread Tim Golden
[python1]
| Do you know of a way to list the users on a Win2K machine? I 
| can't seem to find a module for this.

Interpretation 1: who is in the user database of a given machine?

Investigate the win32net module. Something like this:


import win32net
import win32netcon

MACHINE_NAME = 'VOGBP200'

resume = 0
while 1:
  (_users, total, resume) = \
win32net.NetUserEnum (
  MACHINE_NAME,
  1,
  win32netcon.FILTER_NORMAL_ACCOUNT,
  resume,
  win32netcon.MAX_PREFERRED_LENGTH
)
  for _user in _users:
print _user['name']
  if not resume:
break


Using active directory might also be a possibility.
As with many such questions, the first question is:
how do you do this in Windows generally? And then:
how do you translate that to Python?

Interpretation 2: who is currently logged on to the machine?

This is more difficult. On XP / 2003, there are WMI classes
to tell you this (Win32_LoggedOnUser) but not on 2000.
Likewise, there are LsaEnumerateLogonSessions in XP+,
but not on 2000. 

Anyone else got any ideas?

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Calling a C program from a Python Script

2004-12-09 Thread Istvan Albert
Brad Tilley wrote:
If possible, how much faster would this be over a pure Python solution?
It is like the difference between Batman and Ever.
batman is faster than ever
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a C program from a Python Script

2004-12-09 Thread Brad Tilley
Grant Edwards wrote:
Huh?  What do you mean "write a file open"?  You want to read a
C source file and execute the C source?  If you have access to
a C interpreter, I guess you could invoke the interpreter from
python using popen, and feed the C source to it.  Alternatively
you could invoke a compiler and linker from C to generate an
executable and then execute the resulting file.

for root, files, dirs in os.walk(path)
for f in files:
try:
EXECUTE_C_PROGRAM

You're going to have to explain clearly what you mean by
"EXECUTE_C_PROGRAM".  If you want to, you can certainly run a
binary executable that was generated from C source, (e.g. an
ELF file under Linux or whatever a .exe file is under Windows).
Appears I was finger-tied. I meant "a C program that opens and reads 
files" while Python does everything else. How does one integrate C into 
a Python script like that?

So, instead of this:
for root, files, dirs in os.walk(path)
 for f in files:
 try:
 x = file(f, 'rb')
 data = x.read()
 x.close()
this:
for root, files, dirs in os.walk(path)
 for f in files:
 try:
 EXECUTE_C_PROGRAM
From the Simpsons:
Frink: "Here we have an ordinary square."
Wiggum: "Whoa! Slow down egghead!"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a C program from a Python Script

2004-12-09 Thread It's me
I would expect C to run circles around the same operation under Python.   As
a general rule of thumb, you should use C for time cirtical operations
(computer time, that is), and use Python for human time critical situations
(you can get a program developed much faster).

I just discovered a magical package call SWIG (http://www.swig.org) that
makes writing C wrappers for Python always a child's play.  It's incredible!
Where were these guys years ago when I had to pay somebody moocho money to
develop a script language wrapper for my application!!!

--
It's me


"Brad Tilley" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Grant Edwards wrote:
> > Huh?  What do you mean "write a file open"?  You want to read a
> > C source file and execute the C source?  If you have access to
> > a C interpreter, I guess you could invoke the interpreter from
> > python using popen, and feed the C source to it.  Alternatively
> > you could invoke a compiler and linker from C to generate an
> > executable and then execute the resulting file.
> >
> >
> >>for root, files, dirs in os.walk(path)
> >> for f in files:
> >> try:
> >> EXECUTE_C_PROGRAM
> >
> >
> > You're going to have to explain clearly what you mean by
> > "EXECUTE_C_PROGRAM".  If you want to, you can certainly run a
> > binary executable that was generated from C source, (e.g. an
> > ELF file under Linux or whatever a .exe file is under Windows).
>
> Appears I was finger-tied. I meant "a C program that opens and reads
> files" while Python does everything else. How does one integrate C into
> a Python script like that?
>
> So, instead of this:
>
> for root, files, dirs in os.walk(path)
>   for f in files:
>   try:
>   x = file(f, 'rb')
>   data = x.read()
>   x.close()
> this:
>
> for root, files, dirs in os.walk(path)
>   for f in files:
>   try:
>   EXECUTE_C_PROGRAM
>
>  From the Simpsons:
> Frink: "Here we have an ordinary square."
> Wiggum: "Whoa! Slow down egghead!"


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


Re: Calling a C program from a Python Script

2004-12-09 Thread Fredrik Lundh
Brad Tilley wrote:

> for root, files, dirs in os.walk(path)
>  for f in files:
>  try:
>  EXECUTE_C_PROGRAM

http://docs.python.org/lib/module-subprocess.html

this module in new in 2.4; for older version, os.system() or the os.popen()
family might be what you're looking for.  see the "Replacing Older Functions
with the subprocess Module" section for more info.

 



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


Re: Calling a C program from a Python Script

2004-12-09 Thread Steven Bethard
It's me wrote:
I would expect C to run circles around the same operation under Python.
You should probably only expect C to run circles around the same 
operations when those operations implemented entirely in Python.  In the 
specific (trivial) example given, I wouldn't expect Python to be much 
slower:

for root, files, dirs in os.walk(path)
 for f in files:
 try:
 x = file(f, 'rb')
 data = x.read()
 x.close()
Remember that CPython is implemented in C, and so all the builtin types 
(including file) basically execute C code directly.  My experience with 
Python file objects is that they are quite fast when you're doing simple 
things like the example above.  (In fact, I usually find that Python is 
faster than Java for things like this.)

Of course, the example above is almost certainly omitting some code that 
really gets executed, and without knowing what that code does, it would 
be difficult to predict exactly what performance gain you would get from 
reimplementing it in C.  Profile the app first, find out where the tight 
spots are, and then reimplement in C if necessary (often, it isn't).

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


  1   2   >