Re: [Tutor] I love python / you guys :)

2009-11-16 Thread OkaMthembo
Stefan, you echoed my thinking too :)

On Mon, Nov 16, 2009 at 8:58 AM, Stefan Lesicnik  wrote:

> hi,
>
> Although not a question, i just want to tell you guys how awesome you are!
>
> I am not a programmer, i can do a bit of bash. I have never officially
> learnt programming, but numerous times looked at some perl, c, java
> and never really gotten past the beginning stages of it. That all
> changed when i picked up python. Although my style and use of python
> is probably barbaric at best, I really enjoy it when you can make
> things work. Python was just amazing from a readability / logical
> point of view. If i can think of something, there is a way to do it in
> python. After learning the simple data structures it seems i can
> really do anything i want to.
>
> I really appreciate all the effort the knowledgeable guys put into
> this list (you know who you are! you post answers all the time!). I've
> asked a couple of questions and the answers have always been excellent
> and i've learnt so much.
>
> So i guess i just wanted to say thanks for supporting a great
> language, and helping me as i learn to shape my thinking into better
> and better ways to do things.
>
> stefan
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


[Tutor] Apologies for sent spam

2009-11-16 Thread Albert-Jan Roskam
Hi,
 
I just noticed that a spam message was sent with my email address. Apologies.
I have no idea what caused that. I'll check my windows machine for viruses. Or 
could it have some other cause? Perhaps I should also change my password.

Cheers!!
Albert-Jan

~~
Before you criticize someone, walk a mile in their shoes, that way 
when you do criticize them, you're a mile away and you have their shoes! 
~~


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


Re: [Tutor] Writing code while tired, counterproductive?

2009-11-16 Thread Luke Paireepinart
I hate to be the odd one out here, but I actually find that I am extremely
productive when I'm tired.  It's easier for me to commit completely to the
code, when I'm well-rested I dream about running through fields of
sunflowers and such, get distracted more easily.  The code I write when I'm
tired is usually of marginally worse quality, but it's usually easy to audit
it when I'm rested and fix any problems.  Although if I'm trying to solve
something particularly difficult, especially something I've never done
before, sometimes I won't be able to do it until I wake up a bit.  Note that
this is for being tired, not exhausted.  If I'm exhausted I write a whole
lot of awful code that I have to completely rewrite when I wake up.

On Mon, Nov 16, 2009 at 12:57 AM, OkaMthembo  wrote:

> >From first-hand experience, i would concur :)
>
> A refreshed mind will perform much better than an over-exerted one.
>
>
> On Sat, Nov 14, 2009 at 8:57 PM, Alan Gauld wrote:
>
>>
>> "Modulok"  wrote
>>
>>  Does anyone else find, writing code while tired to be counterproductive?
>>>
>>
>> Yes. Doing anything that is mentally taxing is usually a bad idea when
>> tired!
>>
>> Alan G
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Regards,
> Lloyd
>
> ___
> 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] nul file in Windows

2009-11-16 Thread Timo

Dave Angel schreef:

Timo List wrote:

For my program I disable the py2exe log feature by routing output to the
nul-file.
Code:

if win32 and py2exe:
sys.stdout = open("nul", "w")
sys.stderr = open("nul", "w")

This always worked fine.

Today, I received an email from a user with the following error:
IOError: [Errno 2] No such file or directory: 'nul'

Now, I thought the nul-file always existed, shouldn't it?
Is there another way to disable output, if this one fails?

Cheers,
Timo

  
All you need is an object that behaves like a file, but does nothing 
with the data sent to it.  That's what duck-typing is all about.


I haven't tried it, but I'd start by making a new class:

class  NullFile(object):
   def __init__(self, *arg, **kwarg):
pass
   def write(self, data, *arg, **kwarg):
   pass
def close(self, *arg, **kwarg):
  pass

and just say
   sys.stdout = NullFile()

Thanks, this is what I was looking for.



If you get any exceptions, you could add new methods to this file, 
accordingly.

I already catch exceptions with my own function:
   sys.excepthook = self.exception_hook

Disabling stdout and stderr is to prevent py2exe from generating it's 
own logreport on exceptions.


Cheers,
Timo




DaveA



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


Re: [Tutor] Unexpected iterator

2009-11-16 Thread Alan Gauld


"spir"  wrote


Unpacking is rarely needed. It matches some kind of problems.

...
(parens not needed) It's just an elegant manner to avoid indexing --  
right?


Regarding tuple unpacking...
Absolutely, its a convenience.

Regarding struct unpacking, its an absolute necessity in getting data
out of a binary stream.

Alan G 



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


[Tutor] GzipFile has no attribute '__exit__'

2009-11-16 Thread Stephen Nelson-Smith
I'm trying to write a gzipped file on the fly:

merged_log = merge(*logs)

with gzip.open('/tmp/merged_log.gz', 'w') as output:
for stamp, line in merged_log:
output.write(line)

But I'm getting:

Traceback (most recent call last):
  File "./magpie.py", line 72, in 
with gzip.open('/tmp/merged_log.gz', 'w') as output:
AttributeError: GzipFile instance has no attribute '__exit__'

What am I doing wrong, and how do I put it right?

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


Re: [Tutor] Unexpected iterator

2009-11-16 Thread Kent Johnson
On Mon, Nov 16, 2009 at 12:17 AM, spir  wrote:
> Le Sun, 15 Nov 2009 19:23:33 -,
> "Alan Gauld"  s'exprima ainsi:
>
>> What does 'unpack' mean?  I've seen a few Python errors about packing
>> and unpacking.  What does it mean?
>
> Unpacking is rarely needed. It matches some kind of problems.

Not needed, I suppose, since there is another way to write the code,
but using tuple unpacking can greatly reduce the length and improve
the readability of your code.

> Imagine you parse "codes" each made of name-sep-number. Then when walking 
> through the result you can write:
> for code in codes:
>        (name,sep,number) = code

Or even
  for name, sep, number in codes:
# Do something with name, sep, number

> It's just an elegant manner to avoid indexing -- right?

It avoids indexing and gives meaningful names to values. Compare the
above with the alternatives:
  for code in codes:
name = code[0]
sep = code[1]
number = code[2]
# Do something with name, sep, number

or

  for code in codes:
# Do something with code[0], code[1], code[2]

The first alternative is much more verbose while the second one is
much harder to understand.

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


Re: [Tutor] I love python / you guys :)

2009-11-16 Thread bibi midi
On Mon, Nov 16, 2009 at 1:58 AM, Stefan Lesicnik  wrote:

> hi,
>
> Although not a question, i just want to tell you guys how awesome you are!
>
> I am not a programmer, i can do a bit of bash. I have never officially
> learnt programming, but numerous times looked at some perl, c, java
> and never really gotten past the beginning stages of it. That all
> changed when i picked up python. Although my style and use of python
> is probably barbaric at best, I really enjoy it when you can make
> things work. Python was just amazing from a readability / logical
> point of view. If i can think of something, there is a way to do it in
> python. After learning the simple data structures it seems i can
> really do anything i want to.
>


Hi Stefan,

Your message mirrored my current state. There's TONS to learn in linux like
bash, perl, vim, sed, awk, python, etc. Too much to put in your head and in
the end makes you half-baked e.g. good at start but fades away in the end.
Anyway i hope to follow your lead and be one among the guys here
knowledgeable of the language.

In the same lines of if-you-can-think-of-anything-python-can-do-it i got
inspired to ask a question for the gurus:

When i use our company's LAN i set my proxy variable by hand in .bashrc.
There are 4 files to insert proxy variable:

in ~/.bashrc, /root/.bashrc, /etc/wgetrc and /etc/apt/apt.conf.

The last one is actually rename e.g. mv to apt.conf to activate proxy and mv
to apt.conf.bak to deactivate. The proxy variable is something like this

export http_proxy=http://username:passw...@proxy:port
ftp_proxy=$http_proxy

To activate i uncomment them then source .bashrc. To deactivate i put back
the comment sign. I do it all in vim e.g. vim -o the-3-files-above. For
apt.conf see rename above. I deactivate because i have another internet
connection option via 3G usb modem. But thats another story.

I will do this myself in python so please show me the way. Surely this can
be done.



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


Re: [Tutor] GzipFile has no attribute '__exit__'

2009-11-16 Thread Kent Johnson
On Mon, Nov 16, 2009 at 5:58 AM, Stephen Nelson-Smith
 wrote:
> I'm trying to write a gzipped file on the fly:
>
> merged_log = merge(*logs)
>
> with gzip.open('/tmp/merged_log.gz', 'w') as output:
>    for stamp, line in merged_log:
>        output.write(line)
>
> But I'm getting:
>
> Traceback (most recent call last):
>  File "./magpie.py", line 72, in 
>    with gzip.open('/tmp/merged_log.gz', 'w') as output:
> AttributeError: GzipFile instance has no attribute '__exit__'
>
> What am I doing wrong, and how do I put it right?

gzip.open() doesn't support the context manager protocol needed for it
to be used in a 'with' statement. Just do this old-style:

output = gzip.open('/tmp/merged_log.gz', 'w')
try:
   for stamp, line in merged_log:
   output.write(line)
finally:
  output.close()

See PEP 343 this explanation of context managers if you want to know
why you got this specific error:
effbot.org/zone/python-with-statement.htm
http://www.python.org/dev/peps/pep-0343/

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


Re: [Tutor] GzipFile has no attribute '__exit__'

2009-11-16 Thread Dave Angel

Stephen Nelson-Smith wrote:

I'm trying to write a gzipped file on the fly:

merged_log = merge(*logs)

with gzip.open('/tmp/merged_log.gz', 'w') as output:
for stamp, line in merged_log:
output.write(line)

But I'm getting:

Traceback (most recent call last):
  File "./magpie.py", line 72, in 
with gzip.open('/tmp/merged_log.gz', 'w') as output:
AttributeError: GzipFile instance has no attribute '__exit__'

What am I doing wrong, and how do I put it right?

S.

  
(I get the same result in CPython 2.6, but you should have told your 
python version and OS, just so people can tell you version-specific 
problems.)


In order to use the "with" syntax with an object of a particular class, 
that class has to support the Context Manager protocol, which includes 
both __enter__() and __exit__() methods.  I don't know why the system 
checks first for __exit__(), but there you have it.


GzipFile() class doesn't have such methods (in version 2.6), and 
therefore doesn't support the Context Manager.  So you have to do it the 
"old fashioned" way, with explicit close() method, and a 
try/except/finally.  And unlike regular text files, I don't expect 
you'll find a new file at all usable, if it wasn't properly closed.



Alternatively, you could subclass it, and write your own.  At a minimum, 
the __exit__() method should close() the stream.


DaveA

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


[Tutor] proxy switcher - was Re: I love python / you guys :)

2009-11-16 Thread Stefan Lesicnik
On Mon, Nov 16, 2009 at 1:36 PM, bibi midi  wrote:
>
>
> On Mon, Nov 16, 2009 at 1:58 AM, Stefan Lesicnik  wrote:
>>
>> hi,
>>
>> Although not a question, i just want to tell you guys how awesome you are!
>>
>> I am not a programmer, i can do a bit of bash. I have never officially
>> learnt programming, but numerous times looked at some perl, c, java
>> and never really gotten past the beginning stages of it. That all
>> changed when i picked up python. Although my style and use of python
>> is probably barbaric at best, I really enjoy it when you can make
>> things work. Python was just amazing from a readability / logical
>> point of view. If i can think of something, there is a way to do it in
>> python. After learning the simple data structures it seems i can
>> really do anything i want to.
>
>
> Hi Stefan,
>
> Your message mirrored my current state. There's TONS to learn in linux like
> bash, perl, vim, sed, awk, python, etc. Too much to put in your head and in
> the end makes you half-baked e.g. good at start but fades away in the end.
> Anyway i hope to follow your lead and be one among the guys here
> knowledgeable of the language.
>
> In the same lines of if-you-can-think-of-anything-python-can-do-it i got
> inspired to ask a question for the gurus:
>
> When i use our company's LAN i set my proxy variable by hand in .bashrc.
> There are 4 files to insert proxy variable:
>
> in ~/.bashrc, /root/.bashrc, /etc/wgetrc and /etc/apt/apt.conf.
>
> The last one is actually rename e.g. mv to apt.conf to activate proxy and mv
> to apt.conf.bak to deactivate. The proxy variable is something like this
>
> export http_proxy=http://username:passw...@proxy:port
> ftp_proxy=$http_proxy
>
> To activate i uncomment them then source .bashrc. To deactivate i put back
> the comment sign. I do it all in vim e.g. vim -o the-3-files-above. For
> apt.conf see rename above. I deactivate because i have another internet
> connection option via 3G usb modem. But thats another story.
>
> I will do this myself in python so please show me the way. Surely this can
> be done.
>

Heys,

I do something similair with apt.conf. Below is an older version of an
app i wrote (the new version i have written integrates into network
manager, so when it detects a certain network, it switches all the
corresponding settings!).

This older version has some functions that you might be interested.
Maybe something below helps you.



#!/usr/bin/python

import sys
import fileinput
import re
import netifaces
import glob
import string

from netaddr import IP, CIDR

networks = {}
networks["home"] = {"ip":"192.168.1.0/24","url":"http://192.168.1.2:3142/"}
#networks["home"] =
{"ip":"192.168.1.0/24","url":"http://ecstacy.lsd.co.za:3142/"}
networks["office"] =
{"ip":"172.30.16.16/20","url":"http://ecstacy.lsd.co.za:3142/"}

#Things to keep in sync
sync=["/etc/apt/sources.list","/etc/apt/sources.list.d/*.list"]
#sync=["/etc/apt/sources.list"]

#Search interfaces for IP and compare against variable list
def netcheck():
for interface in netifaces.interfaces():
iface = netifaces.ifaddresses(interface)
if netifaces.AF_INET in iface:
networkaddr = '%s/%s' %
(netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'],
netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask'])
networkaddr = IP(networkaddr).cidr()
print 'networkaddr: %s' % networkaddr
for name, values in networks.iteritems():
network = IP(values['ip']).cidr()
print 'network: %s' % network
if networkaddr in network:
location = networks[name]['url']
print 'Location \'%s\' found. Setting 
proxy to \'%s\'' % (name,location)

#Function to hash out mirrors based on regex - may be useful for
enabling/disabling src package downloads
#Not currently used
def hash():
for line in fileinput.input("test.list", inplace=1):
line = line.strip()
if re.search('^deb', line):
print '#%s' % line
else:
print line

#Function to check if sync list actually exists (maybe should check
for writable?)
def checksync():
for file in sync:
if not glob.glob(file):
print ("Error: %s does not exist" %file)
sys.exit(1)

#Function to replace mirror
def replace(location=False):
for file in sync:
for line in fileinput.input(glob.glob(file), inplace=1):
line = line.strip()

if location:
if re.search('^deb.*http://(.*):3142/', line):
print re.sub('http://(.*):3142/', location, line)
elif re.search('^deb.*http://', line):
print re.sub('http://', location, line)
else:
pri

Re: [Tutor] GzipFile has no attribute '__exit__'

2009-11-16 Thread Sander Sweers
2009/11/16 Dave Angel :
> Alternatively, you could subclass it, and write your own.  At a minimum, the
> __exit__() method should close() the stream.

This triggered my to dig into this a bit. This is not fixed untill
python 3.1 but seems easilly added to the ZipFile class. My attempt to
backport this from python 3.1's gzip.py below seems to work.

Greets
Sander

import gzip

class myGzipFile(gzip.GzipFile):
def __enter__(self):
if self.fileobj is None:
raise ValueError("I/O operation on closed GzipFile object")
return self

def __exit__(self, *args):
self.close()

zfilepath = r'C:\test.gz'
s = 'This is a test'

with myGzipFile(zfilepath,'w') as output:
output.write(s)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing code while tired, counterproductive?

2009-11-16 Thread Albert-Jan Roskam
I find that switching to a completely different approach or strategy becomes 
more difficult when tired. Depending on the context, that could be called 
persistence of perseverence (begin good or bad, respectively). However, in my 
opinion, not being able to view things from a different angle is usually 
counterproductive.

Cheers!!
Albert-Jan

~~
In the face of ambiguity, refuse the temptation to guess.
~~

--- On Mon, 11/16/09, Luke Paireepinart  wrote:


From: Luke Paireepinart 
Subject: Re: [Tutor] Writing code while tired, counterproductive?
To: "OkaMthembo" 
Cc: tutor@python.org
Date: Monday, November 16, 2009, 9:56 AM


I hate to be the odd one out here, but I actually find that I am extremely 
productive when I'm tired.  It's easier for me to commit completely to the 
code, when I'm well-rested I dream about running through fields of sunflowers 
and such, get distracted more easily.  The code I write when I'm tired is 
usually of marginally worse quality, but it's usually easy to audit it when I'm 
rested and fix any problems.  Although if I'm trying to solve something 
particularly difficult, especially something I've never done before, sometimes 
I won't be able to do it until I wake up a bit.  Note that this is for being 
tired, not exhausted.  If I'm exhausted I write a whole lot of awful code that 
I have to completely rewrite when I wake up.


On Mon, Nov 16, 2009 at 12:57 AM, OkaMthembo  wrote:

>From first-hand experience, i would concur :)

A refreshed mind will perform much better than an over-exerted one.





On Sat, Nov 14, 2009 at 8:57 PM, Alan Gauld  wrote:


"Modulok"  wrote


Does anyone else find, writing code while tired to be counterproductive?

Yes. Doing anything that is mentally taxing is usually a bad idea when tired!

Alan G

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



-- 
Regards,
Lloyd

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



-Inline Attachment Follows-


___
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] I love python / you guys :)

2009-11-16 Thread Luke Paireepinart
Accidental off-list reply.
On Mon, Nov 16, 2009 at 5:36 AM, bibi midi  wrote:

>
> In the same lines of if-you-can-think-of-anything-python-can-do-it i got
> inspired to ask a question for the gurus:
>
> When i use our company's LAN i set my proxy variable by hand in .bashrc.
> There are 4 files to insert proxy variable:
>
> in ~/.bashrc, /root/.bashrc, /etc/wgetrc and /etc/apt/apt.conf.
>
> The last one is actually rename e.g. mv to apt.conf to activate proxy and
> mv to apt.conf.bak to deactivate. The proxy variable is something like this
>
> export http_proxy=http://username:passw...@proxy:port
> ftp_proxy=$http_proxy
>
> To activate i uncomment them then source .bashrc. To deactivate i put back
> the comment sign. I do it all in vim e.g. vim -o the-3-files-above. For
> apt.conf see rename above. I deactivate because i have another internet
> connection option via 3G usb modem. But thats another story.
>
> I will do this myself in python so please show me the way. Surely this can
> be done.
>
> Sure it can.

This is actually fairly easy to do.  I would just use regular expressions to
match the lines and comment/uncomment them  depending on if you want to
enable/disable.



Spoiler alert! don't read if you want to solve it yourself.


 Remove/Add comments to any line that matches a specified regular
expression.
##comments are assumed to be the '#' symbol.
 Warning - completely untested code.

import re
regex =  # remove leading spaces and the # comment symbol from a line, if it
exists.

def uncomment(filename, regex, newfile):
remove_comments_regex = ' *#*(.*$)'
for line in open(filename):
if re.match(regex, line): # if we have a matching line we should
remove the comment.
newfile.write(re.match(remove_comments_regex, line).groups()[0])

def comment(filename, regex, newfile):
for line in open(filename):
if re.match(regex, line):
#avoid dual-commenting
if line.strip().startswith("#"):
newfile.write(line)
else:
newfile.write('#' + line)


End of spoiler



As for renaming, look into the os module, there's an easy function for
renaming in there.  Just add a check around the rename function for an
os.path.exists(...) so you can ensure the file exists before you attempt to
rename it, otherwise you might get an exception (or you could just try
renaming it and just catch the exception, either way.)   Then just make a
.py script that can enable and one that can disable, and make sure tehre's
no harm if you run either one multiple times consecutively.

Hope that helps, and yes, we know you guys appreciate the help, that's why
we do it!  We certainly don't get paid anything.  It's nice to hear you say
it anyway though, so thanks!
-Luke
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GzipFile has no attribute '__exit__'

2009-11-16 Thread Kent Johnson
On Mon, Nov 16, 2009 at 7:15 AM, Sander Sweers  wrote:

> This triggered my to dig into this a bit. This is not fixed untill
> python 3.1 but seems easilly added to the ZipFile class. My attempt to
> backport this from python 3.1's gzip.py below seems to work.
>
> Greets
> Sander
>
> import gzip
>
> class myGzipFile(gzip.GzipFile):
>    def __enter__(self):
>        if self.fileobj is None:
>            raise ValueError("I/O operation on closed GzipFile object")
>        return self
>
>    def __exit__(self, *args):
>        self.close()

You might want to report this as a bug against 2.6 and submit this
change as a proposed fix. It's easy to do, see
http://www.python.org/dev/patches/

You could submit your change right in the body of the report if you
don't want to make a diff file. You could suggest an update to the
docs as well.

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


Re: [Tutor] Tutor Digest, Vol 69, Issue 73

2009-11-16 Thread Mario Cavett
 
> A refreshed mind will perform much better than an over-exerted one.
> 
> 
> 
> 
> 
> On Sat, Nov 14, 2009 at 8:57 PM, Alan Gauld  wrote:
> 
> 
> "Modulok"  wrote
> 
> 
> Does anyone else find, writing code while tired to be counterproductive?
> 
> Yes. Doing anything that is mentally taxing is usually a bad idea when tired!
> 
> Alan G
> 
> ___
> Tutor maillist ?- ?tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> -- 
> Regards,
> Lloyd
> 
> ___
> Tutor maillist ?- ?tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> -Inline Attachment Follows-
> 
> 
> ___
> Tutor maillist? -? Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
>   
> -- next part --
> An HTML attachment was scrubbed...
> URL: 
> <http://mail.python.org/pipermail/tutor/attachments/20091116/aaf52501/attachment-0001.htm>
> 
> --
> 
> Message: 3
> Date: Mon, 16 Nov 2009 06:25:34 -0600
> From: Luke Paireepinart 
> To: "[tutor python]" 
> Subject: Re: [Tutor] I love python / you guys :)
> Message-ID:
>   
> Content-Type: text/plain; charset="iso-8859-1"
> 
> Accidental off-list reply.
> On Mon, Nov 16, 2009 at 5:36 AM, bibi midi  wrote:
> 
> >
> > In the same lines of if-you-can-think-of-anything-python-can-do-it i got
> > inspired to ask a question for the gurus:
> >
> > When i use our company's LAN i set my proxy variable by hand in .bashrc.
> > There are 4 files to insert proxy variable:
> >
> > in ~/.bashrc, /root/.bashrc, /etc/wgetrc and /etc/apt/apt.conf.
> >
> > The last one is actually rename e.g. mv to apt.conf to activate proxy and
> > mv to apt.conf.bak to deactivate. The proxy variable is something like this
> >
> > export http_proxy=http://username:passw...@proxy:port
> > ftp_proxy=$http_proxy
> >
> > To activate i uncomment them then source .bashrc. To deactivate i put back
> > the comment sign. I do it all in vim e.g. vim -o the-3-files-above. For
> > apt.conf see rename above. I deactivate because i have another internet
> > connection option via 3G usb modem. But thats another story.
> >
> > I will do this myself in python so please show me the way. Surely this can
> > be done.
> >
> > Sure it can.
> 
> This is actually fairly easy to do.  I would just use regular expressions to
> match the lines and comment/uncomment them  depending on if you want to
> enable/disable.
> 
> 
> 
> Spoiler alert! don't read if you want to solve it yourself.
> 
> 
>  Remove/Add comments to any line that matches a specified regular
> expression.
> ##comments are assumed to be the '#' symbol.
>  Warning - completely untested code.
> 
> import re
> regex =  # remove leading spaces and the # comment symbol from a line, if it
> exists.
> 
> def uncomment(filename, regex, newfile):
> remove_comments_regex = ' *#*(.*$)'
> for line in open(filename):
> if re.match(regex, line): # if we have a matching line we should
> remove the comment.
> newfile.write(re.match(remove_comments_regex, line).groups()[0])
> 
> def comment(filename, regex, newfile):
> for line in open(filename):
> if re.match(regex, line):
> #avoid dual-commenting
>     if line.strip().startswith("#"):
> newfile.write(line)
> else:
> newfile.write('#' + line)
> 
> 
> End of spoiler
> 
> 
> 
> As for renaming, look into the os module, there's an easy function for
> renaming in there.  Just add a check around the rename function for an
> os.path.exists(...) so you can ensure the file exists before you attempt to
> rename it, otherwise you might get an exception (or you could just try
> renaming it and just catch the exception, either way.)   Then just make a
> .py script that can enable and one that can disable, and make sure tehre's
> no harm if you run either one multiple times consecutively.
> 
> Hope that helps, and yes, we know you guys appreciate the help, that's why
> we do it!  We certa

Re: [Tutor] I love python / you guys :)

2009-11-16 Thread Stephen Nelson-Smith
Hello all,

On Mon, Nov 16, 2009 at 6:58 AM, Stefan Lesicnik  wrote:
> hi,
>
> Although not a question, i just want to tell you guys how awesome you are!

+1

I've been a happy member of this list for years, even though I've
taken a 3 year Ruby sabbatical!

I've always found it to be full of invaluable advice, and is, in my
opinion, a real gem in Python's crown.  It's one of the reasons I feel
so confident in recommending python to anyone - they can be guaranteed
a friendly and informational welcome on this list.

Thank you very much - it is greatly appreciated.

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


Re: [Tutor] proxy switcher - was Re: I love python / you guys :)

2009-11-16 Thread Stephen Nelson-Smith
Hi,

>> When i use our company's LAN i set my proxy variable by hand in .bashrc.
>> There are 4 files to insert proxy variable:
>>
>> in ~/.bashrc, /root/.bashrc, /etc/wgetrc and /etc/apt/apt.conf.
>>
>> The last one is actually rename e.g. mv to apt.conf to activate proxy and mv
>> to apt.conf.bak to deactivate. The proxy variable is something like this
>>
>> export http_proxy=http://username:passw...@proxy:port
>> ftp_proxy=$http_proxy
>>
>> To activate i uncomment them then source .bashrc. To deactivate i put back
>> the comment sign. I do it all in vim e.g. vim -o the-3-files-above. For
>> apt.conf see rename above. I deactivate because i have another internet
>> connection option via 3G usb modem. But thats another story.
>>
>> I will do this myself in python so please show me the way. Surely this can
>> be done.

Here's what I knocked up over lunch.  It doesn't cover the moving of
the file, I don't like that it's deep-nested, and I've not tested it,
but I welcome criticism and feedback:

files = ['file1', 'file2', 'file3', 'file4']
settings = ['export http_proxy=', 'ftp_proxy=']

for file in files:
  with open(file, 'rw') as file:
for line in file:
  for setting in settings:
if setting in line:
  if line[0] == '#':
line = line[1:]
  else:
line =  '#' + line
output.write(line)

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


Re: [Tutor] proxy switcher - was Re: I love python / you guys :)

2009-11-16 Thread Luke Paireepinart
> Here's what I knocked up over lunch.  It doesn't cover the moving of
> the file, I don't like that it's deep-nested, and I've not tested it,
> but I welcome criticism and feedback:
>
> files = ['file1', 'file2', 'file3', 'file4']
> settings = ['export http_proxy=', 'ftp_proxy=']
>
> for file in files:
>  with open(file, 'rw') as file:
>

Does this actually work?
I didn't think you could open files as reading and writing?

also you're shadowing the 'file' var, which might be confusing to beginners,
as it's not the same file as in the outer for loop.
Also, 'with' is a 3.0 keyword, right?  That's pretty interesting syntax,
I've never seen it before, but I haven't used 3.x yet.


>for line in file:
>  for setting in settings:
>if setting in line:
>  if line[0] == '#':
>line = line[1:]
>  else:
>line =  '#' + line
>output.write(line)
>

Also, you didn't define 'output' anywhere.  Is this an implicit declaration
via the 'with' syntax?

Thanks,
-Luke

>
>
S.
> ___
> 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


[Tutor] Help on finding the 1000th prime

2009-11-16 Thread Ray Holt
I have posted this on other lists, but have just discovered this one. Can
someone give me help on writing the code necessary to find the 1000th. prime
number. I know I will have to use a while loop, but I can't seem to get the
body of the code to function rightly. I would appreciate any help. I am
taking the online course Introduction to Computer Science and Programming
from the MIT website and this is one of their assignments. The on campus
students are able to collaborate with one another, but I live in Ohio.
Thanks, Ray 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help on finding the 1000th prime

2009-11-16 Thread christopher . henk
mrhol...@sbcglobal.net wrote on 11/16/2009 10:56:07 AM:

> I have posted this on other lists, but have just discovered this one. 

Welcome to the list.  I am sure you will find plenty of folks here 
who will be happy to help you.

> Can someone give me help on writing the code 
> necessary to find the 1000th. prime number.

I seem to recall this problem was recently discussed on the list. 
If you do a quick search you should be able to find a few pointers on one 
way to solve it. 

> I know I will have to use a while loop, but I can't seem to get the body 

> of the code to function rightly. I would appreciate any help. 

The way this list works you will have to give us something to work 
from.  Show us what you tried, how it failed (any error messages, etc), 
what you re thinking, and where you are stuck.  We won't do the work for 
you but try and lead you to the answers. 


> I am taking the online course Introduction to Computer 
> Science and Programming from the MIT website and this is one of their 
assignments. The on campus students are able to 
> collaborate with one another, but I live in Ohio. Thanks, Ray 
___

Good luck with the class, and feel free to ask questions here.

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


Re: [Tutor] Help on finding the 1000th prime

2009-11-16 Thread Kent Johnson
On Mon, Nov 16, 2009 at 10:56 AM, Ray Holt  wrote:
> I have posted this on other lists, but have just discovered this one. Can
> someone give me help on writing the code necessary to find the 1000th. prime
> number. I know I will have to use a while loop, but I can't seem to get the
> body of the code to function rightly.

What have you tried so far? What don't you understand?

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


Re: [Tutor] proxy switcher - was Re: I love python / you guys :)

2009-11-16 Thread Dave Angel

Luke Paireepinart wrote:

Here's what I knocked up over lunch.  It doesn't cover the moving of
the file, I don't like that it's deep-nested, and I've not tested it,
but I welcome criticism and feedback:

files = ['file1', 'file2', 'file3', 'file4']
settings = ['export http_proxy=', 'ftp_proxy=']

for file in files:
 with open(file, 'rw') as file:




Does this actually work?
I didn't think you could open files as reading and writing?

  
Yes, you can, but not this way.  I'm guessing the op was changing his 
mind back and forth, between having two files, one for reading and one 
for writing, and trying to do it in place.  The code does neither/both.


Take a look at fileinput.FileInput()  with the inplace option.  It makes 
it convenient to update text files "in place" by handling all the temp 
file copying and such.  It even handles iterating through the list of files.

also you're shadowing the 'file' var, which might be confusing to beginners,
as it's not the same file as in the outer for loop.
Also, 'with' is a 3.0 keyword, right?  That's pretty interesting syntax,
I've never seen it before, but I haven't used 3.x yet.

  
Good point about 'file' as its a built-in name.  If the code ever has to 
use the std meaning, you have a problem.  Worse, it's unreadable as is.


With was introduced in 2.6, and does work nicely, at least in CPython.
  

   for line in file:
 for setting in settings:
   if setting in line:
 if line[0] == '#':
   line = line[1:]
 else:
   line =  '#' + line
   output.write(line)




Also, you didn't define 'output' anywhere.  Is this an implicit declaration
via the 'with' syntax?

Thanks,
-Luke

  
No, output is an undefined global at present.  As I implied earlier, he 
was probably intending to have a separate file for writing.


S.
  

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




  
Another potential  bug with the code is if more than one "setting" could 
appear in a line. It would change the line for an odd number, and not 
for an even number of matches.


Also, the nesting of output.write() is wrong, because file position 
isn't preserved, and random access in a text file isn't a good idea 
anyway.  But there's not much point in debugging that till the OP 
decides how he's going to handle the updates, via new files and copying 
or renaming, or via inputfile.



DaveA

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


Re: [Tutor] proxy switcher - was Re: I love python / you guys :)

2009-11-16 Thread Stephen Nelson-Smith
Evening,
> Yes, you can, but not this way.  I'm guessing the op was changing his mind
> back and forth, between having two files, one for reading and one for
> writing, and trying to do it in place.  The code does neither/both.

Well, just neither I think!  I didn't check if 'rw' was possible.  My
plan was to read the file and write to the same file as the change was
made, to avoid having to use temporary files and os.move.  But I
wasn't near a machine with python on it, so it was untested.

> Take a look at fileinput.FileInput()  with the inplace option.  It makes it
> convenient to update text files "in place" by handling all the temp file
> copying and such.  It even handles iterating through the list of files.

Will definitely look into that.

> Good point about 'file' as its a built-in name.  If the code ever has to use
> the std meaning, you have a problem.  Worse, it's unreadable as is.

Thanks for that hint.  In what way is it unreadable?  Because the
intent is not clear because of the ambiguity of the name?

>> Also, you didn't define 'output' anywhere.  Is this an implicit
>> declaration

No, just a dumb mistake.

> Another potential  bug with the code is if more than one "setting" could
> appear in a line. It would change the line for an odd number, and not for an
> even number of matches.

Not sure I follow that.  From the OPs description, it appeared he
would be entering these lines in.  I figured it was safe to trust the
OP not to put in duplicate data.  Maybe defensively I should check for
it anyway?

> Also, the nesting of output.write() is wrong, because file position isn't
> preserved, and random access in a text file isn't a good idea anyway.

Could you expand on this?

>  But
> there's not much point in debugging that till the OP decides how he's going
> to handle the updates, via new files and copying or renaming, or via
> inputfile.

I'll look up inputfile, and try again :)

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


[Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread kb1pkl

Hello Tutor list.
I'm running a test to find what the experimental average of a d20 is, 
and came across a strange bug in my code.

import random
list1 = []
def p():
   d = 0
   for number in range(1,1000):
   t = random.randrange(1,19)
   list1.append(t)
   for value in list1:
   d+=value
   print d/1000
   d = 0
for value in range(1,100):
   p()

It works, but I have a logic error somewhere. It runs, and the results 
have a pattern :

9
19
28
37
47
56
66
75
85
94
104
113
...
...
It just adds 10, and every second result, subtracts 1, till it gets to 
0, and then starts again with 9 in singles, and whatever in the 10's, 
etc.

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


Re: [Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread Jeff R. Allen
When you declare list1 before "def p()" you are making it global. That
means it will keep its values between invocations of p(). When you
start function p, you don't reset list1 to empty. You divide each time
by 1000, and but your list1 list is growing and growing and growing.
That's why the total is growing, not giving the answer you were
expecting.

Either you need to reset list1 to empty each time p() starts, or (if
you want to accumulate the results between calls to p()) you need to
divide by the true number of items in the list, not by 1000. So
replace /1000 with /len(list1).

However, that brings me to something else interesting. You are doing
an integer divide. That means you'll get integer results, which for
your purposes are much less interesting than floating point ones.
Replace the /1000 with /1000.0 and see what you get. (Move the
declaration of list1 into p() also.)

Another thing... play in the interpreter with range(1,5) and
range(0,5). Can you see another little bug your program has? It is not
doing precisely what you think it is yet...

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


Re: [Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread vince spicer
On Mon, Nov 16, 2009 at 1:18 PM,  wrote:

> Hello Tutor list.
> I'm running a test to find what the experimental average of a d20 is, and
> came across a strange bug in my code.
> import random
> list1 = []
> def p():
>   d = 0
>   for number in range(1,1000):
>   t = random.randrange(1,19)
>   list1.append(t)
>   for value in list1:
>   d+=value
>   print d/1000
>   d = 0
> for value in range(1,100):
>   p()
>
> It works, but I have a logic error somewhere. It runs, and the results have
> a pattern :
> 9
> 19
> 28
> 37
> 47
> 56
> 66
> 75
> 85
> 94
> 104
> 113
> ...
> ...
> It just adds 10, and every second result, subtracts 1, till it gets to 0,
> and then starts again with 9 in singles, and whatever in the 10's, etc.
> What is causing this?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


I think that one problem you are seeing is caused by the use of integers
When you are dividing sum of the random number by 1000, python is rounding
your output.

Also your list, never gets cleared and you keep adding to the original list,
and you are then dividing by the original 1000


A simple fix is to use floats (PS: cleaned up a bit):

from random import randrange
def p():
mylist = [randrange(1,19) for x in range(1, 1000)]
d = sum(list)
print float(d) / len(mylist)

for value in range(1,100):
p()


Hope this point you in a better direction

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


Re: [Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread Jose Amoreira
Hi!
Everytime your program calls function p, list1 is appended to. It keeps on 
getting bigger and bigger. The function adds all the elements of the list, but 
the total is divided by 1000, even if the list is already much longer that 
1000!

And there's another thing. When var1 and var2 are integer, var1/var2 returns 
the integer division, that is, for instance 3/2=1, 9/10=0, etc (try it!).

I bet that if you divide the sum of the values in list1 by len(list1) 
(otherwise reset the list, so that it remains only 1000 element long) and 
replace the line 'print d/1000' with 'print (d*1.0)/len(list1)' (or 'print 
d/1000.0', if you reset the list every time you call p) your problem is over.

Hope this helps!
Cheers
José Amoreira


On Monday 16 November 2009 07:18:52 pm kb1...@aim.com wrote:
> Hello Tutor list.
> I'm running a test to find what the experimental average of a d20 is,
> and came across a strange bug in my code.
> import random
> list1 = []
> def p():
> d = 0
> for number in range(1,1000):
> t = random.randrange(1,19)
> list1.append(t)
> for value in list1:
> d+=value
> print d/1000
> d = 0
> for value in range(1,100):
> p()
>
> It works, but I have a logic error somewhere. It runs, and the results
> have a pattern :
> 9
> 19
> 28
> 37
> 47
> 56
> 66
> 75
> 85
> 94
> 104
> 113
> ...
> ...
> It just adds 10, and every second result, subtracts 1, till it gets to
> 0, and then starts again with 9 in singles, and whatever in the 10's,
> etc.
> What is causing this?
> ___
> 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] Unexpected Result in Test Sequence

2009-11-16 Thread Tim Peters
[kb1...@aim.com]
> I'm running a test to find what the experimental average of a d20 is,

I don't know what "a d20" is, but your code is picking integers
uniformly at random between 1 and 18 inclusive.  The expected value is
therefore (1+18)/2.0 = 9.5.

> and came across a strange bug in my code.
>
> import random
> list1 = []

Note that you never clear this list.  It just keeps growing, and
growing, and growing ...

> def p():
>   d = 0
>   for number in range(1,1000):
>       t = random.randrange(1,19)
>       list1.append(t)

On average, the sum of the 1000 integers you just added is 9.5 * 1000 = 9500.

>   for value in list1:
>       d+=value

So the sum of the entire list (which you never clear) will be
approximately 9500 times the number of times you've called p().

>   print d/1000

Here you're dividing by 1000 no matter how long the list is,  The
first time you call p(), it does have 1000 integers by the time you
get here.  The second time you call p(), it will have 2000 integers by
the time you get here.  And so on.  So what I expect this to print is
approximately

9500 * the number of times you've called p() / 1000 =
approximately 9.5 times the number of times you've called p()

However, you're using truncating integer division, not floating
division, so the truth of that is obscured.


>   d = 0

This line didn't do anything for you.

> for value in range(1,100):
>   p()
>
> It works, but I have a logic error somewhere. It runs, and the results have
> a pattern :
> 9

As above, approximately 9.5 times 1.

> 19

Approximately 9.5 times 2.

> 28

Approximately 9.5 times 3.

> 37

Approximately 9.5 times 4.

> 47
> 56
> 66
> 75
> 85
> 94
> 104
> 113
> ...

Etc.


> It just adds 10, and every second result, subtracts 1, till it gets to 0,
> and then starts again with 9 in singles, and whatever in the 10's, etc.
> What is causing this?

A couple things:  you're never clearing list1, and you're using
truncating integer division to compute the average.  I /suspect/ you
didn't really intend "randrange(1, 19)" either, but that depends on
what "a d20" means.

Try this instead ;-)

import random
def p():
  list1 = [random.randrange(1, 19) for dummy in xrange(1000)]
  print float(sum(list1)) / len(list1)

for value in range(1,100):
  p()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread Emmanuel Ruellan
In your code, list list1 never gets emptied.

There is another problem : the doc for random.randrange() says it "choose[s]
a random item from range(start, stop[, step])" and range(1, 19) goes from 1
included to 19 _not_ included. Your 'd20' is not a 20-sided dice.

On Mon, Nov 16, 2009 at 8:18 PM,  wrote:

>
>
> Hello Tutor list.
> I'm running a test to find what the experimental average of a d20 is, and
> came across a strange bug in my code.
> import random
> list1 = []
> def p():
>   d = 0
>   for number in range(1,1000):
>   t = random.randrange(1,19)
>   list1.append(t)
>   for value in list1:
>   d+=value
>   print d/1000
>   d = 0
> for value in range(1,100):
>   p()
>
> It works, but I have a logic error somewhere. It runs, and the results have
> a pattern :
> 9
> 19
> 28
> 37
> 47
> 56
> 66
> 75
> 85
> 94
> 104
> 113
> ...
> ...
> It just adds 10, and every second result, subtracts 1, till it gets to 0,
> and then starts again with 9 in singles, and whatever in the 10's, etc.
> What is causing this?
> ___
> 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] proxy switcher - was Re: I love python / you guys :)

2009-11-16 Thread Dave Angel
(Multiple people on this thread have been quoting earlier people without 
keeping the attribution lines  (e.g.    yyy wrote: )
   so I'm not sure who said what any more.  I recognize my own words, 
of course, but for anybody else, your guess is

   better than mine)

Stephen Nelson-Smith wrote:

Evening,
  

Yes, you can, but not this way.  I'm guessing the op was changing his mind
back and forth, between having two files, one for reading and one for
writing, and trying to do it in place.  The code does neither/both.



Well, just neither I think!  I didn't check if 'rw' was possible.  My
plan was to read the file and write to the same file as the change was
made, to avoid having to use temporary files and os.move.  But I
wasn't near a machine with python on it, so it was untested.

  
The string to use is "r+b"   The  r  says you're going to read it.  The 
+ says you're also going to write it.  And the  b  says you don't want 
any character translation going on.  Text files should only be written 
in one direction, or appended, but not updated in-place, except in very 
specific circumstances.


If you're both reading and writing, you need to do a seek() in between.  
So you'll be doing two seeks per loop. And since each line is a variable 
size, you'd have to keep track of that size.  And if you were on a 
Windows machine, the size of the string you see may not match the size 
on the file ( 0d0a becomes 0a when reading a text file).  Finally, even 
if you get all that right, the specific example is trying to replace 
lines with new lines of a different length.  Not in this world.

Take a look at fileinput.FileInput()  with the inplace option.  It makes it
convenient to update text files "in place" by handling all the temp file
copying and such.  It even handles iterating through the list of files.



Will definitely look into that.

  

Good point about 'file' as its a built-in name.  If the code ever has to use
the std meaning, you have a problem.  Worse, it's unreadable as is.



Thanks for that hint.  In what way is it unreadable?  Because the
intent is not clear because of the ambiguity of the name?

  
Exactly.  In that short fragment, there are three meanings for the name 
file.  It's a built-in type until the first time you change it.  Then it 
becomes a string.  And after the with statement it becomes a file 
object.  If you had to check its type, that would be quite difficult.  
And if you needed its name, you've clobbered it.



Also, you didn't define 'output' anywhere.  Is this an implicit
declaration
  


No, just a dumb mistake.

  

Another potential  bug with the code is if more than one "setting" could
appear in a line. It would change the line for an odd number, and not for an
even number of matches.



Not sure I follow that.  From the OPs description, it appeared he
would be entering these lines in.  I figured it was safe to trust the
OP not to put in duplicate data.  Maybe defensively I should check for
it anyway?

  
I'm not sure where these "settings" values come from.  But if these are 
arbitrary command lines, it's plausible that one command works on a file 
whose name looks like one of the other commands.   I'd feel better with 
something like "startswith()"  instead of "in" .  But just as a general 
precaution, I'd put a break in the for loop whenever one of them matches

Also, the nesting of output.write() is wrong, because file position isn't
preserved, and random access in a text file isn't a good idea anyway.



Could you expand on this?

  
As it stands, it only writes the line when it needs to change.  But that 
implies that you've been keeping track of sizes so you can put a seek 
before and after the line, and of course that the size doesn't change.  
Since none of these is true (or practical), my comment was assuming that 
you're using a different "output" file.  So you need to write every 
line, not just the ones that change.

 But
there's not much point in debugging that till the OP decides how he's going
to handle the updates, via new files and copying or renaming, or via
inputfile.



I'll look up inputfile, and try again :)

S.

  


With inputfile, you'll basically copy the file from the supplied 
iterator to stdout (probably using print), doing any conversions on the 
line as you go.


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


Re: [Tutor] GzipFile has no attribute '__exit__'

2009-11-16 Thread Sander Sweers
2009/11/16 Kent Johnson :
> You might want to report this as a bug against 2.6 and submit this
> change as a proposed fix. It's easy to do, see

I poked around in the bug tracker and found [1]. It will be in 2.7 and
was *not* accepted for 2.6.

If anyone wants to add this in themselves see [2].

Greets
Sander

[1] http://bugs.python.org/issue3860
[2] http://svn.python.org/view?view=rev&revision=68484
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] A way to search archives?

