Re: [Tutor] (no subject)

2005-10-31 Thread Andrew P
If I'm not mistaken, that's the Pythonwin debugger spitting messages
to the interactive prompt.  I just used it to step through your your
games framework example :)

Being the first time I'd used any Python debugger, it didn't occur to
me that the look of it was non-standard.

I actually got the same exceptions popping up running his code, even
after fixing the problems I pointed out.  I figured the debugger shows
caught exceptions.  I noticed it before and hadn't given it much
thought, but looking at his code, there are try/except pairs in all
the spots the debugger highlighted:

from ftplib:

try:
import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket
from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn
except ImportError:
import socket

from os.py:

def _get_exports_list(module):
try:
return list(module.__all__)
except AttributeError:
return [n for n in dir(module) if n[0] != '_']

and socket.py:

try:
import _ssl
from _ssl import *
_have_ssl = True
except ImportError:
pass

Thats why I suspect that this:

File "c:\temp\ftp_put_hub.py", line 9, in ?
ftp = ftplib.FTP('ftp.website.com')   # connect to host, default port

Was the only real error being thrown.


On 10/31/05, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > When I ran in debugger, calling the FTP library invokes a no SOCKS
> > module error that the ftplib seems to be trying to access.
>
> Can you tell us which debugger you are using? I don't recognise what's
> going on here.
>
> >>> --Call--
>
> This looks like the Python interactive prompt,
> but whats the --Call-- thing?
>
> Its not valid Python syntax and yet the messages below suggest
> that it is being processed in a semi-sane way.
>
> [Dbg]>>> Traceback (most recent call last):
>
> And I don;t recognise the square brackets [Dbg] either.
> Which debugger is it?
>
> Finally given the number of import errors I'd suggest there is a path
> problem somewhere. But without knowing which OS, which IDE
> and where/how you are executing this I can only guess.
>
> Alan G.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-10-31 Thread Andrew P
Before you hit the debugger, it might be a good idea to just run the
script normally, either at the command line, or inside IDLE/Pythonwin.

Doing so will spit out:

Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'ftplib' is not defined

Because you imported with:

from ftplib import FTP"

you don't need to prepend the module name before you call FTP.  If you
do "import ftplib" instead, then it will work.  Conversely, if you
call with just "FTP("ftp.website.com") it will also work.

 It's really a personal choice which you do, but the second choice is
safer, as it has no chance of polluting your module's namespace if you
accidentally call something FTP.

Also, I noticed when pasting into IDLE that you have mismatched quotes:

ftp.login('user', 'pwd') # user, passwd

Using IDLE/Pythonwin will catch problems like that.

Good luck,

Andrew

On 10/31/05, Roberts, Alice <[EMAIL PROTECTED]> wrote:
>
>
>
> Good morning,
>
>
>
> I'm migrating from DOS scripting to Python, and need a little help.  I got
> this sample from a Google search that brought me to effbot.org,
> http://effbot.org/librarybook/ftplib.htm.  Also, I plugged
> in all my variables when I tested, but replaced with generics for this
> email. ie) ftp.website.com.
>
>
>
> Thank you,
>
>
>
> Alice Roberts
>
> Ambac Assurance Corp.
>
>
>
> from ftplib import FTP
>
> import sys
>
>
>
> def upload(ftp, file):
>
> ftp.storlines("STOR " + file, open(file))
>
>
>
> ftp = ftplib.FTP('ftp.website.com')   # connect to host, default port
>
> ftp.login('user', 'pwd') # user, passwd
>
> ftp.set_debuglevel(1)
>
> ftp.cwd('/temp')
>
> ftp.delete('fname.txt')
>
>
>
> upload(ftp, "fname.txt")
>
>
>
> ftp.quit()
>
> ftp.close()
>
>
>
> When I ran in debugger, calling the FTP library invokes a no SOCKS module
> error that the ftplib seems to be trying to access.
>
>
>
> >>> --Call--
>
> >>> Unhandled exception while debugging...
>
> Traceback (most recent call last):
>
>   File "C:\Python24\lib\ftplib.py", line 42, in ?
>
> import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket
>
> ImportError: No module named SOCKS
>
> >>> --Call--
>
> >>> Unhandled exception while debugging...
>
> Traceback (most recent call last):
>
>   File "C:\Python24\lib\socket.py", line 50, in ?
>
> import _ssl
>
> ImportError: No module named _ssl
>
> >>> --Call--
>
> >>> Unhandled exception while debugging...
>
> Traceback (most recent call last):
>
>   File "C:\Python24\lib\os.py", line 36, in _get_exports_list
>
> return list(module.__all__)
>
> AttributeError: 'module' object has no attribute '__all__'
>
> [Dbg]>>> Traceback (most recent call last):
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 305, in RunScript
>
> debugger.run(codeObject, __main__.__dict__, start_stepping=1)
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py",
> line 60, in run
>
> _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py",
> line 595, in run
>
> exec cmd in globals, locals
>
>   File "c:\temp\ftp_get_hub.py", line 13, in ?
>
> ftp = ftplib.FTP("ftp.website.com")   # connect to host, default port
>
> NameError: name 'ftplib' is not defined
>
> [Dbg]>>> Traceback (most recent call last):
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 305, in RunScript
>
> debugger.run(codeObject, __main__.__dict__, start_stepping=1)
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py",
> line 60, in run
>
> _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py",
> line 595, in run
>
> exec cmd in globals, locals
>
>   File "c:\temp\ftp_put_hub.py", line 3, in ?
>
> import FTP
>
> ImportError: No module named FTP
>
> [Dbg]>>> Traceback (most recent call last):
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 305, in RunScript
>
> debugger.run(codeObject, __main__.__dict__, start_stepping=1)
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py",
> line 60, in run
>
> _GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
>
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py",
> line 595, in run
>
> exec cmd in globals, locals
>
>   File "c:\temp\ftp_put_hub.py", line 9, in ?
>
> ftp = ftplib.FTP('ftp.website.com')   # connect to host, default port
>
> NameError: name 'ftplib' is not defined
>
> [Dbg]>>>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie Question - Python vs Perl

2005-10-31 Thread Andrew P
If you are interested in learning another tool, please, start with
Python.  If you are interested in scripting UNIX, Perl is a fine
choice.  There prevalence matters, and quite a bit.  But sys admins
are usually very Perl-centric, and in my experience monolingual, and a
bit of an insular community :)

