Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread James Mills
On Fri, Jul 30, 2010 at 11:47 AM, David Hutto  wrote:
> This is basically to get feedback, on a better way to show the
> greatest common divisor in fraction, in order to reduce it fully, than
> the one I've come up with. I'm sure there are better ways, so if you
> have simpler method, or critique of what I've done, let me know.

[snip]

I have a far simpler solution:

>>> from tools import gcd
>>> gcd(20, 5)
5
>>>

def gcd(a, b):
while b != 0:
    (a, b) = (b, a%b)
return a

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread James Mills
On Fri, Jul 30, 2010 at 12:10 PM, James Mills
 wrote:
> def gcd(a, b):
>    while b != 0:
>        (a, b) = (b, a%b)
>    return a

Here's another solution that uses a generator called factors to
generate a list of factors for any given value. The gcd function
then uses sets and intersection and the max function to find
the greatest common factor/divisor

http://codepad.org/VJIRyvI8

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A better way for greatest common divisor

2010-07-29 Thread James Mills
On Fri, Jul 30, 2010 at 12:22 PM, Richard D. Moores  wrote:
> On Thu, Jul 29, 2010 at 19:10, James Mills  
> wrote:
>> On Fri, Jul 30, 2010 at 11:47 AM, David Hutto  wrote:
>>> This is basically to get feedback, on a better way to show the
>>> greatest common divisor in fraction, in order to reduce it fully, than
>>> the one I've come up with. I'm sure there are better ways, so if you
>>> have simpler method, or critique of what I've done, let me know.
>>
>> [snip]
>>
>> I have a far simpler solution:
>>
>>>>> from tools import gcd
>>>>> gcd(20, 5)
>> 5
>
> In Python 3.1 that would be
>>>> from fractions import gcd
>>>> gcd(20,5)
> 5

Yes. The code I provided above was code I wrote
for various Euler problems I had been working on
a whiel back. It was written for 2.x

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get str() to use my function?

2010-08-04 Thread James Mills
On Thu, Aug 5, 2010 at 12:37 AM, Alex Hall  wrote:
> Hi all,
> I have a card class. A card object simply consists of a pair of
> numbers; 0,0 might be the ace of clubs, for example. I have a toString
> method in my card class. Is there a way to just say str(card) instead
> of card.toString()? Maybe some sort of basic, built-in function to
> override? TIA. Oh, what about doing the same with operators? For
> example, could I get the program to call my own math functions when it
> sees a card object in a math expression, like
> if(card1==card2)

implement a __str__ method. For example:

$ python
Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
[GCC 4.4.4 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
... def __str__(self):
... return ""
...
>>> foo = Foo()
>>> foo
<__main__.Foo object at 0x83d796c>
>>> str(foo)
''
>>>

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string to list

2010-08-05 Thread James Mills
On Thu, Aug 5, 2010 at 2:38 PM, Vikram K  wrote:
> Suppose i have this string:
> z = 'AT/CG'
>
> How do i get this list:
>
> zlist = ['A','T/C','G']

>>> import re
>>> z = 'AT/CG'
>>> [x for x in re.split("([A-Z]\/[A-Z])|([A-Z])", z) if x]
['A', 'T/C', 'G']
>>>

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modify csv textfile

2010-08-06 Thread James Mills
On Sat, Aug 7, 2010 at 12:35 PM, TGW  wrote:
> I have a pipe delimited text file with 5 columns which looks like this:
> 12345|some text|some more text|example125 oo3 3456|example32423
> 11223|more text|and more|example/73d 77665|example455667
> 12677|text|more|anotherexample 123|anotherexample45
>
> What I want to output is:
> 12345|some text|some more text|example|example32423
> 11223|more text|and more|example|example455667
> ...
> 12677|text|more|anotherexample 123|anotherexample45
>
> So column 4 is where the change occurs, but only if the beginning of the 
> string in column 4  =~ /^example/i  # and it should be case insensitive

So do it :)