2009-11-16 Thread Ray Holt
Is there a way to search the archives?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help on finding the 1000th prime

2009-11-16 Thread bob gailer

Ray Holt wrote:

find the 1000th. prime number.
Break this down into 2 separate problems. (I assume 1 is the first prime 
number)

1 - determining the next prime number
2 - repeating that 1000 times.

A while loop is a way to accomplish 2.

How do you determine the next prime number? There are many algorithms 
for this - you might consult Wikipedia for ideas.


--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A way to search archives?

2009-11-16 Thread Serdar Tumgoren
> Is there a way to search the archives?

Not sure if someone's developed an official search resource, but I've
always found Google search to work well:

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


[Tutor] Do you use unit testing?

2009-11-16 Thread Modulok
List,

A general question:

How many of you guys use unit testing as a development model, or at
all for that matter?

 I just starting messing around with it and it seems painfully slow to
have to write a test for everything you do. Thoughts, experiences,
pros, cons?

Just looking for input and different angles on the matter, from the
Python community.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread Kent Johnson
Please use reply all to reply to the list


-- Forwarded message --
From: Ray Holt 
Date: Mon, Nov 16, 2009 at 1:34 PM
Subject: RE: [Tutor] Help on finding the 1000th prime
To: Kent Johnson 


Basically I can't figure out how to loop through the possible candidates. I
am using version 2.5.6. I creat the varibles :
primeCount =  0
Prime Candidate = 2
While primeCount < 1000
isPrime = True
       primeCanditate = primeCandidate + 2
That's as far as I have gotten. I can't figure out how to loop through the
possible candidates to the 1000th prime.

-Original Message-
From: kent3...@gmail.com [mailto:kent3...@gmail.com] On Behalf Of Kent
Johnson
Sent: Monday, November 16, 2009 12:33 PM
To: Ray Holt
Cc: tutor@python.org
Subject: Re: [Tutor] Help on finding the 1000th prime

On Mon, Nov 16, 2009 at 10:56 AM, Ray Holt  wrote:
> I have posted this on other lists, but have just discovered this one.
> Can someone give me help on writing the code necessary to find the
> 1000th. prime number. I know I will have to use a while loop, but I
> can't seem to get the body of the code to function rightly.

What have you tried so far? What don't you understand?

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


[Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread Kent Johnson
-- Forwarded message --
From: Ray Holt 
Date: Mon, Nov 16, 2009 at 1:55 PM
Subject: RE: [Tutor] Help on finding the 1000th prime
To: Kent Johnson 


I hit the send button before I was ready. Here is the code that doesn't
work.
primeCount = 0
primeCandidate = 2
While primeCount <= 1000:
isPrime = True
       primeCandidate = primeCandidate + 2
       for x in range(2, primeCandidate):
               if primeCandidate % x == 0:
       print primeCandidate, "equals", x, "*", primeCandidate/x
       isPrime = False
Print primeCandidate
       break
If isPrime:
       primeCount = primeCount + 2
Print primeCandidate


-Original Message-
From: kent3...@gmail.com [mailto:kent3...@gmail.com] On Behalf Of Kent
Johnson
Sent: Monday, November 16, 2009 12:33 PM
To: Ray Holt
Cc: tutor@python.org
Subject: Re: [Tutor] Help on finding the 1000th prime

On Mon, Nov 16, 2009 at 10:56 AM, Ray Holt  wrote:
> I have posted this on other lists, but have just discovered this one.
> Can someone give me help on writing the code necessary to find the
> 1000th. prime number. I know I will have to use a while loop, but I
> can't seem to get the body of the code to function rightly.

What have you tried so far? What don't you understand?

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


Re: [Tutor] Do you use unit testing?

2009-11-16 Thread Serdar Tumgoren
> How many of you guys use unit testing as a development model, or at
> all for that matter?

>  I just starting messing around with it and it seems painfully slow to
> have to write a test for everything you do. Thoughts, experiences,
> pros, cons?
>
I just started with Test-Driven Development myself and am also having
some growing pains. I think the urge to write a test for everything
stems from fuzziness about what types of things one should test for
(at least that's the area I'm stumbling on).

Dive Into Python has a great step-by-step tutorial with lots of code
samples for those looking to get started with unit testing, but I've
yet to find a good, high-level overview of use cases for unit testing.

Are there any rules of thumb or perhaps even testing patterns out there?

Would love to hear what others on the list have to say on this.

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


Re: [Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread bob gailer



Here is the code that doesn't work.
  


Thanks for posting the code. What "doesn't work" mean?
error messages?
unexpected results?
or what?

There are several problems in your code.
- The candidates you are testing. Walk thru the program and list a few 
of them and see if you can determine that problem.

- Counting primes as you discover them. Same advice as above.
- indentation is screwed up. Please use only spaces - no tabs.

primeCount = 0
primeCandidate = 2
While primeCount <= 1000:
isPrime = True
   primeCandidate = primeCandidate + 2
   for x in range(2, primeCandidate):
   if primeCandidate % x == 0:
   print primeCandidate, "equals", x, "*", primeCandidate/x
   isPrime = False
Print primeCandidate
   break
If isPrime:
   primeCount = primeCount + 2
Print primeCandidate

  


--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread Modulok
Also watch things like letter case on stuff like 'Print' and 'While',
they should instead be 'print' and 'while', (all lowercase).

-Modulok-

On 11/16/09, bob gailer  wrote:
>
>> Here is the code that doesn't work.
>>
>
> Thanks for posting the code. What "doesn't work" mean?
> error messages?
> unexpected results?
> or what?
>
> There are several problems in your code.
>  - The candidates you are testing. Walk thru the program and list a few
> of them and see if you can determine that problem.
>  - Counting primes as you discover them. Same advice as above.
>  - indentation is screwed up. Please use only spaces - no tabs.
>> primeCount = 0
>> primeCandidate = 2
>> While primeCount <= 1000:
>> isPrime = True
>>primeCandidate = primeCandidate + 2
>>for x in range(2, primeCandidate):
>>if primeCandidate % x == 0:
>>print primeCandidate, "equals", x, "*", primeCandidate/x
>>isPrime = False
>> Print primeCandidate
>>break
>> If isPrime:
>>primeCount = primeCount + 2
>> Print primeCandidate
>>
>>
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
> ___
> 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] A way to search archives?

2009-11-16 Thread Kent Johnson
On Mon, Nov 16, 2009 at 2:34 PM, Ray Holt  wrote:
> Is there a way to search the archives?

At http://mail.python.org/mailman/listinfo/tutor you will find links to:
http://dir.gmane.org/gmane.comp.python.tutor
http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor

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


Re: [Tutor] Do you use unit testing?

2009-11-16 Thread Stephen Nelson-Smith
Great question,

I learned TDD with PyUnit, but since moved to using Ruby, and have
been spoilt by rspec and even cucumber.  My instincts are to write
things test first, but so far I'm not finding PyUnit easy enough to
get going.

Once I get into the groove, I find it's a wonderful way to work - and
avoids some of the drivel I've come up with in the last few days.

As a discipline - work out what we want to test, write the test, watch
it fail, make it pass - I find this a very productive way to think and
work.

S.

On Mon, Nov 16, 2009 at 8:54 PM, Modulok  wrote:
> List,
>
> A general question:
>
> How many of you guys use unit testing as a development model, or at
> all for that matter?
>
>  I just starting messing around with it and it seems painfully slow to
> have to write a test for everything you do. Thoughts, experiences,
> pros, cons?
>
> Just looking for input and different angles on the matter, from the
> Python community.
> -Modulok-
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Stephen Nelson-Smith
Technical Director
Atalanta Systems Ltd
www.atalanta-systems.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "Snack" python-newt version incompatibilities.. (anaconda kickstart)

2009-11-16 Thread Chris Mueller
Hello all.

I'm working on a CentOS 5.2 kickstart interface; and have been happily using

%pre --interpreter /usr/bin/python

to do my management for awhile now with the snack module.  My problem
comes in when I am attempting to use the snack.EntryWindow function;
and setting default values.

The simplified version of my code is below...

(default1,default2,default3,default4)=('1','2','3','4')
#These are all of my prompts.
prompts = [('Static1',default1), ('Static2',
default2),('Static3',default3),('Static4',default4)]
ok, params = snack.EntryWindow(screen, "This is my title",
   "This is my text at top of box",
   prompts,
   help = "")

On my desktop, I have...
$>python -V
Python 2.5.2
The defualt python in CentOS5.2 is..
$>python -V
Python 2.4.3

The snack window behaves as expected on my desktop (default values all
populate and change values as I want/expect), but when I try and run
on the 2.4 python, i get the following(output cleaned up a little bit
as it splays the entire window)...


File "/usr/lib/python2.4/site-packages/snack.py", line 796, in EntryWindow
sg.setField(e, 1, count, anchorLeft = 1)
File "/usr/lib/python2.4/site-packages/snack.py", line 388, in setField
(what.__dict__.has_key('g')):
AttributeError: 'str' object has no attribute '__dict__' selects

With some googling, I managed to find references to a bug in the
python snack module that was fixed, but I was unable to find a working
format of the "prompts" variable to work in my Python 2.4.3.

I tried the above code, as well the suggestion from the link below of

prompts = [Entry(20, 'ham'), Entry(20, 'egg', hidden=True)]

But to no avail. Any help would be greatly appreciated...

http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=340366

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


Re: [Tutor] Do you use unit testing?

2009-11-16 Thread Jeff R. Allen
> As a discipline - work out what we want to test, write the test, watch
> it fail, make it pass - I find this a very productive way to think and
> work.

There's an emotional aspect too. Keeping a positive aspect keeps up
flow, and seeing tests go from failing to passing feels really good.
Making a change you're not completely confident in and seeing tests
start failing immediately is also quite nice .. you immediately feel
how close to correct the change in question is, and if it's worth
fixing up or is leading you the wrong direction and should be reverted
allowing you to take another stab at it.

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


Re: [Tutor] Do you use unit testing?

2009-11-16 Thread Serdar Tumgoren
> I learned TDD with PyUnit, but since moved to using Ruby, and have
> been spoilt by rspec and even cucumber.  My instincts are to write
> things test first, but so far I'm not finding PyUnit easy enough to
> get going.
>

The Dive Into Python chapter walks the process of writing/thinking
through "requirements" as a precursor to writing tests.

http://diveintopython.org/unit_testing/index.html

These aren't high-level abstract requirements per se, but lower-level
requirements based on observations about how a function, method or
class should work. In the Roman numerals example it uses, here's one
of the requirements:

"There is no way to represent negative numbers in Roman numerals."

Based on those observations, he codes up the unit tests, and then
finally the actual functions and methods.

That approach makes sense, but again, it's always tougher when you're
working on your own project
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread christopher . henk
Kent Johnson  wrote on 11/16/2009 04:00:02 PM:

> -- Forwarded message --
> From: Ray Holt 
> Date: Mon, Nov 16, 2009 at 1:55 PM
> Subject: RE: [Tutor] Help on finding the 1000th prime
> To: Kent Johnson 
> 
> 
> I hit the send button before I was ready. Here is the code that doesn't
> work.
Not to nit pick, but try and copy the code exactly as you have it. 
 The code below has capitalization where it doesn't belong and indenting 
is not consistent, so there should be plenty of syntax errors if you tried 
to run it.  This makes it hard to figure out where your particular problem 
is.  Not sure if its a syntax problem or a algorithm problem.  Indentation 
is key in Python so without showing exactly what you have loops and 
branching is hard or impossible to follow.  This is also why it is good to 
include exactly what error you are experiencing.

> primeCount = 0
> primeCandidate = 2

You might find it easier to start with a different primeCandidate 
and handle 2 as a special case.

> While primeCount <= 1000:
> isPrime = True
>primeCandidate = primeCandidate + 2

primeCandidate is going to be 4,6,8,10,12,14,16,18,...
which won't yield many primes. see comment above

>for x in range(2, primeCandidate):
>if primeCandidate % x == 0:
>print primeCandidate, "equals", x, "*", primeCandidate/x
>isPrime = False
> Print primeCandidate
>break
> If isPrime:
>primeCount = primeCount + 2
> Print primeCandidate
> 

It is hard to follow what is in which loop with the rest of the 
code, so I can't say much more on where you are having problems.  It looks 
like you have the parts there just a question of what goes where.

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


[Tutor] search the folder for the 2 files and extract out only the version numbers 1.0 and 2.0.

2009-11-16 Thread MARCUS NG
 Hi all,
I am really new to python and I am trying to create a script that looks at
file versions of a particular file
I have 4 files in a folder. One called myTest1.0.zip, myTest2.0.zip,
test3.txt and test4.zip in a directory/folder called allFiles on my desktop.
so the file structure is as such

C:\Users\blueman\Desktop\allFiles\myTest1.0.zip
and
C:\Users\blueman\Desktop\allFiles\myTest2.0.zip

Aim:
what is the best way to look into the allFiles directory, and only search
the folder for the 2 files myTest1.0.zip and myTest2.0.zip to extract out
only the version numbers 1.0 and 2.0.

what i have for my script so far is

import os
#path of  scripts folder
path="C:/Users/blueman/Desktop/allFiles/"
dirList=os.listdir(path)
for fname in dirList:
print fname

so I did think of listing the file names in an array only to realise that I
wouldn't know which index to query if this script is going to be automated.

what is the best way to obtain the version numbers of the 2 files?
thank you for your time.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] search the folder for the 2 files and extract out only the version numbers 1.0 and 2.0.

2009-11-16 Thread Serdar Tumgoren
> Aim:
> what is the best way to look into the allFiles directory, and only search
> the folder for the 2 files myTest1.0.zip and myTest2.0.zip to extract out
> only the version numbers 1.0 and 2.0.
>
Based on the above file-naming convention, you could get at the
version numbers with a combo of string methods and regular
expressions:

>>> import re  #import the regular expression module
>>> file_list = ['myTest1.0.zip', 'myTest2.0.zip']
>>> for f in file_list:
... if f.startswith("myTest") and f.endswith("zip"):
... version = re.search(r'\d+\.\d+', f).group()
... print version
...
1.0
2.0
>>>

The above regular expression pattern searches the string for one or
more digits, followed by a dot (which has been escaped), followed by
another sequence of one or more digits. The group method returns the
match.

You could also skip the string methods (startswith/endswith) entirely
and just use a regular expression:

>>> for f in file_list:
... version = re.match(r'myTest(\d+\.\d+)\.zip', f).group(1)
... print version
...
1.0
2.0
>>>

You can tweak the regex pattern above if you need more
flexibility/fuzziness in the types of file names you're trying to
match.

No doubt others on the list will have more elegant solutions.
Meantime, this site provides a gentle intro to regular expressions:

http://www.amk.ca/python/howto/regex/

HTH!

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


[Tutor] (no subject)

2009-11-16 Thread Carlos Flores

Dear Python,

I am trying to learn Python to experience my
computer programming knowledge. I am working through the online
textbook How to Think Like A Computer Scientist. I have made it through
chapters 1-5 and completed the exercises at the end. Now I am on
chapter 6 and I am having a lot of trouble and its only going to get
harder from here on. Is there any sources that help with these
exercises that are at the end of each chapter? Its tough not knowing if
I am doing these exercises correctly without seeing the actual answers.


Thanks. 
  
_
Hotmail: Powerful Free email with security by Microsoft.
http://clk.atdmt.com/GBL/go/171222986/direct/01/___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread Shashwat Anand
You'r trying naive algorithm. Finding prime is one of basic elements of
maths and programming. You may look at sieve of
eratosthenesand
sieve
of atkin 

On Tue, Nov 17, 2009 at 3:35 AM,
wrote:

>
>
> Kent Johnson  wrote on 11/16/2009 04:00:02 PM:
>
>
> > -- Forwarded message --
> > From: Ray Holt 
> > Date: Mon, Nov 16, 2009 at 1:55 PM
> > Subject: RE: [Tutor] Help on finding the 1000th prime
> > To: Kent Johnson 
> >
> >
> > I hit the send button before I was ready. Here is the code that doesn't
> > work.
>Not to nit pick, but try and copy the code exactly as you have it.
>  The code below has capitalization where it doesn't belong and indenting is
> not consistent, so there should be plenty of syntax errors if you tried to
> run it.  This makes it hard to figure out where your particular problem is.
>  Not sure if its a syntax problem or a algorithm problem.  Indentation is
> key in Python so without showing exactly what you have loops and branching
> is hard or impossible to follow.  This is also why it is good to include
> exactly what error you are experiencing.
>
> > primeCount = 0
> > primeCandidate = 2
>
>You might find it easier to start with a different primeCandidate
> and handle 2 as a special case.
>
> > While primeCount <= 1000:
> > isPrime = True
> >primeCandidate = primeCandidate + 2
>
> primeCandidate is going to be 4,6,8,10,12,14,16,18,...
> which won't yield many primes. see comment above
>
> >for x in range(2, primeCandidate):
> >if primeCandidate % x == 0:
> >print primeCandidate, "equals", x, "*", primeCandidate/x
> >isPrime = False
> > Print primeCandidate
> >break
> > If isPrime:
> >primeCount = primeCount + 2
> > Print primeCandidate
> >
>
> It is hard to follow what is in which loop with the rest of the
> code, so I can't say much more on where you are having problems.  It looks
> like you have the parts there just a question of what goes where.
>
> Chris
>
> ___
> 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] (no subject)

2009-11-16 Thread Wayne Werner
On Mon, Nov 16, 2009 at 4:52 PM, Carlos Flores  wrote:

>  Dear Python,
>
> I am trying to learn Python to experience my computer programming
> knowledge.
>

Welcome to the wonderful world of Python - we think it's a good extension of
anyone's knowledge


>  I am working through the online textbook How to Think Like A Computer
> Scientist. I have made it through chapters 1-5 and completed the exercises
> at the end. Now I am on chapter 6 and I am having a lot of trouble and its
> only going to get harder from here on. Is there any sources that help with
> these exercises that are at the end of each chapter?
>

I'm not aware of any... if you're worried that you're doing something wrong,
you can always use a pastebin to post your code and have us look at it. If
you're as respectful as you've been so far, you'll probably find someone
willing to take a look to see if your code does what you think it should be
doing.


> Its tough not knowing if I am doing these exercises correctly without
> seeing the actual answers.
>

That's very true! But there are a lot of smart folks on this list who are
happy to help when you get stuck somewhere.

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


Re: [Tutor] Iterable Understanding

2009-11-16 Thread Martin Walsh
Stephen Nelson-Smith wrote:
> Nope - but I can look it up.  The problem I have is that the source
> logs are rotated at 0400 hrs, so I need two days of logs in order to
> extract 24 hrs from  to 2359 (which is the requirement).  At
> present, I preprocess using sort, which works fine as long as the
> month doesn't change.

Still not sure without more detail, but IIRC from your previous posts,
your log entry timestamps are formatted with the abbreviated month name
instead of month number. Without the -M flag, the sort command will ...
well, erm ... sort the month names alphabetically. With the -M
(--month-sort) flag, they are sorted chronologically.

Just a guess, of course. I suppose this is drifting a bit off topic, in
any case, but it may still serve to demonstrate the importance of
converting your string based timestamps into something that can be
sorted accurately by your python code -- the most obvious being time or
datetime objects, IMHO.


>> class LogFile(object):
>>def __init__(self, filename, jitter=10):
>>self.logfile = gzip.open(filename, 'r')
>>self.heap = []
>>self.jitter = jitter
>>
>>def __iter__(self):
>>while True:
>>for logline in self.logfile:
>>heappush(self.heap, (timestamp(logline), logline))
>>if len(self.heap) >= self.jitter:
>>break
> 
> Really nice way to handle the batching of the initial heap - thank you!
> 
>>try:
>>yield heappop(self.heap)
>>except IndexError:
>>raise StopIteration

>> ... which probably won't preserve the order of log entries that have the
>> same timestamp, but if you need it to -- should be easy to accommodate.
> 
> I don't think  that is necessary, but I'm curious to know how...

I'd imagine something like this might work ...

class LogFile(object):
def __init__(self, filename, jitter=10):
self.logfile = open(filename, 'r')
self.heap = []
self.jitter = jitter

def __iter__(self):
line_count = 0
while True:
for logline in self.logfile:
line_count += 1
heappush(self.heap,
   ((timestamp(logline), line_count), logline))
if len(self.heap) >= self.jitter:
break
try:
yield heappop(self.heap)
except IndexError:
raise StopIteration

The key concept is to pass additional unique data to heappush, something
related to the order of lines from input. So, you could probably do
something with file.tell() also. But beware, it seems you can't reliably
tell() a file object opened in 'r' mode, used as an iterator[1] -- and
in python 3.x attempting to do so raises an IOError.

[1] http://mail.python.org/pipermail/python-list/2008-November/156865.html

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


Re: [Tutor] search the folder for the 2 files and extract out only the version numbers 1.0 and 2.0.

2009-11-16 Thread Timo

I find regular expressions alwys hard to get, so here is my solution:

>>> import glob
>>> 
glob.glob('C:\\Users\\blueman\\Desktop\\allFiles\\MyTest[0-9].[0-9].zip')



Cheers,
Timo


MARCUS NG schreef:

Hi all,
I am really new to python and I am trying to create a script that 
looks at file versions of a particular file
I have 4 files in a folder. One called myTest1.0.zip, myTest2.0.zip, 
test3.txt and test4.zip in a directory/folder called allFiles on my 
desktop.

so the file structure is as such

C:\Users\blueman\Desktop\allFiles\myTest1.0.zip
and
C:\Users\blueman\Desktop\allFiles\myTest2.0.zip

Aim:
what is the best way to look into the allFiles directory, and only 
search the folder for the 2 files myTest1.0.zip and myTest2.0.zip to 
extract out only the version numbers 1.0 and 2.0.


what i have for my script so far is

import os
#path of  scripts folder
path="C:/Users/blueman/Desktop/allFiles/"
dirList=os.listdir(path)
for fname in dirList:
print fname

so I did think of listing the file names in an array only to realise 
that I wouldn't know which index to query if this script is going to 
be automated.


what is the best way to obtain the version numbers of the 2 files?
thank you for your time.



___
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


[Tutor] pyce, scripts complete too fast

2009-11-16 Thread rick
Perhaps the wrong list, but I'll ask anyway.  So I'm in the middle of
starting, yet again, to learn some programming.   I have 2.6.4 and 3.1
installed on the desktop (Ubuntu 9.10), 2.6.4 installed on the netbook
(UNR 9.10).   

I was thinking to be ultra portable, I'd put python on the pocket pc.
Now I'm back to the problem that a Windows newbie would have, the
scripts complete before I can see what happened!  I can get right to the
interactive mode, or I can run a script, but not sure where I'd find the
terminal.

Thanks Alan, I was going through your old tutorial, the pointer to the
new was appreciated.

Rick

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


Re: [Tutor] pyce, scripts complete too fast

2009-11-16 Thread Wayne Werner
On Tue, Nov 17, 2009 at 12:51 AM, rick  wrote:

> I was thinking to be ultra portable, I'd put python on the pocket pc.
> Now I'm back to the problem that a Windows newbie would have, the
> scripts complete before I can see what happened!  I can get right to the
> interactive mode, or I can run a script, but not sure where I'd find the
> terminal.
>

Add "raw_input('')" or some such to the end of your
program!

HTH,
Wayne

-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor