Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Kay Schluehr
On Jul 20, 6:45 am, John Nagle <[EMAIL PROTECTED]> wrote:
> Juergen Erhard wrote:
> > On proving programs correct... from my CS study days I distinctly
> > remember thinking "sure, you can prove it correct, but you cannot do
> > actual useful stuff with it".  We might have come a long way since
> > then (late 80s :P), but I don't hold out much hope (especially since
> > the halting problem does exist, and forever will).
>
>  The halting problem only applies to systems with infinite memory.

Sure. But knowing that memory is limited doesn't buy you much because
you achieve an existential proof at best: you can show that the
program must run out of memory but you have to run the program to know
where this happens for arbitrary input values. Moreover you get always
different values for different memory limits. So in the general case
you can't improve over just letting the program run and notice what
happens.

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Diez B. Roggisch
Paul Rubin schrieb:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
>> For example, SPARK does not support dynamic allocation of memory so
>> things such as pointers and heap variables are not supported.
> 
> Right, Spark uses a profile intended for embedded systems, so
> no unpredictable gc delays etc.
> 
>> Which is not to say that trivial code couldn't have errors, and if
>> it's extremely cruical code, it's important that it hasn't errors. But
>> all I can see is that you can create trustable, simple sub-systems in
>> such a language. And by building upon them, you can ensure that at
>> least these won't fail.
> 
> Yes, that's the usual approach.
> 
>> But to stick with the example: if the path-planning of the UAV that
>> involves tracking a not before-known number of enemy aircrafts steers
>> the UAV into the ground, no proven-not-to-fail radius calculation will
>> help you.
> 
> Whether the program uses dynamic memory allocation or not, there
> either has to be some maximum number of targets that it can be
> required to track, or else it's subject to out-of-memory errors.
> If a maximum number is specified, then memory requirements can
> be computed from that.

In other words: you pre-allocate everything and can then proove what - 
that the program is going to be stop working?

  What does that buy you - where is "I'm crashed becaus I ran out of 
memory trying to evade the seventh mig" better than "sorry, you will be 
shot down because I'm not capable of processing more enemie fighters - 
but hey, at least I'm still here to tell you!"

Sorry, but if that's supposed to make a point for static typechecking, I 
don't buy it. Crippling the execution model so that it fits a 
proving-scheme which essentially says "don't do anything complex  with 
me" is no good.

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


Re: Pickled objects over the network

2007-07-20 Thread Hendrik van Rooyen
 Walker Lindley  wrote:

>Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to
send objects across the network. I'm sure >both Pyro and Yami can do that and I
may end up using one of them. For the initial version pickle will work because
we >have the networking issues figured out with it, just not the security
problem. So we may end up just sending strings back >and forth that will let us
fill out an object's member variables on the other end. It's much less cool, but
it seems like it'd >be more secure.
>

This passing of a pickled structure is so handy for simple things like lists of
parameters, and so on, that I wonder if it would not be worth while to somehow
beef up the security of the pickle stuff.

One heretical way I can think of would involve strict "typing" at the receiving
end - if you expect say a dict, then you should somehow specify that anything
else should fail...

as dict  my_received_dict = cpickle.loads(data_from_network)

or, better without a new "as" keyword:

my_received_dict=cpickle.loads(data_from_network,type=dict)

Is this at all feasible?

- Hendrik

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


Re: Real-time Update

2007-07-20 Thread Hendrik van Rooyen

"Alex Martelli" <[EMAIL PROTECTED]> wrote:


> Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> 
> > there is a recipe for this sort of thing, but I keep losing links.
> 
>  .
> 
thanks - but its probably no use - I predict I will lose this too...

: - )

- Hendrik

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


Re: Script to POST to web page with cookies?

2007-07-20 Thread 7stud
On Jul 19, 7:43 pm, Gilles Ganault <[EMAIL PROTECTED]> wrote:
> Hello
>
> I need to write a script to automate fetching data from a web site:
> 1. using the POST method, log on, with login/password saved as cookies
> 2. download page and extract relevent information using regexes
> 3. log off
> 4. wait for a random number of minutes, and GOTO 1
>
> I'm a bit confused with how to get POST and cookies in the same
> script:
> - urllib vs urllib2 vs httplib?
> - "ClientCookie.urlopen("www") behaves identically to urllib2.urlopen,
> except that it deals with cookies automatically"
>
> Has anyone some working code that I could borrow (er... steal) to do
> this?
>
> Thank you.

Also, see here:

http://www.voidspace.org.uk/python/articles/cookielib.shtml

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


Re: Converting between objects

2007-07-20 Thread Bruno Desthuilliers
Nathan Harmston a écrit :
> Hi,
> 
> I have being thinking about this and was wondering with built in types
> you can do things like
> 
> float(1) or str(200)
> 
> is there way I can define conversion functions like this:
> 
> say i have a class A and a class B
> 
> bobj = B()
> aobj = a(bobj)
> 
> in a neater way than just defining a set of methods
> 
> def a(object_to_convert)
># if object_to_convert of type..
># do some stuff
>   return A()
> 
> def b(object_to_convert)
># if object_to_convert of type..
># do some stuff
>   return B()
> 
> Cause this seems a little verbose and not very OO.

Just about the "not very OO" part: in Python, a class is a callable 
object - just like functions - that when called usually returns an 
instance of itself. IOW, a class is a Factory. So, from the client code 
POV, the fact that the factory is a class or function (both being 
callable objects) doesn't make any difference. Remember that OO is about 
objects, not about classes.

> Please correct me if I m wrong or offer me hints as to a better way to 
> do it ?

Others already answered the question. Note that if you need the factory 
to be able to return different subtypes based on it's argument or on 
some 'external' condition (platform, settings, whatever), you can also 
override the class '__new__' method, which is the real constructor 
(__init__ being the initialiser).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "The basics" difficulties

2007-07-20 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> I'm trying to get this basic sample to work:
> http://docs.python.org/ext/dnt-basics.html
> 
> When I get to the last step:
> $ python setup.py build
> 
> I get this error:
> error: Python was build with Visual Studio version 8.0 and
> extensions need to be built with the same version of the compiler,
> but it isn't installed.
> 
> This is bogus, as I do have VS8 installed.  I used it to compile
> the python stuff actually.

So you may want to check why the setup script does'nt detect it.


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


Re: Pickled objects over the network

2007-07-20 Thread Rustom Mody
Thats just what I was saying:

If the IPC issues have been solved on your own terms but the
data-serialization -- what you call making strings -- are not so
satisfactory, you could use yaml (with safe_load) as a replacement for
pickle and continue to use networking and IPC as you are currently
doing.

As I understand it the drop-in replacement for pickle is syck or
pysyck which uses yaml internally. Ive not yet grokked what exactly is
the relation between yaml and syck.

Just to give a sense of the difference between yaml and pickle:

>>> from pickle import dumps
>>> from yaml import dump


>>> l=[1,2,{'color':'blue', 'height': 5}]
>>> print dump(l)
- 1
- 2
- {color: blue, height: 5}

>>> print dumps(l)
(lp0
I1
aI2
a(dp1
S'color'
p2
S'blue'
p3
sS'height'
p4
I5
sa.

On 7/20/07, Walker Lindley <[EMAIL PROTECTED]> wrote:
> Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to
> send objects across the network. I'm sure both Pyro and Yami can do that and
> I may end up using one of them. For the initial version pickle will work
> because we have the networking issues figured out with it, just not the
> security problem. So we may end up just sending strings back and forth that
> will let us fill out an object's member variables on the other end. It's
> much less cool, but it seems like it'd be more secure.
>
>
> -Walker
>
>
> On 7/19/07, Rustom Mody <[EMAIL PROTECTED]> wrote:
> >
> > Irmen de Jong wrote
> > > In what way would Pyro be overkill where Yaml (also a module that you
> need
> > > to install separately) wouldn't be?
> >
> > Sure they are the same to install and sure pyro can do the job (pyro
> > is a nice package).
> >
> > But I got the impression that the questioner wanted to do the
> > networking stuff himself at a low level (using sockets) and the data
> > management using some available library -- pickle.
> >
> > Since pickle has problems
> > -- does not interface well with networking
> > -- security issues
> > -- has an xml option that according to the docs is an order of magnitude
> slower
> >
> > I thought I would point out yaml (with safe-load) which sits somewhere
> > inbetween the xml-pickle and the default pickle.
> >
> > I should also mention here that I find yaml is much more known and
> > used in the ruby and perl world than in the python world.  This is
> > unfortunate considering that both ruby and perl have a traditional
> > syntax (begin end, { } etc ).  On the other hand, python and yaml have
> > similar modern syntactic structures -- structure follows indentation
> > -- and are therefore well matched to each other.
> >
> > So in summary the 'competition' is not between yaml and pyro -- pyro
> > could easily have a pickle-using-yaml option -- but between yaml and
> > xml.
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
>
> --
> This e-mail is licensed under the Creative Commons Attribution-NoDerivs 2.5
> License. To view a copy of this license, visit
> http://creativecommons.org/licenses/by-nd/2.5/ or send a
> letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco,
> California, 94105, USA.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Paul Rubin
Kay Schluehr <[EMAIL PROTECTED]> writes:
> Sure. But knowing that memory is limited doesn't buy you much because
> you achieve an existential proof at best: you can show that the
> program must run out of memory but you have to run the program to know
> where this happens for arbitrary input values. Moreover you get always
> different values for different memory limits. So in the general case
> you can't improve over just letting the program run and notice what
> happens.

Program verification is nothing like the halting problem.  It's not
done by dropping the program into some tool and getting back a proof
of correctness or incorrectness.  The proof is developed, by the
programmer, at the same time the program is developed.  Verifiability
means that the programmer-supplied proof is precise enough to be
checked by the computer.

Think of when you first learned to program.  Most non-programmers have
an idea of what it means to follow a set of steps precisely.  For
example they could tell you an algorithm for sorting a shelf full of
books alphabetically by author.  Programming means expressing such
steps in much finer detail than humans usually require, to the point
where a machine can execute it; it takes a lot of patience and
knowledge of special techniques, more than non-programmers know how to
do, but we programmers are used to it and even enjoy it.

Now think of something like a code review.  There is a line of code in
your program (maybe even an assert statement), that depends on some
variable "x" being greater than 3.  You must have had a reason for
thinking x>3 there, so if the reviewer asks why you thought that, you
can explain your argument until the reviewer is convinced.

Do you see where this is going?  Code verification means expressing
such an argument in much finer detail than humans usually require, to
the point where a machine can be convinced by it; it takes a lot of
patience and knowledge of special techniques, more than most of us
regular "practical" programmers currently know how to do, but the
methods are getting more accessible and are regularly used in
high-assurance software.  In any case there is nothing magic about
it--just like programming, it's a means of expressing precisely to a
machine what you already know informally how to express to a human.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using eggs or py2exe to distribute apps

2007-07-20 Thread Matthias Vodel
Hey,

Use pyInstaller ;)

http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi

Easier to use in comparison to py2exe ... very good tool - try it!

Bye,

Matthias


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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Paul Rubin
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
>   What does that buy you - where is "I'm crashed becaus I ran out of
> memory trying to evade the seventh mig" better than "sorry, you will
> be shot down because I'm not capable of processing more enemie
> fighters - but hey, at least I'm still here to tell you!"

Come on, this is real-time embedded software, not some Visual Basic
app running in Windows.  The internal table sizes etc. are chosen
based on the amount of physical memory available, which has tended to
be pretty small until maybe fairly recently.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class C: vs class C(object):

2007-07-20 Thread [EMAIL PROTECTED]
Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> James Stroud  <[EMAIL PROTECTED]> wrote:
> >Aahz wrote:
> >> In article <[EMAIL PROTECTED]>,
> >> Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
> >>>
> >>>It isn't wrong to use the old style, but it is deprecated, [...]
> >>
> >>
> >> Really?  Can you point to some official documentation for this?  AFAIK,
> >> new-style classes still have not been integrated into the standard
> >> documentation.  Maybe I missed something, though.
> >>
> >> Note very carefully that "going away eventually" is *not* the same as
> >> deprecation.
> >
> >How about "broke" instead of "deprecated":
> >
> >
> > >>> class Old:
> >...   def __init__(self):
> >... self._value = 'broke'
> >...   value = property(lambda self: self._value)
> >...
>
> How is this broken?  Properties are not supported for old-style classes.
> They may not support features introduced in new-style classes, but that's
> hardly the same as "broken".

In particular, old-style classes are noticeably faster than new-style
classes for some things (I think it was attribute lookup that
surprised me recently, possibly related to the property stuff...)

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


Re: Using eggs or py2exe to distribute apps

2007-07-20 Thread [EMAIL PROTECTED]
On Jul 20, 5:39 am, Marcus <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm to the stage where I need to deploy the app I built with wxPython.
> I've been able to successfully build it w/py2exe into a binary (about
> 10MB size in total).
>
> What I'd like to do is create an automatic updater, so that I can have
> users download updated versions of my *application code* without having
> to have them redownload everything (the interpreter, etc) via a complete
> redownload (I want to package some things as "components").
>
> Eggs seem like an ideal solution, but I haven't had any luck using them
> in conjunction with py2exe.
>

It should be possible. exclude your application code from being
packaged, copy an egg file to your disribution directory and add it to
sys.path.


> It would seem that the most effective solution would be to package a
> python interpreter (with wxPython, etc already included) into the
> distributed app's directory and not use py2exe at all; however, since
> everything would be included in the distribution, it would seem that the
> full python distro would be huge (50MB at least), which defeats the
> purpose of wanting to build the app into "components".
>
> Worst-case scenario would be to have them redownload the 10MB update
> each time, but that's less than ideal, since the audience for my program
> would have more frequent/less substantial updates over time, rather than
> big updates all at once.
>
> Any guidance or suggestions are very much appreciated.

You can try bbfreeze from http://cheeseshop.python.org/pypi/bbfreeze/
(of which I'm the author). It has support for egg files. If  you
package your application code as an egg, it will by default copy your
whole egg (either as a directory or zipped) to the distribution
folder.




>
> Marcus


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


Re: class C: vs class C(object):

2007-07-20 Thread Bruno Desthuilliers
Aahz a écrit :
> In article <[EMAIL PROTECTED]>,
> Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>> To make a long story short: Python 2.2 introduced a new object model 
>> which is more coherent and more powerful than the original one. The old 
>> one was kept so far for compatibility reasons, but there's absolutely no 
>> reason to use it no more since "new-style" classes can do anything 
>> "Classic" classes did and much more. IOW, don't even bother with 
>> old-style classes.
> 
> And I'll make my usual knee-jerk response disagreeing with this.  For
> more info, search groups.google.com.

And you'll still make it harder for newcomers to understand why a lot of 
things don't work correctly with their classes. How helpful...

Aahz, the object model switch happened *years* ago, and it's quite clear 
that old style classes have been kept so far for compatibility reasons 
only. It's obvious that one doesn't gain *anything* - except compat with 
years-old pre-2.2 versions of Python - using old-style classes. So *why* 
on earth are you still *advocating* the use of old style classes ??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting between objects

2007-07-20 Thread Alex Popescu
"Nathan Harmston" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hi,
> 
> I have being thinking about this and was wondering with built in types
> you can do things like
> 
> float(1) or str(200)
> 
> is there way I can define conversion functions like this:
> 
> say i have a class A and a class B
> 
> bobj = B()
> aobj = a(bobj)
> 
> in a neater way than just defining a set of methods
> 
> def a(object_to_convert)
> # if object_to_convert of type..
> # do some stuff
>return A()
> 
> def b(object_to_convert)
> # if object_to_convert of type..
> # do some stuff
>return B()
> 
> Cause this seems a little verbose and not very OO.
> 
> Please correct me if I m wrong or offer me hints as to a better way to
> do it ? 
> 
> Many Thanks
> 
> nathan

I think your question is somehow misleading and here is why I'm thinking 
this:
1/ on one side: creating objects from other objects (and this part is 
related to float(1), str(200) and have been covered by the others in 
this thread)
2/ on the otherside: making an object to behave differently or implement 
a new protocol described by the second object (I think this is the 
Pythonic way of calling it).

bests,
./alex
--
.w( the_mindstorm )p.

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


Re: How to organize control access to source code ?

2007-07-20 Thread Paul Rubin
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> > How can we organize development team with code source control policy,
> > that limit access to some portion of code ?
> 
> The question may be of interest, but I'm afraid I don't understand how
> it relates to Python ???

It sounds like a reasonable application of multiple Mercurial
repositories.  Mercurial is a distributed source control system
written in Python.  Does that count?
-- 
http://mail.python.org/mailman/listinfo/python-list


code packaging

2007-07-20 Thread Paul Rubin
I've been through this kind of thing a few times in the past and
received excellent advice here on clpy about how to deal with specific
technical aspects (e.g. how to use setuptools, InnoSetup, etc).  

I'm now wondering where this type of thing is best addressed in more
general terms.  What I usually see happening, in projects I've worked
on and in others, is that developers get the code working on their own
computers, using source control tools and (if we're lucky) tests
developed in parallel with the code, but without much attention to
final packaging until the very end when the code is about to be
shipped.

Is this appropriate?  Inappropriate?  Do your projects start using
serious packaging and distribution tools very early in development,
before the code is anywhere near usable?  Should they?

I'm involved in something that I wish was that way, mainly because I
really don't have any way to put a complete installation on my own
computers; I have to develop my subsystem more or less independently
of the overall app, then toss stuff over the wall to the more central
application guys for integration, which gets slow sometimes because
we're distributed all over.  This is a fairly complex server app that
depends on a lot of external packages and programs running across
multiple machines, so I could see the packaging problem being messy.
It would cause a significant interruption in development to try to
package things so that the non-central developers could install and
hack it without a lot of assistance.  But I think it would be
worthwhile given how much easier it would become to test changes.  We
do plan to bundle up and release the code sometime (maybe as a Debian
package) but for now that's deferred until the code is more complete
and stable.

I'm wondering how other projects go about this.
-- 
http://mail.python.org/mailman/listinfo/python-list


◙►Watch FREE Satellite TV on your PC◄◙

2007-07-20 Thread Gary RAF
Instantly Turn your Computer into a Super TV

• Watch all your favorite shows on your Computer & TV!
• Channels you can’t get any other place in the U.S.A!
• Watch from anywhere in the world!
• Save 1000's of $$$ over many years on cable and satellite bills
• INSTANT DOWNLOAD
• And much, much more!

For More Details: http://tv-pc.xt.cx

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

Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-20 Thread Jean-Paul Calderone
On Thu, 19 Jul 2007 21:07:55 -0500, alf <[EMAIL PROTECTED]> wrote:
>
>Hi,
>
>I need a help with explaining following behavior. Although it is not
>python issue per say, python helped me to write sample programs and
>originally I encountered the issue using python software. So let's
>assume we have two following programs:
>
> [snip - file descriptors inherited by child process]

You can avoid this, if you like.  Set FD_CLOEXEC on the socket after you
open it, before you call os.system:

  old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
  fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)

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


Re: Pickled objects over the network

2007-07-20 Thread Jean-Paul Calderone
On Fri, 20 Jul 2007 09:32:17 +0200, Hendrik van Rooyen <[EMAIL PROTECTED]> 
wrote:
> Walker Lindley  wrote:
>
>>Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to
>send objects across the network. I'm sure >both Pyro and Yami can do that and I
>may end up using one of them. For the initial version pickle will work because
>we >have the networking issues figured out with it, just not the security
>problem. So we may end up just sending strings back >and forth that will let us
>fill out an object's member variables on the other end. It's much less cool, 
>but
>it seems like it'd >be more secure.
>>
>
>This passing of a pickled structure is so handy for simple things like lists of
>parameters, and so on, that I wonder if it would not be worth while to somehow
>beef up the security of the pickle stuff.
>
>One heretical way I can think of would involve strict "typing" at the receiving
>end - if you expect say a dict, then you should somehow specify that anything
>else should fail...
>
>as dict  my_received_dict = cpickle.loads(data_from_network)
>
>or, better without a new "as" keyword:
>
>my_received_dict=cpickle.loads(data_from_network,type=dict)
>
>Is this at all feasible?

No.  You could write a replacement for pickle, though.  Oh, wait...

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


Re: How to organize control access to source code ?

2007-07-20 Thread Bruno Desthuilliers
Paul Rubin a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
>>> How can we organize development team with code source control policy,
>>> that limit access to some portion of code ?
>> The question may be of interest, but I'm afraid I don't understand how
>> it relates to Python ???
> 
> It sounds like a reasonable application of multiple Mercurial
> repositories.  Mercurial is a distributed source control system
> written in Python.  Does that count?

Hmmm, let's see... The reference implementation of Python is written in 
C. Should we then post Python-related questions on c.l.c ?-)

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


Re: Interpreting os.lstat()

2007-07-20 Thread Sion Arrowsmith
=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=  <[EMAIL PROTECTED]> wrote:
>> (a) Running 'stat' is *not the same* as a system call.
>Why do you say that? It is *exactly* the same [ ... ]

Maybe if stat were implemented as

int main(int argc, char** argv) {
struct stat so_what_am_I_supposed_to_do_with_this;
return stat(argv[1], &so_what_am_I_supposed_to_do_with_this);
}

But it obviously does a lot of other stuff, including formatting
the results of the system call for display. Since what it really
at issue here is presentation of the results, I'd say that the
stat system call and the stat program wrapping it are very
different things.

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

Gmail Error using smtplib

2007-07-20 Thread DJ Fadereu
Hello, can anyone help me with this? What am I doing wrong here?

(I've changed private info to /xx)
 I'm getting an authentication error while using a standard script
Gmail:
--SCRIPT-
import smtplib
from email.MIMEText import MIMEText

msg = MIMEText('Hello, this is fadereu...')
>From = '[EMAIL PROTECTED]'

msg['Subject'] = 'Hello'
msg ['From'] = '[EMAIL PROTECTED]'
msg['To'] = '[EMAIL PROTECTED]'

s = smtplib.SMTP('alt1.gmail-smtp-in.l.google.com')
s.set_debuglevel(1)
s.login('[EMAIL PROTECTED]','x')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.close()
ERROR--
Traceback (most recent call last):
  File "C:\Documents and Settings\Acer User\Desktop\Code\S60 scripts
\Fadereu's Codez\gmail.py", line 13, in 
s.login('[EMAIL PROTECTED]','x'')
  File "C:\Python25\lib\smtplib.py", line 554, in login
raise SMTPException("SMTP AUTH extension not supported by
server.")
SMTPException: SMTP AUTH extension not supported by server.

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


Re: Gmail Error using smtplib

2007-07-20 Thread Tim Williams
On 20/07/07, DJ Fadereu <[EMAIL PROTECTED]> wrote:
> Hello, can anyone help me with this? What am I doing wrong here?
>
> (I've changed private info to /xx)
>  I'm getting an authentication error while using a standard script
> Gmail:
> --SCRIPT-
> import smtplib
> from email.MIMEText import MIMEText
>
> msg = MIMEText('Hello, this is fadereu...')
> >From = '[EMAIL PROTECTED]'
>
> msg['Subject'] = 'Hello'
> msg ['From'] = '[EMAIL PROTECTED]'
> msg['To'] = '[EMAIL PROTECTED]'
>
> s = smtplib.SMTP('alt1.gmail-smtp-in.l.google.com')
> s.set_debuglevel(1)
> s.login('[EMAIL PROTECTED]','x')
> s.sendmail(msg['From'], msg['To'], msg.as_string())
> s.close()
> ERROR--
> Traceback (most recent call last):
>  File "C:\Documents and Settings\Acer User\Desktop\Code\S60 scripts
> \Fadereu's Codez\gmail.py", line 13, in 
>s.login('[EMAIL PROTECTED]','x'')
>  File "C:\Python25\lib\smtplib.py", line 554, in login
>raise SMTPException("SMTP AUTH extension not supported by
> server.")
> SMTPException: SMTP AUTH extension not supported by server.
>

The error fairly self-explanitory :)

>>SMTPException: SMTP AUTH extension not supported by server.

In fact, you are trying to send outbound email through an inbound
email server.  You need to use GMAIL's outbound server.

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


Re: Pickled objects over the network

2007-07-20 Thread Sion Arrowsmith
Rustom Mody <[EMAIL PROTECTED]> wrote:
>Since pickle has problems
>-- does not interface well with networking

In what way does pickle not interface well with networking? Other
than, possibly, security issues which you list as a separate problem
with it. I've taken a working XML-RPC system and replaced the XML with
pickle, and had no issues. Other than an order of magnitude
performance gain. (OK, a cow-orker allegedly and unreproducibly found
that cPickle was leaking memory, and as the performance gains weren't
so great with the pure Python implementation, it got shelved and we
stuck with XML-RPC.)

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

Re: Interprocess communication woes

2007-07-20 Thread Murali
On Jul 19, 4:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> Murali <[EMAIL PROTECTED]> wrote:
> >  After some investigation, I found out that this problem had nothing to
> >  do with my GUI app not getting refreshed and I was able to reproduce
> >  this problem with normal python scripts. Here is one such script
>
> >  #File test.py
> >  from subprocess import Popen
> >  from subprocess import PIPE
> >  import sys
> >  if __name__ == '__main__':
> >   prog = sys.argv[1]
> >   proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0)
> >   out = proc.stdout
> >   while proc.poll() is None:
> > print out.readline()
>
> >  Run this program as follows
> >  $ test.py "ping -c 10www.google.com"
>
> >  Now, you would see the responses as if you just launched ping on the
> >  command line. Now, lets look at another program. Here is a simple C++
> >  program that prints numbers 1 to 10 at the passage of every second
> >  (sort of a stopwatch)
>
> >  #include 
> >  #include 
> >  #include 
> >  main ( )
> >  {
> >   timeval t1, t2;
> >   gettimeofday(&t1, NULL);
> >   int prev = -1;
> >   int cur = 0;
> >   while (true)
> >   {
> > gettimeofday(&t2,NULL);
> > if(t2.tv_sec - t1.tv_sec > 10)
> >   break;
> > else
> > {
> >   cur = t2.tv_sec-t1.tv_sec;
> >   if (cur != prev)
> >   {
> > printf("%d\r\n",cur);
> > prev = cur;
> >   }
> > }
> >   }
> >  }
>
> >  if you would build this program and call it lets say timer ($ g++ -o
> >  timer timer.cpp)  and run it with our python script like this
>
> >  $python test.py "./timer"
>
> >  you would see that every time you run the program your results vary
> >  and on top of this the stdout of the timer program gets displayed all
> >  at once presumably when the timer program has completed execution.
>
> >  Why this discrepancy between the ping and timer programs? Is my
> >  test.py script correct? Is there a better or a preferred method for
> >  doing interprocess communication in Python.
>
> Buffering is your problem.
>
> If you add a fflush(stdout); after the printf(...); you'll find the
> c++ program works as you expect.
>
> It is just a fact of life of the C stdio system.  If it is connected
> to a terminal then it will turn off buffering.  If it is connected
> anything else (eg a pipe via subprocess) then it will buffer stuff as
> you've seen.
>
> So you can
>
Thanks Nick. fflush fixed it. Thanks for your pointers on pexpect and
pty module too.

Murali.


> a) modify the c++ prog to add fflush() in or use setvbuf()
> b) use the pexpect module -http://pexpect.sourceforge.net/
> c) use the pty module (unix only)
>
> The pexpect module will connect to the subprogram with pseudo-ttys,
> fooling the program, and the C library, into thinking that it is
> speaking to a terminal and turn off buffering.  Pexpect doesn't work
> on windows.
>
> The fact that ping works is because it uses fflush() - you can see
> this if you "ltrace" it.
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick


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


Re: class C: vs class C(object):

2007-07-20 Thread Hrvoje Niksic
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> In particular, old-style classes are noticeably faster than
> new-style classes for some things (I think it was attribute lookup
> that surprised me recently, possibly related to the property
> stuff...)

Can you post an example that we can benchmark?  I ask because the
opposite is usually claimed, that (as of Python 2.4 or 2.5) new-style
classes are measurably faster.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-20 Thread alf
Jean-Paul Calderone wrote:

> 
> You can avoid this, if you like.  Set FD_CLOEXEC on the socket after you
> open it, before you call os.system:
> 
>  old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
>  fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
> 

thx for responding (I was about to send the question to twisted mailing 
list too ;-).


still would like to find out why it is happening (now FD_CLOEXEC 
narrowed may yahooing/googling searches). While realize that file 
descriptors are shared by forked processes it is still weird why the 
port moves to the child process once parent gets killed. what it the 
parent got multiple subprocesses.

Plus it is kind of unintuitive os.system does not protect from such 
behavoir which is for me more an equivalent of like issuing a ne 
wcommand/ starting a process from the shell.

Thx,

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


Re: class C: vs class C(object):

2007-07-20 Thread Steven D'Aprano
On Thu, 19 Jul 2007 10:42:54 -0700, Aahz wrote:

> In article <[EMAIL PROTECTED]>,
> Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>>
>>It isn't wrong to use the old style, but it is deprecated, [...]
> 
> Really?  Can you point to some official documentation for this?  AFAIK,
> new-style classes still have not been integrated into the standard
> documentation.  Maybe I missed something, though.
> 
> Note very carefully that "going away eventually" is *not* the same as
> deprecation.


*slaps head*

Yes, Aahz is correct, and I for one should have known better: see this
thread, for example, where I not only defend the use of old style classes
but explicitly stated that they *weren't* deprecated.

http://groups.google.com.au/group/comp.lang.python/browse_thread/thread/c33c458568b1027c/52fabc6398a566b6?lnk=st&q=steven+aahz+new+style+classes+&rnum=1#52fabc6398a566b6


Mea culpa.


-- 
Steven.

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Steve Holden
John Nagle wrote:
> Juergen Erhard wrote:
>> On proving programs correct... from my CS study days I distinctly
>> remember thinking "sure, you can prove it correct, but you cannot do
>> actual useful stuff with it".  We might have come a long way since
>> then (late 80s :P), but I don't hold out much hope (especially since
>> the halting problem does exist, and forever will).
> 
> The halting problem only applies to systems with infinite memory.
> 
> Proof of correctness is hard, requires extensive tool support, and
> increases software development costs.  But it does work.
> 
> Check out the "Spec#" effort at Microsoft for current work.
> Work continues in Europe on Extended Static Checking for Java,
> which was developed at DEC before DEC disappeared.
> 
The issue I have with correctness proofs (at least as they were 
presented in the 1980s - for all I know the claims may have become more 
realistic now) is that the proof of correctness can only relate to some 
highly-formal specification so complex that it's only comprehensible to 
computer scientists.

In other words, we can never "prove" that a program does what the 
customer wants, because the semantics are communicated in different 
ways, involving a translation which, since it is necessarily performed 
by humans using natural language, will always be incomplete at best and 
inaccurate at worst.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Gmail Error using smtplib

2007-07-20 Thread supercooper
This works for me...

def SendEmail(msgType,sender,recipient,subject,message):
"""
Sends either a log file or a string message in email to
recipient.
Uses Google smtp server to send the mail.

CHANGELOG:
2006-12-7:Set sender, recipient, subject as input variables
 
-
Inputs:
msgType:If 'log', message is path to log file that is to be
written into email body
sender: Senders email addy
recipient:  Who we want to send to
subject:Email subject line
message:Message body of email
 
-
"""
# determine msg type
if msgType == 'log':
# Send log file in email
fp = open(message, 'rb')
# Create a text/plain message
# Read contents of log file into memory
msg = MIMEText(fp.read())
fp.close()
else:
# If not a log file, just create a text/plain message
msg = MIMEText(message)

# User/pwd
me = '[EMAIL PROTECTED]'
pwd = 'pass'

# Build the email
fromAddr = sender
toAddr = recipient
msg['Subject'] = subject
msg['From'] = fromAddr
msg['To'] = toAddr

# Set up and connect to smtp server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login(me, pwd)
# Send the email
server.sendmail(fromAddr, toAddr, msg.as_string())
server.close()



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


Re: Pickled objects over the network

2007-07-20 Thread Steve Holden
Hendrik van Rooyen wrote:
>  Walker Lindley  wrote:
> 
>> Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to
> send objects across the network. I'm sure >both Pyro and Yami can do that and 
> I
> may end up using one of them. For the initial version pickle will work because
> we >have the networking issues figured out with it, just not the security
> problem. So we may end up just sending strings back >and forth that will let 
> us
> fill out an object's member variables on the other end. It's much less cool, 
> but
> it seems like it'd >be more secure.
> 
> This passing of a pickled structure is so handy for simple things like lists 
> of
> parameters, and so on, that I wonder if it would not be worth while to somehow
> beef up the security of the pickle stuff.
> 
Hmm, I suspect I detect the sounds of the square wheel being reinvented.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Compatibility of python2.5 with pytohn2.3

2007-07-20 Thread Gabriel Genellina
En Wed, 18 Jul 2007 08:36:24 -0300, Gerhard Häring <[EMAIL PROTECTED]>  
escribió:

> VISHAL KANAUJIA wrote:
>> Hi all,
>>  I am new member of this post. I have a C application which uses
>> Python(version 2.3) extensively with SWIG wrappers. I want to upgrade
>> the Python to latest version2.5.
>>
>> Is there any compatibility issue between two versions? Does latest
>> Python2.5 provide backward compatibility to previous Python (Version
>> 2.3 in my case) constructs.

> Short answer: yes.
>
> I've never had any issues here (compiling Python extension code in newer
> Python versions). The other way around that's of course not the case. I
> have to test my extension code against Python 2.4 and Python 2.3  
> regularly,

I would add this single point as the most relevant change in 2.5: "The  
obmalloc changes mean that you must be careful to not mix usage of the  
PyMem_*() and PyObject_*() families of functions. Memory allocated with  
one family's *_Malloc() must be freed with the corresponding family's  
*_Free() function." (On previous versions, mixing calls from different  
families could go mostly unnoticed, as nothing bad would happen).
Regarding Python source files, their encoding declaration is now mandatory  
when they contains any non ascii string.
(Reviewing the "What's new" documents would be a good idea anyway)

-- 
Gabriel Genellina

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


DateTime Differance

2007-07-20 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I've used the eGenix date time module to create two date time objects which
I'm now looking to compare like so:

 

If date 1 is more than 5 minutes older than date 2:

Do something here...

 

After reading through the egenix documentation I'm still a little confused
as the best way to do this. Can anyone offer any advice?

 

Thanks guys,

 

Rob

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

Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Diez B. Roggisch
Paul Rubin wrote:

> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
>>   What does that buy you - where is "I'm crashed becaus I ran out of
>> memory trying to evade the seventh mig" better than "sorry, you will
>> be shot down because I'm not capable of processing more enemie
>> fighters - but hey, at least I'm still here to tell you!"
> 
> Come on, this is real-time embedded software, not some Visual Basic
> app running in Windows.  The internal table sizes etc. are chosen
> based on the amount of physical memory available, which has tended to
> be pretty small until maybe fairly recently.

Since when did we restrict ourselves to such an environment? I was under the
impression that this thread is about the merits and capabilities of static
type-checking?

Besides, even if I accept these constraints - I still think the question is
valid: what goof is a proof if it essentially proofs that the code is
severely limited? After all, memory-allocation _might_ create a crash
depending on the actual circumstances - but it might not. Then, you trade a
mere possibility against a certain limitation.

No, I don't buy that. As I said before: for  the most trivial of tasks that
might be a good thing. But I'm not convinced that restricting one self in
such a manner for more complex tasks isn't going to be a better development
path.

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


Need Help

2007-07-20 Thread pycraze
Hi ,

   I am currently working on NTLM (Windows NT Lan Manager) APS
(Authentication Proxy Server ) . NTLM is MS own proprietary protocol
that will allow successful authentication for only MS browsers .

  NTLM APS was successfully cracked by Rosmanov and i am working
on NTLM APS python package version 0.98 .  I am currently on it to
port to C language .

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


Need Help

2007-07-20 Thread pycraze
Hi ,

   I am currently working on NTLM (Windows NT Lan Manager) APS
(Authentication Proxy Server ) . NTLM is MS own proprietary protocol
that will allow successful authentication for only MS browsers .

  NTLM APS was successfully cracked by Rosmanov and i am working
on NTLM APS python package version 0.98 .  I am currently on it to
port to C language .

  I have a specific issue on the authentication technique which
this APS uses . NTLM APS python package ver 0.98 uses two major types
of authentication process

1) DES
2) MD4 .

 The author has clearly stated that he has adopted both the above
python implementations from Python Cryptology Toolkit ( py-crypto)
version 2.0.1 . I started to use the DES C implementation of py-crypto
so that i can have an equivalent DES python implementation without
breaking a sweat . ;-)

 But both the implementation was totally different . I am getting
different hashed outputs . I compared each byte value of password from
python DES implementation and C implementation , both were not same .

Is anyone out there, can tell me why they are different .
Also i found that the key generation is different between them and
i suspect because of this the outputs are different ? So can this be
that the C implementation of DES in py-crypto had bugs and that it had
been corrected by Rozmanov and implemented in python ?

Also will there be any difference in implementing DES b/w python
and C language ?

Thanks,

Dennis

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


Re: Pickled objects over the network

2007-07-20 Thread Walker Lindley

It is feasible to an extent since loading each builtin object type is
handled by a different function. However, as others have pointed out it
makes more sense to use a more robust protocol than try to patch pickle.


-Walker

On 7/20/07, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:


Walker Lindley  wrote:

>Right, I could use Pyro, but I don't need RPC, I just wanted an easy way
to
send objects across the network. I'm sure >both Pyro and Yami can do that
and I
may end up using one of them. For the initial version pickle will work
because
we >have the networking issues figured out with it, just not the security
problem. So we may end up just sending strings back >and forth that will
let us
fill out an object's member variables on the other end. It's much less
cool, but
it seems like it'd >be more secure.
>

This passing of a pickled structure is so handy for simple things like
lists of
parameters, and so on, that I wonder if it would not be worth while to
somehow
beef up the security of the pickle stuff.

One heretical way I can think of would involve strict "typing" at the
receiving
end - if you expect say a dict, then you should somehow specify that
anything
else should fail...

as dict  my_received_dict = cpickle.loads(data_from_network)

or, better without a new "as" keyword:

my_received_dict=cpickle.loads(data_from_network,type=dict)

Is this at all feasible?

- Hendrik

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





--
This e-mail is licensed under the Creative Commons
Attribution-NoDerivs 2.5License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nd/2.5/ or send a letter to Creative
Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105,
USA.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: class C: vs class C(object):

2007-07-20 Thread George Sakkis
On Jul 20, 5:40 am, Bruno Desthuilliers  wrote:
> Aahz a écrit :
>
> > In article <[EMAIL PROTECTED]>,
> > Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
> >> To make a long story short: Python 2.2 introduced a new object model
> >> which is more coherent and more powerful than the original one. The old
> >> one was kept so far for compatibility reasons, but there's absolutely no
> >> reason to use it no more since "new-style" classes can do anything
> >> "Classic" classes did and much more. IOW, don't even bother with
> >> old-style classes.
>
> > And I'll make my usual knee-jerk response disagreeing with this.  For
> > more info, search groups.google.com.
>
> And you'll still make it harder for newcomers to understand why a lot of
> things don't work correctly with their classes. How helpful...
>
> Aahz, the object model switch happened *years* ago, and it's quite clear
> that old style classes have been kept so far for compatibility reasons
> only. It's obvious that one doesn't gain *anything* - except compat with
> years-old pre-2.2 versions of Python - using old-style classes. So *why*
> on earth are you still *advocating* the use of old style classes ??

FWIW, I am not advocating old style classes and I rarely (if ever) use
them in new code, but I occasionally miss the following feature, which
by the way disproves the assertion that "new-style classes can do
anything Classic classes did":

class Classic: pass
class NewStyle(object):pass

for o in Classic(),NewStyle():
o.__str__ = lambda: 'Special method overriding works on
instances!'
print '%s object: %s' % (o.__class__.__name__, o)


George

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

Re: Pickled objects over the network

2007-07-20 Thread Walker Lindley

It doesn't interface well because the string you end up with often doesn't
fit into a single packet. Therefore you have to add a layer of protocol on
top of it that allows you to check to make sure you have the whole string
received before trying to unpickle it. This the case even if you use
socket's makefile() method to make a file descriptor.


-Walker

On 20 Jul 2007 14:00:06 +0100 (BST), Sion Arrowsmith <
[EMAIL PROTECTED]> wrote:


>Since pickle has problems
>-- does not interface well with networking

In what way does pickle not interface well with networking? Other
than, possibly, security issues which you list as a separate problem
with it. I've taken a working XML-RPC system and replaced the XML with
pickle, and had no issues. Other than an order of magnitude
performance gain. (OK, a cow-orker allegedly and unreproducibly found
that cPickle was leaking memory, and as the performance gains weren't
so great with the pure Python implementation, it got shelved and we
stuck with XML-RPC.)

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

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





--
This e-mail is licensed under the Creative Commons
Attribution-NoDerivs 2.5License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nd/2.5/ or send a letter to Creative
Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105,
USA.
-- 
http://mail.python.org/mailman/listinfo/python-list

Document creation with odfpy

2007-07-20 Thread DarkBlue
Hello

I hope here is the right place to ask this:

I use the python odfpy library to create and
load an  odt file , however, spaces
in the passed in text are removed.

http://opendocumentfellowship.org/development/projects/odfpy

python2.4


from odf.opendocument import OpenDocumentText
from odf.style import Style, TextProperties
from odf.text import H, P, Span

def SaveIt(MYTEXT) :
  doc = OpenDocumentText()
  for line in MYTEXT:
p = P(text=line)
doc.text.addElement(p)
  doc.save('mynewfile.odt')


MYTEXT is a list containing lines from a wx.TextCtrl
if a line is:

abcabc  abcabc abcabc

the result in the odt file looks like:

abcabc abcabc abcabc



Is there anything I am doing wrong ?



Thanks
Db

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


Re: Break up list into groups

2007-07-20 Thread Ron Adam

Matimus wrote:

> Excellent work! One more modification and I get below 10us/pass:
> 
> def getgroups(seq):
>  groups = []
>  push = groups.append
>  iseq = iter(xrange(len(seq)))
>  for start in iseq:
>  if seq[start] & 0x80:
>  for stop in iseq:
>  if seq[stop] & 0x80:
>  push(seq[start:stop])
>  start = stop
>  push(seq[start:])
>  return groups
> 
> -Matt


Looks good to me. :-)

So a generator versions would be...

(not tested)

def getgroups(seq):
  iseq = iter(xrange(len(seq)))
  for start in iseq:
  if seq[start] & 0x80:
  for stop in iseq:
  if seq[stop] & 0x80:
  yield seq[start:stop]
  start = stop
  yield seq[start:]

(I also wanted to compare this to Georges solution, maybe later.)

Now if there is some way to generalize this so it can be used in a broader 
range of situations without loosing too much of it's efficiency.  Of course 
then maybe group by would be better.  

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


NTLM APS python version 0.98

2007-07-20 Thread pycraze
Hi ,

 I am working on NTLM (Windows NT Lan Manager )APS
(Authentication Proxy Server ) , to port to C language .

I am using ethereal to monitor the packets sent between client and
server . NTLM is a MS proprietary protocol designed so that will allow
authentication only from MS browsers .

This  proprietary was cracked and code was written in python by
Rozmanov .

The link to the source pool about NTLM is

http://www.innovation.ch/personal/ronald/ntlm.html

 Have any one worked extensively with NTLM APS python package
0.98 ?

NTLM APS have a 6 step process :- (C) - client (S)- server

1: C  --> S   GET ...

2: C <--  S   401 Unauthorized
  WWW-Authenticate: NTLM

3: C  --> S   GET ...
  Authorization: NTLM 

4: C <--  S   401 Unauthorized
  WWW-Authenticate: NTLM 

5: C  --> S   GET ...
  Authorization: NTLM 

6: C <--  S   200 Ok


After step 6 client must connect to server . But when i run NTLM
APS and watch the packets sent b/w client and server  in ethereal , i
see that client does not recieve 200 Ok at Step 6 , but receives 401
Unauthorized . After this i get a dialog box which requests me to
enter my user name and password  .

I enter the credentials and then the server authorizes the
client .

I am sorry that i cannot give more info on this . I can send the
saved page log from ethereal . That will give a very good idea .

As per theory , it is only a 6 step process  . I am puzzled
regarding this .

thanks ,

dennis

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


Python C Embedded ! Attribute Error

2007-07-20 Thread pycraze
Hi ,

I am using the below C code so that i can embed a Python Code and
get input from a python function and use it in C code .

  Below is the C Code


#include 

int
main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;

if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}

Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('/home/dennis/workplace/
aps098')");
PyRun_SimpleString("sys.path.append('/home/dennis/workplace/aps098/
lib')");
PyRun_SimpleString("import server, logger,config, ntlm_procs,
config_affairs ");
pModule = PyImport_Import(pName);
Py_DECREF(pName);

if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyInt_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
   }
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}


   The python code is a simple code

def pr(var):
 print var

I am getting error

AttributeError: 'module' object has no attribute 'print'
Cannot find function "print"


  I am a newbie to python . I need some to embed python in C . Anyone
Pls help

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


Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-20 Thread Jean-Paul Calderone
On Fri, 20 Jul 2007 08:15:39 -0500, alf <[EMAIL PROTECTED]> wrote:
>Jean-Paul Calderone wrote:
>
>>
>> You can avoid this, if you like.  Set FD_CLOEXEC on the socket after you
>> open it, before you call os.system:
>>
>>  old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
>>  fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
>>
>
>thx for responding (I was about to send the question to twisted mailing
>list too ;-).
>
>
>still would like to find out why it is happening (now FD_CLOEXEC
>narrowed may yahooing/googling searches). While realize that file
>descriptors are shared by forked processes it is still weird why the
>port moves to the child process once parent gets killed. what it the
>parent got multiple subprocesses.

It doesn't actually move.  The file descriptor is a handle onto the port.
A port can have multiple handles which refer to it.  When you fork, you
effectively copy the handle into another process.  Now there are two
handles onto the same port.  If one of the processes exits, the other one
still has a handle, and so the port still exists.  If a process forks
multiple times, then multiple copies are made.  Each process can accept
connections on the port through its own handle.  Exiting just drops the
handle, it doesn't close the port.

>
>Plus it is kind of unintuitive os.system does not protect from such
>behavoir which is for me more an equivalent of like issuing a ne
>wcommand/ starting a process from the shell.

Possibly, but intuitive and software often don't go hand in hand. :)

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


Re: Pickled objects over the network

2007-07-20 Thread Jean-Paul Calderone
On Fri, 20 Jul 2007 08:27:13 -0700, Walker Lindley <[EMAIL PROTECTED]> wrote:
>It doesn't interface well because the string you end up with often doesn't
>fit into a single packet. Therefore you have to add a layer of protocol on
>top of it that allows you to check to make sure you have the whole string
>received before trying to unpickle it. This the case even if you use
>socket's makefile() method to make a file descriptor.

This is somewhat misleading. TCP doesn't guarantee any minimum packet size
larger than a single byte.  Any messaging system which uses strings longer
than one byte must have a framing protocol to be reliable.  So, this isn't
really specific to pickle.  Basically, all protocols have to address this.

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


exec and CodeObjects

2007-07-20 Thread Prepscius, Colin (IT)
Does anybody know how to pass parameters to 'exec
somefunction.func_code'?
 
def f1():
print 'this is f1'
 
def f2(p):
print 'this is f2, p =', str(p)
 
exec f1.func_code
THIS RESULTS IN:  "this is nf1"   WHICH IS NICE
 
exec f2.func_code
THIS RESULTS IN:  TypeError: f2() takes exactly 1 argument (0 given)
WHICH IS EXPECTED
 
exec f2.func_code in {'p':34}
THIS RESULTS IN:  TypeError: f2() takes exactly 1 argument (0 given)
?
 
 
Why?  So I can take a function defined in a script or repl and a
parameter, marshal them, send the results to a remote host, unmarshal
them, and execute the function given the parameter.  Am I going about
this wrongly?  I'd specifically like to avoid having to save the
function in a file, send the file and import it on the remote side.
 
thanks!
Colin


NOTICE: If received in error, please destroy and notify sender. Sender does not 
intend to waive confidentiality or privilege. Use of this email is prohibited 
when received in error.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-20 Thread Jeff McNeil

The open file descriptor/socket shouldn't "move" between processes when you
kill the parent.  When os.system forks, anything you've got open in the
parent will transfer to the child.  Both descriptors reference the same open
port.  Running the same 'ss' and 'cc' code you've supplied behaves like that
on my workstation:

[EMAIL PROTECTED] ~]$ cat ss.py
import socket
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPSock.bind(('', 12345))

import os
os.system("python cc.py")

[EMAIL PROTECTED] ~]$ cat cc.py
import time
time.sleep(2036)

Corresponding lsof output when the above code runs shows the following
before killing the parent.

[EMAIL PROTECTED] ~]$ /usr/sbin/lsof | grep jeff | grep UDP
python18713  jeff3u IPv4  34004  UDP *:italk

python18714  jeff3u IPv4  34004  UDP *:italk



I don't believe FD_CLOEXEC will not stop the child from inheriting your open
file descriptors. Rather, it will ensure they're closed when execl(3) and
friends are called.

-Jeff




On 7/20/07, alf <[EMAIL PROTECTED]> wrote:


Jean-Paul Calderone wrote:

>
> You can avoid this, if you like.  Set FD_CLOEXEC on the socket after you
> open it, before you call os.system:
>
>  old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
>  fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
>

thx for responding (I was about to send the question to twisted mailing
list too ;-).


still would like to find out why it is happening (now FD_CLOEXEC
narrowed may yahooing/googling searches). While realize that file
descriptors are shared by forked processes it is still weird why the
port moves to the child process once parent gets killed. what it the
parent got multiple subprocesses.

Plus it is kind of unintuitive os.system does not protect from such
behavoir which is for me more an equivalent of like issuing a ne
wcommand/ starting a process from the shell.

Thx,

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

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

Re: Pickled objects over the network

2007-07-20 Thread Walker Lindley

Right, it's just a big problem with pickle because if you do a recv at the
wrong time and try to load it with pickle, you'll start getting weird errors
down in the pickle module as opposed to just not getting the full string you
expected if you were using plaintext strings. This is probably me being
spoiled from Java, but they built a stream class that can be used for files,
networks, and many other things while hiding nasty details like this. It
seems like Python could really benefit from this kind of architecture. Of
course, there's probably already something out there that I just don't know
about.


-Walker

On 7/20/07, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:


On Fri, 20 Jul 2007 08:27:13 -0700, Walker Lindley <[EMAIL PROTECTED]>
wrote:
>It doesn't interface well because the string you end up with often
doesn't
>fit into a single packet. Therefore you have to add a layer of protocol
on
>top of it that allows you to check to make sure you have the whole string
>received before trying to unpickle it. This the case even if you use
>socket's makefile() method to make a file descriptor.

This is somewhat misleading. TCP doesn't guarantee any minimum packet size
larger than a single byte.  Any messaging system which uses strings longer

than one byte must have a framing protocol to be reliable.  So, this isn't
really specific to pickle.  Basically, all protocols have to address this.

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





--
This e-mail is licensed under the Creative Commons
Attribution-NoDerivs 2.5License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nd/2.5/ or send a letter to Creative
Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105,
USA.


--
This e-mail is licensed under the Creative Commons
Attribution-NoDerivs 2.5License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nd/2.5/ or send a letter to Creative
Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105,
USA.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-20 Thread Hrvoje Niksic
alf <[EMAIL PROTECTED]> writes:

> still would like to find out why it is happening (now FD_CLOEXEC
> narrowed may yahooing/googling searches). While realize that file
> descriptors are shared by forked processes it is still weird why the
> port moves to the child process once parent gets killed. what it the
> parent got multiple subprocesses.

Netstat probably shows only one of the processes that hold to the
port, possibly the one with the lowest PID (the parent).

> Plus it is kind of unintuitive os.system does not protect from such
> behavoir which is for me more an equivalent of like issuing a ne
> wcommand/ starting a process from the shell.

It is considered a feature that fork/exec'ed programs inherit file
descriptors -- that's how stdin and stdout get inherited all the time.
It doesn't occur often with network connections because shells rarely
have reason to open them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Open HTML file in IE

2007-07-20 Thread 7stud
On Jul 19, 11:09 pm, gravey <[EMAIL PROTECTED]> wrote:
> The URL looks like this:
>
> file:///C|/Temp/Google%20Maps/linktothis.htm?lat=45.0&lng=-20.0&zoom=4&type =k
>
> The Javascript gets the URL from the Javascript location object and
> parses it. I'm assuming that the location object has some kind of
> Windows equivalent that might be set using win32com.client. Can anyone
> shed any light on this?
>
> Thanks

The location object is just your url.  So, if the url of the page you
open in IE is parsed by javascript, then you need to use a url with
the proper information in it.


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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread Paul Rubin
Steve Holden <[EMAIL PROTECTED]> writes:
> The issue I have with correctness proofs (at least as they were
> presented in the 1980s - for all I know the claims may have become
> more realistic now) is that the proof of correctness can only relate
> to some highly-formal specification so complex that it's only
> comprehensible to computer scientists.

Just like software as it is now, is only comprehensible to
programmers.  A long while back there was a language called COBOL
designed to be comprehensible to non-programmers, and it actually did
catch on, but it was cumbersome and limited even in its time and in
its application era, not so readable to non-programmers after all, and
is not used much in new projects nowadays.

> In other words, we can never "prove" that a program does what the
> customer wants, because the semantics are communicated in different
> ways, involving a translation which, since it is necessarily performed
> by humans using natural language, will always be incomplete at best
> and inaccurate at worst.

The types of things one tries to prove are similar to what is less
formally expressed as localized test cases in traditional software.
E.g. for a sorting routine you'd want to prove that output[n+1] >=
output[n] for all n and for all inputs.  As the Intel FDIV bug
incident reminds us, even billions of test inputs are not enough to
show that the routine does the right thing for EVERY input.
-- 
http://mail.python.org/mailman/listinfo/python-list


Images in Tkinter

2007-07-20 Thread Viewer T.
I wrote a class in which I have to use Tkinter images. When I create
an image object in the class and reference it with the image attribute
of label within the class, it does not dhow the image. It just shows a
blank label that conforms to the size of the image. My images is a GIF
image.

My code takes the form:
class Login:
 def __init__(self):
  create image object and other things necessary for class
initialisation
  self.make_widgets
 def make_widgets(self):
  Then I create my widgets

Then, I instantiate the login class.

I use Python 2.5. Does anyone have any idea why my imae does not
diplay itself? I have tried using the image before outside a class and
it works! Also, I tried creating the image object outside class but it
gives a runtime error saying it is too early to create an image
object. Please help!

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


Data type conversion

2007-07-20 Thread ervin ramonllari

Thank you very much,

It was a very helpful tool
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Images in Tkinter

2007-07-20 Thread Matt McCredie

That code doesn't tell me anything. You are going to have to post a more
complete example to get help. Like, enough code so that I can run it and see
the same problem.


Also, I tried creating the image object outside class but it
gives a runtime error saying it is too early to create an image
object. Please help!


You need to call Tkinter.Tk() before you can create an instance of
`PhotoImage' (I don't know why, but I know I got a similar error when I
didn't).

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

Python MAPI

2007-07-20 Thread kyosohma
Hi,

I've been googling all over and can't find any good answers about this
problem. I would like to create some kind of MAPI interface with
Python such that when I open Microsoft Word (or another Office
program) and click File, Send To, Mail Recipient it opens a program I
wrote in Python and uses it to send the email rather than Outlook.

The closest I've come is finding the registry key HKLM\Software\Clients
\Mail which seems to control the default email client. I did figure
out how to redirect mailto directives on websites to my program
successfully, but this is a whole 'nother ballgame.

Any suggestions are welcome. I am considering writing some VBA hooks
in Office Apps in question, but would prefer to avoid that.

Thanks!

Mike

P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows
XP Pro.

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


Re: Trying to choose between python and java

2007-07-20 Thread rvu44vs02
On Sun, 15 Jul 2007 at 22:28:08 -0700, Alex Martelli wrote:
> James T. Dennis <[EMAIL PROTECTED]> wrote:
>...
> >  You can start writing all your code now as: print() --- calling
> >  the statement as if it were a function.  Then you're future Python
> 
> ...except that your output format will thereby become disgusting...:
> 
> >>> name = 'Alex'
> >>> print 'Hello', name, 'and welcome to my program!'
> Hello Alex and welcome to my program!
> >>> print('Hello', name, 'and welcome to my program!')
> ('Hello', 'Alex', 'and welcome to my program!')
> 
> In Python 2.*, the parentheses will make a tuple, and so you'll get an
> output full of parentheses, quotes and commas.  I think it's pretty bad
> advice to give a newbie, to make his output as ugly as this.
> 
> 
> Alex
> -- 

One possible kind of print function that might be used in the interim is
something like:


def print_fn(*args):
"""print on sys.stdout"""
arg_str = " ".join([str(x) for x in args])
print arg_str

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-20 Thread John Nagle
Paul Rubin wrote:
> Kay Schluehr <[EMAIL PROTECTED]> writes:
> 
>>Sure. But knowing that memory is limited doesn't buy you much because
>>you achieve an existential proof at best: you can show that the
>>program must run out of memory but you have to run the program to know
>>where this happens for arbitrary input values. Moreover you get always
>>different values for different memory limits. So in the general case
>>you can't improve over just letting the program run and notice what
>>happens.
> 
> 
> Program verification is nothing like the halting problem.  It's not
> done by dropping the program into some tool and getting back a proof
> of correctness or incorrectness.  The proof is developed, by the
> programmer, at the same time the program is developed.  Verifiability
> means that the programmer-supplied proof is precise enough to be
> checked by the computer.
> 
> Think of when you first learned to program.  Most non-programmers have
> an idea of what it means to follow a set of steps precisely.  For
> example they could tell you an algorithm for sorting a shelf full of
> books alphabetically by author.  Programming means expressing such
> steps in much finer detail than humans usually require, to the point
> where a machine can execute it; it takes a lot of patience and
> knowledge of special techniques, more than non-programmers know how to
> do, but we programmers are used to it and even enjoy it.
> 
> Now think of something like a code review.  There is a line of code in
> your program (maybe even an assert statement), that depends on some
> variable "x" being greater than 3.  You must have had a reason for
> thinking x>3 there, so if the reviewer asks why you thought that, you
> can explain your argument until the reviewer is convinced.
> 
> Do you see where this is going?  Code verification means expressing
> such an argument in much finer detail than humans usually require, to
> the point where a machine can be convinced by it; it takes a lot of
> patience and knowledge of special techniques, more than most of us
> regular "practical" programmers currently know how to do, but the
> methods are getting more accessible and are regularly used in
> high-assurance software.  In any case there is nothing magic about
> it--just like programming, it's a means of expressing precisely to a
> machine what you already know informally how to express to a human.

 Ah. At last, an intelligent comment about program proving.

 One of the biggest problems with proof of correctness is that,
as a first step, you need a language where you don't have to "lie to
the language".  That is, the language must have sufficient power to
express even the ugly stuff.

 Python isn't bad in that regard.  A good example is the "struct"
module, where you can explicitly convert a string of bytes into a
Python tuple.  That's an inherently risky operation, but Python has
a safe and unambiguous way to express it that doesn't depend on the
machine representation of Python types.  In C and C++, this is often
done using casts, and what's going on is neither explicit nor checked.
Note that it's quite possible to implement something like the "struct"
module for C, and it could even be compiled into hard code.  (GCC,
for example, knows about "printf" strings at compile time, so that's
not an unacceptable idea.)

 The big problem with C and C++ in this area is the "array=pointer"
convention.  Again, that's lying to the compiler.  Programmers have to
write "char* p" which is a pointer to a char, when they mean an array
of characters.  That's inherently wrong.  It was a good idea in the 1970s
when it was developed, but we know better now.

 If you were doing proofs of correctness for Python, the biggest headache
would be checking for all the places where some object like a module or function
might be dynamically modified and making sure nobody was patching the code.

 Enough on this issue, though.

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


Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-20 Thread Steve Holden
Hrvoje Niksic wrote:
> alf <[EMAIL PROTECTED]> writes:
> 
>> still would like to find out why it is happening (now FD_CLOEXEC
>> narrowed may yahooing/googling searches). While realize that file
>> descriptors are shared by forked processes it is still weird why the
>> port moves to the child process once parent gets killed. what it the
>> parent got multiple subprocesses.
> 
> Netstat probably shows only one of the processes that hold to the
> port, possibly the one with the lowest PID (the parent).
> 
>> Plus it is kind of unintuitive os.system does not protect from such
>> behavoir which is for me more an equivalent of like issuing a ne
>> wcommand/ starting a process from the shell.
> 
> It is considered a feature that fork/exec'ed programs inherit file
> descriptors -- that's how stdin and stdout get inherited all the time.
> It doesn't occur often with network connections because shells rarely
> have reason to open them.

It would be hard to figure out how (x)inetd or TCP wrappers could work 
without the open connection being passed to the spawned server process.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


path error

2007-07-20 Thread godavemon
I'm on an intel macbook using OS X 10.4 and for some reason my path is
being interpreted incorrectly.  See the example:

[EMAIL PROTECTED] pwd
/Users/dave/til/jared <- dirname = jared
[EMAIL PROTECTED] python
...
>>> import os
>>> os.path.abspath('')
'/Users/dave/til/Jared'   <- dirname = Jared


python is capitalizing my jared directory.  It has worked for a long
time but suddenly doesn't.  I'm working on the project over SVN, could
it be some kind  of incompatibility with someone who submitted using
windows or something?  Any solutions for this?

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


Re: path error

2007-07-20 Thread godavemon
On Jul 20, 11:42 am, godavemon <[EMAIL PROTECTED]> wrote:
> I'm on an intel macbook using OS X 10.4 and for some reason my path is
> being interpreted incorrectly.  See the example:
>
> [EMAIL PROTECTED] pwd
> /Users/dave/til/jared <- dirname = jared
> [EMAIL PROTECTED] python
> ...>>> import os
> >>> os.path.abspath('')
>
> '/Users/dave/til/Jared'   <- dirname = Jared
>
> python is capitalizing my jared directory.  It has worked for a long
> time but suddenly doesn't.  I'm working on the project over SVN, could
> it be some kind  of incompatibility with someone who submitted using
> windows or something?  Any solutions for this?



Also my python version is

Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

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


Re: Python MAPI

2007-07-20 Thread vasudevram
On Jul 20, 10:57 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I've been googling all over and can't find any good answers about this
> problem. I would like to create some kind of MAPI interface with
> Python such that when I open Microsoft Word (or another Office
> program) and click File, Send To, Mail Recipient it opens a program I
> wrote in Python and uses it to send the email rather than Outlook.
>
> The closest I've come is finding the registry key HKLM\Software\Clients
> \Mail which seems to control the default email client. I did figure
> out how to redirect mailto directives on websites to my program
> successfully, but this is a whole 'nother ballgame.
>
> Any suggestions are welcome. I am considering writing some VBA hooks
> in Office Apps in question, but would prefer to avoid that.
>
> Thanks!
>
> Mike
>
> P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows
> XP Pro.

Hi,

1: I don't know much about Windows APIs, but am currently reading the
"Windows Internals" book. Got this idea from it:

Go to http://www.microsoft.com/technet/sysinternals/default.mspx
and check out the SysInternals utilities there. The book says that you
can use some of them to "spy" on what an app is doing - what registry
keys it is reading/writing, lots of other OS-level calls it makes as
it runs. Digging around and using some of these utilities to check out
what an Office app does when you use it to send mail, might help you
figure out a way to do what you want.

2. Try looking for registry entries specific to Office Apps, and look
under those subtrees for likely email-related entries to modify (if
you haven't tried that already). I guess you already know that
fiddling with the registry can be risky and can crash your system, so
take backups, etc.

Using COM via Python may also help - again, some digging required. You
probably already have the PyWin32 Python extensions for Windows COM
(earlier called win32all - see http://wiki.python.org/moin/Win32All) -
if not, its available here:

http://www.python.org/download/releases/2.4.4/
(scroll down the page for the link)

Vasudev Ram
www.dancingbison.com
jugad.livejournal.com
sourceforge.net/projects/xtopdf


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


Re: Python C Embedded ! Attribute Error

2007-07-20 Thread Miki
Hello,

> I am using the below C code so that i can embed a Python Code and
> get input from a python function and use it in C code .
>
>   Below is the C Code
[snipped]

> I am getting error
>
> AttributeError: 'module' object has no attribute 'print'
> Cannot find function "print"
How do you run your program (I suspect with 'pr pr print 1', should be
'pr pr pr 1').

FWIW, the following simplified program works:
#include 

int
main(int argc, char *argv[])
{
PyObject *modname, *module, *args, *value, *func;

Py_Initialize();

PyRun_SimpleString("import sys; sys.path.append(\".\")");

modname = PyString_FromString("pr");
module = PyImport_Import(modname);
Py_DECREF(modname);

if (NULL == module) {
fprintf(stderr, "error: can't load\n");
Py_Finalize();
return 1;
}

func = PyObject_GetAttrString(module, "pr");

args = PyTuple_New(1);
value = PyLong_FromLong(10);
PyTuple_SetItem(args, 0, value);

PyObject_CallObject(func, args);

Py_Finalize();
return 0;
}

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com


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


Weird errors when trying to access a dictionary key

2007-07-20 Thread robinsiebler
I have a data structure that looks like this:

#dates = {'2007': {'25': {'06/23/07': {'aerosmith': [{'sweet
emotion': 1}, {'dream on': 2}],
#  'Metallica': [{'Fade to
Black': 1}, {'Master of Puppets': 1}]},
# 'last_song': [Master of Puppets', 'Fade to Black',
'sweet emotion']}}}

I have a section where I try to loop through a set of dates and print
out all of the songs for a given artist:

if type == 'artist':
rpt_file.writelines('Song Summary for ' + artist + '\n\n')
for year in sorted(rpt_dates):
for week in sorted(rpt_dates[year]):
for date in sorted(dates[year][week]):
if artist in dates[year][week][date]:
report.append(date)
for song in sorted(dates[year][week][date]
[artist]):
rpt_file.writelines('\t' + [song].keys() \
+ '\t' +
[song].values() + '\n')


I get the following error:

Traceback (most recent call last):
  File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 1843, in runMain
self.dbg.runfile(debug_args[0], debug_args)
  File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 1538, in runfile
h_execfile(file, args, module=main, tracer=self)
  File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 596, in __init__
execfile(file, globals, locals)
  File "C:\scripts\python\Songs\song_report.py", line 136, in 
if __name__== '__main__': main()
  File "C:\scripts\python\Songs\song_report.py", line 134, in main
print_rpt(options.type, rpt_dates, dates, args)
  File "C:\scripts\python\Songs\song_report.py", line 107, in
print_rpt
+ '\t' + [song].values() + '\n')
AttributeError: 'list' object has no attribute 'keys'

Here is where it gets weird:

type(song)
Traceback (most recent call last):
  File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 3241, in runcode
locals = self.frame.f_locals)
  File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 1583, in runcode
h_exec(code, globals=globals, locals=locals, module=module)
  File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 520, in __init__
exec code in globals, locals
  File "", line 0, in 
TypeError: 'str' object is not callable
song
{"I Don't Wanna Stop": 1}
song.keys()
["I Don't Wanna Stop"]

For the complete script and data file, go to
http://members.dslextreme.com/users/robinsiebler/python/

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


Pythonic way for missing dict keys

2007-07-20 Thread Alex Popescu
Hi all!

I am pretty sure this has been asked a couple of times, but I don't seem 
to find it on the archives (Google seems to have a couple of problems 
lately).

I am wondering what is the most pythonic way of dealing with missing 
keys and default values.

According to my readings one can take the following approaches:

1/ check before (this has a specific name and acronym that I haven't 
learnt yet by heart)

if not my_dict.has_key(key):
  my_obj = myobject()
  my_dict[key] = my_obj
else:
  my_obj = my_dict[key]

2/ try and react on error (this has also a specific name, but...)

try:
  my_obj = my_dict[key]
except AttributeError:
  my_obj = myobject()
  my_dict[key] = my_obj

3/ dict.get usage:

my_obj = my_dict.get(key, myobject())

I am wondering which one is the most recommended way? get usage seems 
the clearest, but the only problem I see is that I think myobject() is 
evaluated at call time, and so if the initialization is expensive you 
will probably see surprises.

thanks in advance,
./alex
--
.w( the_mindstorm )p.

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


Re: Pythonic way for missing dict keys

2007-07-20 Thread Neil Cerutti
On 2007-07-20, Alex Popescu <[EMAIL PROTECTED]> wrote:
> Hi all!
>
> I am pretty sure this has been asked a couple of times, but I
> don't seem to find it on the archives (Google seems to have a
> couple of problems lately).
>
> I am wondering what is the most pythonic way of dealing with missing 
> keys and default values.
>
> According to my readings one can take the following approaches:

There's also the popular collections.defaultdict. 

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.

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


Re: Weird errors when trying to access a dictionary key

2007-07-20 Thread Zentrader
> rpt_file.writelines('\t' + [song].keys() \
> + '\t' +
> I get the following error:
>
> Traceback (most recent call last):
> AttributeError: 'list' object has no attribute 'keys'

All of these messages are correct.  The first error is
AttributeError: 'list' object has no attribute 'keys'
You are converting the dictionary to a list on this line, and lists do
not have keys
> rpt_file.writelines('\t' + [song].keys() \
   ---> to a list <---
When you print it, you are printing a dictionary, so it does have
keys.  Note the first line has braces, not brackets so it is a
dictionary.  You might want to consider using a dictionary of classes,
with each class containing all of the data that is now in the
hodgepodge of dictionaries, or simply a list with item[0]=year,
item[1]=month, etc.  This is an over-simplified version of using
classes to store data.  There has to be more examples on the web.
[code].class my_class :
.   def __init__(self):
.  self.field_1 = "init field_1"
.  self.field_2 = 0
.
.objectList = []
.for j in range(0, 2):
.objectList.append( my_class() )
.
.objectList[0].field_1= "Test [0] Field 1"
.objectList[0].field_2= "Data for Field #2 for [0]"
.objectList[0].field_3= "Data for Field #3 for [0]"  ## not in
original[/code]

print "objectList[0] =", objectList[0].field_1, ">",
\
   objectList[0].field_2, ">",
objectList[0].field_3
print "objectList[1] =", objectList[1].field_1, ">",
objectList[1].field_2

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


Re: Python MAPI

2007-07-20 Thread kyosohma
On Jul 20, 1:48 pm, vasudevram <[EMAIL PROTECTED]> wrote:
> On Jul 20, 10:57 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Hi,
>
> > I've been googling all over and can't find any good answers about this
> > problem. I would like to create some kind of MAPI interface with
> > Python such that when I open Microsoft Word (or another Office
> > program) and click File, Send To, Mail Recipient it opens a program I
> > wrote in Python and uses it to send the email rather than Outlook.
>
> > The closest I've come is finding the registry key HKLM\Software\Clients
> > \Mail which seems to control the default email client. I did figure
> > out how to redirect mailto directives on websites to my program
> > successfully, but this is a whole 'nother ballgame.
>
> > Any suggestions are welcome. I am considering writing some VBA hooks
> > in Office Apps in question, but would prefer to avoid that.
>
> > Thanks!
>
> > Mike
>
> > P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows
> > XP Pro.
>
> Hi,
>
> 1: I don't know much about Windows APIs, but am currently reading the
> "Windows Internals" book. Got this idea from it:
>
> Go tohttp://www.microsoft.com/technet/sysinternals/default.mspx
> and check out the SysInternals utilities there. The book says that you
> can use some of them to "spy" on what an app is doing - what registry
> keys it is reading/writing, lots of other OS-level calls it makes as
> it runs. Digging around and using some of these utilities to check out
> what an Office app does when you use it to send mail, might help you
> figure out a way to do what you want.
>
> 2. Try looking for registry entries specific to Office Apps, and look
> under those subtrees for likely email-related entries to modify (if
> you haven't tried that already). I guess you already know that
> fiddling with the registry can be risky and can crash your system, so
> take backups, etc.
>
> Using COM via Python may also help - again, some digging required. You
> probably already have the PyWin32 Python extensions for Windows COM
> (earlier called win32all - seehttp://wiki.python.org/moin/Win32All) -
> if not, its available here:
>
> http://www.python.org/download/releases/2.4.4/
> (scroll down the page for the link)
>
> Vasudev Ramwww.dancingbison.com
> jugad.livejournal.com
> sourceforge.net/projects/xtopdf

Thanks for the ideas...I am already monitoring the registry to see
what happens when I switch between two email clients. In this case, I
am switching between Outlook 2003 and Thunderbird 2. The pertinent
registry files are as follows:

# changes which email client to use
[HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail]

# obviously changes the .eml file association
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.eml]

# haven't the fogiest idea what this does, if anything
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{29F458BE-8866-11D5-
A3DD-00B0D0F3BAA7}]

# change mailto functionality
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\DefaultIcon]
@="C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe,0"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command]
@="\"C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe\" -osint -
compose \"%1\""

I assume you're referring to "Process Monitor", which is a really cool
tool. Maybe it'll help, but I usually can't get it to filter out
enough of the noise to make the output useful. I'll give it a go
nonethless.

I am running all my tests in a VM, so I really don't care if the
registry gets hosed at this point.

Thanks again,

Mike

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


Re: Pythonic way for missing dict keys

2007-07-20 Thread Carsten Haese
On Fri, 2007-07-20 at 19:08 +, Alex Popescu wrote:
> Hi all!
> 
> I am pretty sure this has been asked a couple of times, but I don't seem 
> to find it on the archives (Google seems to have a couple of problems 
> lately).
> 
> I am wondering what is the most pythonic way of dealing with missing 
> keys and default values.
> 
> According to my readings one can take the following approaches:
> 
> 1/ check before (this has a specific name and acronym that I haven't 
> learnt yet by heart)
>
> if not my_dict.has_key(key):
>   my_obj = myobject()
>   my_dict[key] = my_obj
> else:
>   my_obj = my_dict[key]

This is called "Look before you leap." Note that "if key in my_dict" is
preferred over has_key().

> 2/ try and react on error (this has also a specific name, but...)
>
> try:
>   my_obj = my_dict[key]
> except AttributeError:
>   my_obj = myobject()
>   my_dict[key] = my_obj
> 

This is called "It's easier to ask for forgiveness than permission."

> 3/ dict.get usage:
> 
> my_obj = my_dict.get(key, myobject())
> 
> I am wondering which one is the most recommended way? get usage seems 
> the clearest, but the only problem I see is that I think myobject() is 
> evaluated at call time, and so if the initialization is expensive you 
> will probably see surprises.

All ways are equally acceptable. The main difference is in the amount of
optimism the code conveys about the existence of the key. Number 1 and 3
convey the notion that you expect the key to be missing, that it's
normal for the key to be missing. Number 2 conveys the notion that the
key is only missing under exceptional circumstances.

As you noted, number 3 is not good if it's expensive to initialize a
myobject() instance, because the object will be created regardless of
whether it'll be needed. In that case, you should go with number 1, or
the following variant of number 3:

my_obj = my_dict.get(key, None)
if my_obj is None: my_obj = myobject()

This only works if the dictionary doesn't contain Nones already. If it
does, you would create a cheap sentinel object instead:

sentinel = object()
my_obj = my_dict.get(key, sentinel)
if my_obj is sentinel: my_obj = myobject()

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: path error

2007-07-20 Thread godavemon
On Jul 20, 11:45 am, godavemon <[EMAIL PROTECTED]> wrote:
> On Jul 20, 11:42 am, godavemon <[EMAIL PROTECTED]> wrote:
>
> > I'm on an intel macbook using OS X 10.4 and for some reason my path is
> > being interpreted incorrectly.  See the example:
>
> > [EMAIL PROTECTED] pwd
> > /Users/dave/til/jared <- dirname = jared
> > [EMAIL PROTECTED] python
> > ...>>> import os
> > >>> os.path.abspath('')
>
> > '/Users/dave/til/Jared'   <- dirname = Jared
>
> > python is capitalizing my jared directory.  It has worked for a long
> > time but suddenly doesn't.  I'm working on the project over SVN, could
> > it be some kind  of incompatibility with someone who submitted using
> > windows or something?  Any solutions for this?
>
> Also my python version is
>
> Python 2.4.4 (#1, Oct 18 2006, 10:34:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.

I deleted the directory and updated.  It fixed the problem.  Still an
odd one, but not a problem anymore.

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


Re: Python MAPI

2007-07-20 Thread vasudevram
On Jul 21, 12:28 am, [EMAIL PROTECTED] wrote:
> On Jul 20, 1:48 pm, vasudevram <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Jul 20, 10:57 pm, [EMAIL PROTECTED] wrote:
>
> > > Hi,
>
> > > I've been googling all over and can't find any good answers about this
> > > problem. I would like to create some kind of MAPI interface with
> > > Python such that when I open Microsoft Word (or another Office
> > > program) and click File, Send To, Mail Recipient it opens a program I
> > > wrote in Python and uses it to send the email rather than Outlook.
>
> > > The closest I've come is finding the registry key HKLM\Software\Clients
> > > \Mail which seems to control the default email client. I did figure
> > > out how to redirect mailto directives on websites to my program
> > > successfully, but this is a whole 'nother ballgame.
>
> > > Any suggestions are welcome. I am considering writing some VBA hooks
> > > in Office Apps in question, but would prefer to avoid that.
>
> > > Thanks!
>
> > > Mike
>
> > > P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows
> > > XP Pro.
>
> > Hi,
>
> > 1: I don't know much about Windows APIs, but am currently reading the
> > "Windows Internals" book. Got this idea from it:
>
> > Go tohttp://www.microsoft.com/technet/sysinternals/default.mspx
> > and check out the SysInternals utilities there. The book says that you
> > can use some of them to "spy" on what an app is doing - what registry
> > keys it is reading/writing, lots of other OS-level calls it makes as
> > it runs. Digging around and using some of these utilities to check out
> > what an Office app does when you use it to send mail, might help you
> > figure out a way to do what you want.
>
> > 2. Try looking for registry entries specific to Office Apps, and look
> > under those subtrees for likely email-related entries to modify (if
> > you haven't tried that already). I guess you already know that
> > fiddling with the registry can be risky and can crash your system, so
> > take backups, etc.
>
> > Using COM via Python may also help - again, some digging required. You
> > probably already have the PyWin32 Python extensions for Windows COM
> > (earlier called win32all - seehttp://wiki.python.org/moin/Win32All) -
> > if not, its available here:
>
> >http://www.python.org/download/releases/2.4.4/
> > (scroll down the page for the link)
>
> > Vasudev Ramwww.dancingbison.com
> > jugad.livejournal.com
> > sourceforge.net/projects/xtopdf
>
> Thanks for the ideas...I am already monitoring the registry to see
> what happens when I switch between two email clients. In this case, I
> am switching between Outlook 2003 and Thunderbird 2. The pertinent
> registry files are as follows:
>
> # changes which email client to use
> [HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail]
>
> # obviously changes the .eml file association
> [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.eml]
>
> # haven't the fogiest idea what this does, if anything
> [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{29F458BE-8866-11D5-
> A3DD-00B0D0F3BAA7}]
>
> # change mailto functionality
> [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\DefaultIcon]
> @="C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe,0"
> [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command]
> @="\"C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe\" -osint -
> compose \"%1\""
>
> I assume you're referring to "Process Monitor", which is a really cool
> tool. Maybe it'll help, but I usually can't get it to filter out
> enough of the noise to make the output useful. I'll give it a go
> nonethless.
>
> I am running all my tests in a VM, so I really don't care if the
> registry gets hosed at this point.
>
> Thanks again,
>
> Mike- Hide quoted text -
>
> - Show quoted text -

You're welcome :)

If Process Monitor has an option to save its output as text files /
CSV files (some of the other SysInternals tools do), you might want to
try using (a Windows version) of grep or awk to filter out the
noise ..

Vasudev


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


Re: Efficiently removing duplicate rows from a 2-dimensional Numeric array

2007-07-20 Thread Zentrader
On Jul 19, 8:35 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Alex Mont" <[EMAIL PROTECTED]> wrote in message
> I have a 2-dimensional Numeric array with the shape (2,N) and I want to
> remove all duplicate rows from the array. For example if I start out
> with:
> [[1,2],
> [1,3],
> [1,2],
> [2,3]]
>
> I want to end up with
> [[1,2],
> [1,3],
> [2,3]].

Converting to a set is the best way to go.  You can convert [1, 2] to
something like "001002" and use that if you first locate, or already
know the largest number.  The brute force way is to loop through the
list and compare this sub-list with list[N+1], then list[N+2], to the
end of the list.  If not found then append to a second list.

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


Re: Pythonic way for missing dict keys

2007-07-20 Thread Alex Popescu
Neil Cerutti <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> On 2007-07-20, Alex Popescu <[EMAIL PROTECTED]> wrote:
>> Hi all!
>>
>> I am pretty sure this has been asked a couple of times, but I
>> don't seem to find it on the archives (Google seems to have a
>> couple of problems lately).
>>
>> I am wondering what is the most pythonic way of dealing with missing 
>> keys and default values.
>>
>> According to my readings one can take the following approaches:
> 
> There's also the popular collections.defaultdict. 
> 
> Usually, the get method of normal dicts is what I want. I use a
> defaultdict only when the implicit addition to the dictionary of
> defaulted elements is what I really want.
> 

This looks like the closest to my needs, but in my case the default value 
involves the creation of a custom object instance that is taking parameters 
from the current execution context, so I am not very sure I can use it.

./alex
--
.w( the_mindstorm )p.



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


Re: Weird errors when trying to access a dictionary key

2007-07-20 Thread robinsiebler
> You are converting the dictionary to a list on this line, and lists do
> not have keys> rpt_file.writelines('\t' + 
> [song].keys() \
>
How am I converting it to a list?


> Note the first line has braces, not brackets so it is a
> dictionary.  

Braces?  What 1st line are you talking about?

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


Re: Weird errors when trying to access a dictionary key

2007-07-20 Thread robinsiebler
Ignore my previous response.  :p

I figured out what my  problem was.  I had [song].keys() when I really
meant song.keys() and really needed str(song.keys()).  I just got a
little too bracket happy.  :p


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


Re: Pythonic way for missing dict keys

2007-07-20 Thread Jakub Stolarski
Version 1 and 2 do different thing than version 3. The latter doesn't
add value to dict.

As it was mentioned before, use:
1 - if you expect that there's no key in dict
2 - if you expect that there is key in dict

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


Re: Pythonic way for missing dict keys

2007-07-20 Thread Carsten Haese
On Fri, 2007-07-20 at 20:10 +, Alex Popescu wrote:
> Carsten Haese <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]: 
> 
> > On Fri, 2007-07-20 at 19:08 +, Alex Popescu wrote:
> >> Hi all!
> >> 
> 
> >
> > [snip...]
> >
> > 
> > This is called "Look before you leap." Note that "if key in my_dict"
> > is preferred over has_key().
> >
> 
> Can you please detail why in is prefered over has_key? Is it about 
> readability/performance?

Yes, it's about both readability and performance:

[EMAIL PROTECTED] ~]$ python -m timeit -s "a={}" "a.has_key('foo')"
100 loops, best of 3: 0.601 usec per loop
[EMAIL PROTECTED] ~]$ python -m timeit -s "a={}" "'foo' in a"
100 loops, best of 3: 0.307 usec per loop

> Unfortunately, the get(key, None) suggestion is not 100% equivalent to 
> my posted code, and once I add the addition of the new object to the map 
> I think 1/ and 3/ are equivalent (if no other 
> readability/performance/etc is involved).

Indeed, I missed that in 1/ and 2/ you're also adding the value to the
dictionary. You could use setdefault instead of get:

my_obj = my_dict.setdefault(key, myobject())

But if you want to defer creation of the default value until it's
actually needed, you're better off with the "Look before you leap"
approach.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Trying to choose between python and java

2007-07-20 Thread James Matthews

You can always use jython. ;)

On 7/20/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


On Sun, 15 Jul 2007 at 22:28:08 -0700, Alex Martelli wrote:
> James T. Dennis <[EMAIL PROTECTED]> wrote:
>...
> >  You can start writing all your code now as: print() --- calling
> >  the statement as if it were a function.  Then you're future Python
>
> ...except that your output format will thereby become disgusting...:
>
> >>> name = 'Alex'
> >>> print 'Hello', name, 'and welcome to my program!'
> Hello Alex and welcome to my program!
> >>> print('Hello', name, 'and welcome to my program!')
> ('Hello', 'Alex', 'and welcome to my program!')
>
> In Python 2.*, the parentheses will make a tuple, and so you'll get an
> output full of parentheses, quotes and commas.  I think it's pretty bad
> advice to give a newbie, to make his output as ugly as this.
>
>
> Alex
> --

One possible kind of print function that might be used in the interim is
something like:


def print_fn(*args):
"""print on sys.stdout"""
arg_str = " ".join([str(x) for x in args])
print arg_str

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





--
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pythonic way for missing dict keys

2007-07-20 Thread Carsten Haese
On Fri, 2007-07-20 at 19:39 +, Alex Popescu wrote:
> Neil Cerutti <[EMAIL PROTECTED]> wrote in 
> news:[EMAIL PROTECTED]:
> 
> > On 2007-07-20, Alex Popescu <[EMAIL PROTECTED]> wrote:
> >> Hi all!
> >>
> >> I am pretty sure this has been asked a couple of times, but I
> >> don't seem to find it on the archives (Google seems to have a
> >> couple of problems lately).
> >>
> >> I am wondering what is the most pythonic way of dealing with missing 
> >> keys and default values.
> >>
> >> According to my readings one can take the following approaches:
> > 
> > There's also the popular collections.defaultdict. 
> > 
> > Usually, the get method of normal dicts is what I want. I use a
> > defaultdict only when the implicit addition to the dictionary of
> > defaulted elements is what I really want.
> > 
> 
> This looks like the closest to my needs, but in my case the default value 
> involves the creation of a custom object instance that is taking parameters 
> from the current execution context, so I am not very sure I can use it.

If by "current execution context" you mean globally visible names, this
should still be possible:

>>> from collections import defaultdict
>>> def make_default():
...return x+y
... 
>>> dd = defaultdict(make_default)
>>> x = 40
>>> y = 2
>>> print dd[0]
42
>>> x = "Dead"
>>> y = " Parrot"
>>> print dd[1]
Dead Parrot
>>> print dd
defaultdict(, {0: 42, 1: 'Dead Parrot'})

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Python MAPI

2007-07-20 Thread kyosohma

>
> If Process Monitor has an option to save its output as text files /
> CSV files (some of the other SysInternals tools do), you might want to
> try using (a Windows version) of grep or awk to filter out the
> noise ..
>
> Vasudev

Well, I ran Process Monitor with some filters enabled to only watch
Thunderbird and MS Word. Unfortunately, that didn't give me any of the
registry edits, so I disabled my filters and ran it without. Now I
have a log file with 28,000 entries. It's amazing to see all the stuff
that happens in just a few moments, but how am I supposed to parse
this mess?

Explorer.exe and outlook express do thousands of the registry calls
and the paths they manipulate vary wildly. Oh well, I'll be off the
clock in about 15 minutes so it can wait until Monday.

Thanks for your help. I'll post if I figure out anything...hopefully
you'll do the same.

Mike

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


Re: Images in Tkinter

2007-07-20 Thread kyosohma
On Jul 20, 11:37 am, "Viewer T." <[EMAIL PROTECTED]> wrote:
> I wrote a class in which I have to use Tkinter images. When I create
> an image object in the class and reference it with the image attribute
> of label within the class, it does not dhow the image. It just shows a
> blank label that conforms to the size of the image. My images is a GIF
> image.
>
> My code takes the form:
> class Login:
>  def __init__(self):
>   create image object and other things necessary for class
> initialisation
>   self.make_widgets
>  def make_widgets(self):
>   Then I create my widgets
>
> Then, I instantiate the login class.
>
> I use Python 2.5. Does anyone have any idea why my imae does not
> diplay itself? I have tried using the image before outside a class and
> it works! Also, I tried creating the image object outside class but it
> gives a runtime error saying it is too early to create an image
> object. Please help!

This might be the problem: 
http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

Mike

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


Re: code packaging

2007-07-20 Thread Miki
Hello Paul,

> I'm now wondering where this type of thing is best addressed in more
> general terms.  What I usually see happening, in projects I've worked
> on and in others, is that developers get the code working on their own
> computers, using source control tools and (if we're lucky) tests
> developed in parallel with the code, but without much attention to
> final packaging until the very end when the code is about to be
> shipped.
[snipped]

IMO you should invest the time a build automated packaging and some
smoke tests for the product.
After this is done, start using some "continuous automation" tools
(like http://cruisecontrol.sourceforge.net/, http://buildbot.net/trac
and others).

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: win32com ppt embedded object numbers reverting back to original numbers

2007-07-20 Thread kyosohma
On Jul 19, 4:33 pm, Lance Hoffmeyer <[EMAIL PROTECTED]> wrote:
> Hey all,
>
> I have a script that takes numbers from XL and inserts them into an embedded
> MSGRAPH dataset in PPT.  The problem is that when I reopen the modified 
> document
> that has been saved as a new filename and activate the embedded datasheet the
> new numbers that were inserted disappear and the old, original numbers come 
> back?
>
> I thought that adding these lines and resetting these variables was supposed 
> to prevent
> this from happening?
>
> del oGraph
> del PWB
> del oHEADER
> del oVALUE
>
> Anyone had experience with this and know what I need to do to keep the 
> embedded datasheet
> from reverting back to it's original numbers after modification?
>
> Thanks in advance,
>
> Lance
>
> #
> #
> # ADD THIS INTO A MODULE IN PPT TO OBTAIN THE PROG ID OF A SLIDE
> #Sub test()
> #MsgBox "The Slide ID of the current slide is:" & _
> #   ActiveWindow.View.Slide.SlideID
> #End Sub
> #
> def attributesbyID(row,base,slideID,spreadsheet):
> sh = wb.Worksheets (spreadsheet)
> sh.Select()
> LIST = xlparams(row, base)
>  POWERPOINT SECTION ##
> for shape in WB.Slides.FindBySlideID(slideID).Shapes:
> if (shape.Type== 7):
> for oXLROW,oXLBASE,oXLLASTCOL,oPPTCELL,oPPTHEADERCELL 
> in LIST:
> oVALUE = sh.Cells(oXLROW,oXLLASTCOL).Value
> oHEADER = sh.Cells(base-1,oXLLASTCOL).Value  
> + " (n="  +  str(int(sh.Cells(oXLBASE,oXLLASTCOL).Value))  + ")"
> PWB = 
> WB.Slides.FindBySlideID(slideID).Shapes(shape.Name)
> oGraph = PWB.OLEFormat.Object
> 
> oGraph.Application.datasheet.Range(oPPTCELL).Value = oVALUE
> 
> oGraph.Application.datasheet.Range(oPPTHEADERCELL).Value = oHEADER
> oGraph.Application.datasheet.Font.Bold=False
> del oGraph
> del PWB
> del oHEADER
> del oVALUE
> ###
> #
> #
> #
>
> def xlparams(row, base):
> lastcol=LASTCOL
> ### EXCEL SECTION TO GET NUMBERS #
> 
> thelist=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"),
>   
> (row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"),
>   
> (row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), 
> (row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ),
>   
> (row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), 
> (row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" ))
> ##
> return thelist
>
> ## attribute(ROW NUMBER, BASE ROW NUMBER, SLIDE NUMBER)
> attributesbyID(14,12,839,"Attributes(116-144)") # This medication has a 
> convenient dosing frequency

I've never done this with Python, but it sounds like your inserting a
linked table rather than a copy of the dataset as an Excel worksheet.
Try doing the insert manually to see which way keeps the data the way
you want, then you'll probably gain insight into what you need to do
in Python.

Mike

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


Re: Pythonic way for missing dict keys

2007-07-20 Thread Alex Popescu
Jakub Stolarski <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> Version 1 and 2 do different thing than version 3. The latter doesn't
> add value to dict.
> 
> As it was mentioned before, use:
> 1 - if you expect that there's no key in dict
> 2 - if you expect that there is key in dict
> 

I may be missing something but I think the 3 approaches are completely 
equivalent in terms of functionality.

./alex
--
.w( the_mindstorm )p.

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


Python Flagged as a Virus by AVG

2007-07-20 Thread James Matthews

I was reading a Microsoft news group  and came across this post

Got this during a scan of my computer:

infected: object C:\hp\bin\python-2.2.3.exe:\comparisons.html

result: trojan horse PHP/MPack.B

status: infected embedded object

inefected: object C:\hp\bin\python-2.2.3.exe

What can/should I do about this?

Thanks for your help.


then there is another post


I got the same thing with my free AVG, but it was not moved to virus valut.
Have no idea what to do. Any help is appreciated!!!

Mine says Comparisons.HTML PHP/MPACKB

Python-2.2.1.exe

then finnaly

I just read on the AVG forum, many folks  have gotten this threat today, it
is a false positive. To clear it, update your virus definitions and then run

another scan. The new update is suppose to fix it. I did an update, then
another scan, and it finally came back clean. Seems it isn't going in
people's virus vaults.

Hope this helps:-)


--
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Interpreting os.lstat()

2007-07-20 Thread Martin v. Löwis
> But it obviously does a lot of other stuff, including formatting
> the results of the system call for display. 

It most decisively does *not* format the results of the system call
"for display". Instead, it converts the C data type holding the
stat result into a Python data type. That data type historically
was a tuple, but now is struct-like type with the same fields as
the C data type.

It's the same as saying "+ does not do addition. It does a lot
of other stuff, including the formatting of the result of the
operation for display".

> Since what it really
> at issue here is presentation of the results, I'd say that the
> stat system call and the stat program wrapping it are very
> different things.

This is probably a matter of opinion. I think it is important
to understand that Python does *not* do any significant code
to os.stat and os.lstat; entirely unlike libraries in other
languages that attempt to also change the programming API in
the process of wrapping the system API.

Regards,
Martin

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


Sorting dict keys

2007-07-20 Thread montyphyton
Consider the following:
>>> a = {1:2, 3:4, 2:5}

Say that i want to get the keys of a, sorted. First thing I  tried:

>>> b = a.keys().sort()
>>> print b
None

Doesn't work. Probably because I am actually trying to sort the keys
of the dictionary without copying them first. If that is the case,
fine. Next thing I do:

>>> b = a.keys()
>>> b.sort()
[1, 2, 3]

Works fine, but I would really like it if I could somehow do it in one
line. As the problem seems to be copying the object, i try the
following:

>>> import copy
>>> b = copy.copy(a.keys()).sort()
>>> print b
None

Hmmm, why doesn't it work? Also,

>>> b = copy.deepcopy(a.keys()).sort()
>>> print b
None

(not that I thought that deepcopy will work since shallow didn't, I
understand the difference :) )
Obviously, I am missing something here. What am I thinking wrong? Why
doesn't copying the object work?
Thanks for all the help

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


Re: Sorting dict keys

2007-07-20 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

> Consider the following:
 a = {1:2, 3:4, 2:5}
> 
> Say that i want to get the keys of a, sorted. First thing I  tried:
> 
 b = a.keys().sort()
 print b
> None
> 
> Doesn't work. Probably because I am actually trying to sort the keys
> of the dictionary without copying them first. If that is the case,
> fine.

.sort returns None.

 b = a.keys()
 b.sort()
> [1, 2, 3]

This snippet is clearly edited, because .sort returns None:

 >>> a = {1:2, 3:4, 2:5}
 >>> b = a.keys()
 >>> b.sort()
 >>> b
[1, 2, 3]

The problem you're having here is that .sort returns None to indicate 
that it mutates the object, rather than returning a new one.  So get the 
keys, sort them, and then move along.

> Works fine, but I would really like it if I could somehow do it in one
> line.

Why is doing it in one line a priority?  Clarity is more important than 
brevity.

Regardless, you can do it in one line with the sorted builtin:

 >>> sorted(a.keys())
[1, 2, 3]

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   We must all hang together, or, most assuredly, we will all hang
separately. -- John Hancock
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting dict keys

2007-07-20 Thread Jean-Paul Calderone
On Fri, 20 Jul 2007 15:27:51 -0700, [EMAIL PROTECTED] wrote:
>Consider the following:
 a = {1:2, 3:4, 2:5}
>
>Say that i want to get the keys of a, sorted. First thing I  tried:
>
 b = a.keys().sort()
 print b
>None
>
>Doesn't work. Probably because I am actually trying to sort the keys
>of the dictionary without copying them first. If that is the case,
>fine. Next thing I do:
>
 b = a.keys()
 b.sort()
>[1, 2, 3]

This is a mis-observation.  b.sort() does /not/ return [1, 2, 3].
b.sort() returns None.  The sort method of the list type performs
an in-place sort and always returns None.  With that in mind, the
rest of your code snippets might make more sense.

I'll leave it to you to figure out how to jam everything into one
line (or, more realistically, another poster in about 2 seconds,
I'm sure), since I don't really see the value in that exercise
myself.

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


Re: Sorting dict keys

2007-07-20 Thread Will Maier
On Fri, Jul 20, 2007 at 03:27:51PM -0700, [EMAIL PROTECTED] wrote:
> Consider the following:
> >>> a = {1:2, 3:4, 2:5}
> 
> Say that i want to get the keys of a, sorted. First thing I  tried:
> 
> >>> b = a.keys().sort()
> >>> print b
> None

list's sort() method sorts the list _in_place_:

>>> l = ['spam', 'eggs']
>>> help(l.sort)
Help on built-in function sort:

sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

That means that doesn't return a sorted version of the list you're
working with. Instead, it sorts the list itself.

If you want to return a sorted list, use (duh) sorted:

>>> sorted(l)
['eggs', 'spam', 'spam']

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting dict keys

2007-07-20 Thread Duncan Smith
[EMAIL PROTECTED] wrote:
> Consider the following:
> 
a = {1:2, 3:4, 2:5}
> 
> 
> Say that i want to get the keys of a, sorted. First thing I  tried:
> 
> 
b = a.keys().sort()
print b
> 
> None
> 
> Doesn't work. Probably because I am actually trying to sort the keys
> of the dictionary without copying them first. If that is the case,
> fine. Next thing I do:
> 
> 
b = a.keys()
b.sort()
> 
> [1, 2, 3]
> 
> Works fine, but I would really like it if I could somehow do it in one
> line. As the problem seems to be copying the object, i try the
> following:
> 
> 
import copy
b = copy.copy(a.keys()).sort()
print b
> 
> None
> 
> Hmmm, why doesn't it work? Also,
> 
> 
b = copy.deepcopy(a.keys()).sort()
print b
> 
> None
> 
> (not that I thought that deepcopy will work since shallow didn't, I
> understand the difference :) )
> Obviously, I am missing something here. What am I thinking wrong? Why
> doesn't copying the object work?
> Thanks for all the help
> 

sort() sorts a list in place and returns None.  For a one-liner:

>>> a = {1:2, 3:4, 2:5}
>>> b = sorted(a.keys())
>>> b
[1, 2, 3]

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


Re: Sorting dict keys

2007-07-20 Thread Alex Popescu
[EMAIL PROTECTED] wrote in news:1184970471.146819.86280
@r34g2000hsd.googlegroups.com:

I am not sure about your scenario, but as you discovered the sort() method 
is modifying the in place list (and doesn't return a new one). 
If you just want to iterate over your dict in an ordered manner than all 
you have to do is:

for k in my_dict.keys().sort():
  # rest of the code

If you just want to keep a list of ordered keys you can probably do 
something like:

key_list = list(my_dict.keys())
key_list.sort()

bests,
./alex
--
.w( the_mindstorm )p.


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


ANN: CharPy, Charlotte, NC Python Group

2007-07-20 Thread Calvin Spealman
I announced the idea earlier, but forgot to mention the state. I
started a mailing list, and I want to find who in the area might be
interested. Join if you can, even if you don't know you'll stick. We
need to see what kind of interest there is in the area.

If you are in the area, even if you aren't sure you'll attend meetups,
can you recommend a good location?

http://groups.google.com/group/charpy

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code packaging

2007-07-20 Thread Ben Finney
Paul Rubin  writes:

> Is this appropriate?  Inappropriate?  Do your projects start using
> serious packaging and distribution tools very early in development,
> before the code is anywhere near usable?  Should they?

Yes. Test-driven development has taught me that putting off important
parts of the development process until the end is rarely a good
idea. So, I try to make a point of writing the first features inside a
complete unit test environment, and inside a complete
distribution/build environment. The tests are run continuously while
developing the code, and the distribution/build process is tested
manually.

I'm looking into the "build-bot" approach used to ensure that the
build process is also run automatically and continually during
development, just like the unit tests http://buildbot.net/>; but
so far I'm running the build manually.

-- 
 \"Read not to contradict and confute, nor to believe and take |
  `\ for granted ... but to weigh and consider."  -- Francis Bacon |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird errors when trying to access a dictionary key

2007-07-20 Thread Ben Finney
[EMAIL PROTECTED] writes:

> I have a data structure that looks like this:
> [...]
> rpt_file.writelines('\t' + [song].keys() + '\t' + [song].values() + '\n')

Forms the list [song] twice, attempting to call the 'keys()' method
and the 'values()' method of that list in turn...

> I get the following error:
> 
> Traceback (most recent call last):
> [...]
> AttributeError: 'list' object has no attribute 'keys'

... which doesn't exist.

> Here is where it gets weird:
> 
> song
> {"I Don't Wanna Stop": 1}
> song.keys()
> ["I Don't Wanna Stop"]

Yes. A list doesn't have a 'keys' or 'values' method, a dict
does. 'song' is a dict. So why are you not calling the 'keys' method
of the 'song' object?

-- 
 \   "If [a technology company] has confidence in their future |
  `\  ability to innovate, the importance they place on protecting |
_o__)  their past innovations really should decline."  -- Gary Barnett |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting dict keys

2007-07-20 Thread Miles
On 7/20/07, Alex Popescu <[EMAIL PROTECTED]> wrote:
> If you just want to iterate over your dict in an ordered manner than all
> you have to do is:
>
> for k in my_dict.keys().sort():
>   # rest of the code

I think you meant sorted(my_dict.keys()), since, as you just pointed
out, the sort() method returns None.

> If you just want to keep a list of ordered keys you can probably do
> something like:
>
> key_list = list(my_dict.keys())
> key_list.sort()

Creating a copy with list() is unnecessary, as keys() already returns a copy.

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


Re: Sorting dict keys

2007-07-20 Thread Roberto Bonvallet
On 20 jul, 18:50, Alex Popescu <[EMAIL PROTECTED]> wrote:
> If you just want to iterate over your dict in an ordered manner than all
> you have to do is:
>
> for k in my_dict.keys().sort():
>   # rest of the code

sort() returns None, so this code won't work either.

--
Roberto Bonvallet

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


Re: PDF2ODT

2007-07-20 Thread Zentrader
On Jul 17, 12:47 pm, orehon <[EMAIL PROTECTED]> wrote:
> Hello,
>   I need to convert PDF to ODT or  PDF to DOC using python!
>
>   I was taking a look 
> athttp://www.kde-apps.org/content/show.php/show.php?content=18638&vote=...
> and this project is outdated.
>
>   So any idea?
>
> Thank you!

I have heard of this but have not tried it.  Your best bet is to use
an existing program, like OpenOffice, and call it with os.system() or
one of the popen varieties if you want to do more than copy to a new
file.
http://freshmeat.net/projects/unoconv/

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


Re: Sorting dict keys

2007-07-20 Thread montyphyton
On 21 srp, 00:47, Duncan Smith <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Consider the following:
>
> a = {1:2, 3:4, 2:5}
>
> > Say that i want to get the keys of a, sorted. First thing I  tried:
>
> b = a.keys().sort()
> print b
>
> > None
>
> > Doesn't work. Probably because I am actually trying to sort the keys
> > of the dictionary without copying them first. If that is the case,
> > fine. Next thing I do:
>
> b = a.keys()
> b.sort()
>
> > [1, 2, 3]
>
> > Works fine, but I would really like it if I could somehow do it in one
> > line. As the problem seems to be copying the object, i try the
> > following:
>
> import copy
> b = copy.copy(a.keys()).sort()
> print b
>
> > None
>
> > Hmmm, why doesn't it work? Also,
>
> b = copy.deepcopy(a.keys()).sort()
> print b
>
> > None
>
> > (not that I thought that deepcopy will work since shallow didn't, I
> > understand the difference :) )
> > Obviously, I am missing something here. What am I thinking wrong? Why
> > doesn't copying the object work?
> > Thanks for all the help
>
> sort() sorts a list in place and returns None.  For a one-liner:
>
> >>> a = {1:2, 3:4, 2:5}
> >>> b = sorted(a.keys())
> >>> b
>
> [1, 2, 3]
>
> Duncan

Thanks, this is what I was looking for. I know that .sort() sorts the
list in-place (the snippet I posted was written in a hurry, not pasted
-- I apologise for that). In fact, this is exactly what puzzles me.
copy.copy returns a new object:

>>> copy.copy(a.keys())
[1,2,3]

Then why doesn't copy.copy(a.keys()).sort() work??
Thanks to everyone who replied!

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


Re: Sorting dict keys

2007-07-20 Thread Roberto Bonvallet
On 20 jul, 19:34, [EMAIL PROTECTED] wrote:
> copy.copy returns a new object:
>
> >>> copy.copy(a.keys())
>
> [1,2,3]
>
> Then why doesn't copy.copy(a.keys()).sort() work??

It works, but you don't notice it, because you don't save a reference
to the new list.
Try this:

  c = copy.copy(a.keys())
  c.sort()

--
Roberto Bonvallet

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


  1   2   >