> #!/usr/bin/env python
> import csv
> import re
>
> filename = raw_input("Enter the filename to edit: ")
>
> reader = csv.reader(open(filename, 'rb'), delimiter='|', 
> quoting=csv.QUOTE_NONE)
> for row in reader:
>    print row
>
> 
> I can print the file, I just need a little help searching and replacing
the column 4 data element.

Use re.match to match the column.

Use csv.writer to write our a new csv file
based on the one you're reading, filtering
and modifying.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a graceful program exit

2010-08-11 Thread James Mills
On Thu, Aug 12, 2010 at 1:42 PM, Bill Allen  wrote:
> I have only learned a couple of ways to cause a Python program to exit:
> sys.exit(0)  &  raise.SystemExit .  I am using this in a try/except block.
> Which is preferred?  Are there other, better ways?

The normal pattern is to have an entry point and an exit point.

main() and SystemExit exception.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] continuous running of a method

2010-08-22 Thread James Mills
On Mon, Aug 23, 2010 at 3:00 PM, Greg Bair  wrote:
> I have a method (I'll call it foo) that will either return None or an object
> depending on a random value generated.  What I want to happen is that if I
> call foo(), i.e, f = foo() and it returns None, to re-call it until it
> returns something else.  I would think this would be done with a while loop,
> but can't seem to get the details right.
>
> Any help would be greatly appreciated.

Quite simple really, and yes you are right. Use a while loop:

>>> from random import seed, random
>>> from time import time
>>> seed(time())
>>> def foo():
... if 0.5 < random() < 0.6:
... return True
...
>>> x = foo()
>>> while x is None:
... x = foo()
...
>>> x
True
>>>

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SSH session problems with network devices

2010-08-26 Thread James Mills
On Fri, Aug 27, 2010 at 2:54 AM,   wrote:
> My Paramiko code works correctly when connecting with a Linux system. But
> when I connect with a router, the connection is dropped immediately after a
> command is exectued, so it isn't possible to send a sequence of interrelated
> commands.

What Router is this ? What OS does it run ?

I may have some experience with this as I often ssh into various
networking devices including Linux servers and systems, etc...

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SSH session problems with network devices

2010-08-26 Thread James Mills
On Fri, Aug 27, 2010 at 8:42 AM,   wrote:
>
> I'm running tests on - Cisco IOS Software, s72033_rp Software
> (s72033_rp-ADVIPSERVICESK9_WAN-M), Version 12.2
>
> It's running SSHv2.0
>
> My solution should be portable to other vendor/models.

Can you "normally" ssh into your Cisco routers and be presented
with a shell of some kind ?

cheers
James

PS: Please post to the list.

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SSH session problems with network devices

2010-08-26 Thread James Mills
On Fri, Aug 27, 2010 at 9:13 AM,   wrote:
>
> Yes. No problem. The point is that I have Python programs that normally
> access these devices by telnet to complex tasks. I have to find a way to use
> SSH to replace the telnet in my code.

I actually have no experience with Cisco devices, but the question
that remains to be seen really is; "Why are your Cisco devices
terminating the SSH connection after the first command ?"

This actually might be a terminal or some kind of configuration issue
(if you can normally ssh into your Cisco devices and get a
prompt/terminal). Ssh'ing and executing remote commands might be
interpreted differently by the Cisco ssh/shell/etc.

It might be worth your while looking into this as it'll have nothing
at all to do with Python or Paramiko..

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input problem

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 6:45 AM, ANKUR AGGARWAL  wrote:
> Suppose i am taking input or various variables like
> a=raw_input("...") //hello
> b=raw_input("")//hi
> c=raw_input("...")//hello
> d=raw_input("..")//hello
> but i want to run a common function when input is hello
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply the
> code for the specific variable ,
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please
> Thanks in advance

How about this design pattern:

def hello():
   print "Hello World!"

prompt = "..."
s = raw_input(prompt)
while s:
   if s == "hello":
  hello()
   elif s == "quit":
  break
   s = raw_input(prompt)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 1:58 PM,   wrote:
> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre

First question. Why are you not using an XML parser (it looks like
your IMDB data files _are_ XML). e.g: elementree (in the standard
library).

>    else len(rgenre)<1: # I was hoping this would take care of the "there is
> no genre information" scenario but it doesn't
>    rg1=rg2=rg3="NA"

the "else" statement does not expect (nor accept) an expression after
it, just write:

else:
   ...

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 2:46 PM,   wrote:
>    rgenre = re.split(r';', rf.info["genre"])
> KeyError: 'genre'

Use something like this:

if "genre" in rf.info:
   rgenre = re.split(..., ...)
else:
   # ... no genre

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: wierd replace problem

2010-09-14 Thread James Mills
On Tue, Sep 14, 2010 at 5:28 PM, Roelof Wobben  wrote:
> Strip ('"'') does not work.
> Still this message : SyntaxError: EOL while scanning string literal
>
> So I think I go for the suggestion of Bob en develop a programm which deletes 
> all the ' and " by scanning it character by character.

I seriously don't understand why you're having so much trouble with this
and why this thread has gotten as long as it has :/

Look here:

$ python
Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
[GCC 4.4.4 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "foo\"bar'"
>>> s
'foo"bar\''
>>> s.replace("\"", "").replace("'", "")
'foobar'
>>>

Surely you can use the same approach ?

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] constructing objects with one set of required options

2010-09-16 Thread James Mills
On Fri, Sep 17, 2010 at 7:43 AM, Gregory, Matthew
 wrote:
> Sorry for what is probably a poor subject line ...
>
> Generally, I'm trying to understand the best way to set up an object's 
> __init__ if there are some required parameters and other parameters that can 
> be specified in a number of ways.  As an example, I'm working on an envelope 
> class that describes a spatial envelope complete with cell size information.  
> Assuming that this envelope needs to have its upper left corner specified and 
> a cell size, I can *either* specify a lower right corner or the number of 
> rows and columns to finish the specification.  Can folks provide guidance on 
> a good way to do this?  Specifically, I'm wondering if some or all options 
> should be by position or by keyword.
>
> Here's my first cut of doing it all by keyword.
>
> class EnvelopeException(Exception):
>    pass
>
> class Envelope(object):
>    def __init__(self, **kwargs):
>        try:
>            self.x_min = kwargs['x_min']
>            self.y_max = kwargs['y_max']
>            self.cell_size = kwargs['cell_size']
>        except KeyError:
>            err_str = 'Not all required parameters were specified'
>            raise EnvelopeException(err_str)
>
>        try:
>            # First try n_cols and n_rows as keyword args
>            self.n_cols = kwargs['n_cols']
>            self.n_rows = kwargs['n_rows']
>        except KeyError:
>            try:
>                # Try x_max and y_min instead
>                self.x_max = kwargs['x_max']
>                self.y_min = kwargs['y_min']
>            except KeyError:
>                err_str  = 'Either the number of rows and columns or '
>                err_str += 'the lower-right coordinate was not specified.'
>                raise EnvelopeException(err_str)
>
>        # calculate the remaining parts of the specification
>        ...
>
> (I realize that I could also specify the x_max and the n_rows or y_min and 
> n_cols and still derive the envelope, but that seemed nonintuitive to me, 
> although maybe I should consider it.)

Rather than present you with what I think (subjective)
might be a "good solution", why don't you look up in the
python documentation how you define methods and
what you can do with them (parameters-wise).

I'll summarize:

def foo(self, a, b, c):
   ...
def foor(self, a, b, *args):
   ...
def foo(self, a, b, c=None):
   ...
def foo(self, a, b, *args, **kwargs):
   ...

There are probably other combinations, but these are
probably the most common.

The point I'm trying to make here is that this is
really "up to you".

Use a combination of variable arguments (*args)
and maybe some arguments with default values
(c=None) or just use **kwargs. Choice is yours :)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] constructing objects with one set of required options

