Re: [Tutor] What Editori?

2010-02-24 Thread Mike
I use and love Pyscripter for Windows.  I guess I am used to the Delphi IDE.

Mike

On Tue, Feb 23, 2010 at 11:24 AM, Giorgio  wrote:
> Hi All,
> what text-editor do you use for python?
> I've always used kate/nano on Linux and Notepad++/PSPad on Win. Today i've
> installed portablepython to my pendrive, and found pyscripter in that. It's
> nice!
> Do you think it's a good editor? Do you know other names?
> Giorgio
>
> --
> --
> AnotherNetFellow
> Email: anothernetfel...@gmail.com
>
> ___
> Tutor maillist  -  tu...@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


[Tutor] string formatting

2012-10-24 Thread Mike
I'm in the process of learning python and migrating away from bash 
scripting. I'm in the process of converting my bash scripts that 
essentially ssh to another host via shared keys, execute commands 
remotely, and exit. To do this I started using paramiko but eventually 
decided to do it w/ subprocess since I am more familiar with that as a 
result of me converting other scripts.


This is what I'm currently working on, the purpose of this is to ssh 
into another machine, make a tarball of dumped .sql files, save the 
tarball with the result of timestamp() as the naming convention, then it 
will eventually clean it up based on file age:



http://dpaste.com/817874/

This is the result after executing the script:




rev@omega:~/code/beavis/test$ ls
bleh1.sql  bleh2.sql  bleh3.sql  ssh-jobs.py

rev@omega:~/code/beavis/test$ ./ssh-jobs.py
tar: Removing leading `/' from member names
/home/rev/code/beavis/test/bleh2.sql
/home/rev/code/beavis/test/bleh3.sql
tar: /home/rev/code/beavis/test/24.10.2012: Cannot stat: No such file or 
directory

tar: 15\:06\:52.tgz: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
rev@omega:~/code/beavis/test$

As you can see it looks like its having issues with the way I'm using 
timestamp() for string formatting, as far as I can tell it is not a tar 
specific problem? Any help/insight on this would be greatly appreciated.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unittest not working

2015-11-19 Thread Mike
I'm trying to unit test a self-built regular expression processor for  an
assignment. I'm trying to set up unit tests for the package, but it's not
executing them. This is my first time trying to use the unittest module, so
I'm sure I'm missing something, I'm just not sure what. I even put a test
case in there I knew would fail just to try it.

Unit Test code:
import unittest
from regex import regexp

class RegexTest(unittest.TestCase):
def fail_test(self):
self.assertEqual(1, 2)

def basic_test(self):
self.assertEqual(regexp('Hello', 'Goodbye'), '')
self.assertEqual(regexp('hello', 'ello'), 'ello')
with self.assertRaises(SyntaxError):
regexp('hello', 'he)')

if __name__ == '__main__':
unittest.main()

Output:
>>>

--
Ran 0 tests in 0.000s

OK
Exit code:  False
>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Better way to insert items into a list

2012-12-08 Thread Mike
Hello everyone,

I was wondering if someone could show me a better way to achieve what
I am trying to do.  Here is my test code:

d=[]
c="00"
a="A,B,C,D"
b=a.split(',')
for item in b:
d.append(item)
d.append(c)
print tuple(d)

Basically what I want to end up with is a tuple that looks like this:
("A","00","B","00","C","00")...

As you can see I want to insert 00 in-between each element in the
list.  I believe this could be done using a list comprehension?

I realize I achieved my goal, but I was wondering what other
alternates could be done to achieve the same results.

Thanks in advance for your assistance.

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


Re: [Tutor] Better way to insert items into a list

2012-12-08 Thread Mike
Thank you.  Works well.
Mike

On Sat, Dec 8, 2012 at 4:18 PM, bob gailer  wrote:
> tuple(sum([list(x) for x in zip(a,[c]*len(a))],[]))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] symlinking dirs with spaces

2013-04-26 Thread mike

Hi all,

I wrote a cli script for syncing my music to a USB mass storage device 
like a phone etc. all it does is it creates a symlink in a dir to 
whatever folder i pass as an argument via ./addsync DIR . My problem is 
i'm having trouble dealing with directories with spaces. when using 
os.symlink I get the error below and when using subprocess it creates 
individual directories for the words separated by white space. any help 
would be appreciated on how to approach this.thanks!


This is the script:

#!/usr/bin/env python
import os
from sys import argv
import subprocess
script, media = argv

# This is the directory you will sync the symbolic links from, to the 
device.

loadDir = "/opt/data/music/load/"

# This is the destination folder, whatever folder the device is mounted to.
destDir = "/media/MOT_"

# Get the current working directory
origDir = os.getcwd()

# Glob the current working directory and the "media" argument together
# to form a full file path
origFul = os.path.join('%s' % origDir, '%s' % media)

linkDir = "ln -s %s %s" % (origFul, loadDir)

# Command to sync if media == "push"
syncCom = "rsync -avzL %s %s" % (loadDir, destDir)

def link():
print "Adding %s to %s..." % (origFul, loadDir)
os.symlink('origFul', 'media')
#subprocess.call(linkDir, shell=True)

def sync():
print "Syncing the contents of %s to %s" % (loadDir, destDir)
subprocess.call(syncCom, shell=True)

if media == "push":
sync()
else:
link()



rev@sheridan:~/code$ ./addsync SPACES\ TEST/
Adding /home/rev/code/SPACES TEST/ to /opt/data/music/load/...
Traceback (most recent call last):
  File "./addsync", line 37, in 
link()
  File "./addsync", line 27, in link
os.symlink('origFul', 'media')
OSError: [Errno 17] File exists
rev@sheridan:~/code$ ls -lh /opt/data/music/load/
total 4.0K
-rwxrwxr-x 1 rev rev 225 Apr 11 09:26 addsync
lrwxrwxrwx 1 rev rev  34 Oct 29 20:30 CCR - Best of CCR -> 
../classic_rock/CCR - Best of CCR/

rev@sheridan:~/code$

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


Re: [Tutor] symlinking dirs with spaces

2013-04-28 Thread mike

On 04/28/2013 12:43 PM, eryksun wrote:

On Sat, Apr 27, 2013 at 9:51 PM, Dave Angel  wrote:


And another little-known fact -- NTFS supports hard links, or at least it
did in 1995, on NT 3.5  As I recall, there wasn't support at the cmd prompt,
but you could create them with system calls.


NTFS has always supported hard links as additional $FILE_NAME
attributes in the MFT file record, but it was primarily meant for the
POSIX subsystem. I did find a Win32 solution for NT 3.x, which may be
what you're recalling. It requires 3 calls to BackupWrite in order to
write a link (i.e. a $FILE_NAME attribute) to an existing file record.
Apparently this was documented by Microsoft circa '96, but the
original article no longer exists online. For an example see
CreateHardLinkNt4() here:

http://cpansearch.perl.org/src/AUDREYT/Win32-Hardlink-0.11/lnw.cpp
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



My apologies for not responding, Dave's insight resolved my problem 
instantly. I am now having problems with a function I've made that is 
supposed to run a find on the media root dir and symlink anything that 
was downloaded within a specific amount of days, here is the code:


#!/usr/bin/env python
import os
from sys import argv
import subprocess
script, media = argv

# This is the directory you will sync the symbolic links from, to the 
device.

loadDir = "/opt/data/music/load/"

# Root dir of the media
musicDir = "/opt/data/music"

# This is the destination folder, whatever folder the device is mounted to.
destDir = "/media/rev/MOT"

# Get the current working directory
origDir = os.getcwd()

# Glob the current working directory and the "media" argument together
# to form a full file path
origFul = os.path.join('%s' % origDir, '%s' % media)

linkDir = ['ln', '-s', '%s' % origFul, '%s' % loadDir]



# Command to sync if media == "push"
syncCom = "rsync -avzL %s %s" % (loadDir, destDir)

def sync_new():
durFind = raw_input("Enter the duration of time in days you want to 
link")

durFind = int(durFind)
fileExcl = "*torrent*"
linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' % 
durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']

subprocess.call(linkNew)

def link():
print "Adding %s to %s..." % (origFul, loadDir)
subprocess.call(linkDir)

def sync():
print "Syncing the contents of %s to %s" % (loadDir, destDir)
subprocess.call(syncCom, shell=True)

if media == "push":
sync()
elif media == "pushnew":
sync_new()
else:
link()


Running the script with the pushnew argument results in the following 
error from find:


find: unknown predicate `-maxdepth 2'

I'm thinking this is also related to my usage of subprocess? I just 
started carving this out right now so I'm still debugging but if anyone 
sees anything obvious I would appreciate it.

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


Re: [Tutor] symlinking dirs with spaces

2013-04-28 Thread mike

On 04/28/2013 07:37 PM, Dave Angel wrote:

On 04/28/2013 08:17 PM, mike wrote:








def sync_new():
 durFind = raw_input("Enter the duration of time in days you want to
link")
 durFind = int(durFind)
 fileExcl = "*torrent*"
 linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
 subprocess.call(linkNew)





Running the script with the pushnew argument results in the following
error from find:

find: unknown predicate `-maxdepth 2'

I'm thinking this is also related to my usage of subprocess? I just
started carving this out right now so I'm still debugging but if anyone
sees anything obvious I would appreciate it.



Your linkNew list doesn't have separate items for each argument to find.
  The first example is that "-maxdepth" and "2" should be separate list
items.  The only other spot I notice is the -exec item, which should be
distinct from the following.

I don't understand why you have things like '%s' % musicDir, when
musicDir is already a string.  That list item should be just musicDir,
which would read much better.


I separated the maxdepth argument with '-maxdepth', '2', seems and now 
it is focusing on the exec portion which i'm trying to figure out how to 
separate and make it sane as far as single/double quotes go.


Can you elaborate on what you mean regarding the musicDir variable? I 
have a loadDir which specifies where the symlinks reside but the actual 
root of the media directory is /opt/data/music and it's organized via 
directories based on genres which is why I am specifying musicDir 
instead of loadDir for this function



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


Re: [Tutor] symlinking dirs with spaces

2013-04-28 Thread mike

On 04/28/2013 08:12 PM, Steven D'Aprano wrote:

On 29/04/13 10:54, mike wrote:


Can you elaborate on what you mean regarding the musicDir variable? I
have a loadDir which specifies where the symlinks reside but the
actual root of the media directory is /opt/data/music and it's
organized via directories based on genres which is why I am specifying
musicDir instead of loadDir for this function


Your command, in part, looks like this:

linkNew = ['find', '%s' % musicDir, ...]

The first item is "find", the name of the command. The second item takes
a variable which is already a string, musicDir, and turns it into a
string using '%s' % musicDir. But it's already a string, so that's just
double-handling. Instead, write this:

linkNew = ['find', musicDir, ...]






Ahhh I see the redundancy now, the function seems satisfied with the 
linkNew list with the exception of how how I'm using '-exec ...'


I get the following when executing:

rev@sheridan:~/code$ ./addsync pushnew
Enter the duration of time in days you want to link
-5
find: missing argument to `-exec'
rev@sheridan:~/code$

this is the currently working list:

linkNew = ['find', 'musicDir', '-maxdepth', '2', '-mtime', '%s' % 
durFind, '-not', '-name', '%s' % fileExcl, '-exec', 'addsync {} \;']



Is this an example where I want to be calling this while emulating a shell?

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


Re: [Tutor] symlinking dirs with spaces

2013-04-28 Thread mike

On 04/28/2013 08:59 PM, Dave Angel wrote:

On 04/28/2013 08:54 PM, mike wrote:

On 04/28/2013 07:37 PM, Dave Angel wrote:

On 04/28/2013 08:17 PM, mike wrote:








def sync_new():
 durFind = raw_input("Enter the duration of time in days you
want to
link")
 durFind = int(durFind)
 fileExcl = "*torrent*"
 linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
 subprocess.call(linkNew)





Running the script with the pushnew argument results in the following
error from find:

find: unknown predicate `-maxdepth 2'

I'm thinking this is also related to my usage of subprocess? I just
started carving this out right now so I'm still debugging but if anyone
sees anything obvious I would appreciate it.



Your linkNew list doesn't have separate items for each argument to find.
  The first example is that "-maxdepth" and "2" should be separate list
items.  The only other spot I notice is the -exec item, which should be
distinct from the following.

I don't understand why you have things like '%s' % musicDir, when
musicDir is already a string.  That list item should be just musicDir,
which would read much better.



I separated the maxdepth argument with '-maxdepth', '2', seems and now
it is focusing on the exec portion which i'm trying to figure out how to
separate and make it sane as far as single/double quotes go.


If I were sure enough about the syntax to find (I only use -exec about
once a year, and have to look it up each time), I could be explicit.

But if you want   -exec addsync {}
you should be using 3 different list items.

I don't think the \; means anything useful since you're not using the
shell.  But if find needs a semicolon there somehow, I might try just ";"

Could you show us exactly what the find command would look like if you
were executing it at the bash shell prompt?




Can you elaborate on what you mean regarding the musicDir variable? I
have a loadDir which specifies where the symlinks reside but the actual
root of the media directory is /opt/data/music and it's organized via
directories based on genres which is why I am specifying musicDir
instead of loadDir for this function



Simple.  Since musicDir is a string,
 "%s" % musicDir
is a verbose way of saying
  musicDir

Likewise for fileexecl.  Neither is an error, just confusing.




I didn't see your response dave, this would be the full syntax:



find /opt/data/music -maxdepth 2 -mtime -5 -not -name "*torrent*" -exec 
addsync {} \;



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


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-03 Thread Mike Hansen
That rooted out the problem. A while ago, I changed the colors to kind 
of match my VIM color theme(ps_color). When I did 
idlelib.PyShell.main(), IDLE came up with my custom color theme. 
However, there was a bunch of warnings about my theme. From IDLE, I 
deleted the theme. Now IDLE will launch normally. I'll set up the color 
theme later. Maybe older color themes aren't compatible with the newer 
IDLE? The color theme must have been laying around. I didn't brute force 
it in or anything like that.

I appreciate the help.
Mike
Danny Yoo wrote:
 

Yowza; that's some bug.  Danny, do you happen to know the bug number?
I can't find it on sourceforge.
 

It's been like that since 2.3 as far as I know. It generates a
connection to localhost to run code in a separate environment.
   

Hi Mike,
I wish I knew what the problem was in better detail.  IDLE is a
part of the Standard Library, so it's actually possible to try turning on
individual pieces of it, one after the other.  Maybe that will help us
debug what's going on.
Start up your console version of Python, and try:
###
 

import idlelib.PyShell
idlelib.PyShell.main()
   

###
That should start IDLE up manually, and if anything bad happens, at least
we should see some errors pop up that will help us debug the situation.
Let's make sure this doesn't fail quietly.  *grin*
Good luck to you!
 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Socket events and wxPython events?

2004-12-05 Thread Mike Eve



To learn Python, I'm adapting a board game to a 
network based games with server and clients. It took a while, but with a little 
help, I've learned about wxPython, wxglade, SPE so that I now have a prototype 
GUI up and running.
 
Now to get the network part up and running... The 
network will be sending commands, responses, and random queries.
 
I'm thinking about 3 approaches, but rather 
than beat my head against the wall, I was hoping to find out if any  of 
these are workable:
 
1) use sockets lib. Do socket send/recv generate 
any kind of event with an event id that can used with the wxPython window 
events? That is, I want to just sit and receive events such as OnPaint, 
OnButton, in the same loop as I receive "OnReceiveSocket" (or whatever it might 
be called).
 
2) create a separate thread which does a select 
then sends a wxPython compatible event which can be intermixed with OnPaint, etc 
(similar to option 1)
 
3) use SocketServer. I noticed the 
 SocketServer class refers to "request handler class" and "handle" 
functions. Do these generate any events which are wxPython 
compatible
 
You probably noticed I'm a little confused about 
what a wxPython compatible event is. I'm not sure if these events and their 
event handling are part of Python or something added by  and unique to 
wxPython.
 
Thanks, Mike
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-07 Thread Mike Hansen
Danny Yoo wrote:
On Fri, 3 Dec 2004, Mike Hansen wrote:
 

That rooted out the problem. A while ago, I changed the colors to kind
of match my VIM color theme(ps_color). When I did
idlelib.PyShell.main(), IDLE came up with my custom color theme.
However, there was a bunch of warnings about my theme. From IDLE, I
deleted the theme. Now IDLE will launch normally. I'll set up the color
theme later. Maybe older color themes aren't compatible with the newer
IDLE? The color theme must have been laying around. I didn't brute force
it in or anything like that.
   


Hi Mike,
Ah, whew, I'm glad that actually worked.  *grin*
The information about the color theme problem is valuable to know: can you
send a message to the IDLE developers with a summary of the situation?
It's possible that a lot of other folks might be running into a similar
startup problem.  Let's make sure that no one else has to go through hoops
to get IDLE working again.  The IDLE development list is:
   http://mail.python.org/mailman/listinfo/idle-dev
Good luck to you!
 

Hi Danny,
I put in a bug report on the python sourceforge site. The idle-dev mail 
list didn't seem appropriate. It seems like a mail list for idle 
developers to discuss the IDLE development plan not for users to post 
about bugs.

Thanks again for your help on this issue.
Mike
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Variable declaration

2010-02-05 Thread Hansen, Mike
Perl has "use strict;" to force variable declaration. 

My insane Perl loving co-workers think it's evil that Python doesn't have 
variable declaration. =)

What are some of the reasons/arguments on why Python doesn't need variable 
declaration? I've gotten around it in Python by using Pyflakes to check my code 
and catch those silly mis-spelling of a variable.

Mike

 



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


Re: [Tutor] Tutor list as pair progamming plush toy

2010-02-12 Thread Hansen, Mike
 

> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Mac Ryan
> Sent: Friday, February 12, 2010 8:33 AM
> To: tutor@python.org
> Subject: [Tutor] Tutor list as pair progamming plush toy
> 
> Have you ever got that piece of advice about - when you have 
> stuck on a
> bug you seem unable to track - getting a plush toy to whom you explain
> your code? (This is of course a workaround if you do not have a fellow
> developer to help you out).
> 
> Well... I found out this advice kind of works for me, with the notable
> difference that my plush toy is this mailing list. It works so
> wonderfully that indeed is several months I do not post any message:
> whenever I get stuck, I begin to write a message to the list, 
> and in the
> process of explaining what is the intended behaviour and outcome of my
> code, I systematically find the bug by myself.
> 
> I know - this is slightly OT for the list - but I thought to share as
> maybe this is a "hidden benefit" the list is bringing to a few people
> without the tutors even knowing it.
> 
> Does anybody else experience the same?
> 
> Cheers, :)
> Mac.
>

This kind of sounds like the rubber duck method of debugging. 

http://lists.ethernal.org/oldarchives/cantlug-0211/msg00174.html

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


Re: [Tutor] The Order of Imports and install order of modules andother matters (XP vs W7, ...)

2010-02-16 Thread Hansen, Mike
> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Kent Johnson
> Sent: Saturday, February 13, 2010 8:06 AM
> To: Wayne Watson
> Cc: Tutor Python
> Subject: Re: [Tutor] The Order of Imports and install order 
> of modules andother matters (XP vs W7, ...)
> 
> On Fri, Feb 12, 2010 at 10:55 PM, Wayne Watson
>  wrote:
> > There seems to be something of a general consensus in 
> ordering import
> > statements. Something like standard library imports first. 
> When using tools
> > like matlablib or tkinter (maybe), must one keep an order 
> among the relevant
> > imports?
> 
> I don't know if there is a general consensus but what I like to do is
> standard library imports
> third-party library imports
> application-specific imports
> 
> Within each group I tend to group "import x" imports before "from x
> import y" imports and alphabetize by module name. I'm not strict about
> that though.
> 

This make me wonder. Is there a document or web site that has Python Best 
Practices? Something along the lines of the Perl Best Practices book, but 
probably shorter. =)

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


Re: [Tutor] The Order of Imports and install order of modules andother matters (XP vs W7, ...)

2010-02-16 Thread Hansen, Mike


From: sri...@gmail.com [mailto:sri...@gmail.com] On Behalf Of Wayne 
Werner
Sent: Tuesday, February 16, 2010 1:07 PM
To: Hansen, Mike
Cc: Tutor Python
Subject: Re: [Tutor] The Order of Imports and install order of modules 
andother matters (XP vs W7, ...)


http://www.python.org/dev/peps/pep-0008/



This make me wonder. Is there a document or web site that has 
Python Best Practices? Something along the lines of the Perl Best Practices 
book, but probably shorter. =)


HTH,
Wayne 


I'm aware of Pep8. It's a good starting point. Anything more in-depth than Pep8 
and the Zen of Python?

Mike

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


Re: [Tutor] The Order of Imports and install order ofmodulesandother matters (XP vs W7, ...)

2010-02-17 Thread Hansen, Mike
> -Original Message-
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Alan Gauld
> Sent: Tuesday, February 16, 2010 5:58 PM
> 
> "Hansen, Mike"  wrote
> 
> > I'm aware of Pep8. It's a good starting point. Anything 
> more in-depth 
> > than Pep8 and the Zen of Python?
> 
> There is the generic book "Code Complete" which is excellent, but 
> definitely not short!
> And it's not Python specific - in fact doesn't even mention 
> Python so far 
> as I recall.
> But its advice is applicable to all languages.
> 
> A bug fan,
> 
> Alan g.

Are you a bug fan of Code Complete? =)

I need to revisit Code Complete. I read a huge amount of the first edition and 
about a 1/3 of the second edition. 

Although you can gather best practices from Pep8, the Zen of Python, The Python 
Cookbook, and other sources, it appears that a central resource for Python best 
practices doesn't exist.

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


Re: [Tutor] What Editori?

2010-02-24 Thread Hansen, Mike
I'm surprised no one has mentioned ActiveState's KOMODO. I primarily use VIM, 
but I hop into KOMODO for doing little scripts and watching the output. KOMODO 
comes in two flavors, KOMODO Edit which is free and KOMODO IDE which costs 
about $300. I suspect that KOMODO Edit does most of what people need. 
For those that don't want the steep learning curve of VIM or Emacs, I'd 
recommend KOMODO. 

Mike
No, I don't work for ActiveState. =)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread Hansen, Mike
> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Kent Johnson
> Sent: Wednesday, March 03, 2010 6:18 AM
> To: Tutor@python.org
> Subject: [Tutor] Bowing out
> 
> Hi all,
> 
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new. I'm planning to stop reading
> and contributing to the list. I have handed over list moderation
> duties to Alan Gauld and Wesley Chun.
> 
> Thanks to everyone who contributes questions and answers. I learned a
> lot from my participation here.
> 
> So long and keep coding!
> Kent

We know what's really going on. You are moving to Ruby Tutor. =)

Good luck with your "something new", and thanks for the many years of help on 
this list.

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


Re: [Tutor] Recommendations on Workshops, Courses, Live Online Training

2010-03-12 Thread Hansen, Mike
> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Tino Dai
> Sent: Thursday, March 11, 2010 12:29 PM
> To: Alan Gauld
> Cc: tutor@python.org
> Subject: Re: [Tutor] Recommendations on Workshops, 
> Courses,Live Online Training
> 
> 
> 
> On Thu, Mar 11, 2010 at 1:22 PM, Alan Gauld 
>  wrote:
> 
> 
> 
>   "Khalid Al-Ghamdi"  wrote
> 
> 
> 
>   I've subscribed to ShowMeDo, but I feel 
> something more than just video
>   tutorials. Do you have any recommendations on 
> where I can find workshops,
>   Courses, Live Online Training where I can 
> interact with a real person that I
>   can ask questions and find the answers I'm looking for.
>   
> 
> 
>   Well (most) folks on the tutor list are live, and real 
> opersons and we
>   answer questions... But if you mean face to face then 
> consider a Python
>   users group - or evenas Linux User Group(more of them) 
> since Linux
>   users are often python users too...
>   
>   
>   
> 
> Alan and the rest of the tutor regulars,
> 
> I do know of a place in North Carolina, and the president 
> of the company 
> spoke @ PyCon this year. I don't know if this is the correct 
> venue to put that 
> sort of information. Guidance please. :)
> 
> -Tino
>  
> 
> 

If you have a pile of $ that you don't know what to do with, or if
your company has deep pockets, then Big Nerd Ranch sounds like fun.

http://www.bignerdranch.com/classes/python

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


[Tutor] How do I find information about a Python object.

2010-03-30 Thread Mike Baker
Hi,

I've downloaded IDLE python for windows.  I've also downloaded Eclipse with
the python addition. I have simple programs that will run on both IDLE and
Eclipse. How do I get more information about a object/variable, such as proc
in the example below.

For example, if I execute the following:
>>> proc = subprocess.Popen(['C:\\Progra~1\\putty\\plink','Catt'],
shell=False)
  I can remote log into our Linux machine named 'Catt'.


How do I find a list of attributes for the object/variable proc?  I've tried
subprocess.__doc__ and subprocess.Popen.__doc__.

Random Googling shows that there are things like process identification
numbers available - such as proc.pid.  How do I find the other options?

Thanks,

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


[Tutor] Remote access from Windows PC to a Linux box

2010-03-30 Thread Mike Baker
Hi,

I'm trying to connect to a Linux box from my Windows machine and execute a
series of commands - (ls, pwd, cat 'somefile', etc...).   I'm using Putty to
do the ssh and have set up with Putty's Pagent agent to allow me to enter a
passphrase once per session to handle security keys between the two boxes
(so, no passwords needed for my remote scripts).

I have code that will give me a remote prompt on the Linux machine where I
can manually enter commands. This works great, but I want a script to always
execute the same series of commands without having to do so manually.   I
also have code that will execute a single command like cat a file and write
the ouput to a new file. However, when I try to use the communicate object
in subprocess, my window hangs.

Here is my working code:
# module name data_collect.y
#
import subprocess

def simp_tst0(s_name):
# Opens a remote connection to "s_name and gives a prompt.
# Works great for executing linux commands.
# Does not exit gracefully when you type exit. The python
# prompt hangs when it gets to the r.communicate command
#
cmmnd_0="C:\\Progra~1\\putty\\plink %s" % s_name
r = subprocess.Popen("%s" % cmmnd_0,shell=False)
(r_stdout, r_stderr) = r.communicate("dir")
#status=r.poll() #Locks up if you try to poll here
print r_stdout
return r

def cat_remote(s_name, file2cat):
# This simple test file opens a remote connection to "s_name", does a
cat on
# file "file2cat" and writes the cat to an output file (out2.txt).
cmmnd_2="C:\\Progra~1\\putty\\plink %s cat %s" % (s_name, file2cat)
q = subprocess.Popen("%s" % cmmnd_2, stdout=open('out2.txt','w'))


def simp_tst3(s_name):
# Runs the initial subprocess.Popen command - creates proc.
# Hangs when you try to use proc.communicate
proc = subprocess.Popen(['C:\\Progra~1\\putty\\plink','Sula'],
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
#Either of the next two commands cause window to hang
#proc.stdin.write("dir")
#(stdout_value, stderr_value) = proc.communicate(input="dir")[0]
return proc

Thanks,

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


Re: [Tutor] Python Examples of processing MS Outlook

2010-04-20 Thread Hansen, Mike
 

> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Peter Meagher
> Sent: Friday, April 16, 2010 3:13 AM
> To: tutor@python.org
> Subject: [Tutor] Python Examples of processing MS Outlook
> 
> Greetings,
> 
>  
> 
> I'm doing a lot of email processing at the moment.  I put 
> together some basic code from within Outlook to open my 
> default inbox, filter email records based on text in the 
> Subject field, then parse the body, finally send the output 
> to a text file.  This is simple stuff but very useful.
> 
>  
> 
> I need to do more, however as a newbie with Python, I figured 
> I could both learn and produce at the same time.
> 
>  
> 
> Does anyone have references to simple MS Outlook 2007 
> processing code that I could vulture for my purposes?  (The 
> code that I adapted was from an old Office 2000 vba text, so 
> the version 2007 may not be that essential to my purposes)
> 
>  
> 
> After much searching, I found a reference to PyWebmail, 
> however it communicates directly to the webmail accounts, is 
> much more than I really need and I want to stay in the 
> Outlook environment for a number of reasons, particularly its 
> interface to Access.
> 
>  
> 
> Thank you.
> 
> Peter Meagher
> 
> 

You probably need to look at Python COM. Another problem with Outlook is that 
it has some security that prevents other programs from controlling it in 
response to various virus attacks. I think there's a way around it.

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


Re: [Tutor] Remote access from Windows PC to a Linux box

2010-04-21 Thread Mike Baker
Thanks Tim,

Your subprocess examples got me started in the right direction.  I've moved
on to a slightly more advanced problem that I need help with.

I want to remotely start a Tshark packet capture session on one of our Linux
machines in the lab.  I want to start the session from my Windows machine
running Python 2.5.  The output capture file needs to be saved on the remote
Linux machine.

The example below nearly does what I want.  It starts Tshark via Putty, runs
for 10 seconds then writes the capture file (out.txt) to a remote Linux
machine.  The problem is that the putty session hangs open while Tshark is
running. So, I can't execute additional Python commands until the Tshark
capture finishes.

I've experimented with the Unix nohup command, but it does not seem to work
as expected with Tshark.  If you call my function below with
>>> test_subp(alt_cmd=1)
then the nohup command is added to the subprocess command list (along with a
trailing '&' to send the command to background).  This should work.  Using
this alternate command, out.txt gets created, but is always empty.


Here is my code:
**
def test_subp(alt_cmd=0):
'''Establish a Putty connection with one of our Linux machines in the
lab.
Send Tshark command to start a data collection session over Putty.
'''
PLINK = 'C:\\Progra~1\\putty\\plink'
sess_name='LabComp1'
if alt_cmd:
'''This command does not work as expected.  The tshark output file
(out.txt)is created,
but there is nothing in it '''
CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
/usr/sbin/tshark', '-a', 'duration:10', '-i',  'wlan0', '-T', 'text',
'-V','>', 'out.txt','&'];
else:
'This command works great, writing tshark output to out.txt on the
remote machine.'
'Unfortunately, this command hangs the putty session until the
tshark capture ends'
CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark', '-a',
'duration:10', '-i',  'wlan0', '-T', 'text', '-V','>', 'out.txt'];
print "The command list you are sending to the subprocess is: \n", "\t",
CMD_LIST

PIPE = subprocess.PIPE
    p = subprocess.Popen(CMD_LIST, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate ()
print 'stdout = ', stdout
print 'stderr = ', stderr
*****

For both runs (atl_cmd=0 or alt_cmd=1), the stdout and stderr printouts at
the end of the script are empty.

Any suggestions would be appreciated.

Thanks,

Mike
***

On Wed, Mar 31, 2010 at 7:42 AM, Tim Golden  wrote:

> On 30/03/2010 17:29, Mike Baker wrote:
>
>> I'm trying to connect to a Linux box from my Windows machine and execute a
>> series of commands
>>
>> I want a script to always
>> execute the same series of commands without having to do so manually.   I
>> also have code that will execute a single command like cat a file and
>> write
>> the ouput to a new file. However, when I try to use the communicate object
>> in subprocess, my window hangs.
>>
>
>
> This works for me:
>
> 
> import os, sys
> import subprocess
>
> PLINK = "plink"
> REMOTE_USER = "tgol...@web30.webfaction.com"
> PIPE = subprocess.PIPE
>
> p = subprocess.Popen ([PLINK, REMOTE_USER, "ls"], stdout=PIPE)
> stdout, stderr = p.communicate ()
> print "#1:", stdout.splitlines ()[0]
>
> with open ("out.txt", "w") as f:
>  p = subprocess.Popen ([PLINK, REMOTE_USER, "cat .bashrc"], stdout=f)
>  p.communicate ()
> print "#2:", open ("out.txt").read ().splitlines ()[0]
>
> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
> stdout, stderr = p.communicate ("ls\nexit\n")
> print "#3", stdout
>
> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
> p.stdin.write ("ls\nexit\n")
> stdout, stderr = p.communicate ()
> print "#4", stdout
>
> 
>
> A few things to note, none of which I believe to be germane to the
> issues you're experiencing:
>
> * You almost never need to use shell=True on a Windows call to subprocess.
>  If in doubt, don't use it.
>
> * Definitely better to pass the list-of-params style as the first param
>  of subprocess.Popen; it sorts out issues with embedded spaces etc.
>
> * The open ("...", "w") in your second example *may* be closing the
>  file immediately. I doubt it, since you'd expect Popen to hold a
>  reference, but I haven't checked the implementation.
>
> TJG
>
> ___
> 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] Remote access from Windows PC to a Linux box

2010-04-21 Thread Mike Baker
Yashwin,

Thanks!  Your nohup redirection worked great!

  - Mike

On Wed, Apr 21, 2010 at 2:45 PM, Yashwin Kanchan
wrote:

> Hi Mike
>
> have you tried running the tshark process in the background...
>
> *CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark &', '-a',
> 'duration:10', '-i', 'wlan0', '-T', 'text', '-V','>', 'out.txt'];*
>
> Or if you are using NOHUP try redirecting this way...
>
> *CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
> /usr/sbin/tshark > out.txt 2> out.err < /dev/null ', '-a', 'duration:10',
> '-i', 'wlan0', '-T', 'text','&'];*
>
> Regards
> Yashwin Kanchan
>
>
> On 21 April 2010 19:15, Mike Baker  wrote:
>
>> Thanks Tim,
>>
>> Your subprocess examples got me started in the right direction.  I've
>> moved on to a slightly more advanced problem that I need help with.
>>
>> I want to remotely start a Tshark packet capture session on one of our
>> Linux machines in the lab.  I want to start the session from my Windows
>> machine running Python 2.5.  The output capture file needs to be saved on
>> the remote Linux machine.
>>
>> The example below nearly does what I want.  It starts Tshark via Putty,
>> runs for 10 seconds then writes the capture file (out.txt) to a remote Linux
>> machine.  The problem is that the putty session hangs open while Tshark is
>> running. So, I can't execute additional Python commands until the Tshark
>> capture finishes.
>>
>> I've experimented with the Unix nohup command, but it does not seem to
>> work as expected with Tshark.  If you call my function below with
>> >>> test_subp(alt_cmd=1)
>> then the nohup command is added to the subprocess command list (along
>> with a trailing '&' to send the command to background).  This should work.
>> Using this alternate command, out.txt gets created, but is always empty.
>>
>>
>> Here is my code:
>> **
>> def test_subp(alt_cmd=0):
>> '''Establish a Putty connection with one of our Linux machines in the
>> lab.
>> Send Tshark command to start a data collection session over Putty.
>> '''
>> PLINK = 'C:\\Progra~1\\putty\\plink'
>> sess_name='LabComp1'
>> if alt_cmd:
>> '''This command does not work as expected.  The tshark output file
>> (out.txt)is created,
>> but there is nothing in it '''
>> CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
>> /usr/sbin/tshark', '-a', 'duration:10', '-i',  'wlan0', '-T', 'text',
>> '-V','>', 'out.txt','&'];
>> else:
>> 'This command works great, writing tshark output to out.txt on the
>> remote machine.'
>> 'Unfortunately, this command hangs the putty session until the
>> tshark capture ends'
>> CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark', '-a',
>> 'duration:10', '-i',  'wlan0', '-T', 'text', '-V','>', 'out.txt'];
>> print "The command list you are sending to the subprocess is: \n",
>> "\t", CMD_LIST
>>
>> PIPE = subprocess.PIPE
>> p = subprocess.Popen(CMD_LIST, stdout=PIPE, stderr=PIPE)
>> stdout, stderr = p.communicate ()
>> print 'stdout = ', stdout
>> print 'stderr = ', stderr
>> *
>>
>> For both runs (atl_cmd=0 or alt_cmd=1), the stdout and stderr printouts at
>> the end of the script are empty.
>>
>> Any suggestions would be appreciated.
>>
>> Thanks,
>>
>> Mike
>>
>> ***
>>
>>  On Wed, Mar 31, 2010 at 7:42 AM, Tim Golden wrote:
>>
>>> On 30/03/2010 17:29, Mike Baker wrote:
>>>
>>>> I'm trying to connect to a Linux box from my Windows machine and execute
>>>> a
>>>> series of commands
>>>>
>>>> I want a script to always
>>>> execute the same series of comm

[Tutor] Fwd: for loop results into list

2010-09-05 Thread Mike Beatty
Should have sent this to the list too


-- Forwarded message --
From: Micheal Beatty 
Date: Sun, Sep 5, 2010 at 2:38 PM
Subject: Re: [Tutor] for loop results into list
To: Andre Engels 


 On 09/05/2010 02:16 PM, Andre Engels wrote:
>
> On Sun, Sep 5, 2010 at 8:51 PM, Micheal Beatty  wrote:
>>
>>  On 09/05/2010 01:26 PM, Evert Rol wrote:

 Hello all,

 I'm having a little problem figuring out how to accomplish this simple
 task. I'd like to take a list of 6 numbers and add every permutation of
 those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1
 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for
 loop, that was the easy part, now I'd like to take the results and count 
 the
 number of times each number occurs.
 My problem occurs when I try to create a list from the results of the for
 loop, it puts each individual number into its own list. I've looked
 everywhere for the solution to this and can find nothing to help.

 Any suggestions would be much appreciated
>>>
>>> If you had some code, that would be very helpful. Now it's a bit of
>>> guesswork what exactly you have (code tends to be clearer than a full
>>> paragraph or two of text).
>>> At least, I currently don't understand what your problem is (or what your
>>> for-loop involves).
>>> Eg, are you looping and calling a function recursively, do you have four
>>> nested loops (or nested list comprehensions)? Or some other convenient loop
>>> to step through all combinations?
>>>
>>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools
>>> module provides a handy utiity:
>>> http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>>> Eg,
>>>
>> map(sum, combinations_with_replacement(range(1,7), 4))
>>>
>>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14,
>>> 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12,
>>> 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11,
>>> 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15,
>>> 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16,
>>> 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20,
>>> 19, 20, 21, 22, 20, 21, 22, 23, 24]
>>>
>>> seems to do what you want.
>>>
>>> But, I'd still say to adopt your own code first, and when you've learned
>>> from that, just use the one-liner above. You're most welcome to ask your
>>> question, best done in combination with code, actual output and expected
>>> output. Then we can point you in the right direction.
>>>
>>> Cheers,
>>>
>>>   Evert
>>>
>> Thanks Evert, here is the code.
>>
>>
>> fourdsix = [1, 2, 3, 4, 5, 6]
>> for i in fourdsix:
>>    for j in fourdsix:
>>        for k in fourdsix:
>>            for l in fourdsix:
>>                fourdsix_result = [i, j, k, l]
>>                attribs = sum(fourdsix_result) - min(fourdsix_result)
>>                print attribs
>>
>> This gives me the proper results, now it's just a matter of getting it into
>> a list so I can further work with the data.
>> I've tried the following
>> attrib_list = [attribs]
>>
>> and
>> attrib_list = []
>> attrib_list.append(attribs)
>> print attrib_list
>>
>> but these both only create a list of the last number.
>
> Put the attrib_list = [] before the beginning of the outer loop, and
> it should work as intended. Now you are creating a new list each time,
> which is not what you want.
>
>
>
This gets me close, as it puts the results together into a list but it
goes through every set of permutations and gives me a list.
e.g.
[3]
[3, 4]
[3, 4, 5]
[3, 4, 5, 6]
[3, 4, 5, 6, 7] and so on
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Can't figure out why this is printing twice

2009-06-08 Thread Mike Hoy
I have the following code:

import gzip
import datetime
date = datetime.date.today()
name = date.strftime('%m-%d-%Y')+'.gz'
date.strftime('%m-%d-%Y')+'.gz'
print "The name of the file will be", name

the output is:
The name of the file will be
The name of the file will be 06-08-2009.gz


I can't figure out why 'The name of the file will be' is printing twice. Any
help appreciated.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can't figure out why this is printing twice

2009-06-09 Thread Mike Hoy
On Tue, Jun 9, 2009 at 3:00 AM, Mike Hoy  wrote:

> Here's the screenshot:
>
> http://img40.imageshack.us/img40/7124/printtwice.png
>
> In case the image goes down here's the code:
> import gzip
> import datetime
> date = datetime.date.today()
> name = date.strftime('%m-%d-%Y')+'.gz'
> print "The name of the file will be", name
>
> Here's the output:
> -
> mho...@blackbox:~/code/python$ python gzip2.py
> The name of the file will be
> The name of the file will be 06-09-2009.gz
> -
> It's Python 2.6.2 on Ubuntu 9.04
>
> -Mike Hoy
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can't figure out why this is printing twice

2009-06-09 Thread Mike Hoy
>
> On Tue, Jun 9, 2009 at 6:34 AM, The Green Tea Leaf <
> thegreenteal...@gmail.com> wrote:
>
>> I got an email from him that he had a gzip.pyc file in that folder.
>> Once he deleted that everything works OK.
>
>
> Heh... I think I've made that mistake before;
>
> "My import statement doesn't work right! When I "import " it tells
> me none of the methods are available!"
>
> And then I realize my file was named that. Doh!
>
> live and learn though, eh?
>
Yea and I knew better than to do that too. Guess I had to make the mistake
to really get it into my head. Funny how that works. You read all about that
stuff in books, but you don't actually know it until you put it into
practice.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Best Python Editor

2009-06-13 Thread Mike Hoy
Try out Vim. It may take you a week to get used to it. Best thing I ever did
was finally get started on Vim. Once I got used to it I was very happy.
Google around for Vim tutorials. There is a #VIM channel on freenode I
believe. There is also a VIM mailing list that is very helpful. You won't
need these for long. Once you get used to it and think you've learned all
you can you find out there's even more stuff you can do with it.

If you wanna try Emacs go for it.

You don't need an IDE for python.

In the very beginning of writing python I wrote on windows using notepad and
Linux using Gedit. While Gedit was better it was nothing compared to Vim.

My favorite thing to do is open vim one one document I'm working on, then
split the screen horizonatally for each other relevent document I'm working
on. I can thing split it vertically as well.

I also know that once you have saved your python document in vim you can
test out your code by typing

:!python %

and it invokes the python interpreter in a shell for that script. Then when
the program is done it returns to Vim.

It also indents and colors syntax for my other languages as well:
C/Java/HTML/CSS.

So it's something that you use for life once you get that feeling of
enlightenment that comes from never having to remove your hands from the
keyboard.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Best Python Editor

2009-06-13 Thread Mike Hoy
>
>
>
> I really like using F5 to run my code, so you can put in your .vimrc so you
> don't have to type it, or just type it every time:
>
> map  :!python %
>
> and every time you hit  it will run your current script.
>
> Thanks for that. It's even better than typing :!python % because it doesn't
spawn a shell separate from the Vim window.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python List Help

2009-10-19 Thread Mike Sweany
Hi all, 

 

I am a PHP developer that just started learning Python for a specific
application and the transition has been pretty easily assisted by google,
but I just don’t see the issue with this one?

 

I’ve got a list that created and populate in a loop that shows the correct
info when I print it, but if I try to print array[0], it says the list index
is out of range.

 

Here is the code snippet. Basically, I have a link here that I am pulling
the href info from and splitting it up, only keeping the 5th value, which I
am then adding to the playerid array.

 

playerid = []

for i in range(0, players):

player = playerlink[i]['href'] 

breakup = player.split('/')

playerid.append(breakup[4])



stats = test.findAll(text=True)

print len(playerid) ß this shows the expected result

print playerid[0] ßthis kills the script

 

 


   33 print len(playerid)


   34 print playerid[0]


   35 



playerid = []

: list index out of range 
  args = ('list index out of range',) 
  message = 'list index out of range' 

If I change the print playerid[0] to print playerid[1], same error, but if I
change it to print playerid[2] or higher, it will show the same error, but
the playerid= [] will show the actual list values in the debug.

Any help would be appreciated, thank you!

 

 

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


Re: [Tutor] Python List Help

2009-10-19 Thread Mike Sweany
Thanks for the reply and Tips Dave... 

I think the formatting came out weird because I didn’t specify plain text
when I created the email.

I'm using Google App Engine and it's internal debugger shows what I posted
earlier when the code breaks, I agree that what I am seeing from the
debugger makes no sense...

Thanks for the tips, I will look at what you have and see if I can make it
work...

>From top to bottom, I am using BeautifulSoup to parse an html document and
what you are seeing is a part of the processing that just didn’t jive with
practices that I had already carried over and had working with the rest of
the code. I don’t have it set up to do the import with an interpreter
session like you laid out below, basically I am printing the stuff as it
goes, it's in a loop and this code is processed multiple times.

Honestly, I need to do some reading on how python works as I was plugging
along on this script with just a couple of hours into python for this
scraping project, but what you have shown me here will help and I will come
back to the list after I have a better understanding of what I am doing.

Thanks,

Mike

-Original Message-
From: Dave Angel [mailto:da...@ieee.org] 
Sent: Monday, October 19, 2009 1:35 PM
To: Mike Sweany
Cc: tutor@python.org
Subject: Re: [Tutor] Python List Help

Mike Sweany wrote:
> Hi all, 
>
>  
>
> I am a PHP developer that just started learning Python for a specific
> application and the transition has been pretty easily assisted by google,
> but I just don’t see the issue with this one?
>
>  
>
> I’ve got a list that created and populate in a loop that shows the correct
> info when I print it, but if I try to print array[0], it says the list
index
> is out of range.
>
>  
>
> Here is the code snippet. Basically, I have a link here that I am pulling
> the href info from and splitting it up, only keeping the 5th value, which
I
> am then adding to the playerid array.
>
>  
>
> playerid = []
>
> for i in range(0, players):
>
> player = playerlink[i]['href'] 
>
> breakup = player.split('/')
>
> playerid.append(breakup[4])
>
> 
>
> stats = test.findAll(text=True)
>
> print len(playerid) ß this shows the expected result
>
> print playerid[0] ßthis kills the script
>
>  
>
>  
>
>
>33 print len(playerid)
>
>
>34 print playerid[0]
>
>
>35 
>
>   
>
> playerid = []
>
> : list index out of range 
>   args = ('list index out of range',) 
>   message = 'list index out of range' 
>
> If I change the print playerid[0] to print playerid[1], same error, but if
I
> change it to print playerid[2] or higher, it will show the same error, but
> the playerid= [] will show the actual list values in the debug.
>
> Any help would be appreciated, thank you!
>
>  
>
>   
I'm very confused about your formatting. You seem to be using tabs with 
a large column setting (prefer 4 columns, and tabs should become spaces 
in the editor). But there's no context. So this stuff is indented, but 
it's not inside a function?? And the numbers 33, 34, and 35, what are 
they from?

What debugger are you running, that somehow displays list values when 
you assign an empty list to playerid? That makes no sense. If it's an 
exotic debugger, then perhaps you should be doing this straight from the 
python interpreter.

I suggest that until you're comfortable enough with python to know what 
to include, that you post exactly what happened, without trying so hard 
to customize it.

Show the file, in its entirety (if it's too big, then you would need a 
smaller example). And put markers at begin and end so we can see what 
part is the file.
Then if you're running from the interpreter prompt, show the whole 
session, from import  to the traceback error.

Note that if you want to print variables from the imported program, 
you'd use

 >>> print mymodule.playerid

The following is not intended to be good programming, it's intended to 
encapsulate what you already had, with some initialization to avoid 
needing other stuff that's presumably irrelevant here.

***file stuff2.py 
#!/usr/bin/env python
#-*- coding: utf-8 -*-

link0 = {"href":"this /is /a /test/of the stuff/before here"}
link1 = {"href":"this /is /a /test/different stuff/before here"}
link2 = {"href":"this /is /a /test/other stuff/before here"}
playerlink = [link0, link1, link2]
players = len(playerlink)

def doit():
global playe

[Tutor] atof error

2005-01-11 Thread Mike Procario

I got an unexpected error today using string.atof. 

ValueError: invalid literal for float(): -17,019.797

To me -17,019.797 looks like a perfectly good floating point
number. I cannot find documentation on what the allowed range is.  


--
Mike Procario
"Another casualty of applied metaphysics" -Calvin and Hobbes

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


Re: [Tutor] Objects, persistence & getting

2005-01-17 Thread Mike Hansen

Subject:
Re: [Tutor] Objects, persistence & getting
From:
"Alan Gauld" <[EMAIL PROTECTED]>
Date:
Mon, 17 Jan 2005 07:48:28 -
To:
"Liam Clarke" <[EMAIL PROTECTED]>, "Tutor Tutor" 
To:
"Liam Clarke" <[EMAIL PROTECTED]>, "Tutor Tutor" 

Well, one thing learning Java is good for is for thoroughly
demystifying OOP.
   


I'd have to disagree here because Java's version of OOP has
very little to do with real OOP. Java just uss classes as
a kind of modularisation mechanism and does not make much
use of tthe real OO features. In fact it doesn't even
support several of the things that enable real OO
programming.
And its class library, a strong feature because it is a
standard, is dreadful from an OOP p[erspective. In fact
I usually refer to Java as a Class Oriented Programming
rather than Object Oriented.
It is possible to use Java in an OOP way (read Brice Eckel's
"Thinking in Java" to see how) but the language itself
encourages a style of programming that is much more like
Pythons modules than true OOP.
 

It's not some magical acronym of programming
goodness, it's just an 'organic' way to organise code.
   

Certainly in Java thats true, and indeed even at the
higher level OOP is a way of organizing code - by
finding high level abstractions and building tree
structures based on common intefaces. But Java doesn't
encourage that structuring as much as Python does!

 

Alan G.
 

I've been reading The Object Oriented Thought Process, and it's been 
clearing up the OOP mystery for me. After reading a big chunk of it, I 
re-read the OOP sections in Learning Python. It's making a lot more 
sense now.

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


Re: [Tutor] Matching with beginning of the line in the character set

2005-02-01 Thread Mike Bell
Alternatively, you could .split() your string and not invoke the
mechanisms dealing with regular expressions.

Is this considered stylistically sloppy in the event that the split
results in a very long array?  Sloppier than REs are to begin with?

I think that the problem with [\A\d] is that \A is zero-length, which
doesn't make sense in the context of [].  Brackets aren't shorthand
for "'or' a bunch of small things together" but rather "'or' a bunch
of these single-character matches together"

mike


On Tue, 1 Feb 2005 13:30:44 -0500, Smith, Jeff <[EMAIL PROTECTED]> wrote:
> Kent,
> 
> I think \b will work for me since I was really looking for [\A\W]
> anyway.
> 
> That still doesn't answer the generalized question about something like
> [\A\d] for instance.
> 
> Thanks,
> Jeff
> 
> BTW, I was using raw strings although I forgot to put that in.
> 
> -Original Message-
> From: Kent Johnson [mailto:[EMAIL PROTECTED]
> Sent: Tuesday, February 01, 2005 1:15 PM
> Cc: Tutor@python.org
> Subject: Re: [Tutor] Matching with beginning of the line in the
> character set
> 
> Smith, Jeff wrote:
> > I want to match a string which is preceeded by a space or occurs at
> > the beginning of the line.  I also don't want to catch the preceeding
> > character as a group.
> >
> > I have found both of the following to work
> >   re.compile('(?:^|\s)string')
> >   re.compile('(?:\A|\s)string')
> 
> How about r'\bstring' ? It doesn't mean quite the same as \sstring but
> it might work for you.
> 
> >
> > But would prefer to use the more concise [] notation.  However
> >   re.compile('[^\s]string')
> 
> As the first character in [], ^ means 'not'.
> 
> > Does not work and
> >   re.compile('[\A\s]string')
> 
> I guess \A doesn't count as a 'character class'? Or do you need to be
> using raw strings?
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] i have a question???

2005-02-03 Thread Mike Bell
>num = num + math.pi/6.0   ## Don't forget .0 or you'll get an integer

the division operator returns a float when either of the operands are
floats -- in this case math.pi is, so you don't have to worry about
passing it 6.0 instead of 6

>>> import math
>>> math.pi
3.1415926535897931
>>> math.pi / 6
0.52359877559829882

>>> type(math.pi)

>>> type(6)

>>> type(6.0)



mike



On Thu, 3 Feb 2005 16:04:25 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
> >From what I understand, range() no longer allows you to use floats as
> arguments. (Or it gives you a deprication warning)
> This tutorial must be old.
> 
> Not the only way, but.
> 
> import math
> num = 0
> while num <= 2*math.pi:
> ## Do stuff to figure pi/6 things
> 
> num = num + math.pi/6.0   ## Don't forget .0 or you'll get an integer
> result.
> print ## Result thingy
> 
> Another way is to use Numarry (Numeric) arange() but that takes extra work.
> ;-)
> Jacob
> 
> 
> > This is from a tutorial
> >
> > "EXERCISE 3.9
> > Use the math library to write a program to print out
> > the sin and cos of numbers from 0 to 2pi in intervals
> > of pi/6. You will need to use the range() function."
> >
> > Range won't let me use pi/6 as an incremator
> > is there some other way i can accomplish this task
> > im new to programming so all the help i can get is
> > greatly appreciated.
> > NI!
> > alex
> >
> >
> >
> >
> > __
> > Do you Yahoo!?
> > The all-new My Yahoo! - What will yours do?
> > http://my.yahoo.com
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] manipulating a file

2005-02-07 Thread Mike Bell
without the explicit newlines in file.write(i), could it be that the
file was closed before the write buffer was ever flushed?

mike


On Mon, 7 Feb 2005 14:58:03 -0500, Smith, Jeff <[EMAIL PROTECTED]> wrote:
> -Original Message-
> From: Alan Gauld [mailto:[EMAIL PROTECTED]
> Sent: Monday, February 07, 2005 2:49 PM
> To: Reed L. O'Brien; tutor@python.org
> Subject: Re: [Tutor] manipulating a file
> 
> >You should add a newline character otherwise you will just
> >get one enormously long line!
> >
> >dstfile.write(i+'\n')
> 
> In these cases, I've taken to doing
> print >> dstfile, I
> 
> ...hmmm starting to look like Perl's many ways to accomplish the same
> thing approach :-)
> 
> Jeff
> ___
> 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's default argument value handling in functions - weird syntax? problem grappling with the concept

2005-02-09 Thread Mike Bell
The function's local variable L is not static, but "default argument
value" is, which is what the documentation means when it says that it
will evaluate these only once.  When the default value is a list (in
your code, not "the empty list" but a list which happens to be empty
when the default arguments are being evaluated), that same object is
used every time the function is called.

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


[Tutor] newbie OSX module path question

2005-02-14 Thread Mike Hall
I'm on OS X, and I cannot get Python to import modules I've saved. I 
have created the the environment.plist file and appended it with my 
desired module path. If I print sys.path from the interpreter, my new 
path does indeed show up as the first listing, yet any attempt at 
importing modules from this directory fails with ImportError. What am I 
doing wrong?

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


Re: [Tutor] newbie OSX module path question

2005-02-14 Thread Mike Hall
Hm, so if I import glob, and then execute this line:
print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py')
I simply get brackets returned:
[]
...not sure what this means. Thanks again.


On Feb 14, 2005, at 5:41 PM, Danny Yoo wrote:

On Mon, 14 Feb 2005, Mike Hall wrote:
Can you show us what your sys.path looks like?  Just do a
cut-and-paste so we can quickly validate it for you.
Thanks for the response. Here's a paste of what sys.path returns. The
first listing is the path inside of environment.plist:
['', '/Local_HD/Users/mike/Documents/pythonModules',
'/Users/tempmike/Documents/pythonModules',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python23.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
python2.3/site-packages']
Can you show us the exact thing you're typing, as well as the literal
error that Python shows?
I will attempt to import using 'import' followed by file name. 
Example:

import module1
The error returned will be:
ImportError: No module named module1

[Meta: Please keep python-tutor in CC, so that all of us on the mailing
list can help you.]
Hi Mike,
Ok, can you do this at the Python prompt?
###
import glob
print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py')
###
Copy and paste the output you see.
If things go wrong, then we will have a good focus point to debug the
problem.  But if things go right --- if you see a bunch of Python 
module
files --- then I will be stuck and will have to think of something 
else.
*grin*


Do you have problems doing an import if your modules's directory is
the current working directory?
Funny you should mention that. After posting to this list, I tried
cd'ing over to the dir I created for modules, and then launched 
Python.
My modules can indeed be imported using this method.  But I'm still
curious as to why I cannot get a successful import (when I'm not 
within
my work dir) when the path is visibly defined within the sys.path
variable? Thanks very much.
Ok, so there appears to be nothing wrong with the modules themselves or
with importing them when they're in the current working directory. We
should then focus on sys.path itself, since that's the mechanism Python
uses to lookup modules that aren't in the current directory.
For the moment, I'll assume that there's something funky with the
pathname.  As mentioned earlier, it could be as subtle as a
case-sensitivity issue.  The glob statement above will help us check to
see if Python can see those files, at least.
Best of wishes to you!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] newbie OSX module path question

2005-02-14 Thread Mike Hall
Ok, I've got it working. The environment.plist file wants a path 
beginning with /Users, not /Local_HD. So simple!  Thanks everyone.

On Feb 14, 2005, at 6:26 PM, David Rock wrote:
* Mike Hall <[EMAIL PROTECTED]> [2005-02-14 18:22]:
Hm, so if I import glob, and then execute this line:
print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py')
I simply get brackets returned:
[]
...not sure what this means. Thanks again.
It means it didn't find anything that matches that pattern, which
suggests that the directory does not contain *.py files. That might be 
a
problem. ;-)

--
David Rock
[EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with error handling in a while loop

2005-02-18 Thread Mike Bell
I haven't tried the code, but it looks like you need to increment on
connection failures, too.  I think it's more pythonic to iterate over
a range, as in the following

for test_port in range(start_port, end_port)

but it would suffice to just move the start_port+=1 outside of the try
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time Controlled Execution

2005-02-21 Thread Mike Bell
On Windows it looks like msvcrt will give you a non-blocking terminal
read -- on mac / *nix systems it looks a little trickier:

http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html

The os module in windows doesn't even have O_NONBLOCK.  That seems like trouble.
m



On Sun, 20 Feb 2005 20:55:40 +0530, Varun Soundararajan
<[EMAIL PROTECTED]> wrote:
> Hi,
> I want to know how to do this:
> I have an executable file, which reads input from stdin provided
> output at stdout or stderr.
> I have to run it for a specific period of time (say 5 secs), get the
> output and display it.
> If i use popen(), this way:
> from subprocess import *
> p = Popen(["test","test.out"], shell=True)
> p.wait()
> print p.stdin,p.stdout
> I dont get output in p.stdout.Apart from this, can u say how to stop
> this subprocess after 5 secs (or whatever time frame specified)?
> signal SIGALRM may not work (as i want it to work in windows & unix).
> -Varun
> ___
> 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] threads

2005-02-25 Thread Mike Bell
If what you want is something that scales up, then you're attacking
the Wrong Problem.  Rather than focus on getting your thread overhead
as small as possible in order to support as much real-time concurrency
as you can, you should (as has been suggested) try to get
simulation-time concurrency without worrying about what happens in
real-time. Then you can have arbitrarily many things happening at
once.

This introduction to discrete event simulation explains the idea:
http://www.dmem.strath.ac.uk/~pball/simulation/simulate.html

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


[Tutor] gensuitemodule?

2005-02-25 Thread Mike Hall
I'm seeing it used in a Python/Applescript tutorial, though am unclear 
on it's exact purpose or usage. Can someone fill me in?

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


[Tutor] Re: Newbie question.

2005-03-04 Thread Mike Hansen

Subject:
Re: [Tutor] Newbie question.
From:
Gwyn Evans <[EMAIL PROTECTED]>
Date:
Fri, 4 Mar 2005 09:37:21 +
To:
tutor@python.org
To:
tutor@python.org
On Fri, 28 Jan 2005 09:42:07 +0200, Adriaan Louw
<[EMAIL PROTECTED]> wrote:
 

I want to learn python as quick as possible, for web programming at first,
and applications later on. Any leads? 
   

Hi,
 I'd start with the basic python tutorials, then have a look at
something like CherryPy (http://www.cherrypy.org/) or Quixote
(http://www.quixote.ca/) for the initial web stuff - there are others,
too. Try & read around each a bit, e.g. web site/mailing lists, then
download & give ones you fancy a try.
 

I would politely disagree here. You need to walk before you can run. If 
you haven't done _any_ web programming before, it's probably best to do 
a small web app using just python's cgi module. I would think that 
CherryPy and Quixote are complex web tools/frameworks that I wouldn't 
recommend to someone new to web programming until they got their feet 
wet doing some basic web programming. After that, then explore more 
advanced web programming with CherryPy or Quixote.

If you have done some basic web programming in other languages, then 
ignore this message.

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


[Tutor] regular expression question

2005-03-08 Thread Mike Hall
I'd like to get a match for a position in a string preceded by a specified word (let's call it "Dog"), unless that spot in the string (after "Dog") is directly followed by a specific word(let's say "Cat"), in which case I want my match to occur directly after "Cat", and not "Dog."

I can easily get the spot after "Dog," and I can also get it to ignore this spot if "Dog" is followed by "Cat." But what I'm having trouble with is how to match the spot after "Cat" if this word does indeed exist in the string.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expression question

2005-03-08 Thread Mike Hall
First, thanks for the response. Using your re:
my_re = re.compile(r'(dog)(cat)?')
...I seem to simply be matching the pattern "Dog".  Example:
>>> str1 = "The dog chased the car"
>>> str2 = "The dog cat parade was under way"
>>> x1 = re.compile(r'(dog)(cat)?')
>>> rep1 = x1.sub("REPLACE", str1)
>>> rep2 = x2.sub("REPLACE", str2)
>>> print rep1
The REPLACE chased the car
>>> print rep2
The REPLACE cat parade was under way
...what I'm looking for is a match for the position in front of "Cat", 
should it exist.


On Mar 8, 2005, at 5:54 PM, Sean Perry wrote:
Mike Hall wrote:
I'd like to get a match for a position in a string preceded by a 
specified word (let's call it "Dog"), unless that spot in the string 
(after "Dog") is directly followed by a specific word(let's say 
"Cat"), in which case I want my match to occur directly after "Cat", 
and not "Dog."
I can easily get the spot after "Dog," and I can also get it to 
ignore this spot if "Dog" is followed by "Cat." But what I'm having 
trouble with is how to match the spot after "Cat" if this word does 
indeed exist in the string.
. >>> import re
. >>> my_re = re.compile(r'(dog)(cat)?') # the ? means "find one or 
zero of these, in other words cat is optional.
. >>> m = my_re.search("This is a nice dog is it not?")
. >>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 
'groups', 'span', 'start']
. >>> m.span()
(15, 18)
. >>> m = my_re.search("This is a nice dogcat is it not?")
. >>> m.span()
(15, 21)

If m is None then no match was found. span returns the locations in 
the string where the match occured. So in the dogcat sentence the last 
char is 21.

. >>> "This is a nice dogcat is it not?"[21:]
' is it not?'
Hope that helps.
___
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] regular expression question

2005-03-08 Thread Mike Hall
This will match the position in front of "dog":
(?<=dog)
This will match the position in front of "cat":
(?<=cat)
This will not match in front of "dog" if "dog" is followed by "cat":
(?<=dog)\b (?!cat)
Now my question is how to get this:
(?<=cat)
...but ONLY if "cat" is following "dog." If "dog" does not have "cat"  
following it, then I simply want this:

(?<=dog)

...if that makes sense :) thanks.

On Mar 8, 2005, at 6:05 PM, Danny Yoo wrote:

On Tue, 8 Mar 2005, Mike Hall wrote:
I'd like to get a match for a position in a string preceded by a
specified word (let's call it "Dog"), unless that spot in the string
(after "Dog") is directly followed by a specific word(let's say  
"Cat"),
in which case I want my match to occur directly after "Cat", and not
"Dog."
Hi Mike,
You may want to look at "lookahead" assertions.  These are patterns of  
the
form '(?=...)' or '(?!...).  The documentation mentions them here:

   http://www.python.org/doc/lib/re-syntax.html
and AMK's excellent "Regular Expression HOWTO" covers how one might use
them:
http://www.amk.ca/python/howto/regex/ 
regex.html#SECTION00054

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


Re: [Tutor] regular expression question

2005-03-08 Thread Mike Hall
Sorry, my last reply crossed this one (and yes, I forgot again to CC 
the list).
I'm experimenting now with your use of the "or" operator( "|") between 
two expressions, thanks.


On Mar 8, 2005, at 6:42 PM, Danny Yoo wrote:

On Tue, 8 Mar 2005, Mike Hall wrote:
Yes, my existing regex is using a look behind assertion:
(?<=dog)
...it's also checking the existence of "Cat":
(?!Cat)
...what I'm stuck on is how to essentially use a lookbehind on "Cat",
but only if it exists.
Hi Mike,

[Note: Please do a reply-to-all next time, so that everyone can help 
you.]

Regular expressions are a little evil at times; here's what I think 
you're
thinking of:

###
import re
pattern = re.compile(r"""dog(?!cat)
...| (?<=dogcat)""", re.VERBOSE)
pattern.match('dogman').start()
0
pattern.search('dogcatcher').start()
pattern.search('dogman').start()
0
pattern.search('catwoman')
###
but I can't be sure without seeing some of the examples you'd like the
regular expression to match against.
Best of wishes to you!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expression question

2005-03-09 Thread Mike Hall
I'm having some strange results using the "or" operator.  In every test 
I do I'm matching both sides of the "|" metacharacter, not one or the 
other as all documentation says it should be (the parser supposedly 
scans left to right, using the first match it finds and ignoring the 
rest). It should only go beyond the "|" if there was no match found 
before it, no?

Correct me if I'm wrong, but your regex is saying "match dog, unless 
it's followed by cat. if it is followed by cat there is no match on 
this side of the "|" at which point we advance past it and look at the 
alternative expression which says to match in front of cat."

However, if I run a .sub using your regex on a string contain both dog 
and cat, both will be replaced.

A simple example will show what I mean:
>>> import re
>>> x = re.compile(r"(A) | (B)")
>>> s = "X R A Y B E"
>>> r = x.sub("13", s)
>>> print r
X R 13Y13 E
...so unless I'm understanding it wrong, "B" is supposed to be ignored 
if "A" is matched, yet I get both matched.  I get the same result if I 
put "A" and "B" within the same group.

On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote:

Regular expressions are a little evil at times; here's what I think 
you're
thinking of:

###
import re
pattern = re.compile(r"""dog(?!cat)
...| (?<=dogcat)""", re.VERBOSE)
pattern.match('dogman').start()
0
pattern.search('dogcatcher').start()

Hi Mike,
Gaaah, bad copy-and-paste.  The example with 'dogcatcher' actually does
come up with a result:
###
pattern.search('dogcatcher').start()
6
###
Sorry about that!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expression question

2005-03-09 Thread Mike Hall
Indeed I do:
>>> import re
>>> x = re.compile('A|B')
>>> s = " Q A R B C"
>>> r = x.sub("13", s)
>>> print r
 Q 13 R 13 C

On Mar 9, 2005, at 12:09 PM, Liam Clarke wrote:
Hi Mike,
Do you get the same results for a search pattern of 'A|B'?
On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall
<[EMAIL PROTECTED]> wrote:
I'm having some strange results using the "or" operator.  In every 
test
I do I'm matching both sides of the "|" metacharacter, not one or the
other as all documentation says it should be (the parser supposedly
scans left to right, using the first match it finds and ignoring the
rest). It should only go beyond the "|" if there was no match found
before it, no?

Correct me if I'm wrong, but your regex is saying "match dog, unless
it's followed by cat. if it is followed by cat there is no match on
this side of the "|" at which point we advance past it and look at the
alternative expression which says to match in front of cat."
However, if I run a .sub using your regex on a string contain both dog
and cat, both will be replaced.
A simple example will show what I mean:
import re
x = re.compile(r"(A) | (B)")
s = "X R A Y B E"
r = x.sub("13", s)
print r
X R 13Y13 E
...so unless I'm understanding it wrong, "B" is supposed to be ignored
if "A" is matched, yet I get both matched.  I get the same result if I
put "A" and "B" within the same group.
On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote:

Regular expressions are a little evil at times; here's what I think
you're
thinking of:
###
import re
pattern = re.compile(r"""dog(?!cat)
...| (?<=dogcat)""", re.VERBOSE)
pattern.match('dogman').start()
0
pattern.search('dogcatcher').start()

Hi Mike,
Gaaah, bad copy-and-paste.  The example with 'dogcatcher' actually 
does
come up with a result:

###
pattern.search('dogcatcher').start()
6
###
Sorry about that!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
'There is only one basic human right, and that is to do as you damn 
well please.
And with it comes the only basic human duty, to take the consequences.
___
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] regular expression question

2005-03-09 Thread Mike Hall
But I only want to ignore "B" if "A" is a match. If "A" is not a match, 
I'd like it to advance on to "B".

On Mar 9, 2005, at 12:07 PM, Marcos Mendonça wrote:
Hi
Not and regexp expert. But it seems to me that if you want to ignora
"B" then it should be
(A) | (^B)
Hope it helps!
On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall
<[EMAIL PROTECTED]> wrote:
I'm having some strange results using the "or" operator.  In every 
test
I do I'm matching both sides of the "|" metacharacter, not one or the
other as all documentation says it should be (the parser supposedly
scans left to right, using the first match it finds and ignoring the
rest). It should only go beyond the "|" if there was no match found
before it, no?

Correct me if I'm wrong, but your regex is saying "match dog, unless
it's followed by cat. if it is followed by cat there is no match on
this side of the "|" at which point we advance past it and look at the
alternative expression which says to match in front of cat."
However, if I run a .sub using your regex on a string contain both dog
and cat, both will be replaced.
A simple example will show what I mean:
import re
x = re.compile(r"(A) | (B)")
s = "X R A Y B E"
r = x.sub("13", s)
print r
X R 13Y13 E
...so unless I'm understanding it wrong, "B" is supposed to be ignored
if "A" is matched, yet I get both matched.  I get the same result if I
put "A" and "B" within the same group.
On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote:

Regular expressions are a little evil at times; here's what I think
you're
thinking of:
###
import re
pattern = re.compile(r"""dog(?!cat)
...| (?<=dogcat)""", re.VERBOSE)
pattern.match('dogman').start()
0
pattern.search('dogcatcher').start()

Hi Mike,
Gaaah, bad copy-and-paste.  The example with 'dogcatcher' actually 
does
come up with a result:

###
pattern.search('dogcatcher').start()
6
###
Sorry about that!
___
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] regular expression question

2005-03-09 Thread Mike Hall
but yeah, it
seems you're expecting it to examine the string as a whole.
I guess I was, good point.

On Mar 9, 2005, at 12:28 PM, Liam Clarke wrote:
Actually, you should get that anyway...
"""
|
Alternation, or the ``or'' operator. If A and B are regular
expressions, A|B will match any string that matches either "A" or "B".
| has very low precedence in order to make it work reasonably when
you're alternating multi-character strings. Crow|Servo will match
either "Crow" or "Servo", not "Cro", a "w" or an "S", and "ervo".
"""
So, for each letter in that string, it's checking to see if any letter
matches 'A' or 'B' ...
the engine steps through one character at a time.
sorta like -
for letter in s:
 if letter == 'A':
#Do some string stuff
 elif letter == 'B':
#do some string stuff
i.e.
k = ['A','B', 'C', 'B']
for i in range(len(k)):
if k[i] == 'A' or k[i]=='B':
   k[i]==13
print k
[13, 13, 'C', 13]
You can limit substitutions using an optional argument, but yeah, it
seems you're expecting it to examine the string as a whole.
Check out the example here -
http://www.amk.ca/python/howto/regex/ 
regex.html#SECTION00032

Also
http://www.regular-expressions.info/alternation.html
Regards,
Liam Clarke
On Thu, 10 Mar 2005 09:09:13 +1300, Liam Clarke <[EMAIL PROTECTED]>  
wrote:
Hi Mike,
Do you get the same results for a search pattern of 'A|B'?
On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall
<[EMAIL PROTECTED]> wrote:
I'm having some strange results using the "or" operator.  In every  
test
I do I'm matching both sides of the "|" metacharacter, not one or the
other as all documentation says it should be (the parser supposedly
scans left to right, using the first match it finds and ignoring the
rest). It should only go beyond the "|" if there was no match found
before it, no?

Correct me if I'm wrong, but your regex is saying "match dog, unless
it's followed by cat. if it is followed by cat there is no match on
this side of the "|" at which point we advance past it and look at  
the
alternative expression which says to match in front of cat."

However, if I run a .sub using your regex on a string contain both  
dog
and cat, both will be replaced.

A simple example will show what I mean:
import re
x = re.compile(r"(A) | (B)")
s = "X R A Y B E"
r = x.sub("13", s)
print r
X R 13Y13 E
...so unless I'm understanding it wrong, "B" is supposed to be  
ignored
if "A" is matched, yet I get both matched.  I get the same result if  
I
put "A" and "B" within the same group.

On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote:

Regular expressions are a little evil at times; here's what I think
you're
thinking of:
###
import re
pattern = re.compile(r"""dog(?!cat)
...| (?<=dogcat)""", re.VERBOSE)
pattern.match('dogman').start()
0
pattern.search('dogcatcher').start()

Hi Mike,
Gaaah, bad copy-and-paste.  The example with 'dogcatcher' actually  
does
come up with a result:

###
pattern.search('dogcatcher').start()
6
###
Sorry about that!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
--
'There is only one basic human right, and that is to do as you damn  
well please.
And with it comes the only basic human duty, to take the consequences.


--
'There is only one basic human right, and that is to do as you damn  
well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

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


[Tutor] Code example

2005-03-12 Thread Mike Wagman
Trying to work on two programs that talk to each other - and just not
getting the basics.

Can someone please show me an example of two programs - you run one in
console one - then when you run one in console two - it talks to the
first program = sending a specific string instructing the first one to
close.

Once I have an example of that - I should be set.


Thanks

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


[Tutor] stopping greedy matches

2005-03-16 Thread Mike Hall
I'm having trouble getting re to stop matching after it's consumed what I want it to.  Using this string as an example, the goal is to match "CAPS":

>>> s = "only the word in CAPS should be matched"

So let's say I want to specify when to begin my pattern by using a lookbehind:

>>> x = re.compile(r"(?<=\bin)") #this will simply match the spot in front of "in"

So that's straight forward, but let's say I don't want to use a lookahead to specify the end of my pattern, I simply want it to stop after it has combed over the word following "in". I would expect this to work, but it doesn't:

>>> x=re.compile(r"(?<=\bin).+\b") #this will consume everything past "in" all the way to the end of the string

In the above example I would think that the word boundary flag "\b" would indicate a stopping point. Is ".+\b" not saying, "keep matching characters until a word boundary has been reached"?

Even stranger are the results I get from:

>>> x=re.compile(r"(?<=\bin).+\s") #keep matching characters until a whitespace has been reached(?)
>>> r = x.sub("[EMAIL PROTECTED]", s)
>>> print r
only the word [EMAIL PROTECTED]

For some reason there it's decided to consume three words instead of one. 

My question is simply this:  after specifying a start point,  how do I make a match stop after it has found one word, and one word only? As always, all help is appreciated.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] stopping greedy matches

2005-03-16 Thread Mike Hall
Liam, "re.compile("in (.*?)\b")" will not find any match in the example 
string I provided. I have had little luck with these non-greedy 
matchers.

I don't appear to have redemo.py on my system (on OSX), as an import 
returns an error. I will look into finding this module, thanks for 
pointing me towards it :)

On Mar 16, 2005, at 2:36 PM, Liam Clarke wrote:
x=re.compile(r"(?<=\bin).+\b")
Try
x = re.compile("in (.*?)\b")
.*? is a non-greedy matcher I believe.
Are you using python24/tools/scripts/redemo.py? Use that to test 
regexes.

Regards,
Liam Clarke
On Wed, 16 Mar 2005 12:12:32 -0800, Mike Hall
<[EMAIL PROTECTED]> wrote:
I'm having trouble getting re to stop matching after it's consumed 
what
I want it to.  Using this string as an example, the goal is to match
"CAPS":

s = "only the word in CAPS should be matched"
So let's say I want to specify when to begin my pattern by using a
lookbehind:
x = re.compile(r"(?<=\bin)") #this will simply match the spot in
front of "in"
So that's straight forward, but let's say I don't want to use a
lookahead to specify the end of my pattern, I simply want it to stop
after it has combed over the word following "in". I would expect this
to work, but it doesn't:
x=re.compile(r"(?<=\bin).+\b") #this will consume everything past
"in" all the way to the end of the string
In the above example I would think that the word boundary flag "\b"
would indicate a stopping point. Is ".+\b" not saying, "keep matching
characters until a word boundary has been reached"?
Even stranger are the results I get from:
x=re.compile(r"(?<=\bin).+\s") #keep matching characters until a
whitespace has been reached(?)
r = x.sub("[EMAIL PROTECTED]", s)
print r
only the word [EMAIL PROTECTED]
For some reason there it's decided to consume three words instead of
one.
My question is simply this:  after specifying a start point,  how do I
make a match stop after it has found one word, and one word only? As
always, all help is appreciated.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


--
'There is only one basic human right, and that is to do as you damn 
well please.
And with it comes the only basic human duty, to take the consequences.

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


Re: [Tutor] stopping greedy matches

2005-03-16 Thread Mike Hall
On Mar 16, 2005, at 5:32 PM, Sean Perry wrote:
I know this does not directly help, but I have never successfully used 
\b in my regexs. I always end up writing something like foo\s+bar or 
something more intense.
I've had luck with the boundary flag in relation to lookbehinds. For 
example, if I wanted to only match after "int" (and not "print") 
(?<=\bint) seems to work fine. I'm a bit frustrated at not being able 
to find a simple way to have a  search stop after eating up one word. 
You'd think the \b would do it, but nope.


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


Re: [Tutor] stopping greedy matches

2005-03-17 Thread Mike Hall
 Very nice sir. I'm interested in what you're doing here with 
the caret metacharacter. For one thing, why enclose it and the 
whitespace flag within a character class? Does this not traditionally 
mean you want to strip a metacharacter of it's special meaning?

On Mar 16, 2005, at 8:00 PM, Christopher Weimann wrote:
On 03/16/2005-12:12PM, Mike Hall wrote:
I'm having trouble getting re to stop matching after it's consumed
what I want it to.  Using this string as an example, the goal is to
match "CAPS":
s = "only the word in CAPS should be matched"

jet% python
Python 2.4 (#2, Jan  5 2005, 15:59:52)
[GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
Type "help", "copyright", "credits" or "license" for more information.
import re
s = "only the word in CAPS should be matched"
x=re.compile(r"\bin ([^\s]+)")
x.findall(s)
['CAPS']


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


Re: [Tutor] stopping greedy matches

2005-03-17 Thread Mike Hall
On Mar 16, 2005, at 8:32 PM, Kent Johnson wrote:
"in (.*?)\b" will match against "in " because you use .* which will 
match an empty string. Try "in (.+?)\b" (or "(?<=\bin)..+?\b" )to 
require one character after the space.

Another working example, excellent. I'm not too clear on why the back 
to back ".." in "(?<=\bin)..+?\b" )" makes the regex work, but it does.

You can't import it, you have to run it from the command line. I don't 
know if it is installed under Mac OSX though. You might be interested 
in RegexPlor:
http://python.net/~gherman/RegexPlor.html

RegexPlor looks fantastic, will be downloading. Thanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] stopping greedy matches

2005-03-17 Thread Mike Hall
I don't have that script on my system, but I may put pythoncard on here 
and run it through that:

http://pythoncard.sourceforge.net/samples/redemo.html
Although regexPlor looks like it has the same functionality, so I may 
just go with that. Thanks.

On Mar 17, 2005, at 1:31 AM, Michael Dunn wrote:
As Kent said, redemo.py is a script that you run (e.g. from the
command line), rather than something to import into the python
interpretor. On my OSX machine it's located in the directory:
/Applications/MacPython-2.3/Extras/Tools/scripts
Cheers, Michael
___
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] stopping greedy matches

2005-03-17 Thread Mike Hall
On Mar 17, 2005, at 11:11 AM, Kent Johnson wrote:
The first one matches the space after 'in'. Without it the .+? will 
match the single space, then \b matches the *start* of the next word.
I think I understand. Basically the first dot advances the pattern 
forward in order to perform a non-greedy match on the following 
word.(?) Very nice.

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


Re: [Tutor] stopping greedy matches

2005-03-18 Thread Mike Hall

On Mar 18, 2005, at 9:27 AM, Christopher Weimann wrote:

On 03/17/2005-10:15AM, Mike Hall wrote:
 Very nice sir. I'm interested in what you're doing here with 
the caret metacharacter. For one thing, why enclose it and the 
whitespace flag within a character class? 

A caret as the first charachter in a class is a negation.
So this [^\s]+ means match one or more of any char that
isn't whitespace.  

Ok, so the context of metas change within a class. That makes sense, but I'm unclear on the discrepancy below.

Does this not traditionally 
mean you want to strip a metacharacter of it's special meaning?


That would be \

Here's where I'm confused. From the Python docs: 

Special characters are not active inside sets. For example, [akm$] will match any of the characters "a", "k", "m", or "$"___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] stopping greedy matches

2005-03-18 Thread Mike Hall
On Mar 18, 2005, at 1:02 PM, Christopher Weimann wrote:
On 03/18/2005-10:35AM, Mike Hall wrote:
A caret as the first charachter in a class is a negation.
So this [^\s]+ means match one or more of any char that
isn't whitespace.
Ok, so the context of metas change within a class. That makes sense,
but I'm unclear on the discrepancy below.
The ^ means begining of line EXCEPT inside a charachter class. There it
means NOT for the entire class and it only means that if it is the very
first charachter. I suppose you could consider that the there are two
separate types of char classes. One is started with [ and the other is
started with [^.
Got it, thanks.


That would be \
Here's where I'm confused. From the Python docs:
Special characters are not active inside sets. For example, [akm$] 
will
match any of the characters "a", "k", "m", or "$"

And the next paragraphs says...
  You can match the characters not within a range by complementing the
  set. This is indicated by including a "^" as the first character of 
the
  class; "^" elsewhere will simply match the "^" character. For 
example,
  [^5] will match any character except "5".


The sad thing is I have read that paragraph before (but obviously 
hadn't absorbed the significance). I'm new to this, it'll sink in. 
Thanks.

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


[Tutor] .readlines() condensing multiple lines

2005-03-22 Thread Mike Hall
Unless I'm mistaken .readlines() is supposed to return a list, where 
each index is a line from the file that was handed to it. Well I'm 
finding that it's putting more than one line of my file into a single 
list entry, and separating them with \r. Surely there's a way to have a 
one to one correlation between len(list) and the lines in the file the 
list was derived from...? 

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


Re: [Tutor] .readlines() condensing multiple lines

2005-03-23 Thread Mike Hall

Liam, "rU" worked like a charm. My previous syntax where the lines were condensing was:

fOpen = file(f, "r")
fRead = fTmp.readlines()

In this instance the size of fRead would not correspond to my line numbers. With  fOpen = file(f, "rU") it now does. Thanks :) 


On Mar 22, 2005, at 7:15 PM, Liam Clarke wrote:

From the docs - 

In addition to the standard fopen() values mode  may be 'U' or 'rU'.
If Python is built with universal newline support (the default) the
file is opened as a text file, but lines may be terminated by any of
'\n', the Unix end-of-line convention, '\r', the Macintosh convention
or '\r\n', the Windows convention. All of these external
representations are seen as '\n'  by the Python program. If Python is
built without universal newline support mode 'U' is the same as normal
text mode. Note that file objects so opened also have an attribute
called newlines which has a value of None (if no newlines have yet
been seen), '\n', '\r', '\r\n', or a tuple containing all the newline
types seen.


So, try 

x = file(myFile, 'rU').readlines()

Or try:

x = file(myFile, 'rU')
for line in x:
#do stuff

Let us know how that goes. 

Regards, 

Liam Clarke

PS 

Worse come to worse, you could always do - 
x = file(myFile, 'r').read()
listX = x.split('\r')



On Tue, 22 Mar 2005 17:10:43 -0800, Mike Hall
<[EMAIL PROTECTED]> wrote:
Unless I'm mistaken .readlines() is supposed to return a list, where
each index is a line from the file that was handed to it. Well I'm
finding that it's putting more than one line of my file into a single
list entry, and separating them with \r. Surely there's a way to have a
one to one correlation between len(list) and the lines in the file the
list was derived from...?

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



-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.

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


Re: [Tutor] .readlines() condensing multiple lines

2005-03-23 Thread Mike Hall
On Mar 23, 2005, at 12:53 AM, Alan Gauld wrote:
Typically what happens is you view the file in an application
that autrowraps long lines so it looks like multiple lines on
screen but in fact it is one long line in the file. In that
case Python will only see the single long line.
I'm using subEthaEdit, which will autowrap long lines, but it also 
displays line numbers, so there's no doubt where one begins and ends :)

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


Re: [Tutor] .readlines() condensing multiple lines

2005-03-23 Thread Mike Hall
On Mar 23, 2005, at 3:17 AM, Kent Johnson wrote:
Anyway, Mike, it seems clear that your file has line endings in it 
which are not consistent with the default for your OS. If reading with 
universal newlines doesn't solve the problem, please let us know what 
OS you are running under and give more details about the data.
Kent, reading universal did indeed solve my problem, but for the record 
I'm on OSX, and was reading from a standard plain text file.

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


[Tutor] Python and Javascript

2005-03-25 Thread Mike Hall
I'm curious on whether or not JavaScript and Python can talk to each 
other. Specifically, can a python function be called from within a JS 
function? Admittedly this is probably more of a JavaScript than Python 
question, but I'd  love to know if anyone can at least point me in a 
direction to research this.

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


Re: [Tutor] Python and Javascript

2005-03-25 Thread Mike Hall
Ryan, I should clarify that what I'd like to do here is unrelated to 
the web. I'm actually just interested in using a local html page as a 
simple gui to launch python calls. So a JS event handler, say a button 
click, would then call a JS function which inside of it would call a 
Python function while handing it arguments (say a path that the JS 
queried from a field in the html page.) That kind of thing. It seems 
like it should be possible, and hopefully easy, but I have no 
experience in calling Python functions from other languages so I'm just 
looking for some input on that. Thanks,

-MH
On Mar 25, 2005, at 12:01 PM, Ryan Davis wrote:
Depends on your environment.
If your js is on a webpage, you can have it make http calls to a 
python web service.  Look for articles on XMLHttpRequest in
javascript to see some examples.

I don't know how else that could be done, but I imagine there are 
other ways.

Thanks,
Ryan
-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On 
Behalf Of Mike Hall
Sent: Friday, March 25, 2005 2:18 PM
To: tutor@python.org
Subject: [Tutor] Python and Javascript

I'm curious on whether or not JavaScript and Python can talk to each
other. Specifically, can a python function be called from within a JS
function? Admittedly this is probably more of a JavaScript than Python
question, but I'd  love to know if anyone can at least point me in a
direction to research this.
-MH
___
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 Javascript

2005-03-25 Thread Mike Hall
On Mar 25, 2005, at 12:41 PM, Alan Gauld wrote:
If you are using WSH on Windows and have the Python active scripting
installed then yes. Similarly if you use IE as web browser then it
can be done in a web page too.

I'm on OSX, and would be doing this through Safari most likely.
-MH
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python and Javascript

2005-03-25 Thread Mike Hall
On Mar 25, 2005, at 1:00 PM, Ryan Davis wrote:
Ok, that explains a lot, but I don't know of any easy way to do have 
javascript talk to python.

I can think of some horrible ways to do it, though.
1. Make a python web service running locally, and build up SOAP calls 
or HTTP posts to it. (same as I suggested earlier)
2. Use XUL and pyXPCOM to make a firefox extension that talks to 
python.  This is probably much more of a pain in the ass than you
want to do, but that's the only way I know of to directly call python 
functions from javascript.
3. Look into web framework Zope, that might have some of this plumbing 
done already.
4. Check out Sajax, http://www.modernmethod.com/sajax/, a framework to 
automate javascript calling your server-side functions.  It
was made for PHP, but looks to have a python version as well.

All of those but #2 require you to set up some kind of server.  Is 
there a reason it has to be an HTML page?

If not, making a GUI might be an alternative that sidesteps this 
altogether.

Yikes, that sounds pretty hairy. Maybe this kind of thing is not as 
straight forward as anticipated. Why HTML you say? Well I've been 
intrigued by Dashboard, which will be in the next OSX release. It 
allows you to create "widgets" which are essentially little html pages 
that do things. This got me thinking how I'd like to tie a small Python 
script I wrote into an html front end (ideally becoming a widget). It's 
looking like this may be trickier than anticipated. In any case, 
thanks.

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


Re: [Tutor] Python and Javascript

2005-03-25 Thread Mike Hall
Danny, great reply. I have looked a bit at pyObjC, and it does indeed 
look cool. I was however hoping to bypass that route altogether and go 
for the simplicity (I thought) that came with the html/js route. 
Perhaps a cocoa bundle is the only way to get what I'm after. Thanks,

-MH
On Mar 25, 2005, at 1:40 PM, Danny Yoo wrote:

Yikes, that sounds pretty hairy. Maybe this kind of thing is not as
straight forward as anticipated. Why HTML you say? Well I've been
intrigued by Dashboard, which will be in the next OSX release. It 
allows
you to create "widgets" which are essentially little html pages that 
do
things. This got me thinking how I'd like to tie a small Python 
script I
wrote into an html front end (ideally becoming a widget). It's looking
like this may be trickier than anticipated. In any case, thanks.
Hi Mike,
Interesting!
You probably know about this already, but PyObjC allows you to write 
Mac
OS X Cocoa applications in Python:

http://pyobjc.sourceforge.net/
and this is a well tested bridge to make Python classes integrate into
Cocoa applications.  For example,
http://www.pycs.net/bbum/2004/12/10/#200412101
mentions the use of PyObjC to make a Mac OS X screensaver.  So it 
appears
to embed very well.

According to the documentation from Apple's Dashboard developer site, 
we
can embed Cocoa bundles into Javascript (there's a brief mention of it
under "Custom Code Plug-ins":

http://developer.apple.com/macosx/tiger/dashboard.html
So in theory, we should be able to inject a Pythonified Cocoa bundle 
into
Dashboard, but then again, I've never tried this before.  *grin*

I haven't dived into doing Mac OS X development yet, but perhaps 
someone
on the PyObjC list might be able to cook up a quick-and-dirty example 
of
this for you.

Try asking on their list and see if you get some useful responses:
http://lists.sourceforge.net/lists/listinfo/pyobjc-dev
Best of wishes to you!

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


Re: [Tutor] Python and Javascript

2005-03-25 Thread Mike Hall
On Mar 25, 2005, at 4:53 PM, Alan Gauld wrote:
intrigued by Dashboard, which will be in the next OSX release. It
allows you to create "widgets" which are essentially little html
pages
There is an API for Dashboard and I'm pretty sure MacPython will
support it - it covers most of the cocoa type stuff. You might be
better checking out the Apple developer site for the Dashboard
hooks and loooking at MacPythons options.
Alan G.

Alan, thanks for pointing me towards a few good approaches to look at. 
Going through some of the developer information I've come across 
mention of JS extensions which allow for system calls within a JS 
function, which should pretty much do what I want. Thanks,

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


[Tutor] Launching a file browser

2005-03-28 Thread Mike Hall
I looked over the global module index and the closest thing I could find relating to my os (osx) was EasyDialogs, which has a few functions pertaining to this, "AskFileForOpen()" being one. Calling any function within EasyDialogs however yields an Apple Event error:

AE.AEInteractWithUser(5000)
MacOS.Error: (-1713, 'no user interaction is allowed')

I get the impression some of these "Mac" modules are more relevant to os 9 than 10(which is Unix), so maybe EasyDialogs is not the right choice here.  Any suggestions are appreciated.



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


Re: [Tutor] Launching a file browser

2005-03-28 Thread Mike Hall
On Mar 28, 2005, at 4:24 PM, [EMAIL PROTECTED] wrote:
So, you are writing a GUI app and you want some kind of open file 
dialog?  Won't
this depend on what toolkit you are using for your GUI?

If you are using Tkinter (which should work on OS X, I think), try:
import tkFileDialog
f = tkFileDialog.askopenfilename()
Check dir(tkFileDialog) for other functions.
But other GUI toolkits will have their own functions.
I my case the gui will be comprised of html and javascript, talking to 
python through system calls. I basically want to know if there's an 
equivalent of the "webbrowser()" module (which launches my browser) for 
file dialogs. This is what EasyDialogs should do, but does not.

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


Re: [Tutor] Launching a file browser

2005-03-31 Thread Mike Hall
On Mar 31, 2005, at 12:21 AM, Max Noel wrote:
It's been too long since I used Python on MacOSX, but IIRC you can't 
just run a Python GUI program from the shell. Or something like 
that...you should ask this one on the python-mac SIG mailing list:
http://www.python.org/sigs/pythonmac-sig/

Kent
	You have to launch your script with pythonw, not with python.
I'm unclear on why a command like webbrowser.open() will comfortably 
launch your default web browser (in my case Safari), but something as 
ubiquitous to an OS as a file browser has special needs to launch. 
Perhaps each application has custom written their file browser, and I'm 
assuming they are each essentially doing system calls to the same 
thing...?

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


Re: [Tutor] Launching a file browser

2005-03-31 Thread Mike Hall
Ah, so it has to do with access to the window manager. That answers a 
lot, thanks.

On Mar 31, 2005, at 4:09 PM, Max Noel wrote:
On Apr 1, 2005, at 00:14, Mike Hall wrote:
On Mar 31, 2005, at 12:21 AM, Max Noel wrote:
It's been too long since I used Python on MacOSX, but IIRC you 
can't just run a Python GUI program from the shell. Or something 
like that...you should ask this one on the python-mac SIG mailing 
list:
http://www.python.org/sigs/pythonmac-sig/

Kent
	You have to launch your script with pythonw, not with python.
I'm unclear on why a command like webbrowser.open() will comfortably 
launch your default web browser (in my case Safari), but something as 
ubiquitous to an OS as a file browser has special needs to launch. 
Perhaps each application has custom written their file browser, and 
I'm assuming they are each essentially doing system calls to the same 
thing...?
	No, the reason for that, IIRC, is that for the program to be able to 
interact with the window manager, it has to be launched with pythonw. 
When the program starts to display stuff elsewhere than in STDOUT or 
STDERR, an application launch is somehow triggered (icon appears in 
the Dock), which for some reason enables the user to interact with the 
program.
	Launching a web browser requires no interaction whatsoever with the 
WM, and can therefore be done with python.

	Yes, the python/pythonw distinction in Mac OS X is stupid, I'll give 
you that. I don't even know why it exists in the first place.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge 
a perfect, immortal machine?"



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


Re: [Tutor] What is the best book to start?

2005-04-01 Thread Mike Hansen

Subject:
Re: [Tutor] What is the best book to start?
From:
"Alan Gauld" <[EMAIL PROTECTED]>
Date:
Fri, 1 Apr 2005 09:05:16 +0100
To:
"Hoffmann" <[EMAIL PROTECTED]>, 
To:
"Hoffmann" <[EMAIL PROTECTED]>, 

I am starting to studying Python. I have some previous
experience with C (beginner level).

Probably the standard tutorial on the web site is the best
place for you to start.

"Learning Python" by Lutz & Ascher,

And this is very good supporting material.

"Python How to Program" by Deitel and others.

And this is particularly good as an intro into the wider areas
such as PyGame, XML/HTML GUIs and Network programming. The early
chapters are done better IMHO by Lutz, aand the official tutor.
Your next purchase should be either or both of:
Python in a Nutshell - a great 'pocket' reference and
Python Programming on Win32 - but only if you are using Windows of
course!
You have more than enough beginner material already.
Alan G.
I'd also try to fit in Dive Into Python [http://diveintopython.org/]. This book 
really got me hooked on Python. It assumes you know some programming.

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


[Tutor] Script (Python) for Zope

2005-04-03 Thread Mike Jaeger
Hello,

I am looking for a Python-script for Zope which counts the objects (files) in 
the current folder and all its subfolders, but I don't know how to implement 
this script. Can somebody help me, please?
Or ist there a newsgroup/mailing list which can help me to find a solution for 
this problem?
Thanks.

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


Re: [Tutor] Launching a file browser

2005-04-04 Thread Mike Hall
On Apr 1, 2005, at 4:12 PM, Jeff Shannon wrote:
At the OS level, these two actions are *completely* different.  The
webbrowser module launches an entirely separate program in its own
independent process, where the "file browser" is opening a standard
dialog inside of the current process and dependent upon the current
process' message loop.  (AFAIK, every GUI environment uses some sort
of message/event loop...)
I don't know Macs, but on Windows, the closest "file browser" parallel
to what the webbrowser module is doing would be
os.system("explorer.exe"), which launches a separate program in an
independent process.  However, if you're trying to get the results of
the file selection back into your own app, you need to do the file
browsing within your own process (or explicitly use some form of
inter-process communication).  In order to use a GUI file-browsing
dialog, you need to follow all the rules for a GUI program.
Thanks Jeff. This further clarifies it for me.
-MH
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] building strings of specific length

2005-04-04 Thread Mike Hall
You can chop off anything past 72 characters with:
s2 = s[:72]
On Apr 4, 2005, at 7:04 AM, Vines, John (Civ, ARL/CISD) wrote:
Hello. I have a question regarding strings.  How do I format a string 
to be a specific length?
For example I need 'string1' to be 72 characters long.

Thanks for your time,
John
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
-MH
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Pychecker

2005-04-22 Thread Mike Hansen
I had a frustrating time yesterday with a small Python program I wrote. I wasn't 
getting the results I expected, so I sprinkled print statements through it. I 
wasn't getting anywhere. I tossed it into Komodo to see if the background syntax 
checker would pick up something I was missing. I then stepped through it and 
finally noticed that I had messed up a variable name.

firstlist = [listItem[:12] for listItem in firstList]
 ^
when I meant
firstList = [listItem[:12] for listItem in firstList]
 ^
doh!
Later, I realized that I should have run it through Pychecker which would have 
picked it up immediately.

With that experience of learning the hard way, I'd recommend that you always run 
your code through Pychecker just after editing it and before running it.

In Perl, you can perl -c somehardtoreadperlprogram.pl that will just check the 
syntax. The above problem would have been caught in Perl since I always use 
strict. Is there a command line option in Python to do a Pychecker-like syntax 
check? I see a -t to check the tabs, but nothing to tell it to check the syntax 
but don't run it. If not, should Pychecker be part of the standard distribution? 
Am I missing something?

Mike
Go ahead and reply to me AND the list since I just get the digest.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pychecker

2005-04-22 Thread Mike Hansen
Thanks Danny.
I'll make sure I use pychecker so I don't shoot myself in the foot with not so 
easy to catch typos in variable names and syntax blunders.

I might check with the pychecker devs to see if there's any effort to get it put 
into the standard distribution. I think it's too handy to not have it in the 
standard distribution.

Mike
Danny Yoo wrote:
On Fri, 22 Apr 2005, Danny Yoo wrote:

In Perl, you can perl -c somehardtoreadperlprogram.pl that will just
check the syntax. The above problem would have been caught in Perl
since I always use strict. Is there a command line option in Python to
do a Pychecker-like syntax check?
Hi Mike,
Unfortunately, no, because there are some really funky things that one
can do in Python that you can't do easily in Perl.

Yikes.  I should correct myself before I get someone angry at me. You can
do this sort of late-binding stuff in Perl too, and in many other
languages.  (Java's reflection mechanism is another kind of late-binding
mechanism, for example.)
But Python makes it extraordinarly easy --- perhaps too much so.  *grin*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Use Strict or Use Warnings was ( Lists of files)

2005-05-17 Thread Mike Hansen
> 
> 
> Subject:
> Re: [Tutor] Lists of files
> From:
> William O'Higgins <[EMAIL PROTECTED]>
> Date:
> Mon, 16 May 2005 15:50:37 -0400
> 
> 
[...]
> 
> One last thing - is there an equivalent of the "use strict" and "use
> warnings" pragmas in Python?  Thanks.

The closest thing I've found is PyChecker. It's kind of like
perl -c hardtoreadperlscript.pl

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


[Tutor] Python debugger under Tiger?

2005-05-18 Thread Mike Hall
Does anyone know of a Python debugger that will run under OSX 10.4? The Eric debugger was looked at, but it's highly unstable under Tiger. Thanks.-MH___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python debugger under Tiger?

2005-05-18 Thread Mike Hall
I should of specified that I'm looking for an IDE with full  
debugging. Basically something like Xcode, but with Python support.


On May 18, 2005, at 3:10 PM, [EMAIL PROTECTED] wrote:

> Quoting Mike Hall <[EMAIL PROTECTED]>:
>
>
>> Does anyone know of a Python debugger that will run under OSX 10.4?
>> The Eric debugger was looked at, but it's highly unstable under
>> Tiger. Thanks.
>>
>
> pdb should work :-)
>
> -- 
> John.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

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


[Tutor] Python debugger under Tiger?

2005-05-19 Thread Mike Hansen
> Subject:
> Re: [Tutor] Python debugger under Tiger?
> From:
> Mike Hall <[EMAIL PROTECTED]>
> Date:
> Wed, 18 May 2005 15:54:18 -0700
> To:
> [EMAIL PROTECTED]
> 
> To:
> [EMAIL PROTECTED]
> CC:
> tutor@python.org
> 
> 
> I should of specified that I'm looking for an IDE with full  debugging. 
> Basically something like Xcode, but with Python support.
> 
> 
> On May 18, 2005, at 3:10 PM, [EMAIL PROTECTED] wrote:
> 
>> Quoting Mike Hall <[EMAIL PROTECTED]>:
>>
>>
>>> Does anyone know of a Python debugger that will run under OSX 10.4?
>>> The Eric debugger was looked at, but it's highly unstable under
>>> Tiger. Thanks.
>>>
>>
>> pdb should work :-)
>>
>> -- 
>> John.
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>

It's too bad that Activestate doesn't have a version of Komodo that runs under 
OS X. They have Windows, Linux, and Solaris, but not OS X.

I wonder if Eclipse using PyDev has visual debugging/stepping/watching that you 
are looking for?

You might want to ask on the python mac mail list
http://mail.python.org/mailman/listinfo/pythonmac-sig

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


Re: [Tutor] Python debugger under Tiger?

2005-05-19 Thread Mike Hall
Great recommendation, thanks.-MHOn May 18, 2005, at 8:12 PM, Lee Cullens wrote:Mike,You may not be looking for a commercial IDE, but I am very happy with  WingIDE and using it with Tiger.Lee COn May 18, 2005, at 6:54 PM, Mike Hall wrote: I should of specified that I'm looking for an IDE with fulldebugging. Basically something like Xcode, but with Python support.On May 18, 2005, at 3:10 PM, [EMAIL PROTECTED] wrote: Quoting Mike Hall <[EMAIL PROTECTED]>: Does anyone know of a Python debugger that will run under OSX 10.4?The Eric debugger was looked at, but it's highly unstable underTiger. Thanks. pdb should work :-)-- John.___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Filtering Spreadsheet Data

2005-05-24 Thread Mike Hansen
> Subject:
> [Tutor] Filtering Spreadsheet Data
> From:
> Luke Jordan <[EMAIL PROTECTED]>
> Date:
> Mon, 23 May 2005 15:30:33 -0500
> To:
> tutor@python.org
> 
> To:
> tutor@python.org
> 
> 
> Hi All,
> 
> I have several frighteningly cumbersome reports to review at my new
> job. I would like to write a python program to help me with my
> analysis. The goal of the program is to filter out information that
> doesn't meet certain requirements and print  relevant results back to
> a legible report that I can do detailed research and analysis on. The
> reports come to me in Excel format.
> 
> I have a solid understanding of basic programming.
> 
> Any guidance/advice/starting points would be greatly appreciated.
> 
> Thanks!
> 
> Luke
> 

Excel has some nice database-like queries itself. Take a look at Advanced 
Filter 
in Help. You can essentially query a worksheet and even send the results to a 
different worksheet. I'd imagine that once you got the query working, you could 
automate it using VBA or Python.

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


Re: [Tutor] Planning a program with algorithm?

2005-06-01 Thread Mike Hansen

> 
> 
> Subject:
> [Tutor] Planning a program with algorithm?
> From:
> ". ," <[EMAIL PROTECTED]>
> Date:
> Sun, 29 May 2005 19:21:33 +
> To:
> tutor@python.org
> 
> To:
> tutor@python.org
> 
> 
> I know how to write a prog.
> 
> But, I don't know how to plan a prog. with algorithm.
[...]
> 
> Any useful advice for algorithm would be appreciated.
> 
> Thanks.

You might want to take a look at the book Code Complete. It really covers the 
nuts and bolts of software construction.

http://www.cc2e.com/

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


[Tutor] question about "hiding" a function/method in a class

2005-06-03 Thread Mike Hansen
I haven't done much OO in Python yet. For various web apps we write, we usually 
write up a DB schema in a spreadsheet. Then we write the sql script that would 
create the tables in the database. I thought it would be neat to save the 
spreadsheet as a csv file and have python write the sql script. So I started to 
write the Python program.

-
#!/usr/bin/env python

"""
SQLGEN takes a csv file of a database schema and writes the sql script that 
will 
create the
tables and fields in the database

Mike Hansen Jun 2005

"""

class DBField(object):
 def __init__(self, fieldName):
 self.fieldName = fieldName
 self.type = ""
 self.size = 0
 self.notNull = False
 self.unique = False
 self.references = ""
 self.default = ""

 def printField(self):
 self.fieldStr = "%s %s" %(self.fieldName, self.type)
 if self.size > 0:
 self.fieldStr = "%s(%s)" %(self.fieldStr, self.size)
 if self.notNull:
 self.fieldStr = "%s NOT NULL" %self.fieldStr
 if self.unique:
 self.fieldStr = "%s UNIQUE" %self.fieldStr
 if self.default:
 self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, self.default)
 # if self.references
 return self.fieldStr

 def __getattr__(self, attrname):
 if attrname == "fieldStr":
 return self.printField()
 else:
 raise AttributeError, attrname

def main():
 pass

def test():
 areas = DBField("area")
 areas.type = "VARCHAR"
 areas.size = 80
 areas.notNull = True
 areas.unique = True
 print areas.fieldStr
 stuff = DBField("stuff")
 stuff.type = "INTEGER"
 stuff.notNull = True
 print stuff.fieldStr


if __name__ == "__main__":
 # main()
 test()
---

I was wondering if I should "hide" the printField function, so I or someone 
else 
won't do x.printField() in the main program but use the x.fieldStr attribute. 
If 
so, how would I do that, def __printField(self):? How would I call it from 
__getattr__? I know I'm not really hiding it ;just mangling it. On the other 
hand, I guess it doesn't matter. What do you think?

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


Re: [Tutor] question about "hiding" a function/method in a class

2005-06-03 Thread Mike Hansen
> Subject:
> Re: [Tutor] question about "hiding" a function/method in a class
> From:
> Kent Johnson <[EMAIL PROTECTED]>
> Date:
> Fri, 03 Jun 2005 09:45:20 -0400
> 
> CC:
> tutor@python.org
> 
> 
> Mike Hansen wrote:
> 
>> class DBField(object):
>>  def __init__(self, fieldName):
>>  self.fieldName = fieldName
>>  self.type = ""
>>  self.size = 0
>>  self.notNull = False
>>  self.unique = False
>>  self.references = ""
>>  self.default = ""
>>
>>  def printField(self):
>>  self.fieldStr = "%s %s" %(self.fieldName, self.type)
>>  if self.size > 0:
>>  self.fieldStr = "%s(%s)" %(self.fieldStr, self.size)
>>  if self.notNull:
>>  self.fieldStr = "%s NOT NULL" %self.fieldStr
>>  if self.unique:
>>  self.fieldStr = "%s UNIQUE" %self.fieldStr
>>  if self.default:
>>  self.fieldStr = "%s DEFAULT %s" %(self.fieldStr, 
>> self.default)
>>  # if self.references
>>  return self.fieldStr
>>
>>  def __getattr__(self, attrname):
>>  if attrname == "fieldStr":
>>  return self.printField()
>>  else:
>>  raise AttributeError, attrname
>> ---
>>
>> I was wondering if I should "hide" the printField function, so I or 
>> someone else won't do x.printField() in the main program but use the 
>> x.fieldStr attribute. If so, how would I do that, def 
>> __printField(self):? How would I call it from __getattr__? I know I'm 
>> not really hiding it ;just mangling it. On the other hand, I guess it 
>> doesn't matter. What do you think?
> 
> 
> Python programmers tend to take the attitude "We're all adults here" 
> towards things like this. We use conventions to put warning labels where 
> appropriate, then trust the client programmer to do what is right for them.
> 
> So, to answer your direct question, yes, you could call the method 
> __printField(), which nominally hides the name from other modules, or 
> _printField(), which by convention marks the method as for internal use 
> only (a warning label). You would call it from __getattr__() as 
> __printField() or _printField(). (A quick experiment would have answered 
> this part of the question.)
> 
> However, for your particular usage of dynamically computing the value of 
> a field, there is a better way to do this - use a property.
> 
> class DBField(object):
>  def _printField(self):
>...
> 
>  # Create a read-only fieldStr attribute whose value is computed by 
> _printField()
>  fieldStr = property(_printField)
> 
>  # Remove _printField so it can't be called directly
>  del _printField
> 
> 
> A few more comments:
> - The name _printField() is a bit of a misnomer since nothing is 
> printed; _getFieldStr() might be a better name.
> - Another, simpler way to do this is to define __str__() instead of 
> _printField() and fieldStr; then clients can just call str(field) to get 
> the string representation. This will work well if you don't need any 
> other string representation.
> - Of course you could also just define getFieldStr() and forget about 
> the fieldStr attribute entirely. This is also a very simple, 
> straightforward approach.
> 
> Kent
> 

Doh, I forgot about properties! If I had read a little more in Learning Python 
on the page with __getattr__, I might have noticed properties.

I might go with the "Simple is better than complex" approach using 
getFieldStr().

I agree that printField wasn't sounding like a good name.

Thanks for the comments.

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


Re: [Tutor] question about "hiding" a function/method in a class

2005-06-03 Thread Mike Hansen

Alan G wrote:
>>I haven't done much OO in Python yet. For various web apps we write,
> 
> we usually
> 
>>write up a DB schema in a spreadsheet.
> 
> 
> Wow! How exactly do you represent a schema in a spreadsheet?
> I confess I cannot conceive of such a thing. Can you send a
> representative sample to illustrate?
> 

Maybe it's not a "schema" exactly.

|Table Name|Fields  |Type   |Size|Primary Key|Not Null|Unique|Foreign Key| ...
|areas |area_id |serial ||x  |x   |x |   |
|  |area|varchar|80  |   |x   |x |   |
|  |enabled |boolean||   |x   |  |   |

|'s represent each cell. It's just a way to organize your thoughts, and have 
something a little more readable than an SQ script for a DB schema. There's 
been 
less than 20 tables in a database for most of these applications that we write. 
It's clear enough to see the relations(there's another column references).

> 
>>create the tables in the database. I thought it would be neat to
> 
> save the
> 
>>spreadsheet as a csv file and have python write the sql script. So I
> 
> started to
> 
>>write the Python program.
> 
> 
> You do know that there are lots of ERD programs that allow you to draw
> the schema as an ERD and generate the SQL DDL directly? In fact even
> Visio
> can do that.
> 
> Alan G.
> 

Can you point me to some Open Source/Free ERD programs that work with 
Postgre?(I'll google after I send this message.) I'd certainly would like to 
look at ways to do this better. Last time I looked at Visio which was Visio 
2000, the ERD stuff cost extra and was very unstable.

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


Re: [Tutor] Controlling Where My Program Ends

2005-06-15 Thread Mike Hansen
> Subject:
> Re: [Tutor] Controlling Where My Program Ends
> From:
> Don Parris <[EMAIL PROTECTED]>
> Date:
> Tue, 14 Jun 2005 23:03:59 -0400
> To:
> tutor@python.org
> 
> To:
> tutor@python.org
> 
> 
> On Wed, 15 Jun 2005 00:59:24 -
> "DC Parris" <[EMAIL PROTECTED]> wrote:
> 
> 
>>Never mind.  I found it - sys.exit()
>>
>>Sorry to have wasted the bandwidth/time.
>>-- 
> 
> 
> This was in reference to a post about exiting from a program.  I couldn't
> figure out why my program wouldn't let me exit from within a sub-menu of the
> console interface.  Since my webmail client goofed up the "from" header, it
> never showed up, and I've cancelled it to avoid wasting everyone's time
> further. I found sys.exit() in the library reference, which allows me to do
> what I want.
> 
> Don
> 

If you use the if __name__ == '__main__': idiom, then you can just use return 
instead of sys.exit()

def main():
 lotsa interesting python code
 if somethinorother:
 # sys.exit()
 return
 more interesting python code

if __name__ == '__main__':
 main()

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


[Tutor] loading an image into a Postgre database

2005-06-21 Thread Mike Hansen
I'm having trouble loading an image into a Postgre database. The code is below 
as well as the traceback in the apache log. Is something up with my 
sqlStatement? Do I need to use something other than %s? How can I avoid that 
type error?

Thanks,

Mike


#! /usr/bin/env python

import cgi
from pyPgSQL import PgSQL
# from pyPgSQL.PgSQL import PgBytea

def main():
 form = cgi.FieldStorage()
 if form.has_key("filename"):
 item = form["filename"]
 imageName = form["imagename"]
 if item.file:
 data = item.file.read()
 data_obj = PgSQL.PgBytea(data)
 connectdb =PgSQL.connect('server:port:database:username:password')
 cur = connectdb.cursor()
 sqlStatement = """INSERT INTO images (image)
   VALUES (%s);
""" % (data_obj)
 cur.execute(sqlStatement)
 cur.close()
 connectdb.commit()
 print "Content-type: text/html\n\n"
 print "image loaded"


if __name__ == '__main__':
 main()


Traceback (most recent call last):
   File "/var/www/htdocs/mtest/imagetest.py", line 28, in ?
 main()
   File "/var/www/htdocs/mtest/imagetest.py", line 20, in main
 cur.execute(sqlStatement)
   File "/usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3038, in 
execute
 self.res = self.conn.conn.query(_qstr)
TypeError: query() argument 1 must be string without null bytes, not str
[Tue Jun 21 14:34:46 2005] [error] [client 10.95.100.11] Premature end of 
script 
headers: /var/www/htdocs/mtest/imagetest.py10.95.100.11] Premature end of script
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loading an image into a Postgre database

2005-06-22 Thread Mike Hansen
Thanks Danny. That did the trick. I think I had thought about putting the 
variables in the execute statement, but I didn't run across any examples. I'll 
need to read the DB API 2.0 docs some more.

Mike

Danny Yoo wrote:
>>Thankfully, you don't have to change much to fix the formatting bug.  The
>>only thing you'll need to do is let the SQL cursor do the value formatting
>>for you:
>>
>>##
>>sqlStatement = """INSERT INTO images (image)
>>  VALUES (%s);
>>cur.execute(sqlStatement, (data_obj))
>>##
> 
> 
> 
> Hi Mike,
> 
> 
> Gaaa.  I was a little sloppy there, wasn't I?  Let me fix that:
> 
> ##
> sqlStatement = """INSERT INTO images (image)
>   VALUES (%s);"""
> cur.execute(sqlStatement, (data_obj,))
> ##
> 
> 
> My apologies!
> 

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


[Tutor] getting an image out of a postgre database

2005-06-23 Thread Mike Hansen
Well, I've managed to get an image into a postgre database, but now I'm having 
trouble getting it out.

#! /usr/bin/env python

from pyPgSQL import PgSQL

def main():
 connectdb = PgSQL.connect('server:port:database:username:password')
 cur = connectdb.cursor()
 sqlStatement = """SELECT image from images where image_id = 1"""
 cur.execute(sqlStatement)
 rec = cur.fetchone()
 # TODO make temp file name include image_id.
 # TODO use tempfile module
 # TODO clean up old temp files
 tempFileName = "1.jpg"
 tempFile = open(tempFileName, "w")
 tempFile.write(rec[0])
 tempFile.close()
 cur.close()

 print "Content-type: text/html\n\n"
 print """"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>

http://www.w3.org/1999/xhtml";>










"""

if __name__ == '__main__':
 main()

Traceback (most recent call last):
   File "./dispimage.py", line 39, in ?
 main()
   File "./dispimage.py", line 16, in main
 tempFile.write(rec[0])
TypeError: argument 1 must be string or read-only character buffer, not instance

So, rec[0] is an instance, but an instance of what? Since I needed to use the 
PgSQL.PgBytea method on the image before inserting it into the database, do I 
need to use a similar method to undo what PgBytea did to it, or am I 
incorrectly 
writing this binary data? I tried PgSQL.PgUnQuoteBytea(rec[0]), but that didn't 
work.

If this is more appropriate for another mail list, let me know.

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


  1   2   3   4   >