Python is more than the equal of Perl by any measure.  Including
system administration.  But moving beyond that is also a lovely
language for building applications, and everything from lightweight
CGI scripts to using hefty web frameworks, of which there are plenty
to choose from.

Perl is a language of exceptions to the rules.  Python tries very hard
to be consistent, which makes it much easier to learn, and much easier
to use, and much, much easier to apply the concepts you have learned
to other languages.  Including Perl, as a second or third language.

Perl can be coerced into big jobs, but it's not very pleasant.   The
best you can hope to keep in your head at once is your own set of
idioms, which will -not- match anybody elses, and will likely change
from week to week on you anyway.   And really when people tell you
they can't read what they wrote the day before when they come back to
it, they aren't lying!

Having said that, I love Perl, because it -is- quirky and sprawling
and lovable.  It's pretty much the worst case scenario of
everything-and-the-kitchen-sink, and really not so bad for all that,
and definitely more fun for it.  So if that appeals, then you'll have
fun too.

But Python tends to be compared to general purpose languages like Java
and C++ more often.  OOP heavyweights of the world.  Actually, let me
find that quote by Bruce Eckel, who wrote the (very) popular "Thinking
in Java" and "Thinking in C++" books.  Here it is:

"I believe it was definitely worth moving from C to C++, and from C++
to Java. So there was progress there. For something as advanced as
Python is over those languages -- and as different -- there will be
some hesitation."

And:

"When you have the experience of really being able to be as productive
as possible, then you start to get pissed off at other languages. You
think, 'Gee, I've been wasting my time with these other languages.'"

That second quote applies to many "language vs language" comparisons,
obviously.  But it's food for thought.

Oh, and never underestimate the power of the interactive interpreter! 
Don't do it!  Ever!

Take care,

Andrew

On 10/30/05, Scott Clausen <[EMAIL PROTECTED]> wrote:
> As a newbie to Python I'd like to know if someone can tell me some
> strengths and weaknesses of this language. The reason I'm asking is a
> friend told me I should learn Perl over Python as it's more
> prevalent.  I'm going to be using it on a Mac.
>
> I'd appreciate hearing any views on this topic. My own view is that
> it's always good to learn new things as you then have more tools to
> use in your daily programming.
>
> Thanks in advance.
>
> Scott
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python myspace module?

2005-10-30 Thread Andrew P
Probably the most useful library from the wwwsearch page Danny pointed
you to is the cookielib, which is built into Python as of 2.3 or 2.4. 
The most useful because you can't scrape by without it on most sites,
and cookies are really no fun to handle manually  Login and forms can
largely be fudged, but it's really nice to have cookies handled
transparently.

You'll want to do something like:

url = "http://www.myspace.com";
cj = cookielib.CookieJar()
myURLOpen = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
myURLOpen.addheaders = [('User-agent', 'Mozilla/5.0')]
urlopen = myURLOpen.open

urlopen(url).read()

I think this came straight from the Python docs originally, where it's
explained a bit more fully.  But this will do two things.  1) set up a
client side cookie, and magically handle all cookie magic for you, and
2) change your user agent to 'Mozilla/5.0', completing the illusion
that you are a browser.  Many sites don't like to see user agents like
"Python-urllib/2.4" :)

The rest is just understanding how forms work.  I've never used a
library, just POSTed/GETted the data directly to login and search
sites.  So I can't say how much easier it would be.  Probably quite a
bit.

You can POST data like:

urlopen("https://www.whatever.com/signin.dll",data=authPairs).close()

where authPairs is something like:

authPairs = urllib.urlencode({'userid':'andrew', 'password':'secret1234'})

You'll have to dig around in the html to see whether forms are using
POST or GET, and what variables they are passing, etc.  But that
should be enough to get you started.  Logged in, and able to fetch
pages and fill out forms manually.

Good luck,

Andrew

On 10/25/05, Ed Hotchkiss <[EMAIL PROTECTED]> wrote:
> looking to write a myspace wrapper/module. what is the best way (hopefully
> using the stdlib not an outside module) to connect to a website and (if
> possible, otherwise ill have to code it?) access forms with GET POST blah
> blah blah ...
>
> thanks!
>
> --
> edward hotchkiss
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] AJAX resources for Python

2005-10-30 Thread Andrew P
Turbogears seconded.  It's a really great collection of tools.

As an alternative, you  may also want to check out Nevow.  From the webpage:

"Nevow includes LivePage, a two-way bridge between JavaScript in a
browser and Python on the server. For 0.3, LivePage has been updated
to operate on Mozilla, Firefox, Windows Internet Explorer 6, and
Safari on Mac OS X. Event handlers can be written in pure Python and
JavaScript implementation details are hidden from the programmer, with
Nevow taking care of routing data to and from the server using
XmlHttpRequest."

You'd use it with Twisted, but it may be the easiest solution once the
initial learning curve is over.  Livepage actually predates the AJAX
terminology, so it's been around a while.  The only major example I've
seen is at http://www.jotlive.com, but it's a pretty good one. 
Multiple people can edit a document interactively at the same time.  I
tried the free account, and it was impressive.

Good luck,

Andrew
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code Readability (was: Recursion and List Comprehensions)

2005-10-29 Thread Andrew P
Sorry.  *blush*  That was some late Friday night craziness.  I just
looked at the code being discussed:

retList=[word[pos]+item for item in permute3(word[0:pos]+word[pos+1:])]

And really didn't want to anybody to confuse that with Python's idea
of elegance.

List comprehensions can get pretty horrible when combined with nested
functions and/or slices and/or multiple implicit loops.  One of the
few areas where Python can get really twisted.

That's a great point, Danny. For me, elegance is an admirable goal
under any circumstance, but includes all the aspects I listed. 
Effeciency -and- understandability.  Throw it under the umbrella of
"graceful" :)

The tools we use are far from perfect, and there are still plenty of
"aha!" moments to go around.  In the real world the fast and ugly
usually go hand in hand.  I'm an optimist, tho.

Anyway, sorry to go so far off topic.  Oh, and by the way, I loved
'The Psychology of Programming'.  That was a really entertaining book,
and thanks again for recommending it.

Andrew