2010-09-16 Thread James Mills
On Fri, Sep 17, 2010 at 8:35 AM, Gregory, Matthew
 wrote:
> Thanks for your reply.  I do understand all the different ways parameters can 
> be passed and realize that it's up to me to choose that signature.  But, 
> mostly, I wanted advice on how to make this signature as intuitive as 
> possible to a user.  So, from my earlier example, a signature with positional 
> args like this is a bad idea:
>
>    class Envelope:
>        def __init__(x_min, y_max, cell_size, *args):
>            ...
>
>    # are args 3 and 4 rows and columns or x_max, y_min?
>    e = Envelope(10, 20, 1, 30, 10)

Don't forget "self".

This signature seems okay to me.

> so I know at least the last two args should probably be keywords, but a 
> signature like this is somewhat confusing to me as well because it's not 
> immediately clear to me what the first three parameters are by looking at the 
> *call* (obviously by looking at the method you can figure it out).
>
>   def __init__(x_min, y_max, cell_size, **kwargs):
>   e = Envelope(10, 20, 1, n_cols=30, n_rows=10)
>   e = Envelope(10, 20, 1, x_max=30, y_min=10)
>
> So I know I'm getting around to answering my own question, but the clearest 
> way to me was to provide all keyword args.  I just didn't know if this was 
> too verbose from a user's standpoint.  Really just a stylistic question that 
> might be best left to the individual.

In my experience, I've always defined explicit arguments and keyword arguments
for constructors and use **kwargs for anything that can be specified as optional
but have defaults. eg:

class Foo(object)
   def __init__(self, a, b, c, x=1, **kwargs):
  super(Foo, self).__init__()

  self.a = a
      self.b = b
  self.c = c

  self.x = x

  self.y = kwargs.get("y", None)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] plotting pixels

2010-09-16 Thread James Mills
On Fri, Sep 17, 2010 at 12:13 PM, Bill Allen  wrote:
> Is there a simple way to plot pixels in Python, without resorting to turtle
> graphics?

Give matplotlib a go.

Alternatively you may want to try pygame or pyglet.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Smart posting - Was: Re: Tutor Digest, Vol 80, Issue 11

2010-10-02 Thread James Mills
On Sun, Oct 3, 2010 at 10:11 AM, Alan Gauld  wrote:
> Please, do not post the entire digest. We don't have time to wade through it
> looking for the few lines you may have added or commented upon.

I'm actually really surprised anyone actually uses and subscribes to
mailing lists and wants to get
digests. It's far easier (for me at least) to just get each email as
it comes in.

--James


-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating a class

2010-10-05 Thread James Mills
On Wed, Oct 6, 2010 at 4:16 AM, T MURPHY  wrote:
> how do i go about creating a class in python.

By using the "class" keyword.

Example:

class Fruit(object):

   def __init__(self, name)
  self.name = name

class Apple(Fruit):

   def __init__(self):
  super(Apple, self).__init__("apple")

apple = Apple()
print apple.name

For more information, I suggest you start reading
the python tutorial (1)

cheers
James

1. http://docs.python.org/tutorial/

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Networking

2010-10-14 Thread James Mills
On Fri, Oct 15, 2010 at 11:22 AM, chris  wrote:
>> But what if I want it to serve one client, go to another and then go back.
>> How does that work?

You do some I/O multi-plexing or multi-processing/threading.

You might want to do some reading on this.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Networking

2010-10-15 Thread James Mills
On Fri, Oct 15, 2010 at 3:06 PM, Evert Rol  wrote:
> The very last example on http://docs.python.org/library/socketserver.html may 
> help you.
> Or perhaps the asyncore/asynchat modules.

Alternatively Twisted (1) or circuits (2)

cheers
James

1. http://twistedmatrix.com/trac/
2. http://bitbucket.org/prologic/circuits/wiki/Home

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decorators (the "at" sign)?

2010-10-25 Thread James Mills
On Tue, Oct 26, 2010 at 12:46 PM, Alex Hall  wrote:
> �...@set_index
>  def get_url(self, index=None):
>  return self.storage[index]['Url']

Decorators in python are used (almost as convenience) to wrap
functions/methods for various purposes.
It might be to do some logging before and after the actual function is
called, or setup static methods, etc.

The "@" symbol was chosen for this, and in the above example the
following is happening:

The method get_url(...) is being decorated (as opposed to being
wrapped) with the set_index(...) function.
(Without knowing too much more about the code you're looking at...)
set_index(...) would be doing something
with the get_url(...) method then returning it.

The best example of this is the following from PEP 318 (1):

def onexit(f):
import atexit
atexit.register(f)
return f

@onexit
def func():
...

This has a similar form to the code you're studying and registers func
with atexit hooks so that when
the application terminates, func(...) gets called.

Hope this helps,

cheers
James

1. http://www.python.org/dev/peps/pep-0318/

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Having Issues with CMD and the 'python' command

2008-12-15 Thread James Mills
"cmd" has _nothing_ to do with Python.

--JamesMills

--
-- "Problems are solved by method"



On Mon, Dec 15, 2008 at 10:51 PM, Lamonte Harris  wrote:
> Every time I start cmd on windows it requires me to "set
> path=%path%;C:\python26" why? I'm getting annoyed...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] configuring web browser PP3E

2009-01-28 Thread James Mills
On Thu, Jan 29, 2009 at 11:31 AM, bmol...@att.net  wrote:
> Traceback (most recent call last):
>  File "webserver.py", line 22, in ?
>srvrobj  = HTTPServer(srvraddr, CGIHTTPRequestHandler)
>  File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/SocketServer.py",
> line 330, in __init__
>  File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/BaseHTTPServer.py",
> line 100, in server_bind
>  File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/SocketServer.py",
> line 341, in server_bind
>  File "", line 1, in bind
> socket.error: (13, 'Permission denied')

srvraddr is being passed a port of 80.
I suspect that you're running on a Mac and that
Mac's being UNIX systems, do not allow you as
a normal user to listen on ports < 1000 without
root privileges.

Solution 1: Run this under sudo
Solution 2: Change the port to 8000

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


Re: [Tutor] configuring web browser PP3E

2009-01-28 Thread James Mills
On Thu, Jan 29, 2009 at 12:17 PM, bmol...@att.net  wrote:
> yes, i'm running on Mac OS X / Unix, but i'm afraid i don't know "where" to
> change the port to 80.  i'm working with the following files straight from
> the book 'Programming Python':

You're not blind are you ? Because I am.

> cgi101.py   (here it is...)
> #!/usr/bin/python
> import cgi
> form = cgi.FieldStorage()# parse form data
> print "Content-type: text/html\n"# hdr plus blank line
> print "Reply Page"# html reply page
> if not form.has_key('user'):
> print "Who are you?"
> else:
> print "Hello %s!" % cgi.escape(form['user'].value)
> cgi101.html (here it is...)
> 
> Interactive Page
> 
> 
> Enter your name:
> 
> 
> 
> 
> and webserver.py (here it is...)
> ##
> # implement HTTP web server in Python which knows how to run server
> # side CGI scripts;  serves files/scripts from current working dir;
> # python scripts must be stored in webdir\cgi-bin or webdir\htbin;
> ##
> webdir = '.'   # where your html files and cgi-bin script directory live
> port   = 80# default http://localhost/, else use http://localhost:/

Chat the above line.

[...]

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


Re: [Tutor] List Changing Order

2010-11-25 Thread James Mills
On Fri, Nov 26, 2010 at 1:47 PM, Corey Richardson  wrote:
> I recall that the keys of dictionaries have arbitrary order, and may change
> over time. Is this true of lists? I can't find the answer from a simple
> Google search. Thank you!

items append to a list retain their order.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to handle exceptions raised inside a function?

2010-12-01 Thread James Mills
On Thu, Dec 2, 2010 at 10:27 AM, Richard D. Moores  wrote:
> Could I have put stats-0.1.1a anywhere, CD-ed to that "anywhere", and
> then run the command?

Yes.

python setup.py install essentially instructs
distutils (or setuptools or distribute - whichever is being used)
to "install" the package into your site-packages or
$PYTHONPATH (if configured that way by means of configuration).

NB: Copying the package's directory into site-packages hwoever
has the same effect. The directory that contains the __init__.py

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with strings in python3

2011-04-18 Thread James Mills
On Tue, Apr 19, 2011 at 10:34 AM, James Mills
 wrote:
> Normally it's considered bad practise to concatenate strings.
> Use a a format specifier like this:
>
>> message = "Bah."
>>
>> if test:
>>   message = "%s %s" (message, " Humbug!")
>>
>> print(message)
>
> Python3 (afaik) also introduced the .format(...) method on strings.

Opps I posted to the wrong list :/

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] jenia. cannot install mysqldb

2011-04-20 Thread James Mills
On Thu, Apr 21, 2011 at 9:35 AM, ivlev jenia  wrote:
> I cannot get the mysqldb library to work.
> I'm trying to setup a Django project on Windows 7 using pydev in eclipse.
> There are the files I'm using: http://sourceforge.net/projects/mysql-python/
>
> Now, for the life of me, I cannot get the mysqldb library to work.
> When I try to run the setup file, after the install windows tells me that
> there was a problem during install.
> I pointed the eclipse project to the mysqldb directory with all the
> setup.exe and all the other files.
> Of course it did not help.
> Can someone please help me?

Forgive my lack of experience with WIndows in general;

However you'll likely need the MySQL C libraries
and a compiler of some kind (Visual Studio / C++ ?)
in order to install mysql-python from source...

You're probably better off finding a pre-built binary
distribution (or a pure python lirbary).

Either way, you'll need MySQL install (at the very least mysqlxx.dll
or something)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list.__init__ within class definition

2011-04-20 Thread James Mills
On Thu, Apr 21, 2011 at 1:21 PM, Alex Companioni  wrote:
> In the following class definition:
>
> class Tomato(list):
>    def __init__(self, data):
>        list.__init__(self, data)
>
> The list.__init__ method (if it is a method, I'm not clear on what
> __init__ actually *is*) creates a list, right? In other words,
>
> l = Tomato([1,2,3])
>
> will create a list l with the values [1,2,3], correct?

What you actually want is this:

>>> class Tomato(list):
... def __init__(self, data):
... super(Tomato, self).__init__(data)
...
>>> l = Tomato([1, 2, 3])
>>> l
[1, 2, 3]
>>>

Your example:

>>> class Tomato(list):
... def __init__(self, data):
... list.__init__(data)
...
>>> l = Tomato([1, 2, 3])
>>> l
[]
>>>

Do you see why ?

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling a python script using subprocess

2011-04-28 Thread James Mills
On Fri, Apr 29, 2011 at 7:18 AM, GoodPotatoes  wrote:
>
> p = subprocess.Popen(r'installModule.py --mods mod1 mod2 mod3', executable = 
> sys.executable, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)

Try this (untested):

p = subprocess.Popen(["/usr/bin/env python", "installModule.py",
"--mods", "mod1", "mod2", "mod3"], stdout = subprocess.PIPE, stderr =
subprocess.STDOUT)

cheers
James

--
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Titles from a web page

2011-05-04 Thread James Mills
On Thu, May 5, 2011 at 1:52 PM, Modulok  wrote:
> You might look into the third party module, 'BeautifulSoup'. It's designed to
> help you interrogate markup (even poor markup), extracting nuggets of data 
> based
> on various criteria.

lxml is also work looking into which provides similar functionality.


-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Programmatically Post to Pastebin

2011-05-10 Thread James Mills
On Wed, May 11, 2011 at 9:57 AM, Lan Rogers  wrote:
> I want to post files stored on a machine to Pastebin (or any similar
> service for that matter) using a python script, and then store a link
> to that post. Also, I would strongly prefer to avoid doing something
> that requires an API key.

A similar tool I wrote (which pastes to codepad.org) is here:

https://bitbucket.org/prologic/tools/src/59d89262e6b1/codepad

The approach would be very similar. Feel free to adapt this.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor