improve this newbie code/nested functions in Python?

2009-03-19 Thread Esmail
Hi,

I'm new to writing Python code. This is a simple client I wrote, it
works, but I feel it doesn't look as clean as it could. Can anyone
make suggestions how to streamline this code?

Also, I am using two nested functions, it seems that nested functions
aren't used that much in Python - is that correct? And if so, how
come?

thanks,

Esmail

ps: I realize there is minimal error checking/exception handling.

#!/usr/bin/env python


import sys
from socket import *
from threading import Thread


class Client(object):
def __init__(self, host="localhost", port=, name = "esmail"):
self._host = host
self._port = port
self._name = name
self._address=(self._host, self._port)
self._sock=socket(AF_INET, SOCK_STREAM)
self._sock.connect(self._address)
self._parent = self
self._keepGoing = True

def info(self):
return self._host, self._port, self._name



class Listener(Thread):
   def __init__(self, parent, tname="listener"):
   Thread.__init__(self,name = tname)
   self._parent = parent
   print self._parent._host

   def run(self):

   while self._parent._keepGoing:
   m = self._parent._sock.recvfrom(1024)
   print m[0]



class Speaker(Thread):
   def __init__(self, parent, tname = "speaker"):
   Thread.__init__(self,name = tname)
   self._parent = parent
   self._parent._sock.send(self._parent._name + "\n")


   def run(self):

   while(True):
   m = raw_input("-> ")
   if m == "bye":
   self._parent._sock.send(self._parent._name + " is
signing off.\n")
   self._parent._sock.send("bye\n")
   self._parent._keepGoing = False
   break;
   else:
   self._parent._sock.send(m + "\n")


def main():

if len(sys.argv) == 4:  # prog name + 3 args
host = sys.argv[1]
port = int(sys.argv[2])
name = sys.argv[3]
c = Client(host, port, name)
else:
c = Client()

print "Client connecting to - host=%s  port=%d   name=%s" % c.info
()

s = Client.Speaker(c)
s.start()

l = Client.Listener(c)
l.start()


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


Re: improve this newbie code/nested functions in Python?

2009-03-20 Thread Esmail
Hi!

On Mar 20, 1:06 am, Terry Reedy  wrote:
>
> What you wrote are two nested classes, not functions.  

Ooops .. yes of course .. simple mistake (it was late .. :)

> In my opinion,
> neither should be nested.  Nothing is gained and something is lost.
> Neither are used by client; indeed both use client.

I nested them because I see them as components of the client which
keeps track of the connection parameters and makes the initial
connection and then hands the info off to the two threads for
processing, and then also helps the two threads communicate with
each other.

This seemed like a good choice to me, can  you (or someone else)
elaborate why this is not a good design? The idea was to encapsulate
all the client info/code in one place.

> I would rename '_parent' (misleading) as 'client' or 'user'.

good suggestion .. I chose parent or could have chosen "outer" since
I was looking for a way for the nested classes to access the
outer class

The series of assignments in __init__ in client was to store the
connection parameters as instance variables in the outer client
class. the __keepGoing__ variable is used to help the two threads
communicate with each other and know when to shut down.

This feedback is exactly the sort of thing I was looking for, thanks,
I'm looking forward to more suggestions.

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


nested classes

2009-03-20 Thread Esmail
Hello all,

I am curious why nested classes don't seem to be used much in Python.
I see them as a great way to encapsulate related information, which is
a
good thing.

In my other post "improve this newbie code/nested functions in
Python?"
(I accidentally referred to nested functions rather nested classes -
it was late)
I asked something similar in the context of a specific example where I
think the
use of nested classes makes sense.

But perhaps not?

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


meta question - how to read comp.lang.python w/o usenet feed/google interface?

2009-03-20 Thread Esmail
Hi all,

I've been reading/posting to usenet since the 80s with a variety of
tools (vn, and most recently Thunderbird) but since my ISP
(TimeWarner) no longer provides usenet feeds I'm stuck.

I am not crazy about the web interface via google groups, is
there another way to read/post this in a nice threaded way,
possibly with some sort of preview?   I'm  also worried about
missing posts in specific threads (such as the ones I start :-)

If you are reading/posting to comp.lang.python with something
other than the regular web interface provided by google and
you are happy with it, would you share it?

Thanks.

Esmail
ps: primarily in Windows these days, though I have Ubuntu on
 a VM available too frequently.
pps: I realize this is somewhat OT, but since this is what I'm
   interested in reading, and didn't know where else to post,
   the message ended up here.
--
http://mail.python.org/mailman/listinfo/python-list


Re: meta question - how to read comp.lang.python w/o usenet feed/google interface?

2009-03-20 Thread Esmail
I'd almost like to think there are a bunch
of nice python programs out there that to
this :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: meta question - how to read comp.lang.python w/o usenet feed/google interface?

2009-03-20 Thread Esmail
Thank you Mark and Albert, exactly the sort of information
I was looking for.

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


Re: improve this newbie code/nested functions in Python?

2009-03-20 Thread Esmail
On Mar 20, 2:02 pm, [email protected] wrote:
> On Mar 19, 10:21 pm, Esmail  wrote:
>
>
>
> > Hi,
>
> > I'm new to writing Python code. This is a simple client I wrote, it
> > works, but I feel it doesn't look as clean as it could. Can anyone
> > make suggestions how to streamline this code?
>
> > Also, I am using two nested functions, it seems that nested functions
> > aren't used that much in Python - is that correct? And if so, how
> > come?
>
> > thanks,
>
> > Esmail
>
> > ps: I realize there is minimal error checking/exception handling.
>
> > #!/usr/bin/env python
>
> > import sys
> > from socket import *
> > from threading import Thread
>
> > class Client(object):
> >     def __init__(self, host="localhost", port=, name = "esmail"):
> >         self._host = host
> >         self._port = port
> >         self._name = name
> >         self._address=(self._host, self._port)
> >         self._sock=socket(AF_INET, SOCK_STREAM)
> >         self._sock.connect(self._address)
> >         self._parent = self
> >         self._keepGoing = True
>
> >     def info(self):
> >         return self._host, self._port, self._name
>
> >     class Listener(Thread):
> >        def __init__(self, parent, tname="listener"):
> >            Thread.__init__(self,name = tname)
> >            self._parent = parent
> >            print self._parent._host
>
> >        def run(self):
>
> >            while self._parent._keepGoing:
> >                m = self._parent._sock.recvfrom(1024)
> >                print m[0]
>
> >     class Speaker(Thread):
> >        def __init__(self, parent, tname = "speaker"):
> >            Thread.__init__(self,name = tname)
> >            self._parent = parent
> >            self._parent._sock.send(self._parent._name + "\n")
>
> >        def run(self):
>
> >            while(True):
> >                m = raw_input("-> ")
> >                if m == "bye":
> >                    self._parent._sock.send(self._parent._name + " is
> > signing off.\n")
> >                    self._parent._sock.send("bye\n")
> >                    self._parent._keepGoing = False
> >                    break;
> >                else:
> >                    self._parent._sock.send(m + "\n")
>
> > def main():
>
> >     if len(sys.argv) == 4:  # prog name + 3 args
> >         host = sys.argv[1]
> >         port = int(sys.argv[2])
> >         name = sys.argv[3]
> >         c = Client(host, port, name)
> >     else:
> >         c = Client()
>
> >     print "Client connecting to - host=%s  port=%d   name=%s" % c.info
> > ()
>
> >     s = Client.Speaker(c)
> >     s.start()
>
> >     l = Client.Listener(c)
> >     l.start()
>
> > main()
>
> How about renaming the Client to SocketConfig, Listener to
> ClientListener and Speaker to ClientSpeaker and put all at the same
> level. The you can do this:
>
>  c = SocketConfig(host, port, name)
>  s = ClientSpeaker(c)
>  l = ClientListener(c)
>
> the other option would be to create a Speaker and Listener factory in
> Client that returns Speakers and Listeners so you can do:
>
> c = Client(host, port, name)
> s = c.Speaker()
> l = c.Listener()


Ah .. I like both .. will probably do the first one (easier) but
keep the 2nd one in mind. Thanks!!

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


Re: nested classes

2009-03-20 Thread Esmail
On Mar 20, 2:41 pm, Chris Rebert  wrote:
> 2009/3/20 Benjamin Kaplan :
>
>
>
>
>
> > On Fri, Mar 20, 2009 at 10:06 AM, Esmail  wrote:
>
> >> Hello all,
>
> >> I am curious why nested classes don't seem to be used much in Python.
> >> I see them as a great way to encapsulate related information, which is
> >> a
> >> good thing.
>
> >> In my other post "improve this newbie code/nested functions in
> >> Python?"
> >> (I accidentally referred to nested functions rather nested classes -
> >> it was late)
> >> I asked something similar in the context of a specific example where I
> >> think the
> >> use of nested classes makes sense.
>
> >> But perhaps not?
>
> > Nested classes in Python don't add much other than an additional level of
> > complexity (and an extra hash lookup). Behavior in python is usually grouped
> > into modules, not into classes. The only reason to nest a class in Python is
> > if the first class is going to generate the second class on the fly.
>
> Verily. See also the principle that "Flat is better than nested" from
> the Zen of Python (http://www.python.org/dev/peps/pep-0020/).

Neat list .. thanks .. just what I'm looking for. I am trying to learn
the idioms of the language, this will help.

> The OP would be better off naming internal classes with leading
> underscores per Python convention rather than nesting them inside
> other classes.

So you would make them "stand-alone/external" classes but "tag" them
with the underscore to document that they are used by some other
classes
as "internal service providers"?

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


Re: nested classes

2009-03-20 Thread Esmail
On Mar 20, 2:35 pm, Steve Holden  wrote:
> Benjamin Kaplan wrote:
>
> > On Fri, Mar 20, 2009 at 10:06 AM, Esmail  > <mailto:[email protected]>> wrote:
>
> >     Hello all,
>
> >     I am curious why nested classes don't seem to be used much in Python.
> >     I see them as a great way to encapsulate related information, which is
> >     a
> >     good thing.
>
> >     In my other post "improve this newbie code/nested functions in
> >     Python?"
> >     (I accidentally referred to nested functions rather nested classes -
> >     it was late)
> >     I asked something similar in the context of a specific example where I
> >     think the
> >     use of nested classes makes sense.
>
> >     But perhaps not?
>
> > Nested classes in Python don't add much other than an additional level
> > of complexity (and an extra hash lookup). Behavior in python is usually
> > grouped into modules, not into classes. The only reason to nest a class
> > in Python is if the first class is going to generate the second class on
> > the fly.
>
> And even then you;d nest it inside a method of the class.

Thanks Steve,

Esmail


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


Re: nested classes

2009-03-20 Thread Esmail

> Yes. It's the same convention used to indicate that a method is
> "private" in Python, since the language itself has no privacy
> mechanisms.

Great - got it!

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


Re: improve this newbie code/nested functions in Python?

2009-03-20 Thread Esmail

> To make a closure, the inner function *must* be nested in the outer.
> To be an instance method, a function *must* be a class attribute, and
> the easier way to indicate that is by nesting.
>
> In this case, the client does *not* use the other two classes, so the
> nesting is misleading.  I think the only time a class *might* be nested
> is when it is used by and only (directly) used by whatever it is nested
> in -- and even then, nesting is not necessary.  A class statement can
> only use global and class local names and not the non-global names in
> the surrounding context.

Thanks Terry, you've gotten me something to ponder.

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


Re: meta question - how to read comp.lang.python w/o usenet feed/google interface?

2009-03-20 Thread Esmail

Terry Reedy wrote:


Ditto, with T-bird. Just add a newsgroup account with news.gmane.org or 
snews.gmane.org (for ssl) as the server and set the rest as you please.


gmane.comp.python.general is a mirror of python-list, from python.org, 
with its spam filtering that exclude most of the crap from gmail and 
g-groups.  gmane mirrors 1000s of other technical mailing lists, 
including about 200 under g.c.python.  I think its downtime is under 1% 
and never terribly long that I have noticed in several years.


Thanks Terry, I appreciate all the help and info.

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


Re: improve this newbie code/nested functions in Python?

2009-03-21 Thread Esmail

Paul Hankin wrote:



I would decouple the speaker and the listener from the client, and
make the client interface more abstract. Simple and descriptive
interfaces   can make code dramatically easier to understand.

class ClientListener(Thread):
  def __init__(self, client, ...):
...

  def run(self):
while True:
   m = self.client.receive_message()
   print m

class ClientSpeaker(Thread):
  def __init__(self, client):
client.connect()
  ...
  def run(self):
while True:
  m = raw_input()
  if m == 'bye':
self.client.disconnect()
...
  else:
self.client.send_message(m)

The 'connect' method can print the client name, the 'disconnect' can
say 'bye' and set _KeepGoing. receive_message can extract the
interesting bit from the socket read. Hope you get the idea.

This way, you don't use the inner workings of client in the Listener
and Speaker classes, and don't violate the 'law of demeter'. If
nothing else, it makes the speaker and listener much easier to read.
If you later want to test these classes, you'll find it a ton easier,
since you can mock the client class.. but perhaps that's a little too
advanced.


Hi Paul,

Yes that was very helpful -- I'm glad I found this group :-)

Best,
Esmail


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





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


script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

Hello all,

I am wondering if anyone is using python to write script files?

Right now I have a bigg'ish bash/tcsh script that contain some grep/awk
command plus various files are processed and created, renamed and
moved to specific directories. I also write out some gnuplot scripts
that later get executed to generate .jpg images.

In any case, the scripts are starting to look pretty hairy and I was
wondering if it would make sense to re-write them in Python. I am not
sure how suitable it would be for this.

I've looked around the web w/o much luck for some examples but come
short. Any comments/suggestions?

Thanks,
Esmail

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


R6034 -- 0.9.1 -- problems installing under XP

2009-03-21 Thread Esmail

I apologize if this is a duplicate, been having lots of problems
posting to this group.

---

Hello all,

I am having problems trying installing iPython under XP.
It works great under Linux and it would be great if I could
also use it when I have to be in Windows.

XP Professional SP2 + SP3 (tried different systems),
iPython-0.9.1, Python 2.6.1

During  "Please wait while running postinstall script .. "
I get the following MS Visual C++ Runtime Error

R6034
An application has made an attempt to load th C runtime library incorrectly.
.

I get this message 4 or 5 times and eventually end up
with this:

*** run_installscript: internal error 0x ***

I've seen this error reported before while searching the web,
so I know I'm not the only one who has run into this problem,
but not seen any solutions.

Can anyone help?

Thanks,
Esmail

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


(SORRY .. )Re: R6034 -- 0.9.1 -- problems installing under XP

2009-03-21 Thread Esmail

Argh .. sorry about this post I was trying to post to
gmane.comp.python.ipython.user (but it's not working),
this was an accident - I didn't mean to send it here
(wrong screen).

Sorry about this.....

Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

Aahz wrote:

In article ,
Esmail   wrote:

I am wondering if anyone is using python to write script files?


These days, I always convert any even slightly complicated script to
Python.


well .. that sounds encouraging ...


I've looked around the web w/o much luck for some examples but come
short. Any comments/suggestions?


Not sure what you're looking for here -- many things you'd run an
external program for in scripting can be accomplished with Python library
calls, and for the rest, you can use the subprocess module (or os.system
if you have no acces to Python 2.4 or higher).


I have access to 2.5 or more recent. I guess I was looking for some
example scripts in Python and perhaps the equivalent in bash/tsch to
show some of the equivalences. I am being impatient, I guess I need to
dig into the language/library documentation a bit more on my own.

Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

Hi Joe,

Joe Riopel wrote:


Are these scripts run on computers that are guaranteed to have Python
installed? If not, can you install Python on them?

I use Python when I can, but sometimes shell scripts just makes sense. T


Yes. Currently I am running the bash/tcsh scripts under Ubuntu. The scripts
process the output of a set of big simulation runs using R. I can run R under
Windows too, but then I can't use the shell scripts to process them, so in
fact Python would make things more portable for me.

Shell scripting works for me for quick and relatively short tasks, as soon
as it gets a bit longer I miss having cleaner control structures and
functions, and Python having such a clean code would be great and make
maintenance easier too as I tweak the code.

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


Re: script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

Aahz wrote:


If you post a sample script you're trying to convert, you may get some
responses that show how different people would write it in Python.


That's a nice suggestion .. I may end up doing this after I do some
readings, just wanted to make sure this is not too outlandish of an
idea :-)

Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

Peter Pearson wrote:

On Sat, 21 Mar 2009 09:26:02 -0400, Esmail  wrote:

I am wondering if anyone is using python to write script files?


If it can be done in a few simple lines of shell script,
fine: make it a shell script. But if it's more complex than
that, Python is clearer.  Just my two cents.


Hi Peter,

Yes, I agree .. the complexity of the script(s) have evolved to the
stage that I was thinking moving to Python makes sense (if that's something
that Python is suitable for - which it appears it is :-)

Cheers,
Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

Ned Deily wrote:


Perhaps the recipe for Pyline might give you some ideas on how to write 
python scripts that play well with other scripts.





ah .. very nice .. thanks!

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


Re: script files with python (instead of tcsh/bash)?

2009-03-21 Thread Esmail

andrew cooke wrote:

Esmail wrote:

just a quick data point here - 


<..>


so you might be better spending the time improving your bash skills than
doing what will be largely drudge work in a language you already know.


I'll have to think about it .. at this point I know both languages about
equally "well" .. (not really), but Python has more universal applicability,
so I thought this might be a good reason to hone my Python skills and come
up with something useful at the same time.

Thanks for the post, the more data points,the better.

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


Re: script files with python (instead of tcsh/bash)?

2009-03-22 Thread Esmail

Nick Craig-Wood wrote:

Esmail  wrote:

 I am wondering if anyone is using python to write script files?


Yes!


<..>


Almost any script that contains a loop I convert into python.


 In any case, the scripts are starting to look pretty hairy and I was
 wondering if it would make sense to re-write them in Python. I am not
 sure how suitable it would be for this.


With python you get the advantages of a language with a very clear
philosophy which is exceptionally easy to read and write.

Add a few classes and unit tests to your scripts and they will be
better than you can ever achieve with bash (IMHO).



Hi Nick,

thanks for including the script, that really helps. Nice way of
finding files.

Two quick questions:

As a replacement for grep I would use the re module and its methods?

What about awk which I regularly use to extract fields based on position
but not column number, what should I be using in Python to do the same?

The other things I need to do consist of moving files, manipulating file
names and piping outputs of one command to the next, so I'm digging into
the documentation as much as I can.

So much to learn, so little time (but so much fun!)

Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-23 Thread Esmail

MRAB wrote:



Two quick questions:

As a replacement for grep I would use the re module and its methods?

What about awk which I regularly use to extract fields based on position
but not column number, what should I be using in Python to do the same?


Just use string slicing.


Would that be equivalent to splitting the string and then subscripting
on the result?

That seems to be the closest to awk .. wouldn't string slicing depend on
column numbers for the line (so to speak)i.e, specific know index values?


The other things I need to do consist of moving files, manipulating file
names and piping outputs of one command to the next, so I'm digging into
the documentation as much as I can.


The 'os' and 'shutil' modules.


Excellent, thanks for the pointers. I was aware of the os module, but
didn't know about the shutil module. The more I dig into Python, the
more I like it and the more I'm impressed. (I do miss bock comments,
when you are trying out new things that is useful .. I know I can use
""" as a substitute though).

Thanks again,
Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-23 Thread Esmail

Hi Gabriel,

Gabriel Genellina wrote:
En Sun, 22 Mar 2009 11:05:22 -0300, MRAB  
escribió:

Esmail wrote:

Nick Craig-Wood wrote:

Esmail  wrote:

<..>

 As a replacement for grep I would use the re module and its methods?


Perhaps; but strings have methods too (`"abc" in line` is easier to 
read, and faster, than the corresponding r.e.)


I'm  a big fan of readability (which is one reason I am attracted
to Python) .. thanks for pointing out the alternative, good to have
options.


The other things I need to do consist of moving files, manipulating file
names and piping outputs of one command to the next, so I'm digging into
the documentation as much as I can.


The 'os' and 'shutil' modules.


And for executing external commands with piping, I'd add the subprocess 
module.


I will take a look at the subprocess module, thanks!

Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-23 Thread Esmail

Hello again Nick,

thanks for the additional script example. I was able to put
something together where I read the whole file into a list
as a series of lines (via readlines()) and then loop through
the lines seeing if the target string was "in" the line .. seems
to have worked reasonably well.

I am sure over time I will pick up the more Python(ic?) ways of
doing things.



I presume you mean something like this

   ... | awk '{print $2}'

In python, assuming you've got the line in the "line" variable, then

In python an equivalent of the above would be

import fileinput
for line in fileinput.input():
print line.split()[1]



cool .. that is what I came up with too!


Note that the fileinput module is really useful for making shell
command replacements!


yes, I am going to have to process a number of files, so I'm also
looking at glob and os.walk(??)


 The other things I need to do consist of moving files, manipulating file
 names and piping outputs of one command to the next, so I'm digging into
 the documentation as much as I can.


Read up on the os module and the subprocess module.  You'll find you
need to do much less piping with python as with shell because it has
almost everything you'll need built in.

Using built in functions is much quicker than fork()-ing an external
command too.


Thanks again for all the useful info and examples, this really has been
a great help.

Esmail

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


Re: loading program's global variables in ipython

2009-03-23 Thread Esmail

Peter Otten wrote:



Use

%run -i myfile.py

or

execfile("myfile.py") # not ipython-specific


thanks for these suggestions Peter, I have had exactly the same problem
and was looking for a way around it -- this will be very helpful.

Esmail

ps: for some reason I am unable to post to the
gmane.comp.python.ipython.user group. For one I can't install the
Windows version of iPython (Linux works superfine :-)

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


Re: script files with python (instead of tcsh/bash)?

2009-03-23 Thread Esmail

Alan G Isaac wrote:

On 3/21/2009 9:26 AM Esmail apparently wrote:

I also write out some gnuplot scripts
that later get executed to generate .jpg images.



See Gnuplot.py


Thanks Alan, I will!

Esmail

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


iPython 0.9.1 install under XP -- R6034

2009-03-24 Thread Esmail

Hello all,

I am having problems trying installing iPython under XP.
It works great under Linux and it would be great if I could
also use it when I have to be in Windows.

XP Professional SP2 + SP3 (tried different systems),
iPython-0.9.1, Python 2.6.1

During  "Please wait while running postinstall script .. "
I get the following MS Visual C++ Runtime Error

R6034
An application has made an attempt to load th C runtime library incorrectly.
.

I get this message 4 or 5 times and eventually end up
with this:

*** run_installscript: internal error 0x ***

I've seen this error reported before while searching the web,
so I know I'm not the only one who has run into this problem,
but not seen any solutions.

Can anyone help?

Thanks,
Esmail


PS: I see a ipython users group, but I have been unable to post to
it despite trying for the last few days. Perhaps someone here
who uses iPython under XP can help.

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


Re: iPython 0.9.1 install under XP -- R6034

2009-03-24 Thread Esmail

Hello David,

David Cournapeau wrote:



If you need ipython quickly, I would simply try building the installer
myself from sources - as ipython does not have dependency and is pure
python, it should be straightfoward to do a 

>

python setup.py bdist_wininst,


Thanks for the suggestion, it seems to have worked, but I don't
think it created any of the .bat files or entries in the startup
menu etc. .. any idea how to those parts set up?

Also, how did you know about the bdist_wininst command line argument?
I looked around for this sort of information, but must have missed
it.

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


Re: script files with python (instead of tcsh/bash)?

2009-03-25 Thread Esmail

Hello David,

R. David Murray wrote:

Esmail  wrote:

Here's a more Pythonic way to do that:

with open('somefile') as f:
for line in f:
if 'somestring' in line:
#do something

In other words, you don't have to read the lines into a list first if all
you are going to do is iterate through them.  


Cool .. stored away for future reference.

In this case I believe I needed the contents in a list because the line
I was looking for was above one that I could easily identify. Ie, once
I had the index, I could go back/up one index to find the line I needed
to process.



(The 'with' clause closes
the file at block exit...which is overkill if this is all the program
is doing since the file will be closed at program termination anyway,
but is a good habit to get in to.)


thanks for reminding me about the 'with' clause. I agree with closing
files and in general being mindful about allocated resources.

Cheers,
Esmail

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


Re: script files with python (instead of tcsh/bash)?

2009-03-25 Thread Esmail

Peter Otten wrote:



In this case I believe I needed the contents in a list because the line
I was looking for was above one that I could easily identify. Ie, once
I had the index, I could go back/up one index to find the line I needed
to process.


Here's one way to avoid the list:

last_line = None
for line in f:
if "somestring" in line and last_line is not None:
 # do something with last_line
last_line = line

Peter



yup .. this will come in handy in case the file is too
big and or really needn't be all in memory. cool. thanks!

Esmail

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


Programming Python 4th Edition?

2009-03-26 Thread Esmail

Hi,

Does anyone know if there is a 4th edition of this book planned
and if so, when it might be coming out?

It looks like a good and comprehensive book but is getting a bit
outdated(?).

And I guess since I'm asking this, I might as well be asking what
your favorite, comparable Python book might be :-)

Thanks,
Esmail

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


Re: Programming Python 4th Edition?

2009-03-27 Thread Esmail

[email protected] wrote:


It isn't a introduction to the Python language like "Learning Python",
it doesn't work as reference like "Python in a Nutshell", it doesn't
contain short idiomatic code like "Python Cookbook". What you are left
with is different application domains and how to apply Python to them.
The book is excellent if you want to do Network, GUI, Databases, etc.
but poor if you want to learn about Python the core language. The
title of the book should be changed from "Programming Python" to
"Applied Python" 


Hi,

I appreciate you taking the time to post. I agree with what you say.
I guess what appeals to me is the nearly encyclopedic nature of the
book .. and I am curious about scripting with python, so it seems to
have some good material on it (though I think there are newer modules
now available for this).

It's good to hear what others think about this book, and others too.

Cheers,
Esmail

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


Re: Programming Python 4th Edition?

2009-03-30 Thread Esmail

Nick Craig-Wood wrote:


I read Programming Python as an experienced programmer and like you I
enjoyed the encyclopedic nature of it.  So if it appeals to you I'd
say go for it!

The fact that it doesn't use the latest version of python isn't a
problem - python doesn't change very quickly and emphasises backwards
compatibility, even for the jump to 3.x.


Cool .. glad to hear that .. esp since all my other Python books are
even a bit more outdated :-)  .. the only thing that I notice missing
is coverage of the subprocess module which I will be using a fair bit
I think.

I had a 40% off coupon for our local Borders, so I couldn't pass that
up to get myself a copy of this book. No regrets.

Cheers,
Esmail


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


Re: python needs leaning stuff from other language

2009-04-02 Thread Esmail

Diez B. Roggisch wrote:

[email protected] schrieb:

python's list needs a thing  list.clear()  like c# arraylist
and


some_list[:] = []


I agree that this is nice and clear, but as a relative newbie
wouldn't

some_list = []

be also acceptable (and pythonic?)?

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


Re: python needs leaning stuff from other language

2009-04-02 Thread Esmail

Emile van Sebille wrote:

Esmail wrote:

Diez B. Roggisch wrote:

[email protected] schrieb:

python's list needs a thing  list.clear()  like c# arraylist
and


some_list[:] = []


I agree that this is nice and clear, but as a relative newbie
wouldn't

some_list = []


This is different -- it creates a new list.  Consider:

 >>> some_list = [1,2,3]
 >>> d = some_list
 >>> d[1]
2
 >>> some_list[:] = ['a','b','c']
 >>> d[1]
'b'
 >>> some_list = [1,2,3]
 >>> d[1]
'b'

the [:] form allows references into the list to remain valid while the
direct assignment dopes not.


Ah .. thanks for clarifying this .. makes sense.

Also, thank you Luis for your post.

Esmail

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


genetic algorithms in Python?

2009-04-08 Thread Esmail

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?

Thanks,
Esmail

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


Re: genetic algorithms in Python??

2009-04-08 Thread Esmail

Hello Mohammed,

Yes, that would great. While I am comfortable with GAs,
I'm still rather inexperienced with Python so seeing some
implementation examples would be very useful.

Thanks,
Esmail

--

Date: Wed, 8 Apr 2009 17:08:48 +0200
Subject: Re: genetic algorithms in Python?
From: [email protected]
To: [email protected]
CC: [email protected]

I have done something in this direction. I will be happy to share my 
experience. However, my code is not generic and needs many things to be 
manually introduced. My GA is standard (selection by roulette wheel or 
tournament, single point cross). Let me know if you are interested!



On Wed, Apr 8, 2009 at 3:25 PM, Esmail  wrote:

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?


Thanks,
Esmail


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


Re: genetic algorithms in Python??

2009-04-08 Thread Esmail

R. David Murray wrote:

Esmail  wrote:

Hello Mohammed,

Yes, that would great. While I am comfortable with GAs,
I'm still rather inexperienced with Python so seeing some
implementation examples would be very useful.


A google for 'python genetic algorithms' turns up a number
of interesting hits.


Agreed .. I did that and came up with a number of hits, but the
"problem" :-) with Python is a plethora of choices, so I wasn't
quite sure which of the finds might be the most promising/useful.

Nothing like a testimony from someone who uses or has used a tool.


I also remember seeing at least one package announced on
python-announce that referred to genetic algorithms,
so you might check the archives of that mailing list
as well.


Yes, that's a good idea, thanks,
Esmail

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


Re: genetic algorithms in Python?

2009-04-08 Thread Esmail

Terry Reedy wrote:

Esmail wrote:

Hello,

Anyone using Python for coding up genetic algorithms? If
so, would you share your favorite modules/libraries/tools?


Search 'Python genetic algorithm' on Google or elsewhere.


Hi Terry,

I did that first, and I came up with a number of hits. The "problem"
with Python is that there's so much available and it's sometimes hard
to decide what to select, so I was looking for some folks who had
use some of the tools and could share their experiences.

Esmail

ps: the "problem" is a good thing to have all things considered :-)

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


is this possible (getting info off web page)

2009-04-09 Thread Esmail

Hi,

I am trying to keep track of two flight bookings on the kayak.com
web site, and would like to automate my query using Python. If I
enter the url below myself into the browser,  a form gets filled
out and the site searches for flights. I would love to be able to
have a simple python script which I can supply with a url and
have it simply display, in text if possible, the best 3 prices.

I thought great opportunity to learn more about Python, and then
presumably re as I parse the text

However, when I use the code below (located via google), I end up
with an alternate page, basically telling me that kayak doesn't like
bots. So, it seems like Kayak has it set up to prevent automated
access?

Is there anyway to do what I would like to do?

Thanks,

Esmail

--

import urllib2

url = 
'http://www.kayak.com/s/search/air?l1=cmh&d1=4/23/2009&l2=yyz&d2=4/26/2009'
res = urllib2.urlopen(url)
page = res.read()

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


Re: Request For Comment

2009-04-10 Thread Esmail

Aahz wrote:

How RFC1 got created:

http://www.nytimes.com/2009/04/07/opinion/07crocker.html


That was great, thanks for posting the link.

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


Re: is this possible (getting info off web page)

2009-04-10 Thread Esmail

bruce wrote:

Hi Esmail.

I've not looked at the site. however, i can give you some general pointers
that might help you in solving your issue.


Excellent advice, thanks for pointing me in those directions. I am not
familiar with curl but will take this as an opportunty to learn about it.
I think looking at the user-agent parameter may also help.

Cheers,
Esmail


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


Re: Startup with Python

2009-04-11 Thread Esmail

Strato wrote:

Hello, I am a beginner in Python , i am not able to set the
environment variable in windows so that i can execute python script
through command prompt , and also i am not able to male *.py as
executable i.e. whenever i double click the file it should run it.
Please help and reply me at [email protected] . Its urgent brother ,
i will wait for your reply.
--
http://mail.python.org/mailman/listinfo/python-list



Take a look at

http://docs.python.org/using/index.html

especially section 3 talks about how to setup Python on the Windows
platform.

Have you tried specifying the whole path in the command window?
For instance I have version 2.6 installed, so I can type

c:\Python26\python.exe script.py

to get this to work.

Good luck,

Esmail
ps: try renaming the .py extension to .pyw and then double click it
(should have worked before too - as far as I know this only prevents
 a command window from opening, but it can't hurt trying).
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if a list contains an item

2009-04-12 Thread Esmail

[email protected] wrote:

python doesn't have a list.contains()   method?



How about the 'in' operator?

In [1]: l1=['aa', 'bb', 'cc']

In [2]: 'aa' in l1
Out[2]: True

In [3]: 'ab' in l1
Out[3]: False

In [4]: 'cc' in l1
Out[4]: True

Will this help?

Esmail


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


Re: Calling user defined functions from a different script..

2009-04-15 Thread Esmail

I think taking a look at

   sys.path.append()

might help.

Esmail

[email protected] wrote:

Hello all,
  I have a situation where I need to call functions present in
a different script whose hierarchy is something like below:

C:\Pythonlib\uitl\script1.py {Place where my functions definitions are
present}

C:\Scripts\script2.py { Place where function calls are made}

   In such a situation how can I import functions from
script1.py and use it in script2.py.



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


sorting two corresponding lists?

2009-04-20 Thread Esmail

Hello all,

I wonder if someone could help me with sorting two corresponding lists.

For instance the first list contains some items, and the second list
contains their value (higher is better)

items = [apple, car, town, phone]
values = [5, 2, 7, 1]

I would like to sort the 'items' list based on the 'values' list so
that I end up with the following two list:

items = [town, apple, car, phone]
values = [7, 5, 2, 1]

So I would like to keep the corresponding value still corresponding
after the sorting.

Is there an easy/nice/Pythonic way to do this?

Thanks,
Esmail

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


Re: sorting two corresponding lists?

2009-04-20 Thread Esmail

Hi Diez,

Thanks for this, I had seen zip() before but had no idea
really what it does, this will serve as good motivation to
find out more.

I'm amazed at what this language can do (and the helpfulness
of the people on the list here).

Best,
Esmail

Diez B. Roggisch wrote:


items = zip(*sorted(zip(values, items)))[1]

To better understand this please note that

a = [1, 2]
b = [3, 4]

zip(*zip(a, b)) == a, b

or, in other words, zip(*argument) is the inverse of an argument created by
zip (under the assumption the a and b have equal length)

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



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


Re: sorting two corresponding lists?

2009-04-20 Thread Esmail

Saketh wrote:



Why not use a dictionary instead of two lists? Then you can sort the
dictionary by value -- e.g.


thanks for the suggestion. I am not sure this is quite suitable for my
application (the example I provided was extremely simplified), but this
is a useful technique to know and has been stored away for future use.

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


Re: sorting two corresponding lists?

2009-04-20 Thread Esmail

Thanks Luis, more code for me to study and learn from.

Esmail

Luis Alberto Zarrabeitia Gomez wrote:


I've used this sometimes:




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


Re: sorting two corresponding lists?

2009-04-21 Thread Esmail

Esmail wrote:


items = [apple, car, town, phone]
values = [5, 2, 7, 1]

I would like to sort the 'items' list based on the 'values' list so
that I end up with the following two list:

items = [town, apple, car, phone]
values = [7, 5, 2, 1]


Hello all,

thanks for all the great suggestions. I used Diez's post as an
opportunity to learn about zip and this this is the code I
ended up drafting:

  li=zip(*sorted(zip(values, items), reverse=True))
  new_items=list(li[1])
  new_vals=list(li[0])

seems to work :-)

Esmail

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


simple question re list iteration semantics

2009-04-21 Thread Esmail

Hello all,

I have a simple question regarding semantics.

Given a list 'li', I can always do this to iterate through all items in
order:

for i in range(0, len(li)):
print li[i]

Will this always be equivalent to


for i in li:
print i

I assume it is, and the order will always be the same, or am I mistaken?

Would the 2nd one be considered more Pythonic? (It looks both
clearer and cleaner to me).

Thanks.

Esmail

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


pyflakes, pylint, pychecker - and other tools

2009-04-21 Thread Esmail

What is the consensus of the Python community regarding these
code checkers?

In particular, are the stylistic recommendations that
pylint makes considered sensible/valid?

Are there any other tools you consider essential to Python
development?

Thanks.
Esmail

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


Re: simple question re list iteration semantics

2009-04-21 Thread Esmail

Thanks everyone, as usual, very informative posts!

Esmail

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


Re: Essential tools for Python development

2009-04-21 Thread Esmail

Great list Ben, I use emacs and will check out the tools
you listed.

What techniques/tools do you recommend for debugging?

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


Re: simple question re list iteration semantics

2009-04-21 Thread Esmail

Paul Rubin wrote:

Esmail  writes:

for i in range(0, len(li)):
 print li[i]

Will this always be equivalent to


for i in li:
 print i


Not the same--after the exit of the first loop, 'i' is the length of
the list.  After the exit of the second loop, 'i' is the last element.


Yes, agreed.


 If you want to have the numeric index available in the loop, use:

  for i,x in enumerate(li):
 ...

then i is the index and x is the element.


ah .. very nice, I didn't know this -- thanks!

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


Re: pyflakes, pylint, pychecker - and other tools

2009-04-22 Thread Esmail

Colin J. Williams wrote:

Esmail wrote:

What is the consensus of the Python community regarding these
code checkers?

In particular, are the stylistic recommendations that
pylint makes considered sensible/valid?


pylint seems a bit heavy handled, a bit too much PEP 8, 


Just having used this for a short while, I would have to agree,
though for someone coming to Python from other languages (like
myself) it does provide some stylistic guidance, at least initially,
to do it the Pythonic way.

which was 
intended as a guide, rather than a prescription.



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


pylab quick reference? (matplotlib)

2009-04-22 Thread Esmail

Hello all,

Does anyone know of a quick reference for the various plotting
functions for pylab? I'm just getting started with this
after years of work with gnuplot.

I found this

  http://matplotlib.sourceforge.net/api/pyplot_api.html

which is very comprehensive and would be good for digging into
specific commands. What I'm looking for is something small enough
to print out (< 10-20 pages) that gives a sufficient overview so
that I know what's available.

I've looked on the web without much success. I'd be grateful if
you have any pointers.

Thanks!
Esmail

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


Re: pylab quick reference? (matplotlib)

2009-04-22 Thread Esmail

norseman wrote:


Just out of curiosity,  have you tried:

import pylab
help(pylab)

The next step is to print it, 


Ah .. I didn't know this, great idea. This is what I used to get
the contents into a file for printing

 python -c 'import pylab;  help(pylab)' > pylab.txt

Thanks,
Esmail



Steve

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



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


Re: pylab quick reference? (matplotlib)

2009-04-22 Thread Esmail

Benjamin J. Racine wrote:

Not exactly what you've described, but I like this... I just spot the type of 
plot I'm looking for, copy the code, and I'm off...

http://matplotlib.sourceforge.net/gallery.html


Wow .. that's some gallery, thanks, that will be useful.


I like this technique better than any formal documentation almost.

Btw, there is a specific matplotlib list as well.  


https://lists.sourceforge.net/lists/listinfo/matplotlib-users


I just discovered it after I posted here :-) .. still glad I did.

Thanks again Ben,

Esmail

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


Re: pylab quick reference? (matplotlib)

2009-04-23 Thread Esmail

Arnaud Delobelle wrote:




 python -c 'import pylab;  help(pylab)' > pylab.txt


Do you know pydoc?


From the (shell) command line, try:


$ pydoc pylab # piped through less
$ pydoc pylab > pylab.txt # stored in a file
$ pydoc -w pylab  # Creates a 'pylab.html' file
wrote pylab.html


Ah .. and there I thought I'd impress everyone with my python
command line :-)

I had heard of pydoc before, but am not familiar with (it's on
my list of Python tools to explore), so many thanks for showing
me how to get a nice html formatted page.

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


Re: Essential tools for Python development

2009-04-23 Thread Esmail

Jeremiah Dodds wrote:


pdb is good if you need to do step-through debugging.

What I normally do in emacs is the following (while working on python 
script, and with the python-mode that comes with emacs22):


C-x 3  #splits the screen into two vertical columns
C-c C-c   #fires up python and sends the current buffer to it
C-x o  #switches to the other column
C-x b Py #switches to the python interactive buffer

This is, I do believe, equivalent to running a script with python -i 
script.py . Drops you into an interactive session where you can interact 
with what you just wrote. Another very handy tool is etags, see the help 
in emacs (You can get to it through C-h i m emacs)


Thanks for the suggestions, I really like using emacs, so I am going to
see how I can integrate it with Python development.
(Unfortunately my Windows version of emacs dosen't seem to be able to
pop into python mode, and I haven't had time to find out why). At this
point I do most of my development under Linux/emacs anyway.

Best,
Esmail
--
http://mail.python.org/mailman/listinfo/python-list


Re: Essential tools for Python development

2009-04-23 Thread Esmail

Alex VanderWoude wrote:


I really like using Winpdb (http://winpdb.org/) which provides a GUI for 
pdb.  It allows you to single-step your code and inspect objects in 
memory.  What exactly is in that silly nextOne variable?  Hey, it's a 
list rather but it's supposed to be a number!  You get the picture.


thanks for the suggestion.

The name made me think that this would be only for the Windows
platform, but it turns out it's multi-platform.

I downloaded the Linux version, but haven't had time to explore it
yet, but plan to.

Esmail

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


Re: sorting two corresponding lists?

2009-04-23 Thread Esmail


My solution, I know the 'zip' version is more elegant, this is just for 
fun:)
 
 >>> items = ['apple', 'car', 'town', 'phone']

 >>> values = [5, 2, 7, 1]
 >>> new_values = sorted(values, reverse = True)
 >>> new_items = [items[x] for x in [i for i in map(values.index, 
new_values)]]

 >>> print(new_values)
[7, 5, 2, 1]
 >>> print(new_items)
['town', 'apple', 'car', 'phone']
 >>>
 


Cool .. always good to know alternative ways of accomplishing
a task.

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


best way to compare contents of 2 lists?

2009-04-23 Thread Esmail

What is the best way to compare the *contents* of two different
lists regardless of their respective order? The lists will have
the same number of items, and be of the same type.

E.g. a trivial example (my lists will be larger),

a=[1, 2, 3]

b=[2, 3, 1]

should yield true if a==b

I suppose I could sort them and then compare them. I.e.,

sorted(a)==sorted(b)


I am wondering if there is a more efficient/preferred way to do so.

Thanks,
Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-23 Thread Esmail

Esmail wrote:

What is the best way to compare the *contents* of two different
lists regardless of their respective order? The lists will have
the same number of items, and be of the same type.

E.g. a trivial example (my lists will be larger),

a=[1, 2, 3]

b=[2, 3, 1]

should yield true if a==b

I suppose I could sort them and then compare them. I.e.,

sorted(a)==sorted(b)


I am wondering if there is a more efficient/preferred way to do so.


oh, I forgot to mention that each list may contain duplicates. So I
suppose this means I would have to sort the two lists and compare them
afterall, unless there's another way?


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


Re: best way to compare contents of 2 lists?

2009-04-23 Thread Esmail

David Robinow wrote:

On Thu, Apr 23, 2009 at 9:31 PM, Esmail  wrote:

What is the best way to compare the *contents* of two different
lists regardless of their respective order? The lists will have
the same number of items, and be of the same type.

E.g. a trivial example (my lists will be larger),

a=[1, 2, 3]

b=[2, 3, 1]

should yield true if a==b

I suppose I could sort them and then compare them. I.e.,

sorted(a)==sorted(b)


I am wondering if there is a more efficient/preferred way to do so.

Thanks,
Esmail

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



set(a) == set(b)# test if a and b have the same elements

# check that each list has the same number of each element
# i.e.[1,2,1,2] == [1,1,2,2], but [1,2,2,2] != [1,1,1,2]
for elem in set(a):
  a.count(elem) == b.count(elem)


Ah .. this part would take care of different number of duplicates
in the lists. Cool.

thanks,
Esmail


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



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


Re: best way to compare contents of 2 lists?

2009-04-23 Thread Esmail

Hans DushanthaKumar wrote:
'set' comes to mind, 


Yes, I thought about that, but I wasn't sure how to potentially
deal with different number of duplicates in the lists. The post
by David seems to address that issue nicely.


though I'm not sure if there are performance
inplications with large amopunts of data.


Yes, I wonder about these sort of things too, not knowing too
much about how Python does things internally.

Thanks for the suggestion,
Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

John Yeung wrote:

 so does your initial solution,
which I like best:


sorted(a)==sorted(b)


This is concise, clear, and in my opinion, the most Pythonic.  It may
well even be the fastest.  


Great .. I can live with that :-)

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

MRAB wrote:


You could use Raymond Hettinger's Counter class:

http://code.activestate.com/recipes/576611/

on both lists and compare them for equality.


thanks for the pointer, I'll study the code provided.

Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

Thanks all, after reading all the posting and suggestions for
alternatives, I think I'll be going with

sorted(a)==sorted(b)

it seems fast, intuitive and clean and can deal with
duplicates too.

Best,
Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-24 Thread Esmail

Piet van Oostrum wrote:

John Yeung  (JY) wrote:



JY> It takes care of the duplicates, but so does your initial solution,
JY> which I like best:



sorted(a)==sorted(b)



JY> This is concise, clear, and in my opinion, the most Pythonic.  It may
JY> well even be the fastest.  (If you didn't have to match up the numbers
JY> of duplicates, the set solution would be most Pythonic and probably
JY> fastest.)


But it may fail if the list cannot be sorted because it contains
incomparable elements:


Ah .. good point .. something I had not considered. Lucky for me in
this case it's not an issue, but something I'll keep in mind for the
future.

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


Re: Learning Python the quick way

2009-04-25 Thread Esmail

Tim Chase wrote:



2) if it's slow, profile it and check your algorithm(s), recoding if 
you're using some algorithm with a bad big-oh profile



<..>


However the first rule:  profile first!



Tim,

Do you have a favorite profiling tool? What should someone new
to Python (but not programming) use?

Thanks,
Esmail

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


Re: Learning Python the quick way

2009-04-25 Thread Esmail

Thanks Tim,

Esmail

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


Re: best way to compare contents of 2 lists?

2009-04-25 Thread Esmail

norseman wrote:


Of course each method has its time and place of use and Python has some 
well oiled list search and list maintain routines of its own. List 
comparisons are most accurate when using presorted ones. (Some things 
don't lend themselves to sorting very well. Like paragraphs, books, 
chapters, computer programs, manuals, etc... These need the searchers 
(equivalent to the Unix diff) for checking equivalence.)



HTH

Steve


Thanks Steve for bringing up various items to consider for these sort
of tasks, very helpful indeed.

Best,
Esmail

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


Re: debugging in IPython

2009-04-25 Thread Esmail

I seem to recall something about starting up the python
(and ipython) interpreter with the -i flag, but I am not
certain.

There is a ipython mailing list/user group too, you may
want to post your query there too.

Esmail

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


Re: pyflakes, pylint, pychecker - and other tools

2009-04-27 Thread Esmail

Zooko O'Whielacronx wrote:
I like pyflakes.  I haven't tried the others.  I made a setuptools 
plugin named "setuptools_pyflakes".  If you install that package, then 
"python ./setup.py flakes" runs pyflakes on your package.


Regards,


Thanks Zooko

I decided to give all of them a try :-)

Esmail

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


print(f) for files .. and is print % going away?

2009-04-30 Thread Esmail

Hello all,

I use the print method with % for formatting my output to
the console since I am quite familiar with printf from my
C days, and I like it quite well.

I am wondering if there is a way to use print to write
formatted output to files?

Also, it seems like I read that formatting with print is
going away eventually and we should start using something
else? Is that true and if so, what?

Thanks,
Esmail

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


Re: print(f) for files .. and is print % going away?

2009-04-30 Thread Esmail

Matt Nordhoff wrote:

Esmail wrote:

Hello all,

I use the print method with % for formatting my output to
the console since I am quite familiar with printf from my
C days, and I like it quite well.

I am wondering if there is a way to use print to write
formatted output to files?

Also, it seems like I read that formatting with print is
going away eventually and we should start using something
else? Is that true and if so, what?

Thanks,
Esmail




Hi Matt,


String formatting has nothing to do with the print statement/function.
It's an operator, just like doing "foo" + "bar"; you can use it wherever
you want.


Ah .. so this means I could use this formatting with the
write method for files .. that is great news (you don't
want to see the ugly code I put together there .. :-)


See <http://docs.python.org/library/stdtypes.html#string-formatting>
Also see <http://docs.python.org/library/string.html#formatstrings> for
information on the replacement for the old string formatting, Python
2.6's new str.format().


Will do .. so do you think it's good to move to the new format,
or will the older one still be around for a while?

Thanks again!

Esmail

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


Re: print(f) for files .. and is print % going away?

2009-04-30 Thread Esmail

Hi Duncan,

Thanks for the information, I'll dig deeper :-)

(for some reason I can't get the from __future__ import
to work,

>>> from __future__ import print_function
  File "", line 1

SyntaxError: future feature print_function is not defined

but I am probably making some silly mistake, plus
I have been meaning to find out more about this too, so
this is a good chance to learn something new).

Thanks again!

Esmail

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


Re: print(f) for files .. and is print % going away?

2009-04-30 Thread Esmail

Duncan Booth wrote:

Esmail  wrote:


(for some reason I can't get the from __future__ import
to work,


You can only use the print function on 2.6 and later. If you have an older 
version of Python then you'll get that error.


Ooops, yes, you wrote that and I tried with 2.6 under Windows
(my Ubuntu has 2.5) .. I must have typed something wrong when I
tried this with 2.6 because it's working fine now :-)

Thanks again Duncan,

Esmail

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


Re: print(f) for files .. and is print % going away?

2009-04-30 Thread Esmail

Hi!

[email protected] wrote:


There is also the Template class in the stdlib string module, for unix
shell/perl style "formatting".

The old mod (%) formatting will be around in 3.1 and that version not
even out yet, so it will be around for a couple more years at the very
least. 

<...>

I hope that the information will help you decide what to use.


absolutely, very useful information, thanks!

Esmail

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


Re: print(f) for files .. and is print % going away?

2009-04-30 Thread Esmail

hello,

Lie Ryan wrote:


There has never been print-with-formatting in python, what we have is 
the % string substitution operator, which is a string operation instead 
of print operation.


Yes, I see that now, thanks for clarifying it. I guess I thought
so because I've always associated the % formatting with printing.


I am wondering if there is a way to use print to write
formatted output to files?


Of course:

f = open(...)
open.write('%s' % foo)


very nice ..


or using the new superpowerful str.format()
 >>> 'foo: {0} bar: {baz:3.1f} {1:e}'.format(123, 456.789, baz = 123.456)
'foo: 123 bar: 123.5 4.567890e+02'


I'll have to check it out - thanks again,

Esmail

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


for with decimal values?

2009-05-02 Thread Esmail

Hello all,

Is there a Python construct to allow me to do something like
this:

   for i in range(-10.5, 10.5, 0.1):
 ...

If there is such a thing already available, I'd like
to use it, otherwise I can write a function to mimic this,
but I thought I'd check (my search yielded nothing).

Thanks,
Esmail

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


Re: for with decimal values?

2009-05-02 Thread Esmail

Thanks all, I appreciate the various suggestions and
caveats. Just wanted to make sure I'm not re-inventing
the wheel as Python seems to have already so much.

Cheers,
Esmail

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


Re: for with decimal values?

2009-05-02 Thread Esmail

[email protected] wrote:

Esmail:

Is there a Python construct to allow me to do something like
this:
for i in range(-10.5, 10.5, 0.1):


Sometimes I use an improved version of this:
http://code.activestate.com/recipes/66472/


neat .. lots of code to study there. Thanks,
Esmail

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


Re: for with decimal values?

2009-05-02 Thread Esmail

Ben Finney wrote:


Note that those values are of type ‘float’, which is a distinct type
from ‘Decimal’ with very different behaviour.


If there is such a thing already available, I'd like to use it,
otherwise I can write a function to mimic this, but I thought I'd
check (my search yielded nothing).


You can write a function to do it.

Alternatively, this case seems simple enough that you can write a
generator expression. Assuming you want ‘Decimal’ values:

>>> from decimal import Decimal
>>> amounts = (Decimal(mantissa)/10 for mantissa in range(-105, 105))
>>> for amount in amounts:
... print amount
...



Another nice solution stored away for use!

Thanks,
Esmail

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


Re: for with decimal values?

2009-05-03 Thread Esmail

Gabriel Genellina wrote:


Isn't so easy. You have representation errors and rounding errors here, 
and they accumulate. The last number printed should be 10.4 but I get 10.5:

...
10.3
10.4
10.5
(or more precisely, 10.459)

Also, after exiting a for loop, the *last* value used is retained. In 
your while loop, the ctr variable contains the *next* value.



All this discussion makes me wonder if it would be a good idea
for Python to have this feature (batteries included and all) - it
would have its uses, no?

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


need help with properties

2009-05-09 Thread Esmail

Hi,

I am just reading about properties in Python. I am thinking
of this as an indirection mechanism, is that wrong? If so, how
come the getter/setters aren't called when I use properties
instead of the functions directly?

What am I missing here? I have a feeling I am overlooking
something simple here...

Thanks,
Esmail

---
#!/usr/bin/env python

#
# quick test to deal with 'private' attributes and
# python properties ...
#

import sys

class Rectangle(object):

def __init__(self):
self.__width = 0
self.__height = 0


def setSize(self, width, height):
print 'in setter'
if (width < 0) or (height < 0):
print >> sys.stderr, 'Negative values not allowed'
else:
self.__width = width
self.__height = height


def getSize(self):
print 'in getter'
return self.__width, self.__height


size = property(getSize, setSize)

r = Rectangle()
print r.getSize()
r.setSize(-40, 30)
print r.getSize()

print '-'
size = 3, 7
print size

print '-'
size = -3,7
print size



The program output:


in getter
(0, 0)
in setter
Negative values not allowed
in getter
(0, 0)
-
(3, 7)
-
(-3, 7)

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


Re: need help with properties

2009-05-09 Thread Esmail

hi Scott,

Scott David Daniels wrote:

Esmail wrote:

I am just reading about properties in Python. I am thinking
of this as an indirection mechanism, is that wrong? If so, how
come the getter/setters aren't called when I use properties
instead of the functions directly?

Because you weren't actually using them.  You were writing:
size = 3, 7
not:
r.size = 3, 7


duh!! .. I knew it had to be something sill .. how do I represent
a red face in ASCII ? ;) I was concentrating so much on the new
feature I totally didn't see this.

I appreciate your code with annotations, helpful.


def setSize(self, shape): # a setter takes a single arg
width, height = shape
print 'in setter'
if width < 0 or height < 0:
print >> sys.stderr, 'Negative values not allowed'
else:
self._width = width
self._height = height



r.setSize((-40, 30))


Just curious, is there a way to pass more than one arg to a setter, or
do we always have use some sort of unpacking at the other end?

Thanks,

Esmail

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


Re: need help with properties

2009-05-09 Thread Esmail

Steven D'Aprano wrote:


All you've done in this second block is define a new object called "size" 
and assign the tuple (3, 7) to it. 


oops .. yes, you are right, and I am embarrassed...

[Aside: you might not be aware that it

is commas that make tuples, not brackets. The brackets are for grouping.)


Helpful clarification, thanks!

"size" has nothing to do with your Rectangle class, or the property. 
Apart from the accidental similarity of name between "Rectangle.size" and 
"size", it's unrelated to the property you created.


What you probably intended to do was this:

print '-'
r.size = 3, 7
print r.size


Yup, I know Python is a dynamically typed language, but I wish it would
point this sort of silliness out .. but there are tradeoffs. I should
probably run pyflakes/pychecker/pylint on my my tiny test/try out codes
too.

Best,
Esmail

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


Re: need help with properties

2009-05-09 Thread Esmail

Scott David Daniels wrote:



<... good stuff ... >


the Python 3.X world is wisely losing the unpacking in parameter
passing trick.


Thanks Scott, useful information,

Esmail

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


ConfigParser examples?

2009-05-15 Thread Esmail

Hi all,

Can anyone point to on the web, or possibly share a simple example
of the use of the ConfigParser module?

I have a program that has a lot of flags in various places (yes,
ugly I know), so I am trying to consolidate this information in
a configuration file so that the program can pull the necessary
information from this place without the need to edit the program
and its flags.

Some sample code for using ConfigParser would be helpful - haven't
been able to find any on-line so far beyond the standard documentation.

Thanks,
Esmail

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


Re: ConfigParser examples?

2009-05-16 Thread Esmail

Hi Gabriel,

Gabriel Genellina wrote:


The (excellent!) article series by Doug Hellmann, "Python Module of the 
Week", covers ConfigParser (and almost the whole standard library by now).


http://www.doughellmann.com/PyMOTW


Thanks for the pointer, I hadn't come across this site before, it
looks like a place with a lot of useful information!

Esmail


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


Re: Your Favorite Python Book

2009-05-21 Thread Esmail

Shawn Milochik wrote:

On Mon, May 11, 2009 at 5:52 PM,   wrote:

Sam,

In no specific order (I brought them all):

Wesley Chun's "Core Python Programming"

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



I second the Wesley Chun recommendation wholeheartedly. 


This book keeps getting mentioned, I'll have to check it out.
Perhaps some of you can share what about it you like in
particular.

Thanks,
Esmail

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


Re: Your Favorite Python Book

2009-05-21 Thread Esmail

Gökhan SEVER wrote:

Hello,

I received an autographed copy of CPP, 2nd Edition after joining to 
Safari's "What is Python" webcast. They published the recorded session 
online as well. Check  
http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcasts.php


As you will see from the lecture, he is a very motivated instructor. 
Mostly likely you will want to grab a copy of the book after watching 
the condensed Python introduction course.




Hi Gökhan

This looks interesting .. I have access to Safari books, but for some
reason I can't access this webcast via it .. so perhaps I have to sign
up for a trial membership for this? I'd prefer to do this w/o .. so I
guess I'll poke around a bit more. Thanks for the lead,

Esmail

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


Optimizing math functions

2009-05-23 Thread Esmail

Hello all,

I would like to maximize or minimize a given math function over a
specific set of values, in Python preferably.

I was checking out Wolfram Alpha (http://www70.wolframalpha.com/)
and it can do simple optimization problems in math, such as

maximize 15*x - x**2 over 0 to 15

(http://www70.wolframalpha.com/input/?i=maximize+15*x+-+x**2+over+0+to+15)

which finds the maximum value and input for x in the range 0 to 15.
Very cool. (This is of course a very simple example).

What it apparently can't do is for maximize (or minimize) functions
that contain two variables, x and y, or more. So for example a simple
example would be

   maximize x**2 + y**2 over x:0 to 15, y:0-12  -- this does not work
-- though I'm unclear about
-- the correct syntax too.

Is there some sort of simple Python module that would allow me to
evaluate this type of function?

In this particular instance I am interested in the minimum of

  x * sin(4*x) + 1.1 * sin(2*y), where x,y in range 0-10

though in other problems the range may not be identical for x and y.

Thanks,

Esmail

ps: Does anyone know if Octave or some other free Linux (or Windows)
program might also do this in a simple way? My preference would
still be a Python solution that would be simple to use, ie plug in
the function, the ranges and have it pop out the solution :-)

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


Re: Optimizing math functions

2009-05-23 Thread Esmail

Steven D'Aprano wrote:

On Sat, 23 May 2009 09:22:59 -0400, Esmail wrote:


Hello all,

I would like to maximize or minimize a given math function over a
specific set of values, in Python preferably.

...

What it apparently can't do is for maximize (or minimize) functions that
contain two variables, x and y, or more. 


Function minimization is a well-studied problem. You will find oodles of 
references to doing function minimization if you google. In fact, if you 
google for "python function minimization" you should find about 63,000 
links.


Hi Steven,

Right you are (63,700!) ... I don't know what search string I used
before, but clearly not this rather obvious one .. duh.


Minimizing functions of two variables is difficult, as a general rule. 
Nevertheless, there are tools for doing so. Check out SciPy.


I will - thanks. I have tools for 1D, I mostly am interested in 2D
optimization at this point, mostly as a way to verifying some results
I am calculating.

Hopefully SciPy will provide a nice simple interface to help me do
this.

Thanks,
Esmail

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


Python -> R?

2009-05-23 Thread Esmail

Hello!

Anyone using Python scripts and accessing some of R's functionality?
If so, what are you using? I have read about RPy, is that a good
solution? Are there others that can be recommended or are preferred?

I would prefer to code in Python instead of R :-)

Thanks,
Esmail

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


  1   2   >