Re: [Tutor] python and sqlite

2010-01-31 Thread Chris Fuller

Since v2.5, SQLite is included in the Standard Library.  You can get docs at 
the Python website, or in the handy chm that comes with the Windows 
distribution.

Cheers

On Sunday 31 January 2010, Samuel de Champlain wrote:
> My project is relatively light and postgresql or mysql might be overkill.
> Does python work well with sqlite?
> If so, can you point me towards the proper libraries and manuals/tutorials?
> Thanks.
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] packing up python code to transfer to another machine

2010-02-10 Thread Chris Fuller

There are two obvious "gotchas".  One is binary extensions.  If you are using 
modules that are not "pure Python", you will have to find *nux versions for 
your target.

The other problem is impossible to solve in general, but most of the time, 
it's less trouble than the first problem.  Python is a dynamic language.  
Dependencies can be created at runtime (using __import__, exec, or execfile, at 
least), and it's certainly possible to write code that has unpredictable 
dependencies.  Usually, however, the unknown dependency is drawn from a finite 
pool that is predictable.  If you include all the bits that each third party 
modules comes with (and the same for your code, if it does any of these 
tricks), you should be Ok, but you can't prove it without analyzing the code.

If you know the package dependencies (usually documented), you can work with 
that.  matplotlib requires numpy, for instance.  If this isn't enough, there's 
the modulefinder module.  Note that it won't detect dynamic dependencies, so 
you have to know what third party stuff is included, and make sure you include 
all of it (or less, but only if you know what you're doing).  Modulefinder also 
makes a lot of noise, and will include stuff you don't want or need.

Another problem is platform compatibility.  If you rely on the windows API, or 
filesystem idiosyncrasies, like drive letters, you'll have to fix those; but 
these are less surprising and easy to catch.

Cheers


On Wednesday 10 February 2010, dwba...@earthlink.net wrote:
> I have become a true Pythonaholic. My newest problem is
> 
> I have a rather large Python code (1.5yrs + developing!) currently running
>  on Windows machines that imports several modules, some from external
>  libraries. It allows the user to easily access MySQL databases and plot
>  selected columns and such.
> 
> I would like to bundle my (code + libraries + modules) and transfer all to
>  a *nix environment, rather than just transferring my code over and then
>  having to download and install all the relevant libraries again.
> 
> Is this possible? I would think so with Python but am not sure.
> 
> Is there a Python package that does this? If so, what?
> 
> Thanks in advance.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Compile py to exe in ubuntu

2010-02-10 Thread Chris Fuller

Using freeze or another tool of its ilk is only going to make you an 
executable for that platform.  If you want an executable for a different 
platform, you need to set up a native Python environment with all the 
dependencies installed where Python can find them, and then use that platform's 
tools for making a standalone version.

Cheers
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive generator

2010-03-07 Thread Chris Fuller

Here's a (more or less) useful example.  It generates the "nth triangular 
series" (my term), n=2 is the triangular numbers, n=3 the tetrahedral numbers 
(n has a correspondence to dimension).  Each series is the sum of the elements 
of the previous one.  They are also the columns of Pascal's Triangle.

Probably only "useful" if you enjoy playing around with math.

def triangular(n):
   if n == 0:
  while True:
 yield 1
   else:
  g = triangular(n-1)
  a = 0
  while True:
 a += g.next()
 yield a


I wouldn't use that to build Pascal's triangle, by the way (usually you want 
it rowwise).  Here's my code.

def pascal():
   r = 0
   l = [1]
   yield l

   while True:
  l  = [1] + [ l[i] + l[i+1] for i in range(r) ] + [1]
  r +=  1

  yield l

>>> g=pascal()
>>> for i in range(9):
...  print ' '.join(['%2d'%(i,) for i in g.next()])
... 
 1
 1  1
 1  2  1
 1  3  3  1
 1  4  6  4  1
 1  5 10 10  5  1
 1  6 15 20 15  6  1
 1  7 21 35 35 21  7  1
 1  8 28 56 70 56 28  8  1

Here are the triangular-ly generated numbers (I made them a square, just to 
illustrate an interesting property.)
>>> for i in range(7):
...  g=triangular(i)
...  print ' '.join(['%3d'%(j,) for j in [g.next() for k in range(7)]])
... 
  1   1   1   1   1   1   1
  1   2   3   4   5   6   7
  1   3   6  10  15  21  28
  1   4  10  20  35  56  84
  1   5  15  35  70 126 210
  1   6  21  56 126 252 462
  1   7  28  84 210 462 924


Cheers

On Sunday 07 March 2010, spir wrote:
> Hello,
> 
> Is it possible at all to have a recursive generator? I think at a iterator
>  for a recursive data structure (here, a trie). The following code does not
>  work: it only yields a single value. Like if child.__iter__() were never
>  called.
> 
> def __iter__(self):
> ''' Iteration on (key,value) pairs. '''
> print '*',
> if self.holdsEntry:
> yield (self.key,self.value)
> for child in self.children:
> print "<",
> child.__iter__()
> print ">",
> raise StopIteration
> 
> With the debug prints in code above, "for e in t: print e" outputs:
> 
> * ('', 0)
> < > < > < > < > < > < > < > < >
> 
> print len(t.children) # --> 9
> 
> Why is no child.__iter__() executed at all? I imagine this can be caused by
>  the special feature of a generator recording current execution point. (But
>  then, is it at all possible to have a call in a generator? Or does the
>  issue only appear whan the callee is a generator itself?) Else, the must
>  be an obvious error in my code.
> 
> 
> Denis
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Linux lib path

2010-04-10 Thread Chris Fuller

I'm using Debian.  Used to be etch, but I did a double dist-upgrade recently.  
So, whatever the current testing release is.  My shell is zsh, but bash should 
work the same.

PYTHONPATH should have worked.  CLASSPATH is for Java.


Here's the documentation link you want: 
http://docs.python.org/install/index.html#inst-search-path
http://docs.python.org/library/site.html


Files that end in ".pth" are read by Python and the contents are added to 
sys.path.


0 % python
Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path
False

0 % export PYTHONPATH=/home/cfuller/tmp
0 % python
Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path
True


What I prefer to do, rather than mucking around with environment variables 
(which isn't reliable, say if its called from a daemon, init script, or maybe 
a non-interactive shell, and probably other esoterica) is to use .pth files.  
These are just a listing of directories for Python to add to sys.path.  A lot 
of packages include some of their own, you should find some in site-packges.  
Used to be you had to put them there to get them loaded, but there is new per-
user support in Python 2.6 and 3k: http://www.python.org/dev/peps/pep-0370/.

0 % export PYTHONPATH= 
0 % python
Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path


0 % mkdir -p ~/.local/lib/python2.6/site-packages
0 % echo /home/cfuller/tmp > ~/.local/lib/python2.6/site-packages/tmp.pth
0 % python2.6
Python 2.6.5 (r265:79063, Mar 18 2010, 23:38:15) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path
True



Cheers


On Friday 09 April 2010, Joson wrote:
> Hi all,
> 
> How to append a path ("/var/myprog/src") to sys.path, but not in the
>  dynamic way like sys.path.apend(packpath), please?
> I use debian os. and I'd tried to set the classpath in /etc/profile (export
> CLASSPATH="..."), and the pythonpath too (export PYTHONPATH="..."). I found
> it didn't work.
> 
> Best regards,
> 
> Joson
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaring methods in modules.

2010-04-11 Thread Chris Fuller

This actually isn't so hard with classes (not instances of the class).  Just 
use setattr().  The first parameter of the function will be the instance, 
called "self" by convention.  This should work with both old and new style 
There's stuff in the new module for adding stuff to instances, but I haven't 
played around with it recently.  A little fiddling around in the interactive 
interpreter should clear up anything you're uncertain about, though.

Cheers


On Sunday 11 April 2010, Ray Parrish wrote:
> Hello,
> 
> I am working on some stuff, and I would like to be able to write a
> module which can be imported, and after it's been imported I would like
> to be able to access it's functions as methods.
> 
> In other words, if I do the import of module ISPdetector, I want to then
> be able to make calls like the following -
> 
> ipAddress = "123.123.123.123"
> emails = ipAddress.GetEmailAddresses()
> 
> where GetEmailAddresses() is defined in module ISPdetector. Do I just
> wite that function in ISPdetector.py as a normally deffed function, or
> does it have to be part of a class within the module?
> 
> Thanks for any help you can be.
> 
> Later, Ray Parrish
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Declaring methods in modules.

2010-04-11 Thread Chris Fuller

Sorry, should have included a concrete example.  Although, as the others have 
said, I'm not sure how it helps with what you (seem) to want to do.

0 % cat bar.py
def the_answer(self):
   return 42
0 % cat foo.py
import bar

class A:
   pass


setattr(A, '__call__', bar.the_answer)

a=A()
print a()

class B(object):
   pass


setattr(B, '__call__', bar.the_answer)

b=B()
print b()

0 % python foo.py 
42
42


Cheers
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to do excel in python

2010-08-05 Thread Chris Fuller

There are many ways.  The simplest is to export the file to CSV and load that, 
but you'll only get one worksheet, and it's a big hassle to update the Excel 
file that way.  You can save the spreadsheet as an ODF file, which is a fully 
documented XML format that Python can read and write easily, but you might 
give up some Excel features (but a lot fewer than with CSV format).

You can also have the spreadsheet open in excel and talk to it from Python via 
COM.  If you're on Windows and have Excel, this approach can be the most 
flexible.

http://docs.python.org/library/csv.html
http://www.linuxjournal.com/article/9347
http://www.google.com/search?q=excel+com+python

Cheers

On Thursday 05 August 2010, invincible patriot wrote:
> hi, can any one tell me how can I access MS excel worksheet in python and
> how can I access itz individual cells..??
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Distributing Python Code for Commercial Porpoises?

2010-08-06 Thread Chris Fuller

It sounds like maybe you could use Enthought Python, which is a bundle of most 
of the popular numerical libraries by the scipy sponsors.  Not free, however, 
there's a trial version.

http://enthought.com/products/epd.php

The problem of bundling stuff is a real thorny one and has been beaten to death 
many times in this list and elsewhere.  It really doesn't solve the problem, 
anyway, if you want your friend to be able to play with and rerun the code.

Another idea is to make a virtual machine that you can duplicate or even mail 
back and forth with just the stuff required.  Then you'd need an OS license for 
it (or use a minimal Linux, like Arch or DSL, but you probably want to stick 
to the Windows platform, I'd guess.)

Cheers

On Friday 06 August 2010, Wayne Watson wrote:
> Yes, porpoises was a (old) pun.
> 
> Back in Feb. I raised a question related to Subject. I just wanted to
> know if Python code could be compiled in some sense. Robert Berman
> pitched in with some help. Although I was making progress, I put it off
> for a future date. I really don't want to get into py2exe here, but am
> wondering if there are Python vendors who in some way sell their product
> in compiled form?
> 
> My intent though is really not to produce a commercial product. My
> question relates to difficulty my partner and I have to exchanging py
> programs w/o him stumbling. I send him a py program written using
> Windows Python 2.5. He has the same. I've executed it IDLE and it works
> fine. He executes, and it squawks per my post here on finding a version
> #, showing his output. We need to make sure we are on the same playing
> ground with numpy and scipy. I don't think we are. He barely knows
> Python, but did, supposedly, a install of it, numpy and scipy from the
> same written direction I use. I think he mistakenly installed a
> different version of numpy. So how can we make sure we or anyone are on
> the same playing field? Perhaps we should resort to command like
> execution. I am not confident that using py2exe will solve this problem.
> Is there a Python tool that provides some thorough description of a
> Python installation?

___
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-12 Thread Chris Fuller

The preferred and most graceful way is to use neither, as others have pointed 
out.  However, you can't return an exit code that way, and it sometimes isn't 
feasible to structure your code to allow it.  I prefer SystemExit, because it 
doesn't require adding something to the namespace (the sys module), and it 
seems a bit more pythonic.  You can trap it, however, which bugs me.  I think 
these two should exhibit the same behavior.  I'd use sys.exit for "real" code, 
even though it appeals less aesthetically, because it is less prone to doing 
something unexpected (one of Python's guiding principles, btw).

Cheers


On Wednesday 11 August 2010, 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?
> 
> 
> Thanks,
> Bill Allen
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Plotting a Linear Equation

2010-09-25 Thread Chris Fuller

It sounds to me like you need to set a nonzero linewidth.  The default is to 
not fill in the space between points.  Check out the documentation at 
http://matplotlib.sourceforge.net/contents.html.  It's a lot to wade through, 
but worth it when you learn how to unlock the power of the software.

Cheers

On Thursday 23 September 2010, Corey Richardson wrote:
>   Hello tutors. Probably the wrong mailing list, but someone might know.
> I want to use matplotlib (or similar) to plot an equation in
> slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've
> read and tested, you can only plot with a series of points. I could make
> two points out of those manually, but I was wondering if anyone knew of
> an easier way. Thanks.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system()? popen2()? How to execute a command & save its output?

2010-09-29 Thread Chris Fuller

You might also consider pexpect.
http://pexpect.sourceforge.net/

It's designed for interactive console applications like ftp.

For popen() style access, the recommended approach is the subprocess module.  
You should be able to find an example in the docs to fit your application.
http://docs.python.org/library/subprocess.html

Cheers


On Wednesday 29 September 2010, James Hartley wrote:
> I'm needing to transfer the following shell construct to Python, plus save
> the output of execution:
> 
> FTP_SITE='ftp.somesite.com'
> ftp -a  $FTP_SITE < binary
> prompt off
> cd /some_dir
> dir
> bye
> EOF
> 
> Here, the FTP client accepts commands from STDIN, so all commands are saved
> in a temporary file which is redirected to the client application.
> 
> I also need to save whatever output is generated.  How can this be done in
> Python?
> 
> Thanks.
> 
> Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving my C++ code to Python?

2010-10-15 Thread Chris Fuller
SWIG supports opaque pointers that you can pass into and out of Python without 
any problems.

Working with SWIG isn't that bad for basic stuff, although it can get 
complicated if you need to have it interpret exotica like references, 
structures, or such for Python.  Having a good C++ background should cut a lot 
of the difficulty out of that, though.  The documentation is pretty good, 
although finding what you need can involve a lot of scrolling around in long 
web pages.
http://www.swig.org/

If you are going to use a command line interface, you might check out these 
modules from the standard library:
http://docs.python.org/library/cmd.html
http://docs.python.org/library/shlex.html

You might also see if numpy can replace some of your C++ code.  It's fast, and 
integrated into Python.
http://numpy.scipy.org/

Cheers

On Friday 15 October 2010, Paul wrote:
> I would like to make modules for python.  The problem is that the
> vector of structs that is very large.  First, is it possible to pass
> such structures around to and from python and C/C++?  What would be
> the overhead cost of having a large structure that needs to be passed
> to and from the C/C++ modules?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] variable numbers of for loops (also iteration/recursion)

2010-11-23 Thread Chris Fuller
You can always substitute Iteration for Recursion by making the stack an 
explicit part of your code. As an example, imagine you are traversing this 
directory tree:

birds
birds/owls
birds/owls/snowy
birds/owls/barn
birds/owls/great-horned
birds/eagles
birds/eagles/golden
birds/eagles/bald
birds/eagles/osprey

Where the third-level items are files, rather than more directories.

In a recursive approach, a function is defined that does the recursion. This is 
a feature of recursion. You can't slip it inline with your code (unless your 
language supports inline functions and the right sort of scoping rules, but 
you probably don't want to try that here). The function takes a directory, 
iterates through the contents, calling itself again for every subdirectory.

Your application code calls the function with the argument of "birds". The 
function then calls itself twice, once with "owls" and again with "eagles". 
The contents of these are files, and not directories, so recursion ends.

In an iterative approach, there is a stack and a loop. The loop stops when the 
stack is empty. The loop pops the most recently pushed item from the stack, 
and then pushes onto the stack any subdirectories.

We start with the directory "birds" on the stack. The loop pops "birds" and 
then pushes "owls" and "eagles". It loops twice more to process these, and 
then stops.


Your program is really more iterative than recursive. I couldn't manage a 
recursive expression of the problem. You can always make a iterative version 
of a recursive algorithm, but not necessarily the other way. This makes sense 
when you inspect the problem. Your solution is abstractly equivalent to an n-
dimensional "cube" with side length equal to the length of the alphabet, not 
anything that looks like a tree. One thing I noticed about your generated code 
is that it can be collapsed into a list comprehension:

>>> allwrds('ab',2)
listOfWords=[]
for l0 in alphabet:
for l1 in alphabet:
word = "".join([eval("l"+str(i)) for i in range(n)])
listOfWords.append(word)

['aa', 'ab', 'ba', 'bb']

is equivalent to

>>> alphabet='ab'
>>> [l0+l1 for l0 in alphabet for l1 in alphabet]
['aa', 'ab', 'ba', 'bb']

Now, the result is a 1D list of length len(alphabet)**n. Why not iterate over 
that space, and fill in the blanks? Think of your problem modeled as a n-
dimensional hypercube. The value at any element is equal to the concatenation 
of the n indices of that element's location. Some 2D examples:

allwrds('ab',2):
   a   b
a aa  ab
b ba  bb

allwrds('abc',2):
   a   b   c
a aa  ab  ac
b ba  bb  bc
c ca  cb  cc

Mapping from n dimensions to 1D isn't hard if you know the size of each 
dimension. In this case, they're all equal. I'll use a 3D example to make it 
more clear:

i = 0

  j=0  1  2
k
0   0  1  2
1   3  4  5
2   6  7  8

i = 1

  j=0  1  2
k
0   9 10 11
1  12 13 14
2  15 16 17

i = 2

  j=0  1  2
k
0  18 19 20
1  21 22 23
2  24 25 26

Find the i,j,k for 1D index 17.
Start with the highest order index (i). Divide by the product of the sizes of 
the lower dimensions, which is the length of the alphabet squared. This 
alphabet is length 3, so we divide by 9. We get 1 rmdr 8. i=1. Now take the 
remainder and repeat. 8 divided by 3 is 2 rmdr 2. j=2. You could take it 
another step if using n-cubes and powers of the dimension size, since 3**0 
equals one, and the next answer is still 2, but this fails when the dimensions 
aren't all equal. k=2. Got that?

Now these i,j,k values are just indices into the alphabet! Just get the letter 
at that indexd and join them up. Here's the code:

def allwrds(alphabet, n):
   listOfWords=[]
   for i in range(len(alphabet)**n):
  word = ''
  q = i
  for j in range(n-1):
 q, r = divmod(q, len(alphabet))
 word += alphabet[q]
 q = r
  word += alphabet[q]
  listOfWords.append(word)
   return listOfWords


Cheers
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newton–Raphson's method

2009-02-16 Thread Chris Fuller

You should look into Numpy or ScientificPython.
http://numpy.scipy.org
http://dirac.cnrs-orleans.fr/plone/software/scientificpython

Also, the main Python Wiki has a page devoted to numeric/scientific topics:
http://wiki.python.org/moin/NumericAndScientific

Cheers

On Monday 16 February 2009 12:33, Jojo Mwebaze wrote:
> Hello There
>
> Any body who has implemented Newton–Raphson's method for nonlinear systems
> of equations in python. Consider the case where we want to solve
> simultaneously
>
> f(x,y) = 0
>
> g(x,y) = 0
>
> Please assist with the code.
>
> Regards
>
> Jojo.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File locking: cross platform?

2009-02-20 Thread Chris Fuller

There's a recipe in the Python Cookbook that addresses this:
http://code.activestate.com/recipes/65203/

There are probably others floating around, too.

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


Re: [Tutor] Converting "HH:MM:SS" to datetime

2009-03-01 Thread Chris Fuller
On Sunday 01 March 2009 12:04, Wayne Watson wrote:
>  Ok, how do I do what's mentioned in Subject?

There's an inverse to the strftime() function, strptime(), also in the time 
module, that will do this.

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


Re: [Tutor] Difference in minutes between two time stamps

2009-03-02 Thread Chris Fuller
Use time.strptime() to parse them into seconds since the start of epoch, and 
then an ordinary numeric subtraction will work.

Cheers

On Monday 02 March 2009 19:45, Judith Flores wrote:
> Hello,
>
>I can't seem to figure out the syntax to calculate the difference in
> minutes between two time stamps. I already read the documentation about
> datetime and time modules, but I was unable to implement the code.
>
> My code will be fed with two timestamps (as styrings):
>
> start="09:35:23"
> end="10:23:00"
>
> Could someone guide me on how to calculate the difference in minutes
> between both stamps?
>
> Your help is very much appreciated.
>
> Thank you,
>
> Judith
>
>
>
> ___
> 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] wxPython vs PyQt

2009-03-04 Thread Chris Fuller

There is a not-free GUI builder, wxDesigner, that isn't too bad (except for 
costing money).  http://www.roebling.de

The GLADE GUI builder for Gtk is very nice, however.
http://www.pygtk.org/

For windows:
http://gladewin32.sourceforge.net/

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


Re: [Tutor] Gtk time control and Glade

2009-03-17 Thread Chris Fuller

Make your own.  You can have empty containers in glade that you fill in at 
runtime, or you could create the interface in glade, perhaps a couple of 
ComboBoxes.  I would leave an empty container and create a reusable widget 
descended from gtk.HBox that implements validation or anything else that it 
would need to do.  Maybe it could default to the current time, for instance.

I know its possible to configure glade to use custom widgets, but I've never 
bothered to learn about since it's so easy (and free of caveats that I might 
become subject to) to leave empty space for runtime use.

Here's a quick and dirty (and untested!) example:

class TimeEntry(gtk.HBox):
def __init__(self):
gtk.HBox.__init__(self)

self.hr = \
w = gtk.ComboBox()

for i in range(24):
w.append_text('%02d'%(i,))

self.pack_start(w, False, False, 0)
w.show()

w = gtk.Label(':')
self.pack_start(w, False, False, 0)
w.show()

self.min = \
w = gtk.ComboBox()

for i in range(60):
w.append_text('%02d'%(i,))

self.pack_start(w, False, False, 0)
w.show()

def get(self):
return '%02d:%02d' % (self.hr.get_active(),self.min.get_active())

Cheers

On Tuesday 17 March 2009 09:25, Robert Berman wrote:
> I am writing a Blood-Glucose Analysis application for Diabetics. I am
> using Python 2.5 under Ubuntu 8.10 and Glade 3.4.5.
>
> Manually recorded test results require a calendar control for the date
> of the test (no problem) and a timer control for the time of the
> test(big problem). While Glade certainly supports a calender control
> with a great deal of documentation, there is not an available time
> control for Glade. Nor was I able to find a general time control for
> Gtk. I did find one for wxwidgets but I am not using wxwidgets nor am I
> using PyQt.
>
> I am reasonably sure such a control exists. I know I'm not the only
> individual who needs date and time controls. But, using Google has
> provided all kinds of information, there has not been a specific
> statement about any specific controls. At this time I do not feel I have
> the level of expertise to build my own control and it is something I
> would rather not have to do.
>
> Have any of you heard of such an available time control specifically for
> Gtk and available or capable of being used by Glade.
>
> Thank you for any insights and suggestions.
>
>
> Robert Berman
> ___
> 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 and Tkinter Programming by Grayson--New Version?

2009-03-17 Thread Chris Fuller

This is a super book for beginners who are new to GUI programming.  Tkinter is 
easy to use, and comes included with Python.  Serious programmers will 
probably want something faster, better looking, and with nicer features, but 
they can be tricky to figure out and install.  I still prefer Tkinter for 
quick and dirty work or programs with simple interfaces.

Pmw is a very nice system.  I wish it was easily adapted to other GUI 
toolkits.  Development on it has mostly ended, although not entirely, there 
was a new release within the last year.  You will find it very useful if you 
write anything moderately interesting with Tkinter.

This book does not cover the Tix widget set, which was originally created for 
Tcl/Tk and later included with Tkinter, after this book was published.  I 
find that Pmw covers most of the problem space that Tix is suited for, but a 
beginner may have a different experience.

I was disappointed when I heard that this book was no longer in print.  I 
still have my copy, however, so all I need to do is make sure I clutch onto 
it tightly, and I'll be aright :)

Cheers

On Tuesday 17 March 2009 10:08, Wayne Watson wrote:
>  I've poked around at the pieces of the book in Subject, which are on the
> web--two chapters. It was published in 2000, first ed. It looks quite good,
> and certainly is big, 680 or so pages. He sells a digital version. It uses
> Pmw, which I barely no more than how to spell it. Is that even current any
> longer? I'd like to think the author is going to produce another version.
> Anyone know? Here's a clipped version of the contents. It got good review
> on Amazon.
>
>  bout the cover xxii
>  author online xxiii
>  Part 1 Basic concepts 1
>
>  1 Python 3
>      1.1 Introduction to Python programming and a feature review 3
>
>      Why Python? 4, Where can Python be used? 5
>
>      1.2 Key data types: lists, tuples and dictionaries 5
>
>      Lists 5, Tuples 7, Dictionaries 8
>
>      1.3 Classes 9
>
>      How do classes describe objects? 9, Defining classes 9, Neat Python
> trick #10 9, Initializing an instance 10, Methods 10, Private and public
> variables and methods 11, Inheritance 11, Multiple inheritance 11, Mixin
> classes 11
>
>  2 Tkinter 12
>      2.1 The Tkinter module 12
>
>      What is Tkinter? 12, What about performance? 13, How do I use Tkinter?
> 13, Tkinter features 14
>
>      2.2 Mapping Tcl/Tk to Tkinter 14
>      2.3 Win32 and Unix GUIs 15
>      2.4 Tkinter class hierarchy 16
>      2.5 Tkinter widget appearance 17
>  3 Building an application 18
>      3.1 Calculator example: key features 21
>      3.2 Calculator example: source code 21
>      3.3 Examining the application structure 27
>      3.4 Extending the application 28
>
>  Part 2 Displays 29
>
>  4 Tkinter widgets 31
>      4.1 Tkinter widget tour 31
>
>      Toplevel 32, Frame 33, Label 35, Button 36, Entry 37, Radiobutton 37,
> Checkbutton 38, Menu 39, Message 42, Text 43, Canvas 44, Scrollbar 45,
> Listbox 45, Scale 46
>
>      4.2 Fonts and colors 47
>
>      Font descriptors 47, X Window System font descriptors 47, Colors 48,
> Setting application-wide default fonts and colors 49
>
>      4.3 Pmw Megawidget tour 49
>
>      AboutDialog 50, Balloon 50, ButtonBox 51, ComboBox 52, ComboBoxDialog
> 53, Counter 54, CounterDialog 55, Dialog 56, EntryField 56, Group 57,
> LabeledWidget 58, MenuBar 59, MessageBar 59, MessageDialog 61, NoteBookR
> 61, NoteBookS 62, NoteBook 63, OptionMenu 64, PanedWidget 65, PromptDialog
> 66, RadioSelect 66, ScrolledCanvas 67, ScrolledField 68, ScrolledFrame 69,
> ScrolledListbox 70, ScrolledText 70, SelectionDialog 71, TextDialog 72,
> TimeCounter 73 ... snip
>  8 Dialogs and forms 140
>      8.1 Dialogs 141
>
>      Standard dialogs 141, Data entry dialogs 142, Single-shot forms 146,
> Tkinter variables 152
>
>      8.2 A standard application framework 155
>      8.3 Data dictionaries 165
>      8.4 Notebooks 172
>      8.5 Browsers 175
>      8.6 Wizards 184
>      8.7 Image maps 191
>      8.8 Summary 198
>  9 Panels and machines 199
>      9.1 Building a front panel 199
>      9.2 Modularity 201
>      9.3 Implementing the front panel 201
>      9.4 GIF, BMP and overlays 215
>      9.5 And now for a more complete example 220
>      9.6 Virtual machines using POV-Ray 232
>
>      And now for something completely different... #10 The Example 233
>
>      9.7 Summary 236
>  10 Drawing blobs and rubber lines 237
>      10.1 Drawing on a canvas 238
>
>      Moving canvas objects 243
>
>      10.2 A more complete drawing program 244
>      10.3 Scrolled canvases 251
>      10.4 Ruler-class tools 254
>      10.5 Stretching canvas objects 258
>      10.6 Some finishing touches 262
>      10.7 Speed drawing 271
>      10.8 Summary 275
>  11 Graphs and charts 276
>      11.1 Simple graphs 276
>      11.2 A graph widget 279
>
>      Adding bargraphs 286, Pie charts 289
>
>      11.3 3-D graphs 292
>      11.4 Strip charts 296
>      11.5 Summary 298
>  12

Re: [Tutor] Python and Tkinter Programming by Grayson--New Version?

2009-03-17 Thread Chris Fuller
What sets Pmw apart is the framework it provides for the creation of your own 
megawidgets.  It handles labels, forwards options from the constructor to the 
constructors of the subcomponents, forwards method calls (say your megawidget 
is descended from a Frame, but the main feature is a Scale widget), includes 
a set of standard data validators, etc.

Cheers

On Tuesday 17 March 2009 16:27, Alan Gauld wrote:
> "Chris Fuller"  wrote
> > This book does not cover the Tix widget set, which was originally
> > created for
> > Tcl/Tk and later included with Tkinter, after this book was
> > published.  I
> > find that Pmw covers most of the problem space that Tix is suited
> > for, but a
> > beginner may have a different experience.
>
> Between the new Tkinter standard widgets (Paned Window, Spinbox etc)
> and Tix virtually everything in PMW is available in the standard
> library. and
> there are some extras not in PMW like a Grid and Tree for example.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Geometry Management and Other Basics

2009-03-19 Thread Chris Fuller
With respect to grid and pack, all siblings must use the same manager.  Do 
otherwise and your application will hang.  Children/parents may use different 
managers.  I don't believe there are any restrictions on place, as it doesn't 
do any negotiation.

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


Re: [Tutor] adding dictionary values

2009-03-20 Thread Chris Fuller
You should iterate over the keys of the dictionary:
for k in a.keys():
because if you iterate over the full dictionary, your items are the values, 
not the keys.  Otherwise your code looks correct, and I don't think its 
terribly bad form.  You could do something interesting with sets:
sa = set(a.keys())
sb = set(b.keys())

The next step could be a for loop, but if you enjoy terseness and taking 
advantage of language features (also should be faster for big enough dicts):
c = dict( \
   [(k, a[k]+b[k]) for k in sa&sb ] + \
   [(k, a[k]) for k in sa-sb ] + \
   [(k, b[k]) for k in sb-sa ]
)

which creates a new dict from a list of key, value pairs.  The list is a sum 
of three lists:  those keys in both a and b, those only in a, and those only 
in b.

Cheers

On Friday 20 March 2009 10:11, Emad Nawfal wrote:
> Hi Tutors,
> I have two pickled dictionaries containing word counts from two different
> corpora. I need to add the values, so that a word count is the sum of both.
> If the word "man" has a count of 2 in corpus A and a count of 3 in corpus
> B, then I need a new dictionary that  has "man": 5. Please let me know
> whether the following is correct/incorrect, good/bad, etc.
> Your help appreciated:
>
> def addDicts(a, b):
> c = {}
> for k in a:
> if k not in b:
> c[k] = a[k]
> else:
> c[k] = a[k] + b[k]
>
> for k in b:
> if k not in a:
> c[k] = b[k]
> return c
>
> # test this
> dict1 = {"dad": 3, "man": 2}
> dict2 = {"dad": 5, "woman": 10}
> newDict = addDicts(dict1, dict2)
> print(newDict)
> # This gives
>
> {'dad': 8, 'woman': 10, 'man': 2}
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding dictionary values

2009-03-20 Thread Chris Fuller

Oops! The dictionary iterates over keys, not values as I stated (and 
demonstrated by your working code).  Consequently, the example I gave could 
be more succinctly expressed by:
sa = set(a)
sb = set(b)

Sorry for the error.
Cheers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using C in python

2009-03-25 Thread Chris Fuller

There's a section in the Python docs just on this topic: 
http://docs.python.org/extending/index.html

There's probably also some stuff in the wiki, although I'm not familiar with 
anything specific:  http://wiki.python.org/moin/

The SWIG documentation is extensive, and while not the user-friendliest, 
should get you started:  http://www.swig.org/doc.html

The quick intro to SWIG is that you create and "interface file" which defines 
how Python interfaces to your C code.  In the braindead simple cases, this 
can be simply the header files with your function prototypes.  In actual 
usage, it's a good deal more complicated, but the SWIG docs show you the way.

Cheers

On Wednesday 25 March 2009 16:13, amit sethi wrote:
> what are the ways in which i can use C in python programs . I know there is
> SWIG bindings are there any other . Also Could anyone explain how Swig
> bindings work?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Functional Derivatives

2009-04-20 Thread Chris Fuller

You should look up "numerical methods" or similar.  There are ways of 
rearranging your calculations to minimize the loss of precision.  You could 
also try a numerical/scientific library like GMP (for integers or rational 
numbers).  I don't know of any (Python) library for extended precision 
floats, but there ought to be.

Cheers

On Monday 20 April 2009 18:53, Matt wrote:
> I'm trying to calculate the derivative of a function in Python like so:
>
> def D5(func,h=1e-5):
>     ""' Return derivative of function func'''
>     def df(x):return (func(x+h)-func(x))/h
> df.__name__ = func.__name__ + '_dx'
>     return df
>
> However, I run into the problem of limited float precision. This is
> evident for this:
> import math
> print D5(D5(D5(D5(math.sin(0.3)
>  => -5551.11512313
> print math.sin(0.3)
>  => 0.295520206661
> Is there any way that any of you can think of to avoid this for
> general-purpose functions? Thanks.
> ___
> 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] Functional Derivatives

2009-04-20 Thread Chris Fuller
His problem was composing four functions, each with a small error.  The first 
two applications work well enough, but there is a about a percent error in 
the third composition.  The big source of error is f(x+h)-f(x).  Subtracting 
two floating point numbers that are nearly equal is a known source of 
innaccuracy.  Scaling all the terms by a very large number reduced the error, 
but not as well as fewer compositions.

Cheers

BIGNUM = 1

def D5(func, h=1e-5):
""' Return derivative of function func'''
def df(x):
return (BIGNUM*func(x+h)-BIGNUM*func(x))/(BIGNUM*h)
return df

import math

print D5(math.sin)(0.3)
print math.cos(0.3)

print D5(D5(math.sin))(0.3)
print -math.sin(0.3)

print
print D5(D5(D5(math.sin)))(0.3)
print -math.cos(0.3)

# actually, other powers, higher or lower, work less well..
BIGNUM = 1e10
print D5(D5(D5(math.sin)))(0.3)
print -math.cos(0.3)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Number cruncher

2009-04-22 Thread Chris Fuller
Most teachers use spreadsheets for this.  Is there a reason you'd like to use 
Python?  A spreadsheet would be easier to create and less error prone.

If you don't have a copy of Microsoft Orifice handy, you can use Gnumeric or 
Open Office.

Cheers

On Wednesday 22 April 2009 10:54, John Jenkinson wrote:
> I need to write code that determines a students final grade based on the
> number of each type of assignment turned in with its corresponding weighted
> percentage.  There will be 15-20 inputs.  I have not reached this point in
> my learning of python, so I would like to request a resource that would
> help me for this project.
>
> - John Jenkinson
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] split or replace

2009-06-05 Thread Chris Fuller
On Friday 05 June 2009 06:18, Norman Khine wrote:
> Hello,
> What is the way to group each value so that I get a list, from a string
> like:
>
> dir = '/expert/forum/expert/expert'
> list = ['/expert', '/forum', '/expert', '/expert']
>
> I've tried:
> >>> dir = '/expert/forum'
> >>> dir.split('/')
>
> ['', 'expert', 'forum']
>
> >>> dir.replace("/expert","")
>
> '/forum'
>
> >>> dir = '/expert/forum/expert'
> >>> dir.replace("/expert","")
>
> '/forum'
>
> Thanks

Your code will be more portable if you use the os.path module.  I'd do 
something like this:

import os.path as osp
import os

path = '/bear/duck/gecko/toad'
l = []
b = True
a = path
sep = os.sep

while b:
a,b = osp.split(a)
l.append(osp.join(sep,b))

l.pop()
l.reverse()

print l
['/bear', '/duck', '/gecko', '/toad']

If you wanted something more consice, you could use a list comprehension:
['/'+i for i in path.split('/')]

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


Re: [Tutor] Best Python Editor

2009-06-13 Thread Chris Fuller
On Saturday 13 June 2009 04:44, Eddie wrote:
> Hi guys,
>
> What would you regard as the best free Python editor to use on Windows
> for a new guy? Searching Google i see that there is quite a few out
> there and is "VIM" the best one to go with?
>
> Regards
> Eddie

I've tried a lot of editors, and my current favorite (cross platform, many 
languages/just text) is Kate (http://www.kate-editor.org/kate), available on 
windoze via KDE on Windows (http://windows.kde.org/), select kdesdk-msvc from 
the list of packages while in the installion tool.

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


Re: [Tutor] distutils MANIFEST.in

2009-06-17 Thread Chris Fuller

Use os.path.walk or similar to build the file before you call setup().

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


Re: [Tutor] how to manage an encrypted file?

2009-06-19 Thread Chris Fuller
On Friday 19 June 2009 17:23, Robert Lummis wrote:
> Could you recommend a module or methods I should use to manage an
> encrypted text file? I want to store passwords and associated contact
> information in a file and feel confident that if the file is stolen
> the information couldn't be read.

Use the PyCrypto module.

It (not so) recently changed maintainers, there isn't a release yet at the 
main site: http://www.dlitz.net/software/pycrypto/, so use the old site for 
now, http://www.amk.ca/python/code/pycrypto.html.  If you're using Linux, 
check to see if there's already a package for your distribution.

There are windoze binaries at 
http://www.voidspace.org.uk/modules.shtml#pycrypto.

Cheers


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


Re: [Tutor] list comprehension problem

2009-07-03 Thread Chris Fuller
On Friday 03 July 2009 15:37, Emile van Sebille wrote:
> On 7/3/2009 1:21 PM Kent Johnson said...
>
> > On Fri, Jul 3, 2009 at 3:49 PM, Dinesh B
> >
> > Vadhia wrote:
> >> d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1]
> >>
> >> and we want:
> >>
> >> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84,
> >> 95, 96]
> >> dd = [ sum(d[:j]) for j in range(len(d)) ][1:]
> >>
> >> gives:
> >>
> >> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84,
> >> 95]
> >
> > In [9]: [ sum(d[:j+1]) for j in range(len(d)) ]
> > Out[9]: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73,
> > 78, 84, 95, 96]
>
> So, did we get an 'A'...
>
> Emile
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

The problem with these list comprehensions is that they have O(n**2) 
complexity.  Whether they are faster or not depends on the speedup from the 
list comprehension and the length of the input.  I'd be inclined to favor the 
linear for loop.

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


Re: [Tutor] int to bytes and the other way around

2009-07-06 Thread Chris Fuller
The only things that matter are the arguments and the result.  It sounds to me 
like a good case use for SWIG (http:://www.swig.org).  You can do really 
complicated stuff with swig, and it takes a correspondingly steep learning 
curve to achieve, but doing simple stuff is really simple.  It sounds like 
the first example in the SWIG docs could be straightforwardly adapted to your 
problem.

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


Re: [Tutor] segmentation fault

2009-07-12 Thread Chris Fuller
On Sunday 12 July 2009 11:09, Rick Pasotto wrote:
> I've got a script that I wrote several years ago and have been happily
> using daily. Suddenly when I try to run it I get a segmentation fault.
>
> I'm running debian testing so probably some recent update caused the
> breakage. How can I find out what's gone wrong?

Crashing the Python interpreter isn't easy.  The most common ways I've seen 
are errors in C extensions, unpickling, and the ctypes module.

You might have some C extensions that need to be recompiled for the new 
version of Python, or an update to your C extensions that requires a newer 
version of Python.

The usual troubleshooting advice applies.  Strategically placed print 
statements (I actually prefer using UDP sockets for logging), separate your 
code into blocks and see if you can narrow down where the error is occurring, 
use a debugger, etc.

Depending on the complexity of your code, you might even be able to find out 
if there's some input somewhere that isn't validated, although this probably 
isn't the problem in your case.

At each step, verify what you think you've learned.  If it isn't repeatable, 
you can't test the fix.

But yeah, check for resource exhaustion too.  That one can bite you 
unexpectedly.

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


Re: [Tutor] how to know if process is running?

2009-07-28 Thread Chris Fuller
On Tuesday 28 July 2009 10:45, shawn bright wrote:
> Hey all,
>
> I have an app that runs in a GUI written in pygtk. It spawns several
> threads, and runs all the time.
> It is mission critical that we can never have two instances of this
> running at once.
>
> So, my question is, how can i write something that will know if there
> is an instance of that something already running?
>
> I am doing this in python 2.5 on Ubuntu, if that matters ( which i
> suspect it does ).

The usual way is with file locks, but these are tricky to do in a cross 
platform way, and I find that when the program crashes unexpectedly, it can 
take awhile for the locks to get cleaned up by the operating system.

What I do is open an UDP socket.  The code is dead simple:

from socket import socket, AF_INET, SOCK_DGRAM

def check_port(addr):
   s = socket(AF_INET, SOCK_DGRAM)

   try:
  s.bind( addr )
   except SocketError, e:
  if type(e.args) == tuple:
 if e[0] == errno.EADDRINUSE:
return True

  raise

   else:
  s.close()
  return False

def check_port(addr):
   return check_port(addr, SOCK_DGRAM)

# returns False if the port is bound
def socket_lock(port, check_only=False):
   s = socket(AF_INET, SOCK_DGRAM)
   addr = ('localhost', port)

   if not check_port(addr):
  if not check_only:
 s.bind( addr )
 return s
  else:
 return True
   else:
  return False


addr is the address tuple used by the socket module.  First element is 
hostname (usually "localhost"), and the second element is the port number.  
Note that you need root/Administrator privileges to open a port under 1024.

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


Re: [Tutor] Program to Simulate Keystrokes

2009-08-04 Thread Chris Fuller
On Tuesday 04 August 2009 12:43, Megan Land wrote:
> Hi,
>
> I'm working on a python script to automate a program we run at work.  The
> program is run from one command.  The only problem is that it asks you to
> hit enter to continue after it runs.  Is there a way I can do this?
>
> If at all possible I need a program that will work on Windows and Linux (I
> know a tall order).  I'm trying to keep this simple but if I have to use
> two different programs I will.
>
> Thanks for the help!
>
> Megan Land
> FVT Blade EMET Test Engineer
> ml...@us.ibm.com

If your needs are basic, popen will probably suffice.  But, there is a module, 
Pexpect, that is made just for this job.
http://sourceforge.net/projects/pexpect/

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


Re: [Tutor] this module

2009-08-08 Thread Chris Fuller
On Friday 07 August 2009 21:31, Mark Young wrote:
> Hi, I was reading a tutorial, and it mentioned the "import this" easter
> egg. I was curious, and looked up the contents of the module, and dscovered
> that it had attributes c, d, i, and s. I was wondering if anyone had any
> clue what these attributes were supposed to mean. I think (this.s) is the
> zen of python in some foreign language (dutch maybe?), but I have no clue
> what the significance of the others are. Just wondering if anyone knew, (or
> if they mean anything at all).
>
> Also, I was wondering, when a user first imports this, how does the module
> print the zen of python? I can't figure out how it does it.

"Use the source, Luke!"

You can find this.py, along with the rest of the standard library (most of 
which is written in Python, as opposed to being compiled C code) wherever 
your Python was installed.  For instance, /usr/lib/pythonx.y on unixy 
machines (including macs), and C:\Pythonxy\Lib on that other operating 
system.

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


Re: [Tutor] this module

2009-08-08 Thread Chris Fuller
Something else to note: you can find any module's location by looking it up in 
the dictionary sys.modules.  For instance:

Python 2.4.4 (#2, Oct 22 2008, 19:52:44)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> import sys
>>> sys.modules['this']


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


Re: [Tutor] Pyduino

2009-09-07 Thread Chris Fuller
There are a few projects attempting something like this, but it is not easy to 
get a language like Python running on the minimalist resources found in a 
microcontroller.  Google "python microcontroller" (without the quotes).. you 
could also try the plural form to see if that brings up other hits.  In the 
best case, you are going to have a limited subset of the language in some 
way, I'm sure.

There is a fairly mature gcc toolchain for the Atmel AVR microcontrollers, so 
you can also use that.  At least for straight C, I dunno about C++, Fortran, 
Objective C, Ada, or the others.

Cheers

On Monday 07 September 2009 20:31, Joshua Harper wrote:
> I just bought an arduino and id like to use python instead of the arduino
> language, any tips, tutorials, anything, i googled but there isnt much on
> it really...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Wrapper of C++

2009-10-08 Thread Chris Fuller
It might also be a good application for numpy (http://www.numpy.org/)

Cheers

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cannot convert eps to png using PIL

2009-10-15 Thread Chris Fuller

It's trying to launch GhostScript, and failing.  The broken pipe is a clue 
that its trying to communicate with external software.  Most likely, you 
don't have ghostscript installed.  Google Ghostscript and you should find 
instructions for installing on windows (I'm fairly sure there is a port).  As 
for getting it to work with PIL, I'd just try getting it on your path 
(os.environ['PATH'] should work, too).  But you want to talk to the 
GhostScript folks; this isn't a Python problem, and there isn't an alternate 
solution that is more Pythonic.

Cheers

On Thursday 15 October 2009 23:23, LL wrote:
> Hi.. I also asked this question on the imaging group but thought people
> here might have insights as well..
>
> all of the following code executes interactively except the last line.
> Converting a .jpg file to .png works fine. I'm using the PIL version for
> Python 2.6. Any suggestions will be greatly appreciated. Thanks, Lance
> 
> PythonWin 2.6.3 (r263:75183, Oct  5 2009, 14:41:55) [MSC v.1500 32 bit
> (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see
> 'Help/About PythonWin' for further copyright information.
>
> >>> import os
> >>> import zlib
> >>> import Image
> >>> os.chdir("c:\\foo")
> >>> img = Image.open("foo1.eps")
> >>> img.save("foo1.png")
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python26\lib\site-packages\PIL\Image.py", line 1372, in save
> self.load()
>   File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 283, in
> load self.im = Ghostscript(self.tile, self.size, self.fp)
>   File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 72, in
> Ghostscript gs.write(s)
> IOError: [Errno 32] Broken pipe
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cannot convert eps to png using PIL (LL)

2009-10-17 Thread Chris Fuller

Like I said, you need to find out what's going wrong with GhostScript.  Also, 
converting image formats is something PIL does internally, without requiring 
a (large) external package like GhostScript, which is an interpreter for a 
different language (PostScript), which your eps files are coded in.

Cheers

On Saturday 17 October 2009 00:51, LL wrote:
> > It's trying to launch GhostScript, and failing.
>
> Not sure this is the problem. Ghostscript is installed on my machine. Also,
> I am able to convert .jpg to .png.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PyGTK: is there a library for both Linux and Windows

2009-10-21 Thread Chris Fuller

The version of GTK for windows I like to use is at 
http://gladewin32.sourceforge.net/, but it is rather out of date.  It's main 
advantage is everything is bundled up in a nice installer.  You can also get 
it from the main site at ftp://ftp.gtk.org/pub/gtk, but you have to grab 
several files and install manually.  I've never tried to figure out which 
ones, but I expect it wouldn't be hard.  You could check the dependencies of 
the PyGTK shared objects,  i.e. with http://www.dependencywalker.com/

You could also just get a more current, but still bundled up runtime from 
Pidgin (http://www.pidgin.im/), and install glade separately, as its only a 
single file.

Note that you'll need to get PyGTK from the gnome site 
http://ftp.gnome.org/pub/gnome/binaries/win32/.  Get PyGTK, PyObject, and 
PyCairo.

Yes, glade is awesome.  You'll need to learn how to hook the signals into your 
code.  There are a lot of tutorials out there, but the ones I used are at the 
Linux Journal site:
http://www.linuxjournal.com/article/6586
http://www.linuxjournal.com/article/7421
http://www.linuxjournal.com/article/4702

There's a bit of a caveat.  You will find in most cases that the system Python 
and GTK (or numpy, PIL, etc) that your distribution provides is lagging 
somewhat behind what you can easily install on a Windows box, since there's 
aren't so many interdependencies.  I'm just now starting to playing around 
with ArchLinux to see if I can get aruond this.

Cheers

On Wednesday 21 October 2009 08:42, Nicola De Quattro wrote:
> Hi
> I'm starting to design some windows for my little tool.
> I've two questions for you:
> 1) In this page http://www.pygtk.org/downloads.html there are two
> different library for Windows and GNU/Linux, but I want my application
> to be executed identically under Windows and under GNU/Linux. Is PyGTK
> a good choice? There are some difference between PyGTK library under
> Windows and under GNU/Linux, that is have I to develop two different
> versions of my tool?
> 2) Do you suggest to use Glade to design windows? Note: I'm totally
> new both to python and to GUI design (I've always worked on signal
> processing, never develop a MMI) so I'm searching something that can
> be as much as possible both "educational" and friendly.
>
> Thank you for your help
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PyGTK: is there a library for both Linux and Windows

2009-10-21 Thread Chris Fuller

on differences:

The downloads include binaries, so there have to be distinct files for Linux 
and Windoze.  If you download the same versions, there shouldn't be any 
noticeable differences, with one big exception:  multithreading and PyGTK 
don't mix well on Windows.  Your application might run perfectly (and look 
correct) on Linux, but in Windoze it's a mess.  You can find workarounds, but 
I haven't come across one that looked reliable.  If you have Python 2.6 or 
higher, you can use the multiprocessing module (also available separately for 
earlier versions) to emulate threads with processes, which will relieve the 
problem, but make it a little harder for your threads (processes) to 
communicate with each other.

Cheers
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PyQT forum?

2009-10-29 Thread Chris Fuller
Start with the main site.  There are links to wikis/mailing lists/etc there.
http://www.riverbankcomputing.co.uk/software/pyqt/

Also, you might be interested in the fully-free alternate, PySide, sponsored 
by Nokia:
http://www.pyside.org/

Cheers


On Wednesday 28 October 2009 11:17, Christopher Spears wrote:
> I'm starting to learn PyQt.  Can anyone recommend a good mailing list or
> forum?
>
> Thanks.
>
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be
> a color television set." -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "There is no such thing as luck; there is only adequate or inadequate
> preparation to cope with a statistical universe." -Robert A. Heinlein,
> "Have Space Suit - Will Travel"
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Chris Fuller

My approach has been to store it as an array and then build the integer as 
needed.  This code requires Python 2.5 or later.

def bits2int(l):
   return sum([2**i if j else 0 for i,j in enumerate(l)])

To convert the other way:

def int2bits(m, n):
   return [int(bool(m&(1<>= inc

   return i

floating point is so messy and slow :)

Cheers

On Wednesday 02 December 2009 12:08, Robert Berman wrote:
> Hi,
>
> I am trying to represent a number as a list of bits: for example the bit
> representation of the integer 8. I did find a number of articles
> pertaining to a module called bitarray but I was unable to
> download/install that package. I am using Linux on Ubuntu 9.10; Python
> 2.6.2.
>
> I am almost certain there is a relatively easy way to convert an integer
> that can be represented by 32 bits into an array of bits that I can
> iterate over looking for switched on bits or switched off bits.
>
> Any information such as recipes or past articles in this list providing
> methods to create and manipulate  bit arrays would be most appreciated.
>
> Robert
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No beep from winsound.Beep(500, 500)

2009-12-19 Thread Chris Fuller

Something to keep in mind is that the audio output of your computer and the 
system speaker are independent.  Sometimes the BELL character (ACSII 0x07) 
will sound the system speaker, spending on your OS, drivers, etc.

The winsound docs say it's the speaker, which is connected to the motherboard 
with an odd four pin connector (with only two wires).  It's normally only used 
during boot up, so it could have been left disconnected and not missed.

Cheers

On Saturday 19 December 2009, Richard D. Moores wrote:
> My laptop, a Toshiba Satellite running Python 3.1 and Vista 64-bit
> 
> SP2, with the speakers on and otherwise working, won't give me a beep:
> >>> from winsound import Beep
> >>> Beep(500, 500)
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> Beep(500, 500)
> RuntimeError: Failed to beep
> 
> Please give me some hints as to what I can do about this.
> 
> Thanks,
> 
> Dick Moores
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to compare elements of 2 lists

2007-12-25 Thread Chris Fuller
The most concise way to do this is to transpose the list (convert a axb array
to bxa), then complare the elements that are pairs of one value each of the 
original lists.

You have two lists, a and b.  Put these into a list and you have a 2x6 
2d "array".

>>> [a,b]
[[4, 3, 2, 6, 7, 9], [8, 6, 3, 3, 2, 7]]

A quick way to do a transposition is to use the built-in zip() function. This 
doesn't do error checking! If you need to do this in production code, you 
need to check that the lists are of even lengths. zip() will truncate the 
lists until they are all teh same size!

>>> zip(*[a,b])
[(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]

So, to get a list of booleans, you can do this:
>>> [x>y for x,y in zip(*[a,b])]
[False, False, False, True, True, True]

Cheers

On Tuesday 25 December 2007 09:00, sith . wrote:
> Hi,
> I've read the posts on comparing 2 lists and couldn't find the answer to my
> question. I have 2 lists
>   a = [4,3,2,6,7,9]
> b = [8,6,3,3,2,7]
>   How can I determine if the elements in a are larger or smaller than the
> elements in b.
>
>   for i in a:
> for u in b:
> i > u
>   does not return the result I seek.
>
> In this example, 4 from a is compared to 8,6,3,3,2,7 then 3 from a is
> compared to all the elements in b. I'd like
> 4 to 8,
> 3 to 6,
> 2 to 3 and so on; like 2 columns in excel, the third column would be a new
> list of boolean values. Can someone help please?  Thank you.
>
>
> -
> Never miss a thing.   Make Yahoo your homepage.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to compare elements of 2 lists

2007-12-25 Thread Chris Fuller

I didn't think of that.  But for an arbitrary 2D list, you need the asterisk 
syntax.

On Tuesday 25 December 2007 19:00, you wrote:
> Chris Fuller wrote:
> >>>> zip(*[a,b])
> >
> > [(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]
>
> This can be just zip(a, b)
>
> Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to compare elements of 2 lists

2007-12-26 Thread Chris Fuller

"Arbitrary" means any size, and particularly, an unknown size.  If you don't 
know how big the list is when you are writing the code, you need to use this 
syntax.

It's also more concise and less error prone than zip(l[0], l[1], l[2]) if you 
have got a 2D list of known length.

On Wednesday 26 December 2007 08:51, you wrote:
> Chris Fuller wrote:
> > I didn't think of that.  But for an arbitrary 2D list, you need the
> > asterisk syntax.
>
> I don't know what you mean by "an arbitrary 2D list". You need the *
> syntax when your arguments are *already* in a list. For any number of
> arguments,
>zip(*[a, b, ..., x, y, z])
> can be written more simple as
>zip(a, b, ..., x, y, z)
>
> Kent
>
> > On Tuesday 25 December 2007 19:00, you wrote:
> >> Chris Fuller wrote:
> >>>>>> zip(*[a,b])
> >>>
> >>> [(4, 8), (3, 6), (2, 3), (6, 3), (7, 2), (9, 7)]
> >>
> >> This can be just zip(a, b)
> >>
> >> Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to compare elements of 2 lists

2007-12-26 Thread Chris Fuller
On Wednesday 26 December 2007 10:03, Alan Gauld wrote:
> I thought I was following this but now I'm not sure.
>
> Do you mean that if I have a list L that contains an arbitrary
>
> number of sublists that I can call zip using:
> >>> zip(*L)
>
> rather than
>
> >>> zip(L[0],L[1],, L[n])
>
> If so I agree.
>
Yes.  You could build up a string and call eval(), but otherwise this wouldn't 
be possible, without iterating through manually.  (using evail() is usually 
not a good idea, avoid it if you can)

> But any time that you use the *[] format it is easier to
> just put the content of the [] into the zip directly, which is what,
> I think, Kent is saying?
>

Yes, for the original example, zip(a,b) is equivalent, and probably clearer.  
Certainly simpler.  Sorry to be confusing.  I realize now that lots of my 
code have lists of known length and need a little tweaking :)

I just remembered another way to do this, with map():
>>> a=range(4)
>>> b=['a','b','c','d']
>>> map(None,a,b)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

This also doesn't complain if the lists are uneven, but instead of truncating, 
it pads the short ones with None's.  I almost never use map() now that we 
have list comprehensions, however.  map(None, *(a,b)) also works if you 
are "transposing" an unknown number of lists.

Cheers

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


Re: [Tutor] How Do I Make Imports Work

2007-12-27 Thread Chris Fuller
On Thursday 27 December 2007 08:29, [EMAIL PROTECTED] wrote:
>
> e = Elevator()
> e.show_state()
>
> raw_input("\n\nPress the enter key to exit.")
>

Two observations:

This "module-level" code that does the testing will be run when the module is 
imported.  A more flexible approach would be to place it in a test() function 
and call it whenever you desire.  The test() function could even be a method 
of the class, if it makes sense to do that.  If you had a lot of classes, and 
each needed its own demo/test function, for instance.  If they all worked 
together, maybe one test function for all would suffice.

If you start to collect a lot of modules, you will probably want to organize 
them into directories.  It is a hassle to append stuff to sys.path every time 
you start python, so you may want to consider setting up .pth files.

See the python docs: http://docs.python.org/lib/module-site.html

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


Re: [Tutor] Dynamically named objects

2007-12-28 Thread Chris Fuller

You might find a dictionary useful. Each element in a dictionary is associated 
with a "key", which can be a string.

objectlist = {}
o = eval("class1" + "()")
objectlist["object1"] = o
o.method("hello world")

Also, try to avoid using eval(), it usually makes troubleshooting and 
maintenance harder and can lead to security problems in some cases. You could 
have a dictionary of classes and look them up on the fly:

classlist = { "classone" : classone, "classtwo" : classtwo }

objectlist = {}
cls = classlist[user_input]
o = cls()
objectlist["object1"] = o
o.method("hello world")

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


Re: [Tutor] python CLI parser

2007-12-28 Thread Chris Fuller

TUGZip (www.tugzip.com) is another free (as in speech) alternative.  It has a 
distinct interface from 7-zip that some may prefer.

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


Re: [Tutor] send file/mail to imap

2007-12-28 Thread Chris Fuller
On Friday 28 December 2007 09:31, Tim Michelsen wrote:
> Hello,
> I have a mbox file locally on my notebook.
>
> I would like to send this file to my IMAP account using python.
>
> Does anyone know a module or tutorial which does this?
>
> I tried
> * IMAPClient 0.3 - http://pypi.python.org/pypi/IMAPClient/0.3
> but it doesn't contain a send function.
>
> Thanks in advance for any hints,
> Timmie
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Batteries included!

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

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


Re: [Tutor] Careful Dictionary Building

2007-12-28 Thread Chris Fuller
first thing.. you are duplicating a lot of effort inside your loops. getting 
rid of that will speed things up:

dict = {}
for record in list:
rid = record[0]
    if rid in dict:
    dict[ rid ].append( record )
    else:
    dict[ rid ] = [record]

The other thing I see isn't a speed problem. You are overwriting two python 
built-in types when you use variables named "list" and "dict". You probably 
want to avoid doing this, because someday yuou want to use the built-ins, and 
you code wil exhibit goofy errors when you try.

The only thing I can suggest that might speed it up more is to use a set type 
instead of a list, if the ordering doesn't matter to you. I've seen that 
change result in 20-30 percent speedups, but YMMV. If you can't start with a 
set, you can create a new one by passing the list to the set constructor. 
This may or may not help you speedwise, but try it out.

You could play around with psyco, but I don't know if it would help much in 
this case.

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


Re: [Tutor] Installing problem in matplotlib

2007-12-31 Thread Chris Fuller

Is there a reason you are building from scratch?  There are binaries for 
win32, and most linux distributions.

You will need the development packages for libpng, zlib, and freetype, and 
others, depending on the GUI backends you want to use.  These can be 
configured in the setup.cfg file.  See 
http://matplotlib.sourceforge.net/installing.html.

If you are doing something like creating images for a web server, you may not 
need any GUI backends at all.  This is not an unusual use-case!

If you don't know which backend you'd like to use, select Tk, GTK, and wx.  
This will cover the examples and give you a feel for the different toolkits.  
Tk is a nice one for beginners, although the others are generally faster, 
better looking, and more capable, although the just-released new version of 
Tk addresses most of these.  Que flamewar.

I use GTK myself, but I still have a fondness for the simplicity and elegance 
of Tk, and still use it for quick and simple tasks.

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


Re: [Tutor] how to sort the data inside the file.

2007-12-31 Thread Chris Fuller
On Monday 31 December 2007 06:19, goldgod a wrote:
> hello all,
>             Please find the attached file. I want to sort the content
> of this file based on the "bytes" in descending order. How can i do
> it, any pointers to it.

This is a classic case for the use of regular expressions.  A powerful tool, 
but can be tricky.  I create a RE for a record, and than use the findall() 
function to get all of them in a list.  I'll walk you through it.

A not of caution: once you get the hang of REs, using them will leave you 
feeling giddy!

Note:  I load the whole file into memory and parse it in one piece.  If your 
log is up in the megabytes, it might make more sense to read it in line by 
line.

All of this is well documented in the Python Library Reference.


The code:

import re

fd = open('test', 'r')
s = fd.read()
fd.close()

# seperate into records
lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

# iterate through the records, and convert the text of the size to an integer
for fields in lin:
   if   fields[3] == ' M':
  mul = 100
  #mul = 1024000
  #mul = 1048576

   elif fields[3] == ' k':
  mul = 1000
  #mul = 1024

   else:
  mul = 1

   lout.append( (fields[0], fields[1], int(fields[2])*mul) )

# now sort
lout.sort(lambda a,b: cmp(a[2], b[2]))


Most of processing is happeneing in the single line
lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

Here is the regular expression
'\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes'

>From left to right:
\s*  The \s designates whitespace, the asterisk matches zero or multiple 
instances.

([^\s]+)  The parentheses designate a "group", which can be referenced later, 
and represents the hyphen delimited IP address.  It also works in the 
familiar order-of-operations manner.  We'll see this in the last piece,  The 
square brackets designate a list of valid characters.  The caret inside is an 
inversion: match anything that isn't in the set.  \s designates whitespace, 
so this matches one or more characters of not-whitespace stuff.

\s+  The plus matches one or multiple instances of whitespace.

([^\s]+)  The second referenced group, which is the domain name in your file.

\s+  matches the whitespace between fields

(\d+)  the third referenced ("matched") group, which is one or more decimal 
digits.

( [kM])?  Now the tricky bit.  The [kM] matches any character in the set, so 
either "k" or "M".  The space inside the group includes the space preceeding 
the "k" or "M" and the ? applies to the whole group, and matches zero or one 
instance, which allows records that have only "bytes" to be matched.  These 
will have None returned for that group, and " k" or " M" if these were 
present.

bytes  This is pretty obvious.  Nothing funny going on here.

I hope that made sense.

The other tricky bit is the sort.  In python, lists can be sorted in place, if 
you pass a function that determines the relative precedence of two elements.  
The cmp() built-in is a shorthand that makes this easy.  What this line does 
is sorts the list according to the value of the third element.  Reverse the a 
and b to get a descending sort.


An interesting note:  I mismatched some parentheses at first, and I ended up 
multiplying the string that converted to int rather than the int.  
Python will happily convert a million digit int for you, but damn it takes a 
long time!

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


Re: [Tutor] how to sort the data inside the file.

2007-12-31 Thread Chris Fuller
On Monday 31 December 2007 10:36, Chris Fuller wrote:
> lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)

This is incorrect.  The first version of the script I wrote split the file 
into records by calling split('bytes').  I erroneously assumed I would obtain 
the desired results by sinmply adding "bytes" to the RE.  The original RE 
could have been written such that this would have worked, (and would have 
been a little "cleaner") but it wasn't.  The space should be obligatory, and 
not included with the [kM] group.

I tried some of Kent's suggestions, and compared the run times.  Nested 
split()'s are faster than REs!  Python isn't as slow as you'd think :)

   # seperate into records (drop some trailing whitespace)
   lin = [i.split() for i in s.split('bytes')[:-1]]

   for fields in lin:
  try:
 if   fields[3] == 'M':
mul = 100

 elif fields[3] == 'k':
mul = 1000

  except IndexError:
 mul = 1

  lout.append( (fields[0], fields[1], int(fields[2])*mul) )

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


Re: [Tutor] help with list permutations

2008-01-03 Thread Chris Fuller
This is a good case for recursion. My solution is in two steps. A 
straightforward application of recursion (I was casting about semi-randomly) 
yields a attractive tree structure:

   root
   a  b
 c d e  c de
 f f f  f ff
g h   g h   g hg h   g h  g h

It returns a list, of course, but when unpacked in two dimensions looks like a 
tree. Trees are often represented this way in programming.

One thing to note is that the tree structure naturally preserves the order of 
the lists, as required.


Here is the code:

def recursion_is_your_friend(l):
   if len(l) == 1:
  return l
   else:
  return [ (i, recursion_is_your_friend(l[1:])) for i in l[0] ]

l = recursion_is_your_friend([['a','b'],['c','d','e'],['f'],['g','h']])


The idea is that each element of the first list in the list has all the rest of 
the lists applied to it. Something like that. Talking about recursion isn't a 
skill I have much skill in. Cue groaning!

The next step is to trace all the paths from the root to the leaves. There is a 
wikipedia page that discusses this: 
http://en.wikipedia.org/wiki/Depth-first_search. Stacks would seem a natural 
way to do this to me. It can also be done with more recursion. I may implement 
something a little later, but this should get you started. Another way to look 
at step two is to start at the leaves and follow the (unique) path back to the 
root.

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


Re: [Tutor] PHP & Python suggestions....

2008-02-04 Thread Chris Fuller
On Sunday 03 February 2008 17:35, GTXY20 wrote:
> Hi all,
>
> First off let me say how helpful and informative this mailing list is. It
> is very much appreciated.
>
> Anyway, I am looking for some suggestions for reading up on how to call
> Python from PHP scripts, specifically calling from a PHP web application -
> PHP will call python script with some arguments and python will run on the
> server and return the results within another PHP page.
>
> Once again thanks.
>
> GTXY20.

You can also use python in server-side scripting, at least with apache and 
mod_python.  You can use it the same way as PHP.  This might not be suitable 
for what you need to do, but if you could do it this way, it would probably 
be faster.

Cheers
Chris Fuller

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


Re: [Tutor] Ending a script

2008-02-06 Thread Chris Fuller
On Wednesday 06 February 2008 09:23, Damian Archer wrote:
> When I am running a script in cmd the script runs but the cmd windows
> closes immediately after the script has finished.
>
> Is there anyway I can freeze the cmd window until a user actually closers
> it??

There are numerous ways to do this, the simplest (and least interesting) being 
to use raw_input() to prompt the user to hit ENTER.

A more elegant way would be to redirect the text somewhere else, perhaps a GUI 
textbox, or even out a network socket to an independent logging process.  
This is simple to do in python.  All you need is a class with a write() 
method.  Asign sys.stdout and sys.stderr to an instance of such a class.  You 
can use the same instance, or treat them seperately.

When the interpreter prints some output, or an exception is raised, the output 
will be passed to the write() methods of these objects, and your code can 
perform any arbitrary manipulations upon the output that is desired.

Handling exceptions is actually a bit trickier, of course, since the default 
action is to terminate the program (although not always if it occurs in a GUI 
callback), but there are other uses for sys.stderr.  A lot of modules will 
display error or warning messages on it, for instance. 

There is a bigger caveat:  these do not correspond to the stdout and stderr 
used by the OS and the underlying C inside the interpreter.  Many python 
modules wrap C libraries (pygtk, for instance), and the messages displayed at 
runtime will not be handled with any python-awareness.  You can still 
redirect these, but you have to make low-level operating system calls, and 
the details differ ever so slightly from standard POSIX systems if you are 
suffering under the yoke of Redmond.

The attached program demostrates these concepts, except the nasty lowlevel OS 
dependent bit.

Cheers


redirtk.py
Description: application/python
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Binary chop function - this works, but I'm not sure why

2008-02-13 Thread Chris Fuller
On Wednesday 13 February 2008 18:49, Arun Srinivasan wrote:
> I'm trying to learn Python, and I decided to try kata 2  from the
> CodeKate website. It's basically just a challenge to implement a binary
> search in different ways.
>
> I wrote an implementation that works, but I'm confused as to why.
>
> def chop(search_int, sorted_list):

> if len(sorted_list) == 1 or 2:

This condition is always true.  You meant to say:  len(sorted_list) == 1 or 
len(sorted_list) == 2"

or: "len(sorted_list) in 1,2"

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


Re: [Tutor] how to display terminal messages in dialog window using tkinter

2008-02-21 Thread Chris Fuller
There's a post on this list from me, with example code, from a couple of weeks 
ago that solves this:  
http://mail.python.org/pipermail/tutor/2008-February/060025.html

Cheers


On Thursday 21 February 2008 11:15, brindly sujith wrote:
> hi
>
> i m developing a application using tkinter
>
> i want the messages that we get in the terminal to be displayed in the
> tkinter dialog box
>
> do we have any option for that
>
> thank you
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] file transfer through serial modem -- pythin code

2008-02-26 Thread Chris Fuller
You probably want to start with PySerial:
http://pyserial.sourceforge.net/

But, the details really depend on the application.. what are you talking to at 
the other end?  Do you need a general terminal program?

You can probably find xmodem and zmodem libraries, but if you control both 
ends, rolling your own would be easy enough, just be sure to check for data 
corruption.  Zmodem is preferred, since Xmodem can pad the end of the file 
with NULLs.

If you are working through a modem, you will need to be familiar with the 
Hayes AT Command Set.  Google is your friend.

Answering incoming calls is harder, you need access to the modem control lines 
(or you can tell the modem to answer manually).  This is a platform specific 
problem.

You might start out with a null modem cable between two computers (or even the 
same computer, with two serial ports), just to get familiar with the system.


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


Re: [Tutor] How to open IE7 to a certain URL?

2008-02-29 Thread Chris Fuller
On Friday 29 February 2008 06:28, Dick Moores wrote:
> I keep missing a certain weekly program on my local NPR station. My
> idea is to record it using software I have, Easy Hi-Q Recorder. I can
> set it to start recording when the program starts, 8pm, but I need to
> have the program playing on my computer. The URL for the station's
> audio is http://www.kuow.org/real.ram .
>
> I've got this so far:
>
> #!/usr/bin/env python
> #coding=utf-8
> import time
> b = '20:00:00'
> while True:
>  a = time.strftime('%H:%M:%S')
>  time.sleep(0.5)
>  if a == b:
>  print "TIME!"
>  break
>
> Obviously, I need to replace the  'print "TIME"'  line with something
> that will open IE7 to http://www.kuow.org/real.ram . But what?
>
> Thanks,
>
> Dick Moores
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


You might consider passing the URL directly to the audio player.  This is 
usually all the web browser does for you, although its possible there's a 
different URL defined on that page each time, but then you could parse the 
page in python using urllib and re, or something similar.  Not only that, 
launching IE7 is a time and memory consuming activity, and definitely lacks 
grace.

I dunno how your media player works, but this did the job for me (from the 
command prompt):

"c:\Program Files\Real Alternative\Media Player Classic\mplayerc.exe" 
http://www.kuow.org/real.ram

You could put this directly into your windows scheduler, and not use python at 
all.  Start Menu>All Programs>Accessories>System Tools>Scheduled Tasks
You'll get an option to set the command line at the end of teh wizard, if you 
check "show advanced options"

You could have a python process running in the background that executed this 
command through the subprocess module, at the appointed time.  You could even 
use something like FireDaemon to turn it into a service.  But, it seems 
better to use the windows scheduler.

Cheers

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


Re: [Tutor] How to open IE7 to a certain URL?

2008-02-29 Thread Chris Fuller
On Friday 29 February 2008 18:25, Tiger12506 wrote:
> time.sleep is not exactly accurate, so I would suggest that you use this
> method, short 5 minutes or so and then do a sleep(10) or so in a loop to
> get closer to the time.

Another advantage to shorter sleeps is it reduces the latency of anything else 
your program needs to do, such as exit gracefully, reschedule the event, or 
whatever.  Not too short, because that uses more CPU time.

It also makes a difference if the clock gets reset :)

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


Re: [Tutor] How to open IE7 to a certain URL?

2008-02-29 Thread Chris Fuller

I left out the daily increment. there should be a event_time += 86400  end of 
the inner loop.


while True:
   while time()http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to open IE7 to a certain URL?

2008-02-29 Thread Chris Fuller
On Friday 29 February 2008 12:24, Dick Moores wrote:
>  http://www.kuow.org/real.ram .


Try this to start, then turn into a service with FireDaemon, 
http://www.firedaemon.com/.  You'll need to fill in the quit() function, and 
the particulars for your media player.

from time import mktime, strftime, strptime, localtime, time, sleep

# return true if the program should exit
def quit():
   pass

import subprocess
def launch():
   args = ( 'c:\\pathto\\cmd', 'http://www.kuow.org/real.ram' )
   subprocess.call(args)

# get the seconds since epoch of midnight, add the desired time of day,
# and convert back into seconds since epoch. We'll wake up just a bit
# early, so we can use a coarser timer.

event_time = mktime(strptime(strftime('%Y%m%d',
   localtime(time()))+'19:59:40','%Y%m%d%H:%M:%S'))

while True:
   while time()http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with encoder & decryption keys

2008-03-01 Thread Chris Fuller
On Friday 29 February 2008 16:30, Trey Keown wrote:
> Hey all,
>   Been away for a while. So, I'm in the process of making a program for
> encrypting and decrypting strings of text. And I was wondering how it
> would be possible to perhaps keep keys in a .pyc file, and keep them
> from being isolated, and messages being intercepted. So... is it
> possible to decompile things within a .pyc file?
>   This isn't for any serius project, just me attempting to make something
> to prove that I can do it.
>
> Thanks for any help.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

The best you can do is to make it tricky to reverse engineer.  Same goes for 
compiled code or assembly, only those are admittedly closer to the "bare 
metal".  Java and C# Care also "byte-compiled" languages, and I think Java 
has some security features, although I don't know what they are.

Don't use a fixed constant.  Compute the key, and spread the dependencies 
around.  You could mix in a deterministic random number generator.

Of course, this is all useless if your program can be inspected while its 
running.  It's impossible, in principle, really, when the recipient of the 
secret message and the eavesdropper are the same entity.

Still, unless you have determined adversaries, it won't be worth the trouble.  
Plenty good enough for casual use, but don't bet national security on it or 
anything.

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


Re: [Tutor] sorting objects on two attributes

2008-03-03 Thread Chris Fuller
Almost.  And better than my original idea.  You could have a hierarchical sort 
function:

def hiersort(a,b):
   if a.attr1 != b.attr1:
  return cmp(a.attr1, b.attr1)
   else:
  if a.attr2 != b.attr2:
 return cmp(a.attr2, b.attr2)
  else:
 return cmp(a.attr3, b.att3)


l.sort(hiersort)

You can keep nesting for more than three attributes, or you could make it 
arbitrary by setting it up recursively and setting the attribute hierarchy as 
a parameter somewhere.  But that's probably unnecessarily fancy.

Cheers

On Monday 03 March 2008 08:42, Andreas Kostyrka wrote:
> Well, this assumes that all named attributes do exist. If not, you need
> to replace x.attr with getattr(x, "attr", defaultvalue) ;)
>
>
> l.sort(key=lambda x: (x.content_type, x.submit_date))
>
> Now, you can construct a sorted list "t":
>
> t = []
> for key, item_iterator in itertools.groupby(l, key=lambda x:
> (x.content_type, x.submit_date)): sorted_part = sorted(item_iterator,
> key=lambda x: x.submit_date) t.append((sorted_part[-1].submit_date, key,
> sorted_part))
>
> t.sort()
>
> t = sum([x[2] for x in t], [])
>
> Totally untested, as written in the MTA :)
>
> Andreas
>
> Am Montag, den 03.03.2008, 22:19 +0800 schrieb Eric Abrahamsen:
> > I have a grisly little sorting problem to which I've hacked together a
> > solution, but I'm hoping someone here might have a better suggestion.
> >
> > I have a list of objects, each of which has two attributes, object_id
> > and submit_date. What I want is to sort them by content_type, then by
> > submit_date within content_type, and then sort each content_type block
> > according to which block has the newest object by submit_date. (This
> > sequence of sorting might not be optimal, I'm not sure). I'm actually
> > creating a list of recent comments on blog entries for a python-based
> > web framework, and want to arrange the comments according to blog
> > entry (content_type), by submit_date within that entry, with the
> > entries with the newest comments showing up on top.
> >
> > I don't believe a single cmp function fed to list.sort() can do this,
> > because you can't know how two objects should be compared until you
> > know all the values for all the objects. I'd be happy to be proven
> > wrong here.
> >
> > After some false starts with dictionaries, here's what I've got.
> > Queryset is the original list of comments (I'm doing this in django),
> > and it returns a list of lists, though I might flatten it afterwards.
> > It works, but it's ghastly unreadable and if there were a more
> > graceful solution I'd feel better about life in general:
> >
> >
> > def make_com_list(queryset):
> > ids = set([com.object_id for com in queryset])
> > xlist = [[com for com in queryset if com.object_id == i] for i in
> > ids]
> > for ls in xlist:
> > ls.sort(key=lambda x: x.submit_date)
> > xlist.sort(key=lambda x: max([com.submit_date for com in x]),
> > reverse=True)
> > return xlist
> >
> > I'd appreciate any hints!
> >
> > Thanks,
> > Eric
> > ___
> > 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] Simple reg-ex syntax?

2008-03-13 Thread Chris Fuller

How I would improve this:

compile the regular expression.  This is more efficient.
self.digit_extractor = re.compile('(\d+)')

then, use the findall method:
self.allNumbers = self.digit_extractor.findall(self.aString)
which will even work with multiline strings, but doesn't convert to integers.

To convert, use a list comprehension:
self.allNumbers = [int(i) for i in self.digit_extractor.findall(self.aString)]

Cheers

On Wednesday 12 March 2008 21:59, Allen Fowler wrote:
> Hello,
>
> I have code that looks something like:
>
> self.aString = "abc123xyz"
> self.theNumber = int(re.search('(\d+)',self.aString).group())
>
> Is there a more Pythonic way of doing this? (Both the reg-ex and the Int
> coercion.)  How about when I will need to extract more than one substring?
>
> Thank you,
>
> :)
>
>  
> ___
>_ Never miss a thing.  Make Yahoo your home page.
> http://www.yahoo.com/r/hs
>
> ___
> 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] my first project: a multiplication trainer

2008-03-15 Thread Chris Fuller

The basic approach I use in these sorts of problems is to generate the 
choices, remove them from a list as they are asked, and then stop when this 
list is empty.


If you don't need the list of questions afterwards, this will work:

from random import choice

questions = [ [i,j] for i in range(1,10) for j in range(1,10) ]
false_answers = []

while questions:
   q = choice(questions)
   del questions[questions.index(q)]

   # stuff


If you'd like to keep the original question list, make a proxy list, and 
choose from that:

questions = [ [i,j] for i in range(1,10) for j in range(1,10) ]
false_answers = []

choices = range(len(questions))

while choices:
   proxyq = choice(choics)
   del choices[choices.index(proxyq)]

   q = questions[proxyq]

   # stuff


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


Re: [Tutor] signal trapping in a class instance

2008-03-15 Thread Chris Fuller
SIGKILL is not trappable.  You probably want SIGTERM.  Furthermore, this 
signal will be sent to the process, not some thread or class instance within 
a process.

Maybe you need some other mechanism?  Is the signal going to be from the same 
python process?  If so, just call it directly.  Otherwise, there are a great 
deal of other interprocess communications options.  Sockets are probably the 
most cross platform nd widely understood.  Check out the UDPServer class in 
the standard library.

You'd need to write a client script to send the commands, but this is trivial 
once you have the server set up.

Cheers

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


Re: [Tutor] signal trapping in a class instance

2008-03-15 Thread Chris Fuller
I read your post again, and it looks as though you might want to use the 
atexit module.  Another idea would be to trap the SIGTERM signal and to keep 
a registry of instances, and then to invoke a cleanup method of each 
instance.

Another important note: trapping signals will have no effect if your process 
terminates itself.

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


Re: [Tutor] my first project: a multiplication trainer

2008-03-16 Thread Chris Fuller
On Sunday 16 March 2008 08:03, Guba wrote:
> Hello!
>
> I like the idea of retaining my original questions by creating a proxy
> list, but I wasn't able to understand (find) the proxy list:
>
> Chris Fuller wrote:
> > from random import choice
> >
> > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ]
> > false_answers = []
> >
> > choices = range(len(questions))
>
> This I don't understand: len(questions) simply gives 81;
> range(len(questions)) counts them all up: 0,1,2...80.

Each element in the proxy list is the index of a distinct element in the 
original list.

>
> > while choices:
> >proxyq = choice(choices)
>
> here choice(choices) picks ONE item  out of choices (e.g. 56) and
> assigns it to proxyq
>
> >del choices[choices.index(proxyq)]
>
> here the item (56) just assigned to proxyq gets removed from choices
> (question: why not use pop() for these last two steps?)

choice() returns a random element from the list of choices, not its index.  
One could call pop() instead of del, but del is probably a little faster, and 
doesn't return a value that we wouldn't use anyway.  pop() wouldn't give us a 
random element, unless passed a random argument, such as 
pop(choice(range(len(choices, but that would be very cumbersome.

>
> >q = questions[proxyq]
>
> here q is assigned to item 56, i.e. [7, 3], out of questions (which
> contains all 81 possible questions).
>
> Now, because we are operating in a while loop, 81 item are generated and
>  81 items are accordingly picked out of the questions list, all this
> without repetition of items..
>
> If I am right (am I?) with my interpretation, then I still don't
> understand how/where we generated a proxy list... I think we are just
> running a while loop without having generated a list out of its ouput!??

This isn't like a for loop that iterates through the elements of a list.  It 
is a while loop that repeats until some condition is false.  I used a bit of 
a shortcut when I used "while choices:": this is equivalent to "while 
len(choices)>0", or "stop the loop when the choices list is empty".  The 
deletion is necessary, so that choice() doesn't return the same element again 
later.

It seems to me that a better way to do this would be to use random.shuffle() 
on the choices list, and iterate through that in a for loop.
>
> Cheers for a short comment!

Ha!  How about a long one?  I have attached some example code.  It is easier 
to see how this works with working code.  The first uses choice(), the 
second, shuffle().
>
> Guba


mt1.py
Description: application/python


mt2.py
Description: application/python
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] my first project: a multiplication trainer

2008-03-16 Thread Chris Fuller

Oops, I based those examples on my initial solution, not the preferred one 
that preserved the questions.  Here is some better code.  They only use the 
shuffle method, and I've elaborated a bit on the basic solution, to 
illustrate some ideas for improvement.

Some things you might try as an exercise:  provide an escape command, rather 
than having to use ctrl-c; eliminate the symmetrical questions, i.e. only one 
of 3x5 and 5x3 need be presented.

Cheers


mt1.py
Description: application/python


mt2.py
Description: application/python


mt3.py
Description: application/python
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] my first project: a multiplication trainer

2008-03-17 Thread Chris Fuller

You should try some of the Python tutorials out there.  There's a difference 
between tuples and lists, and the parameter list passed to the string 
formatting operator must be a tuple.  String formatting will also solve your 
second problem.

Also, the library reference is your friend.  I particularly like the Beazley 
book, if you want something in hardcopy, but one of the less terse and more 
introductory O'Rielly books might suit you better.

Here's a partial list of (mostly) tutorial resources that I've compiled:

http://wiki.python.org/moin/BeginnersGuide
http://www.uselesspython.com/gettingstarted.html
http://www.freenetpages.co.uk/hp/alan.gauld/
http://www.secnetix.de/olli/Python/
http://pythonology.org/

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


Re: [Tutor] python, wxpython and postgresql

2008-03-17 Thread Chris Fuller
Unless you have a specific reason for choosing postgresql (an excellent 
database, just not the easiest), such as having an existing 
installation, desiring networked access, or nice features such as type 
safety, you might want to consider SQLite instead. Also, if you stick to 
the DB-API spec, you will have a fairly easy time of switching databases 
later, should you wish to.

http://www.python.org/peps/pep-0249.html

Cheers

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


Re: [Tutor] python, wxpython and postgresql

2008-03-17 Thread Chris Fuller
There are at least a couple of python interfaces to postgresql, but psycopg 
follows the DB-API spec.  You shouldn't have to use the postgresql engine 
directly.

http://www.initd.org/pub/software/psycopg/

The cool bit is that the examples you see that follow DB-API will apply to 
postgresql, except for the initial connection part.

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


Re: [Tutor] Python to C++

2008-03-20 Thread Chris Fuller
On Wednesday 19 March 2008 18:52, Dinesh B Vadhia wrote:
> Say because of performance, you might want to re-write/convert Python code
> to C++.  What is the best way (or best practice) to do this wrt the tools
> available?
>
> Dinesh

You also might want to use some profiling tools, or skip that step if it's 
known, and simply rewrite the slowest parts.  It isn't too hard to integrate 
Python with C code, there are tutorials in the bundled documentation (also 
available on the Python website).

http://docs.python.org/ext/ext.html

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


Re: [Tutor] Maybe advanced pexpect question?

2008-03-23 Thread Chris Fuller
What about Alt keys?  I was thinking terminal control voodoo.  But I don't 
know any.  man 5 termcap might be a start, though.

Cheers

On Sunday 23 March 2008 06:58, Kent Johnson wrote:
> Nathan McBride wrote:
> > I've used pexpect for a few projects and love it.  Basically pexpect
> > lets you spawn a program and interact with it from code like you
> > yourself were running it in a console.  How would you send the ctrl key?
>
> I don't use pexpect, so I am guessing...
>
> The ctrl key by itself is not a character so you can't send that. ctrl-C
> is a character that is represented in a string as \x03. I expect you
> would send a control character with sendline(), for example to sent
> ctrl-C try
>child.sendline ('\x03')
>
> 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


Re: [Tutor] Maybe advanced pexpect question?

2008-03-23 Thread Chris Fuller

What about Alt keys?  I was thinking terminal control voodoo.  But I don't 
know any.  man 5 termcap might be a start, though.

Cheers

On Sunday 23 March 2008 06:58, Kent Johnson wrote:
> Nathan McBride wrote:
> > I've used pexpect for a few projects and love it.  Basically pexpect
> > lets you spawn a program and interact with it from code like you
> > yourself were running it in a console.  How would you send the ctrl key?
>
> I don't use pexpect, so I am guessing...
>
> The ctrl key by itself is not a character so you can't send that. ctrl-C
> is a character that is represented in a string as \x03. I expect you
> would send a control character with sendline(), for example to sent
> ctrl-C try
>child.sendline ('\x03')
>
> 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


Re: [Tutor] Library for Disk Usage (UNIX)

2008-03-26 Thread Chris Fuller
On Wednesday 26 March 2008 09:11, Tom Tucker wrote:
> Hello all. I'm looking for a builtin Python library capable of providing
> similar output to what the unix df command provides.  Obviously, I'm trying
> to avoid a system call if possible.  I'm looking for the following fields
> at a mimimum, total size, used, and /path. Suggestions?  I was looking at
> os.stat(/path)[WXYZ}, and os.path.getsize, but they are lacking.
>
> Thanks for the help,
>
> Tom

You need to know the size of the blocks that the filesystem uses.  Use the 
statvfs module and the os.statvfs function.

Cheers


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


Re: [Tutor] parse emails as they come in

2008-03-28 Thread Chris Fuller

The email and mailbox modules might help you out.  Multiple email messages 
will probably parse as an mbox format mailbox.

http://docs.python.org/lib/module-email.html
http://docs.python.org/lib/module-mailbox.html

Cheers

On Friday 28 March 2008 03:14, linuxian iandsd wrote:
> good morning everybody !
>
> I have scripted a small program to parse a 5 lines email message as it
> comes in to my inbox (this is handled by procmail & here is a wonderful
> intro to it : http://linuxfocus.org/English/November1997/article8.html)
>
> so every email is being parsed & information is extracted from it.
>
> but sometimes two or more emails come in at once so the input file that my
> python script has to parse is more than five lines !! my question is how do
> i effeciently manage this from within my original script.
>
> thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Setting the PC Clock to Correct Time

2008-04-19 Thread Chris Fuller
On Saturday 19 April 2008 10:45, Wayne Watson wrote:
> I have a Python program that runs 24/7, but is activated around dusk and
> de-activated from its task around dawn. My clock drifts about 4 sec/day.
> Is there some function that will fetch the correct time from the
> internet and reset the clock? I'd like to reset the clock each time the
> program is activated at dusk.

You need an NTP (network time protocol) client.  You may have one built in to 
your operating system.

Check out http://www.pool.ntp.org/ for tips on how to get started.

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


Re: [Tutor] Setting the PC Clock to Correct Time

2008-04-19 Thread Chris Fuller
I just checked my laptop (XP Pro), and you can set the time server (or use the 
default), but it only updates once a week.  So your computer's time could be 
off by thirty seconds by the time of the next synchronization.  It might be 
enough, but you also need to be aware so you aren't confused into thinking it 
isn't working when its off by four seconds the next day.

I used to have my linux desktop synchronize every six hours.  The full blown 
NTP client runs more or less continuously, and can keep you within 
milliseconds of the standard.

Cheers

On Saturday 19 April 2008 10:45, Wayne Watson wrote:
> I have a Python program that runs 24/7, but is activated around dusk and
> de-activated from its task around dawn. My clock drifts about 4 sec/day.
> Is there some function that will fetch the correct time from the
> internet and reset the clock? I'd like to reset the clock each time the
> program is activated at dusk.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Debug C library in python program

2008-04-28 Thread Chris Fuller

I expect if you take that route, you would have to compile the Python 
interpreter with debugging enabled, and then run that with gdb.  A better 
idea might be to recompile your library to produce debugging output at 
strategic locations, and then output it to the console or a socket to some 
logging program.  Note that the C stdout/stderr usually doesn't correspond to 
the ones in Python's sys module.

Cheers

On Monday 28 April 2008 02:03, tuyun wrote:
> Hi
> May be this is a basic question, but I havent find answer through google :(
> I'm not familiar with python. I wrote a C library, and some body used the
> library in his python program, and found a bug of my library, I want to
> figure out what's wrong in my library. So how can I make a breakpoint for a
> suspect function in my C library when he is "running in " a python program.
> Is there a debugger or what, which like gdb, I just need to issue:b
> ? Thanks in advance for my "amateurish question" :(
>
> Thanks
> Twomol
> _
> 用手机MSN聊天写邮件看空间,无限沟通,分享精彩!
> http://mobile.msn.com.cn/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why?

2008-05-29 Thread Chris Fuller
On Wednesday 28 May 2008 20:32, bob gailer wrote:
> Robert William Hanks wrote:
> >  Need ti find out whem a number o this form i**3+j**3+1 is acube.
> >  tryed a simple brute force code but, why this not work?
> >
> > def iscube(n):
> > cubed_root = n**(1/3.0)
> > if round(cubed_root)**3 == n:
> > return True
> > else:
> > return False
> >
> > for i in range(1,1000):
> > for j in range(1,1000):
> >  soma= i**3 +j**3 +1
> >  if isCube(soma):
> >  print i
> >  print j
> >  print soma
>
> Assuming you fixed the problem, do you know of any cases for which i**3
> +j**3 +1 is a cube?
>
> Also note this program will run for a LONG time.
>
> You can shorten the run time:
>
> for i in range(1,1000):
> for j in range(j,1000): # test each combination once
>  soma =  i**3 +j**3 +1
>  cubed_root = soma**(0.333) # function call and division take
> extra time and there is no need for either
>  if abs(cubed_root  - round(cubed_root)) < .01: # this is a
> guess at close enough, and cheaper than cubing?
>  print i
>  print j
>  print soma

Actually, another flaw is the isCube (or iscube) function.  This will produce 
false cubes, due to the rounding and floating point approximations.

If you turn the problem around, and iterate through all n**3, and then iterate 
through all i,j less than n, and find all the i,j such that 
i**3+j**3+1==n**3, the run time will be much, much less for any given n, and 
eliminates the approximations.

Cheers

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


Re: [Tutor] Controlling applications

2008-06-10 Thread Chris Fuller
On Monday 09 June 2008 14:13, Alan Gauld wrote:
> You need to find an API that lets you work at the X windows
> protocol level. I don;t know of one but will be surprised if
> there isn't such a beast around somewhere!

This made me think of Tcl's send() function.  This web page has some links 
that may (or not) be useful:

http://wiki.tcl.tk/1055

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


Re: [Tutor] Writing a script to interact with an interactive commandprogram

2008-06-10 Thread Chris Fuller

On the subject of controlling interactive programs and Tcl, one can hardly 
forget expect.. now add Python and you probably have what you want:

http://www.noah.org/wiki/Pexpect

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


Re: [Tutor] references to containing objects

2008-06-23 Thread Chris Fuller

You can also subclass the dictionary type so that this happens transparently.  
You could do something similar with lists.

class Container(dict):
   def __setitem__(self, key, value):
  dict.__setitem__(self, key, value)
  if hasattr(value, 'setParent'):
 if callable(value.setParent):
value.setParent(self)

class Contained:
   def setParent(self, p):
  self.parent = p

bag = Container()
print id(bag)

item1 = Contained()
item2 = Contained()

bag['a'] = item1
bag['b'] = item2

print id(item1.parent)
print id(item2.parent)


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


Re: [Tutor] String concatenation too slow

2008-06-30 Thread Chris Fuller
You could try creating a list of strings, and then using a ''.join(list) to 
concatenate, but you are probably going to be best off using the cStringIO 
module (http://docs.python.org/lib/module-cStringIO.html).  Try timing all 
three and see how they compare when joining lots of strings.  The length of 
the strings probably won't matter as much as the number of them.

Cheers

On Tuesday 01 July 2008 00:12, Shrutarshi Basu wrote:
> I'm working on a program to create Lindenmayer systems. These systems
> depend on heavy string rewriting to form complex patterns.I've been
> using string concatenation to read through the string, and then create
> the new one based on a dictionary lookup. However it becomes very slow
> once the string gets very long (several thousand characters). Part of
> it is undoubtedly due to the fact that the algorithm is quadratic (i'm
> trying to find a better way) but I was wondering if there might be a
> faster alternative to string concatenation. Would appending to a list
> of strings be faster? I'm going to be doing thousands of these
> appends, so even a small boost would be helpful.
> Thanks,
> Basu
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamic Method Creation

2008-07-10 Thread Chris Fuller
On Thursday 10 July 2008 09:09, George Flaherty wrote:
> Hello,
>
> I am trying to port over some old code from Ruby into Python.  In my old
> ruby code I had a UnitTest class that created a bunch of test methods (i.e.
> def test_MyTestFunction) dynamically through the ruby method
> define_method(http://www.ruby-doc.org/core/classes/Module.html#M000396).
>
> This functionally allowed me to create any number of methods dynamically
> within a particular class. My problem is I have never done this nor can
> find any examples of this within python and I am pretty sure python can
> handle this?
>
> If anyone could point me in the right direction?
> thanks
>
> -george
>

If you have an existing class, you can bind new methods to it by simply using 
setattr().  
>>> class A:
...   pass
...
>>> setattr(A, 'x',lambda self: 'foo')
>>> a=A()
>>> a.x()
'foo'
>>> class B(A):
...  pass
...
>>> b=B()
>>> b.x()
'foo'

You can also use new.classobj() to create arbitrary classes on-the-fly.  See 
the documentation for the  new module, and google "python metaclasses"

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


Re: [Tutor] where to report a bug?

2008-07-25 Thread Chris Fuller
On Friday 25 July 2008 09:04, Rick Pasotto wrote:
> I have a script that works fine on my linux machine but bombs out when
> run under windows using the exact same data files. The script downloads
> a file then unzips it and then scans the resulting file for certain
> records. Under Windows it gets a memory error in the unzip routine.
>
> Where should I send the error report?

Quoth
http://www.python.org/dev/faq/#where-can-i-submit-view-bugs-for-python

6.1   Where can I submit/view bugs for Python?
The Python project uses Roundup for bug tracking. Go to 
http://bugs.python.org/ for all bug management needs. You will need to create 
a Roundup account for yourself before submitting the first bug report; 
anonymous reports have been disabled since it was too difficult to get in 
contact with submitters. If you previously had used SourceForge to report 
Python bugs, you can use Roundup's "Lost your login?" link to obtain your 
Roundup password.

Make sure you are using the latest version, at least for that series (2.4.x, 
2.5.x, 2.6.x), and make some attempt to search the database to see if its a 
known bug.

You might also make sure that your linux and windows systems have the same 
version of Python installed.  For instance, If they are sharing files created 
by the Pickle module, this can fail if the Pickle format was updated with the 
newer version.

Do include some example code in your bug report.  Share with this list if you 
are uncertain about anything.

Which reminds me, I have a glitch that bombs with the cStringIO module but 
works with StringIO.  Thanks!

Thanks for your support in making Python better!

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


Re: [Tutor] Memory error - how to manage large data sets?

2008-07-28 Thread Chris Fuller
On Monday 28 July 2008 10:56, Karthik wrote:
> Hi,
>
>
>
> I am new to Python programming, I was trying to work out a few problems in
> order to grasp the knowledge gained after going through the basic chapters
> on Python programming. I got stuck with a memory error.
>
>
>
> Following is what I did,
>
>
>
> 1. I need to find the sum of all numbers at even positions in the
> Fibonacci series upto 2 million.
>
> 2. I have used lists to achieve this.
>
> 3. My program works good with smaller ranges. Say till 10,000 or even
> 100,000. However when I compute the sum for bigger ranges it gives me the
> memory error.
>
> 4. Also could someone tell me how to get the result in the form of an
> exponent. For instance, I would prefer 10^5 rather  10.
>
>
>
> Thanks in advance,
>
> Karthik

It sounds like you are storing all the fibonacci numbers as you generate them.  
Why?  You only need the previous two to find the next in the sequence.  The 
sum is a single number that you can add every other element in the sequence 
to.  You only need to store three numbers in memory.  Storing millions is 
wasteful, and doesn't scale very well.

To find an exponent, use the "**" operator.  For instance, 2**3 is 8, and 3**2 
is 9.

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


Re: [Tutor] Memory error - how to manage large data sets?

2008-07-28 Thread Chris Fuller

There's no need to keep any lists.  The sum can be done on the fly, which is 
perhaps a bit slower, but takes a constant amount of ram.  Even storing every 
other element (or every third, which is what he's trying to do: the elements 
that are even numbers, not every other element.. See his example code, or 
Project Euler, problem two, which seems to be the original source) will still 
take a lot of ram.

Something like this:

a = 0
b = 1

total = 0

while True:
   c = a+b
   a = b
   b = c

  if c>1e6:
break

  if c%2 == 0:
total += c

print total

By the way,  working through those problems will really exercise your 
programming and math skills.  It's a great way to get started, if you enjoy 
those kind of puzzles.


Can you see why every third element must be even?
Cheers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Memory error - how to manage large data sets?

2008-07-29 Thread Chris Fuller

The original post was a little ambiguous: "I need to find the sum of all 
numbers at even positions in the Fibonacci series upto 2 million."

But the project euler page 
(http://projecteuler.net/index.php?section=problems&id=2) is clear: "Find the 
sum of all the even-valued terms in the sequence which do not exceed four 
million."

Depending on which value you are after, it may not be necessary to enumerate a 
million terms of the fibonacci sequence.  In fact, only about thirty are 
needed.

Now if you want to do the harder problem, I suggest using GMP or some other 
Numerical extension, and not Python :)

Or play some interesting math tricks.  The wikipedia page on fibonaccis lists 
a lot of identities that could be exploited in intriguing ways.

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


  1   2   >