On 10/29/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
> > > I agree.  When writing for keeps (i.e. production code) I prefer
> > > clarity and ease of maintenance over 'elegance' or 'trickiness'.
> > > This exercise is intended, in part, to sharpen my understanding of
> > > Python idioms.  If I can write highly idiomatic code that works,
> > > chances are better that I will be able to decipher it when I come
> > > across it elsewhere.
>
> > Since when is elegance a dirty word?
>
> It's not.  But there are tradeoffs.  As a concrete example, we can take a
> look at Bram Cohen's fairly recent request for a pure-Python suffix tree
> implmementation:
>
> http://www.livejournal.com/users/bramcohen/22069.html
>
> He's specifically requesting for an implementation for a data structure
> algorithm that is easy to maintain, and he's willing to sacrifice the
> elegant optimal solution!  But that's because he wants to make sure he can
> understand
> I'm not sure I agree with Bram --- the "Ukkonen" algorithm for building
> suffix trees isn't bad, and I can probably cook it up if I'm careful ---
> but I can see why he values a simple implementation.
>
>
d the code later on.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code Readability (was: Recursion and List Comprehensions)

2005-10-29 Thread Andrew P
Since when is elegance a dirty word?

Elegance is the soul of good programming.   A simple and graceful
solution to the widest number of cases, efficient and easy to
understand in application.  Sometimes subtle, but always beautiful.

In language design, software architecture, algorithms, it is the
rushing light of clarity that banishes dark and smelly corners.  It's
side effects are many--reusable code, effortless speed, painless
maintenance, reduced complexity.

The dreams shared by physicists, mathematicians, and engineers, are
dreams of elegance.

It is heartbreaking to see a concise and useful term maligned by dense
one-liners, which are seldom anything except hard to read.  Simple and
short ain't the same thing.

And having indulged in possibly very off-topic interlude, let me point
out that recognizing a donut when you see it, doesn't make you a
baker.  Trust me,  I'm not baking donuts.

And judging by the amount of Escher-like pretzels that continute to be
baked in the world,  we have a long ways to go before we get more than
the occasional sighting or passing whiff of something sweet and round
with a hole in the middle. .

Take care,

Andrew

On 10/28/05, Carroll, Barry <[EMAIL PROTECTED]> wrote:
> Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> <>
>
> >>PS Don't get too crazy about eliminating intermediate variables, they can
> >>make the code more readable.
> >>
> >>Kent
>
> I agree.  When writing for keeps (i.e. production code) I prefer clarity and
> ease of maintenance over 'elegance' or 'trickiness'.  This exercise is
> intended, in part, to sharpen my understanding of Python idioms.  If I can
> write highly idiomatic code that works,  chances are better that I will be
> able to decipher it when I come across it elsewhere.
>
> Barry
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-21 Thread Andrew P
On 10/21/05, Kent Johnson <[EMAIL PROTECTED]> wrote:

>For simple examples just look at Python's built in string, list and dict
>classes.

-Using- OOP isn't the problem :)  It's impossible to ignore it's usefulness when
programming in Python.  But getting from there to thinking non-procedurally is,
as has been pointed out, a tiny bit difficult.

My frustration/abject fear was with this particular example being very hard to
decipher, and not seeing any advantages to it being laid out that way.  I
assumed there were some, where this kind of thing had benefits.

>You can also think of classes very pragmatically, as another tool available to
>organize your code, just like modules and functions. Classes add some useful
>capabilities to your toolkit. This essay gives some simple motivating examples
>of why a beginner might want to use classes:
>http://personalpages.tds.net/~kent37/blog/stories/15.html


I realize after all these reposnses that I should have mentioned that  I do use
classes to do exactly that.  Bundle logic and data, but then call the classes
I've made procedurally.  It's handy, having methods attached to objects, and to
be able to use any object that supports the same interface interchangeably.

But I have the nagging feeling I still have it all upside down and inside out.
Writing a bunch of objects that are supposed to interact in dynamic ways at
runtime with nobody leading the band, and all.  Maybe if I'm not writing a
a library or framework I shouldn't worry so much.

>
>There is a very real cost to OOP that responsibility for some action can be
>distributed among multiple cooperating classes, so to trace through an
>operation you may have to follow a chain from one class to the next. When the
>design is well done, the benefit of useful abstractions outweighs this cost.
>Done poorly, you can write object-oriented spaghetti code. The key is to have a
>clear idea of the responsibility of each class.
>

For all I know people are using IDEs that let them write unreadable code that
simultaneously allows loosest coupling between classes, and most reuse of code
at the expense of readability.  Giant jellyfish-like automatons that are easy
to maintain with appropriate tools.  I'm still not sure that impression is
wrong :)

I do my best learning by reading good examples.  I imagine most people do.
There is just no substitute for understanding what somebody else has done well,
tip to tail.  I am just mistrustful of something so hard to puzzle out.

>Stepping through the code in a debugger can be useful to
understanding the flow.

I've never actually used a Python debugger. Or any debugger.  That was such a
commonsense answer I'm embarassed I didn't try it first.

Thanks again, Kent :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-20 Thread Andrew P
Hi Alan, thanks for taking the time to answer so thoroughly.  I've
responded to a few things below.   But let me say right off I have
gone through the OOP section in your excellent tutor.  It was one of
my main resources learning Python.  I actually have Bertand Meyer's
book here (and have written a couple small programs in Eiffel!) based
on your recommendation, but I think my main confusion is stemming from
composition vs inheritance, and it's effect on program
readability/understandability.  I went to "Learning Python" looking
for that composition example trying to make things a little more
concrete.

On 10/20/05, Alan Gauld <[EMAIL PROTECTED]> wrote:

> However its not a terrible example either...
>
> > Am I too stupid for OOP?
>
> Definitely not but for some people OOP is not as naturally intuitive as it
> is to others. For some reason those with a background in math seem
> to find OOP less intuitive, I dunno if that applies to you though :-)

I was referring specifically to being able to follow how the classes
interacted to obtain the results.  I know that objects interact
dynamically at runtime, so there may only be so much I can infer, but
I am trying to read code to get an idea of how to write it, and it was
discouraging to be stymied by an example from "Learning Python",
especially a do-nothing example..

> Absolutely. You are not supposed to try to follow the chain of command
> to the bottom, you are supposed to work with theobjects as stand alone
> mini programs. YOu don;t think about how they work inside any more
> than you read the Python interpreter source code every time you call it
> (I assume you don't do that???!) Objects are tested independantly and
> thereafter we just trust them to do what they claim to do.

How does this relate to composition vs inheritance?  When you have
multiple classes composed of multiple parts of multiple other classes,
doesn't that freeze your interface decisions early on?  It seems to
really tightly bind classes together.  I think I just need to track
down a real-world example, maybe.  This was probably the wrong one to
choose.  I just can't picture how it would even be possible to write
and grow.

Inheritance, subclassing, and overloading are much simpler concepts,
and relatively straightforward to read, at any rate, ignoring design
issues :)  You can point to a class and say ok, this is inheriting
that class's methods, or overloading an abstract class.  Perhaps it's
just the interaction between classes that is giving me a problem.

> > Instead of functions and arguments there are methods, classes,
> > and instances being passed about willy-nilly
>
> There should be messages which include objects as their arguments.
> Its important to conceptually separate messages from methods. We
> send a message to an object and it responds by executing a method
> - which method we mauy not know(this is polymorphism!) - and we
> get a result back. We pass objects around so that the receiving object
> can call methods of that object - this is somewhat akin to passing
> function pointers or lambdas in more traditional languages.
>

I should have been more clear here, as well.  I was talking more
specifically about the example as composition.  I think I am just
missing something conceptually.  I've written basic classes for myself
before that just bundle logic and state, and I think they were
reasonable choices for objects.  But really it was just a way to
interact with an object procedurally, like I do every day with Python.

I'm just not sure how to organize the piecemeal composition of new
classes from existing ones, in any sensical way.  Or for that matter,
how to arrange a bundle of classes with no "leader" :)  Speaking of
structural programming biases.  But at least I recognize that hurdle,
and can see how it would be possible.

> At risk of too much blatant self promotion try the OOP topic in my tutor.
> Also try reading through the Games framework (hmgui.zip) that I submitted
> to Useless Python (or is described in the paper book version of my tutor)
>

Well, that sounds like a real-world example I can look at :)  Thanks
again for your time, Alan.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-20 Thread Andrew P
I've been reading about composition vs inheritance, and went back to
"Learning Python" to look at something I found very confusing a year
ago.  Turns out I still find it very confusing :)

The code at the bottom was taken from the OOP chapter, it's a solution
to one of the end-of-chapter problems.

Honestly, this toy program is enough to make my head spin.  Am I too
stupid for OOP?  Here is me trying to decipher it:

 Starting here:

x = Lunch(  )   # Self-test code
x.order('burritos') # If run, not imported

You have to look at the method of class Lunch:

def order(self, foodName):  # Start a Customer order simulation.
self.cust.placeOrder(foodName, self.empl)

check the instance name:

self.cust = Customer(  )

to see what class it belongs to, jump to class Customer, look up the
method being called:

 def placeOrder(self, foodName, employee):  # Place order with Employee.
self.food = employee.takeOrder(foodName)

 which uses employee as an argument, which was, looking back up, an
instance of class Employee:

class Employee:
def takeOrder(self, foodName):# Return a Food, with requested name.
return Food(foodName)

which seems to return an instance of food?  I don't really understand
that,  but I've already forgotten what it was I started off looking to
find :)

x.result(  )

Which is just entirely too much for my brain to hold at once.  I'm
sorry if this sounds like whining, but this entire program seems as
bad as trying to decipher the GOTO-crazy scribblings of a lunatic. 
There is no linearity, and the extra abstraction of the classes just
adds another layer of complexity.  Instead of functions and arguments
there are methods, classes, and instances being passed about
willy-nilly and no (for me) easy way to follow the path or make sense
of it.

Is this just an example of a technique with a constant complexity
factor that looks ridiculous on a toy program, but very quickly
becomes useful on larger ones?  Are there tools that make reading
something like this more clear?

Thanks,

Andrew


#
# lunch program
#

class Lunch:
def __init__(self):# Make/embed Customer and Employee.
self.cust = Customer(  )
self.empl = Employee(  )
def order(self, foodName):  # Start a Customer order simulation.
self.cust.placeOrder(foodName, self.empl)
def result(self):   # Ask the Customer about its Food.
self.cust.printFood(  )

class Customer:
def __init__(self): # Initialize my food to None.
self.food = None
def placeOrder(self, foodName, employee):  # Place order with Employee.
self.food = employee.takeOrder(foodName)
def printFood(self):   # Print the name of my food.
print self.food.name

class Employee:
def takeOrder(self, foodName):# Return a Food, with requested name.
return Food(foodName)

class Food:
def __init__(self, name):  # Store food name.
self.name = name

if __name__ == '__main__':
x = Lunch(  )   # Self-test code
x.order('burritos') # If run, not imported
x.result(  )
x.order('pizza')
x.result(  )
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] file opening and errors.

2005-10-20 Thread Andrew P
It's not in direct answer to your question, but a real short answer is
"Python doesn't need 'or die' here."  It throws exceptions gleefully
whenever it encounters an error:

>>> f = open('no_such_file')

Traceback (most recent call last):
  File "", line 1, in ?
IOError: [Errno 2] No such file or directory: 'no_such_file'

>>> import os
>>> os.rmdir('/squeak')

Traceback (most recent call last):
  File "", line 1, in ?
OSError: [Errno 41] Directory not empty: '/squeak'

This behavior highlights one of the philosophical differences between
the languages.

Another reversal of stances to keep in mind is that variables are
local by default in Python, and global by default in Perl.

These are also two of my absolute favorite differences.  Silent errors
and global variables never sat well with me.  Die and my are the
general use cases :)

Good luck,

Andrew

On 10/20/05, Dan Klose <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I usually use perl but fancy a bit of a change so have started playing
> with python.
>
> using perl to open a file or directory I usually use:
>
> open(FILE, $file) or die "Error: $!\n";
>
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".
>
> With python I have use a try except block but I have no idea how I would
> get the same warning from python as I would from perl (the reason for
> the exception), I am not even sure if this is possible (I assume it must
> be) as google searching has been fruitless.
>
> Thanks for any help, pointers and suggestions.
>
> Dan.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if-else statements

2005-10-14 Thread Andrew P
Well, on the bright side, at least Python is being taught in schools.

My younger sister is a CS major just starting her programming courses,
and it's Java/C++ all the way.  I am becoming convinced that lines of
code are not only related to the number of bugs and development speed,
but learning speed as well.  Too much time tripping over syntax and
you miss the important bits.

On 10/14/05, Danny Yoo <[EMAIL PROTECTED]> wrote:

> Otherwise, it really does sound like you're just pushing your homework on
> us.  The jist of your questions right seem to be "This program doesn't
> work: help me fix it."  This is not really interesting to us.  We really
> want to help you get unstuck, but we don't want to do your homework.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] extract plain english words from html

2005-10-14 Thread Andrew P
You could try: http://www.aminus.org/rbre/python/cleanhtml.py

YMMV, as the kids say.  But I did choose this over BeautifulSoup or
Strip-o-gram to do this particular thing.  I don't remember -why- I
chose it, but there you go.  Easy enough to test all three :)

Oh, and if you just want a whole page prettily formatted:

lynx -dump page.html > file.txt

is often the easiest way.

Good luck,

Andrew

On 10/14/05, Marc Buehler <[EMAIL PROTECTED]> wrote:
> hi.
>
> i have a ton of html files from which i want to
> extract the plain english words, and then write
> those words into a single text file.
>
> example:
> 
> 
> <... all kinds html tags ...>
> 
> this is text
> 
>
> from the above, i want to extract the string
> 'this is text' and write it out to a text file.
> note that all of the html files have the same
> format, i.e. the text is always surrounded by the same
> html tags.
> also, i am sorting through thousands of
> html files, so whatever i do needs to be
> fast.
>
> any ideas?
>
> marc
>
>
> ---
> The apocalyptic vision of a criminally insane charismatic cult leader
>
>http://www.marcbuehler.net
> 
>
>
>
> __
> Yahoo! Music Unlimited
> Access over 1 million songs. Try it free.
> http://music.yahoo.com/unlimited/
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to speed up this code?

2005-10-13 Thread Andrew P
It's way past my bedtime, but any use of numpy/numarray that involves
two nested for loops to step over each element is the wrong solution
:)  You need to figure out how to get rid of that inner for. 
That is what is slowing you down.  

Compare these two ways to multiply a 1000 element array by 100. 
The first one steps over the elements one at a time, multiplying each
one in turn.  The second multiplies the entire array at
once.  Which boils down to looping over 2000 rows, instead of
4,000,000 elements :)

If I was more awake, I'd try to figure out how you can do that. 
But this should give you an idea of what arrays are useful for, and how
to approach the problem.

>>> def time_loop(num):
...     a = arange(1000)
...     b = zeros(1000)
...     t = time.clock()
...     for i in range(num):
...         for i in range(len(a)):
...             b[i] = a[i] * 100.0
...     print time.clock() - t
...     
>>> time_loop(10)
59.7517100637


>>> def time_numeric(num):
...     a = arange(1000)
...     b = zeros(1000)
...     t = time.clock()
...     for i in range(num):
...         b = a*100
...     print time.clock() - t
...     
>>> time_numeric(10)
1.44588097091

On 10/13/05, Pujo Aji <[EMAIL PROTECTED]> wrote:
I have code like this: 
def f(x,y):     return math.sin(x*y) + 8 * x  
def main():     n = 2000     a = zeros((n,n), Float)     xcoor = arange(0,1,1/float(n))     ycoor = arange(0,1,1/float(n)) 
    for i in range(n):         for j in range(n):             a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x 
    print a[1000,1000]     pass 
if __name__ == '__main__':     main() 
I try to make this run faster even using psyco, but I found this still slow, I tried using java and found it around 13x faster... 
public class s1 { 
        /**          * @param args          */         public static int n = 2000;         public static double[][] a = new double[n][n];         public static double [] xcoor = new double[n]; 

        public static double [] ycoor = new double[n]; 
        public static void main(String[] args) {                 // TODO Auto-generated method stub                 for (int i=0; i                        xcoor[i] = i/(float)(n);                         ycoor[i] = i/(float)n; 
                } 
                for (int i=0; i                        for (int j=0; j 
                   
          a[i][j] = f(xcoor[i], ycoor[j]);                         }                 } 

                System.out.println(a[1000][1000]); 
        }         public static double f(double x, double y){                 return Math.sin(x*y) + 8*x;         } 

}  Can anybody help? 
pujo 

___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please look at my wordFrequency.py

2005-10-11 Thread Andrew P
Just want to add a little something here, because reading over this thread, I think there may have been some confusion: 

Kent wrote:

for e in saveRemovedForLaterL:    L.append(e)could be
L.extend(e)

I think he might have meant:

for e in saveRemovedForLaterL:    L.append(e)could be

L.extend(saveRemovedForLaterL)

The difference between these is that one is explicitly looping with
Python, accessing each element of the first list one at a time,
appending it to the other one at a time.  Whereas if you call
extend() instead, it will be doing that looping for you with the
extend() method, written in C, and very quickly indeed.  I would
worry less about what is written in C vs what is built-in, and does
implicit looping for you.  Any time you can avoid stepping over a
list one element at a time, is usually the faster way.

>>> lst = [1,2,3,4]
>>> lst2 = [5,6,7,8]
>>> lst.extend(lst2)
>>> print lst
[1, 2, 3, 4, 5, 6, 7, 8]

Compare this to:

>>> lst = [1,2,3,4]
>>> lst2 = [5,6,7,8]
>>> for num in lst2:
...     lst.append(num)    
>>> print lst
[1, 2, 3, 4, 5, 6, 7, 8]


FWIW, append is generally used to generate a list from something calculated on the fly:

>>> lst = []
>>> for i in range(10):
...     lst.append(i)
...     
>>> print lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Ah. But how can I know what is in C code and what isn't? For example, ina previous post you say that 
L.extend(e) is in C, and imply thatL.append(e) isn't, and that therefore L.extend(e) should be used.Well, back to Hetlands' Beginning Python.Dick


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please look at my wordFrequency.py

2005-10-11 Thread Andrew P
If it makes you feel any better, this isn't an easy problem to get 100%
right, traditionally.  Heck, it might not even be possible. 
A series of compromises might be  the best you can hope for.

Some things to think about, however.  Can you choose the
characters you want, instead of the (many, many) characters you don't
want?  This might simplify matters.

What do most words look like in English?  When is a hyphen part of
a word, what about dashes?  A dash in the middle of a sentence
means something different than one at the end of line.

As far as other special/impossible cases...what is the difference
between dogs' and 'the dogs' when you are counting words?  What
about acronyms written like S.P.E.C.T.R.E, or words that include a
number like 1st?  You can add point 5 to the list.  Which are
more common cases, which collide with other rules.  What's the
minimum amount of rules you can define to take the maximum chunk out of
the problem?

That is enough of my random rambling.

A lot of it might magically fall into place once you try what Danny
suggested.  He is a smart guy.  Doing my best to have clearly
defined, self-contained functions that do a specific task usually helps
to reduce a problem to more manageable steps, and visualize what is
happening more clearly. 

Good luck,

Andrew
On 10/10/05, Dick Moores <[EMAIL PROTECTED]> wrote:
Script is at:Example text file for input:<
http://www.rcblue.com/Python/wordFrequency/first3000linesOfDavidCopperfield.txt>(142 kb)(from )Example output in file:
(40 kb)(Execution took about 30 sec. with my computer.)I worked on this a LONG time for something I expected to just be an easy
and possibly useful exercise. Three times I started completely over witha new approach. Had a lot of trouble removing exactly the characters Ididn't want to appear in the output. Wished I knew how to debug other
than just by using a lot of print statements.Specifically, I'm hoping for comments on or help with:1) How to debug. I'm using v2.4, IDLE on Win XP.2) I've tried to put in remarks that will help most anyone to understand
what the code is doing. Have I succeeded?3) No modularization. Couldn't see a reason to do so. Is there one or two?Specifically, what sections should become modules, if any?4) Variable names. I gave up on making them self-explanatory. Instead, I
put in some remarks near the top of the script (lines 6-10) that I hopedo the job. Do they? In the code, does the "L to newL to L to newL to L"kind of thing remain puzzling?(lines 6-10)# meaning of short variable names:
#   S is a string#   c is a character of a string#   L, F are lists#   e is an element of a list5) Ideally, abbreviations that end in a period, such as U.N., e.g., i.e.,viz. op. cit., Mr. (Am. E.), etc., should not be stripped of their final
periods (whereas other words that end a sentence SHOULD be stripped). Itried making and using a Python list of these, but it was too tough towrite the code to use it. Any ideas? (I can live very easily without a
solution to point 5, because if the output shows there are 10 "e.g"s,I'll just assume, and I think safely, that there actually are 10 "e.g."s.But I am curious, Pythonically.)Thanks very much in advance, tutors.
Dick Moores[EMAIL PROTECTED]___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regex help

2005-10-09 Thread Andrew P

If the format is consistent enough,  you might get away with something like:

>>> p = re.compile('MediaBox \[ ?\d+ \d+ (\d+) (\d+) ?\]')
>>> print p.search(s).groups()
('612', '792')

The important bits being:  ? means "0 or 1 occurences", and you
can use parentheses to group matches, and they get put into the tuple
returned by the .groups() function. So you can match and extract what
you want in one go.

http://www.amk.ca/python/howto/regex/ is a fairly gentle introduction
to regular expressions in Python if you want to learn more.

Having said all that, usually you would use a library of some sort to
access header information, although I'm not sure what Python has for
PDF support, and if that's -all- the information you need, and the
-only- variation you'll see, regex probably won't be too bad :)


On 10/9/05, Bill Burns <[EMAIL PROTECTED]> wrote:
I'm looking to get the size (width, length) of a PDF file. Every pdffile has a 'tag' (in the file) that looks similar to thisExample #1MediaBox [0 0 612 792]or thisExample #2MediaBox [ 0 0 612 792 ]
I figured a regex might be a good way to get this data but thewhitespace (or no whitespace) after the left bracket has me stumped.If I do thispattern = re.compile('MediaBox \[\d+ \d+ \d+ \d+')
I can find the MediaBox in Example #1 but I have to do thispattern = re.compile('MediaBox \[ \d+ \d+ \d+ \d+')to find it for Example #2.How can I make *one* regex that will match both cases?
Thanks for the help,Bill___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling Objects

2005-10-05 Thread Andrew P
To do:

$color = "Green";
print "$color apple.\n";

You would want:

color = "Green"
print "%s apple." % color

Both of which would print "Green apple."  That is actually
something I like about Perl, but it reinforces some bad habits, at
least for me.  Boilerplate coding, as it were, when doing quick
and dirty web stuff, which always ends up growing!  That and
inline regex will probably be the hardest thing to get used to.  

Good luck with Python, but you really won't need it.  I wrote a
script in Perl today to show a friend how to do something, and it
reinforced the amazing amount of -stuff- you need to remember to use
Perl, and the mind-draining way you can't type without thinking about
which way you will type it.   I swear it scares people away
from other languages for life :)

Python will be much, much easier to learn.  And hopefully you'll
spend more time typing what you want, than deciding how you should type
it, while doing the exact same things you always did.On 10/5/05, Eric Walker <[EMAIL PROTECTED]> wrote:
Thanks Kent.. I think that would work for what I am doing. So is it safe tosay that python doesn't do variable interpolation like perl..?
Thanks in advance.Python Newbie...

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to prevent ftplib from locking my script

2005-10-04 Thread Andrew P
Normally I wouldn't pipe up here because threads really can be very tricky.  But check out:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883

I use this recipe, originally from "Python in a Nutshell", all the
time, to solve exactly your problem.  Slow network stuff that I
don't have to/want to babysit.

The recipe is well-commented, with an easy-to-follow usage
example.  Basically though, Python's Queue module really takes
away a lot of the trickiness here, acting as a thread-safe place to put
jobs, and put results, without worrying about locks or sephamores or
whatever it is people worry about.  And the callback functions you
can pass in with the job may be all you really need to report
success/failure of the jobs.

All in all, it's probably easier to just read the code.

Good luck.
On 10/4/05, Tim Rupp <[EMAIL PROTECTED]> wrote:
Hi list,I'm trying to write a python script that uses ftplib to send items to alocal server I have. I want to be able to give ftplib a file to send,and then just have it sort of go into the background and do its thing
while the script does other "stuff"My attempts at it so far have caused the whole script to wait until theftp transfer finishes (essentially pausing the rest of the script).Any ideas on how I can just make it go away, allowing me to do other
stuff like output various info? Can threads be used? If so, does anyonehave good resources to point me to for python threading?Thanks in advance!Tim___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beautiful soup

2005-10-04 Thread Andrew P
Oops, Paul is probably right.  I thought urllib2 opened local
files in the absence of an identifier like "http://".  Bad assumption on my part.  I remembered that
behavior from somewhere else, maybe urllib.

That path beginning with "\\C:\\" could still bite you, however.  Good luck,

Andrew

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beautiful soup

2005-10-04 Thread Andrew P
With error messages like that, the interesting bits are usually at the end:

OSError: [Errno 2] No such file or directory:
'\\C:\\Python24\\FRE_word_list.htm
That should read "C:\\Python24\\FRE_word_list.htm".  

I use UNIX-style paths, which work fine for me under Windows, so it
would just be "/Python24/FRE_word_list.htm" which is a bit
cleaner.  I am not sure if that is dependable behavior, however.

Andrew

On 10/4/05, David Holland <[EMAIL PROTECTED]> wrote:
I tried to use this script which I found on the web :-import urllib2, pprintfrom BeautifulSoup import BeautifulSoupdef cellToWord(cell):   """Given a table cell, return the word in that
cell."""   # Some words are in bold.   if cell('b'):  return cell.first('b').string.strip()  #Return the bold piece.   else:  return cell.string.split('.')[1].strip()   #
Remove the number.def parse(url):   """Parse the given URL and return a dictionarymapping US words to   foreign words."""   # Read the URL and pass it to BeautifulSoup.
   html = urllib2.urlopen(url).read()   soup = BeautifulSoup()   soup.feed(html)   # Read the main table, extracting the words fromthe table cells.   USToForeign = {}   mainTable = soup.first
('table')   rows = mainTable('tr')   for row in rows[1:]:# Exclude the first(headings) row.  cells = row('td')  if len(cells) == 3:  # Some rows have asingle colspan="3" cell.
 US = cellToWord(cells[0]) foreign = cellToWord(cells[1]) USToForeign[US] = foreign   return USToForeignif __name__ == '__main__':   url ="">'
http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm'   USToForeign = parse(url)   pairs = USToForeign.items()   pairs.sort(lambda a, b: cmp(a[0].lower(),b[0].lower()))  # Web page order
   pprint.pprint(pairs)and it works well.  However I change it to get it tolook at a file on my PC, then I get this message :-Traceback (most recent call last):  File "C:\Python24\beaexp2", line 43, in -toplevel-
USToForeign = parse(url)  File "C:\Python24\beaexp2", line 20, in parsehtml = urllib2.urlopen(url).read()  File "C:\Python24\lib\urllib2.py", line 130, inurlopenreturn _opener.open(url, data)
  File "C:\Python24\lib\urllib2.py", line 358, in openresponse = self._open(req, data)  File "C:\Python24\lib\urllib2.py", line 376, in_open'_open', req)  File "C:\Python24\lib\urllib2.py", line 337, in
_call_chainresult = func(*args)  File "C:\Python24\lib\urllib2.py", line 1119, infile_openreturn self.open_local_file(req)  File "C:\Python24\lib\urllib2.py", line 1135, in
open_local_filestats = os.stat(localfile)OSError: [Errno 2] No such file or directory:'\\C:\\Python24\\FRE_word_list.htmAny idea how to solve it ?  The file is on my PC.I am using Python 2.4
 on Win XP.Thanks in advance.David___How much free photo storage do you get? Store your holidaysnaps for FREE with Yahoo! Photos 
http://uk.photos.yahoo.com___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Book recommendations

2005-09-30 Thread Andrew P
Thanks Danny.  That outline of How to Solve It  reminded me of an idea that resonated strongly with me in 
Programming Pearls, and I just looked it up and sure enough,  Bentley was referencing the same Polya book:

"Most of the structures exemplify what Polya calls the Inventor's
Paradox in his How To Solve It: "the more general problem may be easier
to solve". In programming this means that it may be harder to solve a
73-case problem directly than to write a general program to handle the
N-case version, and then apply it to the case that N=73. "

So, you definitely felt where I'm coming from.

I've only programmed in Python and Perl, and BBC BASIC on my Amstrad
NC100, but I've already intuited that procedural languages share more
in common than not.  So old books are fine, and Cobol and Fortran
with bits next to them explaining what they do shouldn't be too hard to
figure out :)

Thanks again.

Andrew
On 9/30/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
Hi Andrew,Another book that I enjoy is Gerald Weinberg's "The Psychology of ComputerProgramming":http://www.dorsethouse.com/books/psy.html
because when we write computer programs, we should recognize that althoughtechnique plays a large part in a program, so does the personality behindthe keyboard.Weinberg's demonstrations of how people's ego come into play during the
creative act of programming are realy eye-openers, and even though theexamples in his book use *gasp* Fortran and Cobol, they're still very veryrelevant.The mathematician George Polya wrote an excellent book on problem solving
called: "How to Solve It".  Definitely look at this one; his insights intoproblem solving apply very well to computer programming.  An outlinesummary of his book is here:
http://www.cis.usouthal.edu/misc/polya.htmlHope this helps!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] find data in html file

2005-09-30 Thread Andrew P
It's free now to use the API.  You just "self-certify" and get 10,000 calls a month.

Imac, if you use the API, let me save you some trouble.  REST is
useless, SOAP is overly complicated, which leaves XML over HTTP which
is really quite nice.  I am not speaking generally, but talking
about the ebay implementatiosn before anybody beats me up :)

Besides, no Python tool I could find would parse that accursed WSDL
file, making SOAP a useless layer over the exact same request as XML
over HTTP.

Personally tho, I just scrape what I want, for a variety of
reasons.  Number one being when the API breaks, you are
screwed.  If your scrape breaks, it's usually 5 minutes to suss
out and fix.  And breaking happens much, much less often than you
might think.  It's a little more initial (monkey) work, since you
don't have a nicely formatted XML file coming back.  But the same
principles apply.  You need to choose a tool to parse stuctured
data.  Elementtree + PDIS Xpath, or BeautifulSoup, either way you
are making a tree and extracting data from it :)

Don't worry if none of this makes sense right now.  It's a bit of
a learning curve going down either road, but they are more parallel
than not.  Sign up with ebay, get your developer tokens and all
that jazz, download elementree and start making some requests, and
parsing what you get back with the tool of your choice.  If that
suits your purposes, it is probably the easiest way.
On 9/30/05, paul brian <[EMAIL PROTECTED]> wrote:
> But to get the data like price,bidders,shipment etc without the official> eBayAPI is hard.> Maybe anyone has a solution made ? Ebay specifically change around their HTML codes, tags and formatting
 (in quite a clever way) to stop people doing exactly what you are trying to do. I think it changes every month. Like people say, use the API - You need to become an "ebay developer" (signup) and can use your own code or the python-ebay thing for free
 in "the sandbox", but must pay $100 or so to have your code verified as "not likey to scrunch our servers" before they give you a key for the real world. Its a bit of a pain, so i just hacked turbo-ebay a while back and made
 do.  Worked quite well really.Paul Brianm. 07875 074 534t. 0208 352 1741___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Book recommendations?

2005-09-30 Thread Andrew P

Thanks Mike.  Many a google search has landed me on his site, and I always end up reading more than what I landed on :)

All of the above are great picks. I'd also recommend Joel On Software. It's acollection of his articles from his web site.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Book recommendations?

2005-09-30 Thread Andrew P
Thanks for the recommendations, Kent.

Kent wrote:
How could I forget the Gang of Four? This is the book that started the Design Patterns movement.
Gamma, Helm, Johnson & Vlissides, Design Patternshttp://www.aw-bc.com/catalog/academic/product/0,1144,0201633612,00.html



I probably shouldn't forget this either.  OOP is largely a mystery
to me, and it's hard/impossible to read anything about it without a
reference to that book. 


Kent wrote: 
By
the way bookpool.com is my favorite place to buy technical books, their
prices are often lower than Amazon.com and shipping is reasonable and
fast.
Let me make my own quick recommendation for half.com, and alibris.com.
  I like to look at those for any used copies before ordering
new.  They are both listings from independent booksellers around
the country, with standardized shipping.  I also have many
under-a-dollar books of the non-technical variety from both places on
my bookshelf.  

I end up buying technical books new about half the time, since newer
ones hold so much value used.  I'm not ecstatic about ordering
from Amazon on the best of days, so the recommendation is appreciated.

Thanks again,

Andrew
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Book recommendations?

2005-09-29 Thread Andrew P
I was just thinking about Jon Bentley's Programming Pearls,
and how much I really liked it.  Nothing has really changed since
1986, and all the pseudo code translated nicely into Python.  It
was by far the most fun I've had reading any book about
programming.  Especially solving problems he presented before
turning the page, or trying damned hard to!

Does anybody have any recommendations for other books on programming
practices in general?  Any fun or philosophical reads on software
architecture/design? 

I saw that Alan Gauld recommends Code Complete, and went ahead and ordered that second hand :) 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] script question

2005-09-28 Thread Andrew P
Have you benchmarked it yet?  4000 lines isn't very many, even for
an older machine.  Starting the Python interpreter usually takes
most of the time with simple scripts like this.  Honestly,
benchmark :)

You might find it easier to do::

interface_list = INI.items(section)for i in interface_list:
    if i[1] == interface:
    ...
the items method just returns the whole section in a list of tuples, so don't have to build it yourself.

One last you may also want to consider is lowercasing any input,
because last I checked ConfigParser lowercases what it parses whether
you want it to or not :)

So if somebody searches for NetworkDevice10, ConfigParser will return
it as networkdevice10, and you won't get a match.  That certainly
bit me a couple times.

Good luck.
On 9/28/05, Chris Hallman <[EMAIL PROTECTED]> wrote:

Thanks for all the input!!! I really appreciate it. I need to post a
correction to my script. What I sent was an early version. I made a few
minor modifications:



import ConfigParser, string, sys, ossection = sys.argv[1]interface = sys.argv[3]INI=ConfigParser.ConfigParser()INI.read("c:\utils\interfaces.ini")interface_entries=[p for p in INI.options
(section)]interface_list=[INI.get(section, pw) for pw in interface_entries]for i in interface_list:	if i == interface:		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])



I've researched what you all have suggested and I may need to switch to
reading the ini file line by line or using a different file parser. The
ini file is only 100 lines long now, but will likely grow to 500 line
and maybe to 4000 lines. To give you a better background of what I'm
doing with this script, it's running on a network management system
that receives traps. After some processing of the raw trap, messages
get sent to this script for further processing. These messages are for
interface down traps from routers and switches in our network. I use
this script to mitigate the number of interface down messages on our
console. I need to do this because we do not need to know when every
port has gone down (i.e. user ports). This script searches the ini file
for a device name match. Once it has found a match and if the interface
matches as well, I need to message forwarded to the console (the
Windows command). If no matching device or interface is found, then the
script can just exit.
- Show quoted text -
On 9/26/05, Kent Johnson <[EMAIL PROTECTED]
> wrote:
Kent Johnson wrote:> *TEST FIRST* Don't optimize until you know it is too slow and you> have a test case that you can time to see if your 'optimizations' are> making it faster.Pardon my shouting :-)
Kent___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web development

2005-09-28 Thread Andrew P
I've used CherryPy on a couple of projects now.  I use it with
HTMLTemplate
(http://freespace.virgin.net/hamish.sanderson/htmltemplate.html) and
SQLObject (http://sqlobject.org/). 

This has the advantage of being about as Pythonic as you can get, since
everything you manipulate is represented as an object. 
HTMLTemplate is especially nice since it completely separates the html
from your code.  I can, have, and do change the interface
frequently with impunity, and vice versa.  Contrast this with
something like inline PHP.  It's also editable in any old wsywig
HTML editor.  But you are free to choose whatever persistent
storage and templating system you like.

CherryPy is low level, and will force you to make decisions about what
templating you want to use, and what you want to use for a
backend.  But the upside is, it feels no different than writing
any other program.  Just do what you've always done, choose
supporting packages you like, and it's off to the races.  It's
even it's own webserver. So edit, run, edit run.  Same as always.

I can tell you why I didn't choose some others.  Zope is a chunky,
labyrinth-like framework.  My friend runs Plone, built with Zope,
and it's easily the most resource heavy thing running on my
server.  That just sent me running.  Webware uses some sort
of JSP/ASP/PHP alike, which makes me cringe in horror.  HTML and
code do not belong together in a big inline spaghetti lovefest. 
IMHO :)  

Twisted is an "asynchronous networking framework", and I haven't used
it, but actually looks fairly small, has it's own webserver, and a very
very nice looking templating system which has the same philosophy as
HTMLTemplate, but has some really cool feautures like livepage, which
seems to be the same thing as AJAX, a la google maps.  I just
haven't had a reason to check it out, but it would be first on my list
to check.  It's more of a kitchen sink approach, or general
purpose if you prefer, but does seem cool.  So if you are looking
for something like that, well.  Build websites, write chat
programs! 

OK.  Enough early morning rambling :)  Good luck choosing. 

On 9/27/05, Don Jennings <[EMAIL PROTECTED]> wrote:
Earlier this month, Kent posted that Jython and Velocity are a good wayto develop dynamic web sites. After a little searching, it seems thatthere are quite a few options for web development in Python (perhapstoo many?). So, rather than ask for recommendations of which one to
use, what I would really like to know are how people decided to use anyparticular framework.Thanks!DonP.S. As an aside, does anyone have any experience with django? (Ireally like the name since I am fond of django reinhardt, the jazz
guitarist.)___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor