[Tutor] help with random.randint

2010-02-02 Thread David

Hello list,

I thought this was easy even for me, but I was wrong, I guess.
Here is what I want to do: take two random numbers between 1 and 99, and 
put them into a list.


import random
terms =  []
for i in range(2):
terms = random.randint(1, 99)
print terms

This prints just one number (the last one generated in the loop?)

So I tried to change line 4 to the following:
terms += random.randint(1, 99)
hoping that it would add a second integer to my terms list. But I get an 
error:


/home/david/Documents/Python-Projekt/multiplier.py in ()
  2 terms =  []
  3 for i in range(2):
> 4 terms += random.randint(1, 99)
  5 print terms
  6

TypeError: 'int' object is not iterable
WARNING: Failure executing file: 

I understand this error thus: once an int has been placed into the list 
terms, no further int can be added. But: terms is a mutable list, and 
NOT an 'int' object!


So here are my questions: what is the problem, and how can I generate 
two random numbers and store them (preferably in a tuple)?


Many thanks,

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


Re: [Tutor] help with random.randint (cont. -- now: pseudo code)

2010-02-02 Thread David

Hello Benno, list,

thanks for those clarifications, which, well, clarify things ;-)

This is my latest creation:

import random

def createTerms():
terms =  []
for i in range(2):
terms.append(random.randint(1, 99))
j = terms[0]
k = terms[1]
print "%3d\nx%2d" % (j, k)

createTerms()

Which works. However, it merely prints a multiplication task. Anyway, 
this was just a prelude. In the end, I want far more, namely to create, 
ask, and verify some multiplication questions. Here is my pseudo code of 
this little project:




pool = []
correct = 0
incorrect = 0

def createQuestions:
generate all multiplication combinations possible
append as tuple to pool
eliminate 'mirrored doubles' (i.e. 7x12 and 12x7)
randomize pool

def askQuestions:
for question in pool:
calculate solution
take answer from user
if user answer == solution:
correct += 1
remove question from pool
else:
incorrect += 1

def showStats:
print number of questions asked
print number of questions answered correctly
print percentage of correct answers

def askFaultyAnswers:
answer = raw_input("Try again the incorrect questions? (y/n) ")
if answer == "y":
aksQuestions()
else:
break


createQuestions()
askQuestions()
showStats()
askFaultyAnswers()
print "good-bye!"



I think it is sensible to

* first create all possible solutions, then
* kick out doublettes, and only then
* ask questions

I have some questions though:

Is the overall structure and flow of this program okay? What are the 
main problems you can spot immediately?


In the very end I would like to take this code as a basis for a wxPython 
program. Are there any structural requirements I am violating here?


If I want to limit the number of questions asked, say to 20, would I 
operate with slicing methods on the randomised pool?


How would you go about showing stats for the second run (i.e. the 
FaultyAnswers)? Right now I am thinking of setting the global variables 
correct and incorrect to 0 from _within_ askFaultyAnswers; then I would 
run showStats() also from _within_ askFaultyAnswers. Good idea?


Many thanks for your guidance and input!

David






On 03/02/10 12:25, Benno Lang wrote:

On Wed, Feb 3, 2010 at 12:21 PM, David  wrote:

Hello list,

I thought this was easy even for me, but I was wrong, I guess.
Here is what I want to do: take two random numbers between 1 and 99, and put
them into a list.

import random
terms =  []
for i in range(2):
terms = random.randint(1, 99)


All you're doing here is assigning an integer value to 'terms', twice.
This assignment means 'terms' is no longer a list, but is now just an
int. What you want is probably:
terms.append (random.randint(1, 99))


So I tried to change line 4 to the following:
terms += random.randint(1, 99)


You can't freely mix types with python operators, i.e. a_list += an_int
But you can use += with 2 ints or 2 lists, so you could do:
terms += [random.randint(1, 99)]
I think using append is much nicer though.


I understand this error thus: once an int has been placed into the list
terms, no further int can be added. But: terms is a mutable list, and NOT an
'int' object!


The int was never added to the list in the first place, because list
+= int is not something Python understands.


So here are my questions: what is the problem, and how can I generate two
random numbers and store them (preferably in a tuple)?


I hope what I wrote above answers the first question.
IIRC tuples are immutable, so you either to create the list first and
then convert it to a tuple:
terms_tuple = tuple(terms)

Or you can create a tuple from the beginning (without a loop):
terms_tuple = (random.randint(1, 99), random.randint(1, 99))

HTH,
benno



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


Re: [Tutor] help with random.randint

2010-02-02 Thread David

Hello Bob,

thanks for your comments!


On 03/02/10 14:51, bob gailer wrote:


or if you seek terseness:

terms = [random.randint(1, 99) for i in 'ab']


Do I understand correctly that 'ab' here merely serves to produce a 
'dummy sequence' over which I can run the for loop?


David

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


Re: [Tutor] help with random.randint (cont. -- now: pseudo code)

2010-02-03 Thread David

Bob,

brilliant stuff -- I am truly awed by this. Create a default-filled 
matrix and mark combinations used so as to take them out of the game? 
Wow. This is new to me.


On 03/02/10 15:46, bob gailer wrote


def askQuestions(): # generate and ask questions:
for i in range(NQ):
while 1: # loop till we get an unused combo
x, y = [random.randint(1,MAX) for i in 'ab']
if mtable[x][y] == 1: # combo is available
break
askQuestion(x,y)
# indicate asked
mtable[x][y] = 0
mtable[y][x] = 0


Here you lose me, though. Where does mtable come from, what does it do? 
You don't introduce it as a variable, and when I google it, nothing much 
comes of if...


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


Re: [Tutor] help with random.randint

2010-02-03 Thread David

Hello Eike,

thanks for the explanation, all this is really helpful -- I certainly 
have learned sth. today!
I wonder, though, how I would get my number pairs, which I need later 
on, if I were to follow your solution. I am asking because as I 
understand your code, the list terms is a list of integers here, but not 
of x,y pairs, right? (I can see that this was a problem of my code right 
from the start, btw.)


David

On 03/02/10 19:08, Eike Welk wrote:

Hello David!

On Wednesday February 3 2010 04:21:56 David wrote:


import random
terms =  []
for i in range(2):
terms = random.randint(1, 99)
print terms


Here is an other solution, which is quite easy to understand and short:

import random
terms =  []
for i in range(2):
 terms += [random.randint(1, 99)]
print terms


Note the rectangular brackets around "[random.randint(1, 99)]". This creates a
list which a single number in it. This small list can then be added to the
already existing list "terms".


Eike.
___
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] how to graph percentile -- matplotlib, Inkscape, or what?

2010-02-06 Thread David

Dear List,

given a list of scores (n = 20, say) a group students received in an 
exam, I can use


sarray = [list of scores]
score = student's score
scipy.stats.percentileofscore(sarray, score, kind='mean')

to calculate the percentile for a given student. What I would like to do 
is to create a graph in which on the horizontal axis the student's 
precentile (i.e. performance vis-a-vis her classmates) is indicated by 
means of a needle stuck into the axis:


   O (63%)  
|__|__|
| |
0100

I suspect that I cannot plot this with matplotlib, and my next best 
guess would be Inkscape, with which I have no scripting experience 
whatsoever.


Is Inkscape the way forward for this little project? What are my 
alternatives?


Thanks for your ideas!

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


Re: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what?

2010-02-06 Thread David

Hello Alan,

thanks for the guidance, I will then dig a little deeper into 
matplotlib. I guess the reason why I discarded it before is that I 
understood matplotlib to be a curve plotting tool, and not so much a 
tool to draw graphics. I will investigate!


David


On 06/02/10 17:15, Alan Gauld wrote:


"David"  wrote

is to create a graph in which on the horizontal axis the student's
precentile (i.e. performance vis-a-vis her classmates) is indicated by
means of a needle stuck into the axis:

O (63%) |__|__|
| |
0 100

I suspect that I cannot plot this with matplotlib, and my next best
guess would be Inkscape, with which I have no scripting experience
whatsoever.


Why do you think you couldn't do it with matplotlib?
It seems a fairly basic request.
I have no experience with either package but matplotlib is the first
place I'd look for this.

There is also gnuplot which I've used outside Pytthon, but it could do
this too I'm sure.

OTOH It would be fairly easy to roll your own in a vanilla GUI Canvas
widget. Its only a few stratight lines and text after all.
Or even to use a scroll bar or progress bar widget to indicate the result.



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


[Tutor] if item.find(extension)!= -1: -- what's the -1?

2010-02-06 Thread David

Hello again,

in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes 
frequent use of the term -1 in his code, but doesn't tell to what aim. 
For want of search terms Google is not helpful. Could someone please 
enlighten me by means of a one-liner as a reply?


Thank you!

David


Example Code:

for item in filelist:
if item.find(extension)!= -1:
snaplist.append(item)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if item.find(extension)!= -1: -- what's the -1?

2010-02-06 Thread David

Thank you Wayne, Kent,

it's easy to see clearly once told what to focus on ;-)

David


On 07/02/10 00:35, David wrote:

Hello again,

in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes
frequent use of the term -1 in his code, but doesn't tell to what aim.
For want of search terms Google is not helpful. Could someone please
enlighten me by means of a one-liner as a reply?

Thank you!

David


Example Code:

for item in filelist:
if item.find(extension)!= -1:
snaplist.append(item)
___
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



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


Re: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what?

2010-02-07 Thread David

Yes, you are right, I initially certainly didn't think of it as a function.
Right now I am wondering if it would not be more straight forward to 
take for the 'axis' a bitmap background and place the needle (another 
bitmap) at the right position of the background. Come to think of it, 
PyX might be a good choice for this sort of thing. But again, I have not 
practical experience with that tool.


David


On 07/02/10 02:29, Alan Gauld wrote:


"David"  wrote in message news:4b6d37e4.9050...@gmx.net...

matplotlib. I guess the reason why I discarded it before is that I
understood matplotlib to be a curve plotting tool, and not so much a
tool to draw graphics. I will investigate!


It is but a single point on a an axis is a pretty basic curve!
But as I say, I've never used it, I just assumed this should be verging
on the trivial for it.

Alan G.


___
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] NameError: global name 'celsius' is not defined (actually, solved)

2010-02-09 Thread David

Hi guys,

I just wrote this message, but after restarting ipython all worked fine.
How is it to be explained that I first had a namespace error which, 
after a restart (and not merely a new "run Sande_celsius-main.py"), went 
away? I mean, surely the namespace should not be impacted by ipython at 
all!?


Many thanks,

David


Dear List,

this should be so basic that I feel bad asking this question here, but I 
don't get it.


I am having a look at Sande's book "Hello World". The topic is 
'Modules', and the code comes directly from the book.


I have two files: Sande_celsius-main.py and Sande_my_module.py.

I import the latter from within the former.

# file: Sande_celsius-main.py
from Sande_my_module import c_to_f
celsius = float(raw_input("Enter a temperature in Celsius: "))
fahrenheit = c_to_f(celsius)
print "That's ", fahrenheit, " degrees Fahrenheit"


# this is the file Sande_my_module.py
# we're going to use it in another program
def c_to_f(celsius):
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

When I run Sande_celsius-main.py, I get the following error:

NameError: global name 'celsius' is not defined
WARNING: Failure executing file: 

First of all, this error message doesn't exactly tell me _where_ the 
problem is, does it? It could be a problem with(in) the imported 
function c_to_f... I wish he would tell me: "Problem in file x, line y".


Secondly, the name celsius in the global namespace of ~-main.py is 
merely a variable, which later is then used as a parameter to c_to_f. I 
do not see a problem here.


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


Re: [Tutor] NameError: global name 'celsius' is not defined (actually, solved)

2010-02-09 Thread David

Hello Wesley,

thanks for your reply. I was surprised about the limited information 
too. Sadly (?), I can't reproduce the error any more...


David



On 10/02/10 11:13, wesley chun wrote:

I just wrote this message, but after restarting ipython all worked fine.
How is it to be explained that I first had a namespace error which, after a
restart (and not merely a new "run Sande_celsius-main.py"), went away? I
mean, surely the namespace should not be impacted by ipython at all!?
 :
# file: Sande_celsius-main.py
from Sande_my_module import c_to_f
celsius = float(raw_input("Enter a temperature in Celsius: "))
fahrenheit = c_to_f(celsius)
print "That's ", fahrenheit, " degrees Fahrenheit"

# this is the file Sande_my_module.py
# we're going to use it in another program
def c_to_f(celsius):
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

When I run Sande_celsius-main.py, I get the following error:

NameError: global name 'celsius' is not defined
WARNING: Failure executing file:



Python interpreters including the standard one or IPython should tell
you a lot more than that. how are you executing this code? would it be
possible to do so from the command-line? you should get a more verbose
error message that you can post here.

best regards,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
 http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com



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


Re: [Tutor] Coin flip game

2010-02-11 Thread David

Hello Lawrence,

let me try to clarify this (warning: am a beginner myself).

On 12/02/10 06:15, Jones, Lawrence D wrote:

Hi,

I'm new to the list and to Python. I'm reading through Michael Dawson's 'Python 
programming: for absolute beginners' and at the end of chapter 3 he's set a 
challenge where the reader has to create a coin flip game. My code now works, 
but only after I randomly switched pieces of the code around and, basically, 
pulled my hair out because it wouldn't work.

My code is below. But can someone please explain to me why the following 
variable has to be placed where it is for the code to work? I thought it would 
need to go nearer the start of the code i.e. just before heads = 0, tails = 0 
etc:

 coin = random.randrange(2)


Python runs through your code, step by step. I believe it starts at the 
top and goes down, following the logic of your code. When you make 
Python refer to a variable in your while loop that Python has not 
encountered yet, then it will not know what to do -- and complain about 
it. Solution: let Python know of the variable _before_ you then start to 
work with it.




Also, why does the randrange integer have to be '2'? I only discovered this 
worked by complete accident. I tried '1' and '0,1' as my integers but they just 
didn't work.


That is because your coin has _two_ sides, and you therefore want a 
random choice out of _two_ possibilities. With the random.randrange(2) 
function the choices will be 0 and 1, satisfying your demands. This 
means that the randrange() function goes up to, but not including, the 
integer you supply. It amounts to two choices in the end all the same 
because the counting starts with 0 instead of 1.
That is, if you chose randrange(1) you will get only one answer, namely 
0. If you type randrange(0) then you will get an error message 
(ValueError: empty range for randrange). Which makes sense. Remember, 
randrange() goes up to, but not including the integer supplied.


HTH,

David












Thanks,

Lawrence


import random
print "The Coin Flip Game\n"

heads = 0
tails = 0
count = 0

while count<  100:
 coin = random.randrange(2)
 if coin == 0:
 heads = heads + 1
 else:
 tails = tails + 1
 count += 1

print "Heads: ", heads
print "Tails: ", tails

raw_input("\nPress enter to exit.")







___
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] New Python testing book

2010-02-12 Thread David

Hi Alan,

On 12/02/10 17:34, Alan Gauld wrote:


Amazon are remarkably reticent about the actual contents.

See here: http://tinyurl.com/y9dy62p

I am, btw, always happy to see 'book announcements' on this list -- keep 
them coming!


David
___
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 David
>> After six years of tutor posts my interest and energy have waned and
>> I'm ready to move on to something new. 
Another new Python student that received understanding from your style
and knowledge, great teacher. I hope you will post some more tutorials
on Kents Korner when you find the time and motivation, thanks again;
David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Passing arguments to CGI script

2010-06-15 Thread David
Hi, I'm trying to pass arguments to a python script running on my
webserver. Here is the script:

import cgi
import cgitb
import sys
cgitb.enable()

form = cgi.FieldStorage()
title = form.getvalue("title")
print """Content-type: text/html

"""
print form.keys()
print """

"""

When I run it on the website like
http://mf-doom.com/album.py?title=blah it just prints out an empty
array. Is there something wrong with my code? Or is there something
wrong with the way my server's configured?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] test

2010-11-05 Thread David
On 6 November 2010 16:20, Steven D'Aprano  wrote:
> Luke Paireepinart wrote:
>>
>> You don't get your own e-mails back.
>
> I do.
>
> Perhaps it's an option when you sign up?

For any list (like this one) hosted by mailman, the default is set by
list administrator, but every user can customise this at their list
config via the URL mentioned in the footer.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] help with loop that is to be fed out of a word list

2009-02-09 Thread David
Dear list,

out of "Thinking in Python" I take the following code, which
"takes a word and a string of required letters, and that returns True if
the word uses all the required letters at least once".


def uses_all(word, required):
for letter in required:
if letter not in word:
return False
return True

Now, I want to feed this code a list of words. This is what I have so far:


def uses_all(required):
fin = open('words.txt')
for line in fin:
word = line.strip()
for letter in required:
if letter not in word:
# print "False!"
return False
print word

required = raw_input("what letters have to be used? ")
print required

uses_all(required)


The code runs, but does not print the words. All I get it the output of
the 'print required' command:

da...@ubuntu:~/Documents/Tools/Python/Code$ python downey_9.5.py
what letters have to be used? zhg
zhg
aa
z
da...@ubuntu:~/Documents/Tools/Python/Code$

I realise that my loop fails to execute beyond the first word in the
list ("aa"), but why?   

Thanks in advance for your insights!

David

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


[Tutor] Program to report if file was modified today

2009-02-11 Thread David

Hi Everyone and thanks for the list and your help.
In my adventure in learning Python (never programed before) I am 
attempting to findout if a file has been modified today given a search 
path. It is working somewhat. Here it is;


#!/usr/bin/python
import sys
import os
import time

def Mod():
"""Find files modified today, given a file path."""
latest = 0
dir = os.path.dirname(sys.argv[1])
for fname in os.listdir(dir):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(dir, fname)).st_mtime
if modtime > latest:
latest = modtime
out = time.strftime('%Y-%m-%d', time.localtime(latest))
my_list = [fname, out]
print fname
now = time.strftime('%Y-%m-%d', time.localtime())
if my_list[-1] == now:
print "This file has changed today."
print "*"*30
else:
    print "This file did not change"

results;
./py_lastmod_date.py /home/david/

py_pyparse_end.py
This file did not change
**
cologne_time.py
This file did not change
**
py_find_word_prefix.py
This file did not change
**
py_round_by_five.py
This file did not change
**
graphics.py
This file did not change
**
py_countdown_generator.py
This file did not change
**
py_compare_time.py
This file has changed today.
**
py_lastmod_date.py
This file has changed today.
**

OK here are my questions.
Is there an easier way of doing this?
Why does it only return 8 results, I have a ton of .py files in /home/david
Why do both the if and else get printed?
How do I do this without all the if statments?
I don't understand the if modtime > latest part, is this to loop over 
the files and put the oldest last? I found that part in another program 
and my program does not work without it.

Thank you,
-david


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Program to report if file was modified today

2009-02-11 Thread David

bob gailer wrote:


1) That can't be the entire program, as there is no call to Mod()!

Yep, it was lost in my copy paste
2) Convention says function names start with lower case. Save initial 
caps for class names.

Thanks for the reminder, I had forgotten :)

3) Get rid of latest - that is why you are not getting all the files.

For some reason when I take that out it reports all file have been modified.

4) Use glob.glob() so you can specify *.py
5) It is not necessary to convert times to strings. You can get midnight 
today from int(time.localtime())

OK

6) Move calculation of now outside the loop, as it does not change.

Good Point, makes since now.

7) my_list is not necessary.
Ok, my reason was to make sure the file and date remained together but 
It works fine without it.

8) revised (untested) code:

I get this error with the int(time.localtime())
 start_of_today = int(time.localtime())
TypeError: int() argument must be a string or a number, not 
'time.struct_time'


Thanks Bob,
I really only want it to report when a file has been modified so this 
seems to work, next I will work on putting glob.glob working plus any 
other suggestions.


#!/usr/bin/python
import sys
import os
import time

def mod():
"""Find files modified today, given a file path."""
latest = 0
now = time.strftime('%Y-%m-%d', time.localtime())
dir = os.path.dirname(sys.argv[1])
for fname in os.listdir(dir):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(dir, fname)).st_mtime
if modtime > latest:
latest = modtime
out = time.strftime('%Y-%m-%d', time.localtime(latest))
if out == now:
print fname, "has changed today. "
else:
    pass
mod()

results;
david [09:25 PM] opteron ~ $ ./py_lastmod_date.py /home/david/
py_compare_time.py has changed today.
py_lastmod_date.py has changed today.

-david

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Program to report if file was modified today

2009-02-12 Thread David
Kent Johnson wrote:
> On Wed, Feb 11, 2009 at 11:21 PM, bob gailer  wrote:
>   
>
Thanks Alan and Kent,
This works as expected;

#!/usr/bin/python
import sys
import os
import time

def mod():
"""Find files modified today, given a file path."""
now = time.strftime('%Y-%m-%d', time.localtime())
dir = os.path.dirname(sys.argv[1])
for fname in os.listdir(dir):
if fname.endswith('.py'):
modtime = os.stat(os.path.join(dir, fname)).st_mtime
out = time.strftime('%Y-%m-%d', time.localtime(modtime))
if out == now:
print fname, "has changed today. "
mod()

-david

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


Re: [Tutor] Program to report if file was modified today

2009-02-12 Thread David
David wrote:
> Kent Johnson wrote:
>   
>> On Wed, Feb 11, 2009 at 11:21 PM, bob gailer  wrote:
>>   
>>
>> 
> Thanks Alan and Kent,
> This works as expected;
> 
> #!/usr/bin/python
> import sys
> import os
> import time
>
> def mod():
> """Find files modified today, given a file path."""
> now = time.strftime('%Y-%m-%d', time.localtime())
> dir = os.path.dirname(sys.argv[1])
> for fname in os.listdir(dir):
> if fname.endswith('.py'):
> modtime = os.stat(os.path.join(dir, fname)).st_mtime
> out = time.strftime('%Y-%m-%d', time.localtime(modtime))
> if out == now:
> print fname, "has changed today. "
> mod()
> 
> -david
>
>   
Sorry and Bob :)

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


[Tutor] *nix tail -f multiple log files with Thread

2009-02-13 Thread David

Hi everyone,

I copied a program from C to track multiple log files. I would like to 
be able to print a label when a log file is updated. Here is the program;


#!/usr/bin/python
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 3
queue = Queue()
logfiles = ["/var/log/messages",
"/var/log/apache2/access_log",
"/var/log/apache2/error_log"]

def logtailer(i, q,):
while True:
lfile = q.get()
sudo = "sudo"
tail = "tail"
arg = "-f"
ret = subprocess.call([sudo, tail, arg, lfile])
q.task_done()

for i in range(num_threads):
worker = Thread(target=logtailer, args=(i, queue))
worker.setDaemon(True)
worker.start()

for lfile in logfiles:
queue.put(lfile)

queue.join()

And here is a sample of the output;

[Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not 
exist: /var/www/localhost/htdocs/moodle/favicon.ico
[Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not 
exist: /var/www/localhost/htdocs/moodle/favicon.ico
Feb 13 09:02:26 opteron sudo:david : TTY=pts/4 ; PWD=/home/david ; 
USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log
Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened for 
user root by david(uid=0)
Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed for 
user root
Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x 
/usr/sbin/run-crons && /usr/sbin/run-crons )

Feb 13 09:18:33 opteron su[10678]: Successful su for root by david
Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root
Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session opened 
for user root by david(uid=1000)
127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET 
/theme/custom_corners/favicon.ico HTTP/1.1" 200 894
127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET 
/lib/speller/spellChecker.js HTTP/1.1" 200 15980

127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718
127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET 
/theme/custom_corners/styles.php HTTP/1.1" 200 30709


I would like to be able to add a label like;


[Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not 
exist: /var/www/localhost/htdocs/moodle/favicon.ico
[Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not 
exist: /var/www/localhost/htdocs/moodle/favicon.ico


Feb 13 09:02:26 opteron sudo:david : TTY=pts/4 ; PWD=/home/david ; 
USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log
Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened for 
user root by david(uid=0)
Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed for 
user root
Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x 
/usr/sbin/run-crons && /usr/sbin/run-crons )

Feb 13 09:18:33 opteron su[10678]: Successful su for root by david
Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root
Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session opened 
for user root by david(uid=1000)


127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET 
/theme/custom_corners/favicon.ico HTTP/1.1" 200 894
127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET 
/lib/speller/spellChecker.js HTTP/1.1" 200 15980

127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718
127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET 
/theme/custom_corners/styles.php HTTP/1.1" 200 30709


I can create the label like this;
def label()
print "<%s\n>" % lfile

But I have no idea how to get it to work when a thread is updated.
thanks
-david



--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] *nix tail -f multiple log files with Thread

2009-02-15 Thread David

David wrote:

bob gailer wrote:

Did the C program accomplish that? If so, it might help to see that 
code. If not why mention it?


It is here if you want to check it out;
http://dwabbott.com/downloads/logtailer.c.txt


Your example output falls short of your stated goal as I understand 
it! My guess is that you want what you showed:

Is this accurate?


Yes, thanks for the reply, It was good practice but come to find out
that tail will do what I want on its own. The only thing I would like to
do is add color to the labels but that is for another list :)
I am new to python and never programed before and would like to thank
everyone on the list. It has made learning python fun.
-david

Resent because I forgot to reply all :(


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] *nix tail -f multiple log files with Thread

2009-02-16 Thread David
Bill Campbell wrote:
>
> The ``swatch'' program, written in perl, does this by using the
> gnu-tail program via a pipe using.
>
>   gtail --follow=name --lines=1 file1 file2 ...
>
> Use the source Luke.
>
> Bill
>   
Thanks Bill,
That looks like the right tool for the job at hand. Looking at setting
up the configuration file, a stumbling block in my learning to program
is my lack of a good understanding of regular expressions. I have
started studying grep, sed and awk. It is a lot more fun to just write
little python programs and watch in amazement when they work as
expected. I have been avoiding this phase of learning.
-david

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


Re: [Tutor] *nix tail -f multiple log files with Thread

2009-02-16 Thread David
Bill Campbell wrote:
> On Mon, Feb 16, 2009, David wrote:
>   
>> Bill Campbell wrote:
>> 
>>> The ``swatch'' program, written in perl, does this by using the
>>> gnu-tail program via a pipe using.
>>>
>>> gtail --follow=name --lines=1 file1 file2 ...
>>>
>>> Use the source Luke.
>>>
>>>   
> ...
>   
>> That looks like the right tool for the job at hand. Looking at setting
>> up the configuration file, a stumbling block in my learning to program
>> is my lack of a good understanding of regular expressions. I have
>> started studying grep, sed and awk. It is a lot more fun to just write
>> little python programs and watch in amazement when they work as
>> expected. I have been avoiding this phase of learning.
>> 
>
> Looking at other people's scripts can be very enlightening.  When I started
> learning Xenix in 1982, there were about 2 books on the subjects, Jean
> Thompson's blue one, and I forget the other.  I learned a lot by reading
> system administration scripts, once I figured out that these were working
> programs.
>
> One of the best books I've ever seen for general *nix text processing and
> use of tools is ``Unix Text Processing'' by Dougherty and O'Reilly.  It has
> been out of print for years, but can probably be found through
> bookfinder.com It has lots on regular expressions, using ``vi'', etc.
>
> There is information on regular expressions in any book on python, perl,
> and other scripting languages.  O'Reilly has a book ``Mastering Regular
> Expressions'' which is probably pretty good, but I have never read it.
>
> Bill
>   
OK, I found ``Unix Text Processing`` for $5 and I did start ``Mastering
Regular Expressions so I have the material, now I just need a
photographic memory to speed the process up :)
-david

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


[Tutor] Class instance understanding = None

2009-02-26 Thread David

Hi Everyone,
I go through the archived [Tutor] mail list to find programs others have 
tried to do. I found one that would keep track of a petty cash fund. 
please point out my misunderstanding.

Here is what I started with;

#!/usr/bin/python

from reportlab.lib.normalDate import ND
#import cPickle as p
#import pprint

today = ND()

class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self, amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
print 'The current date is: ', today.formatUS()


data = float('100.00')
a = Account(data)
p = a.getbalance()
print 'balance = ', p
remove_data = float('50.00')
w = a.withdraw(remove_data)
print "withdraw = ", w
add_data = float('50.00')
add = a.deposit(add_data)
print "deposit = ", add


results;
The current date is:  02/27/09
balance =  100.0
withdraw =  None
deposit =  None

expected results;
The current date is:  02/27/09
balance =  100.0
withdraw =  50.0
deposit =  100.0

thanks,
-david


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Class instance understanding = None

2009-02-27 Thread David
Thank you spir and Andre for the explanation. You are very good 
teachers. I can now continue. I am sure I will be back. Next I am going 
to set up a menu to enter amounts and also a way to store the resulting 
balance. Is cPickle a good way to do this?

-david


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Class instance understanding = None

2009-02-27 Thread David
Thank you spir and Andre for the explanation. You are very good 
teachers. I can now continue. I am sure I will be back. Next I am going 
to set up a menu to enter amounts and also a way to store the resulting 
balance. Is cPickle a good way to do this?

-david
--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Class instance understanding = None

2009-02-27 Thread David

Andre Engels wrote:



The more preferable method is to leave the class alone, and call
getbalance by hand:

data = float('100.00')
a = Account(data)
p = a.getbalance()
print 'balance = ', p
remove_data = float('50.00')
a.withdraw(remove_data)
w = a.getbalance()
print "withdraw = ", w
add_data = float('50.00')
a.deposit(add_data)
add = a.getbalance()
print "deposit = ", add

Some other things:
1. data = float('100.00') is unnecessarily clumsy - you can specify
floats directly without creating a string first by doing data = 100.0
2. You are creating a lot of variables only to use them for the one
and only time on the next line. That's not necessarily bad, it
sometimes improves readability especially if a lot is being done
(which can then be split up in more readable parts), but doing it this
much mostly causes your coding to look more complicated than it
actually is. I would either prefer something like this:

data = 100.0
remove_data = 50.0
add_data = 50.0# first all input-like elements, so I know
where to go when I want to change something trivial
a = Account(data)
print 'balance = ',a.getbalance()
a.withdraw(remove_data)
print 'balance after withdraw = ',a.getbalance()
a.deposit(add_data)
print 'balance after deposit = ',a.getbalance()

doing away with p, w and add, or the even shorter variant where data,
remove_data and add_data are also removed:

a = Account(100.0)
print 'balance = ',a.getbalance()
a.withdraw(50.0)
print 'balance after withdraw = ',a.getbalance()
a.deposit(50.0)
print 'balance after deposit = ',a.getbalance()


Ok almost there, here is what i have now;
http://linuxcrazy.pastebin.com/m6b090d2d

My problem now is the balance is updated from the file that is pickled 
fine, but the first entry goes is not added to that total. I know it is 
in this part;


start_total()
start = 0
a = Account(start)

but when I change it to;
start_total()
start = start_total()
a = Account(start)

here is the error;
Enter Amount: 100
Traceback (most recent call last):
  File "./py_pettycash.py", line 77, in 
menu()
  File "./py_pettycash.py", line 53, in menu
a.deposit(cash)
  File "./py_pettycash.py", line 15, in deposit
self.balance = self.balance + amt
TypeError: unsupported operand type(s) for +: 'NoneType' and 'Decimal'

-david


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Class instance understanding = None

2009-02-27 Thread David

David wrote:


but when I change it to;
start_total()
start = start_total()
a = Account(start)

here is the error;
Enter Amount: 100
Traceback (most recent call last):
  File "./py_pettycash.py", line 77, in 
menu()
  File "./py_pettycash.py", line 53, in menu
a.deposit(cash)
  File "./py_pettycash.py", line 15, in deposit
self.balance = self.balance + amt
TypeError: unsupported operand type(s) for +: 'NoneType' and 'Decimal'

-david



Ok I got it, same problem I had before no return :)

def start_total():
fname = open("cash.dat", "r")
contents = cPickle.Unpickler(fname)
data = contents.load()
print "The current balance is", data
fname.close()
return data

start = start_total()
a = Account(start)

Thanks all, any other comments?, I am going to add some error checking 
but, I am so happy, woopee


-david

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] UNSUBSCRIPTABLE?

2009-03-08 Thread David

bob gailer wrote:

Kapsicum wrote:



On Mon, Mar 9, 2009 at 1:18 AM, WM. > wrote:


Traceback (most recent call last):
 File "C:\Python26\TicTacToeD.py", line 165, in 
   main()
 File "C:\Python26\TicTacToeD.py", line 150, in main
   DisplayBoard(board)
 File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard
   print "\n\t", board[1], "|", board[2], "|", board[3]
TypeError: 'function' object is unsubscriptable

 
error means the object returned is not of type sequence


No. It means that the object does not have a way to handle []. Many 
objects are subscriptable besides sequences.


dict, set, objects with certain "special methods" e.g., __getitem__


how about;
print "\n\t", board[0], "|", board[1], "|", board[2]

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] UNSUBSCRIPTABLE?

2009-03-08 Thread David

WM. wrote:

I am using Python 26 on a Windows XP

OK, here are the three lines mentioned following the error message.

Traceback (most recent call last):
  File "C:\Python26\TicTacToeD.py", line 165, in 
main()
  File "C:\Python26\TicTacToeD.py", line 150, in main
DisplayBoard(board)
  File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard
print "\n\t", board[1], "|", board[2], "|", board[3]
TypeError: 'function' object is unsubscriptable


line 165 = main()

def main():
DisplayInstruct()
puter, human = Pieces()
turn = X
board = NewBoard
DisplayBoard(board)

line 150 = DisplayBoard(board)

line 69
def DisplayBoard(board):
"""Display board on screen."""
print "\n\t", board[1], "|", board[2], "|", board[3]
print "\t", "__"
print "\t", board[4], "|", board[5], "|", board[6]
print "\t", "__"
print "\t", board[7], "|", board[8], "|", board[9], "\n"

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



so you have this
def NewBoard():
"""Create new game board."""
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board

for your DisplayBoard I have this;

def new_board():
"""Create new game board."""
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board

def display_board(board):
"""Display game board on screen."""
print "\n\t", board[0], "|", board[1], "|", board[2]
print "\t", "-"
print "\t", board[3], "|", board[4], "|", board[5]
print "\t", "-"
print "\t", board[6], "|", board[7], "|", board[8], "\n"



--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] i can only write one line of code on python shell help please ?

2009-03-09 Thread David
mustafa akkoc wrote:
> Hello , 
>
> - In python shell ,   i can only write one line of code when I go to
> next line this sign appears  >>>  how can write the code like in
> script mode and run
>
> thanks  
> -- 
> Mustafa Akkoc
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
This should help;
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


[Tutor] Newby Linux Program review + help with regular expressions

2009-03-09 Thread David
This program generates a report of a Linux System and some important 
.conf files. The goal is for users to be able to post their information 
and compare with others, ask for help etc. Am I using the subrocess 
module too much because I am comfortable with the commands? Should I 
just write this type of program in bash. I am trying to get rid of all 
the comments generated in the report. I got rid of blank lines and lines 
starting with #. But can not figure out how the get rid of a line like;

#This is a comment with 5 spaces
I never programed before so everything is new to me.
Here is my code;
http://asterisklinks.com/wiki/doku.php?id=wiki:gentoo_report
The report it generates is at the bottom. I didn't want to post it all here.
Thanks,
-david

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] (no subject)

2009-03-17 Thread David

Alan Gauld wrote:






Combine the two hints so far to improve it, then look even more closely 
at range() to see how to do the decreasing lengths.





Thanks for the tips, I have been trying to figure it out also. I did get 
it after about 3 hours :)


-david

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Distributing MySQL with my application

2009-03-23 Thread David

Lauren Snyder wrote:



2. I also like the idea of writing a script to check to see if MySQL is
installed. However, I need pointers on writing this script and also the
script to auto install MySQL on another user's computer. 


Thank you again for your help and brilliant ideas!
Lauren



Are these Windows or Linux users? If Linux each distro has its own 
package managers. It would be very hard to install and setup MySQL for 
different platforms and distro's. An option is to use [0] down the page 
a little, or your own remote MySQL server [1]



[0] Database Systems for Embedding Into Applications
http://wiki.python.org/moin/DatabaseInterfaces

[1] 
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html



--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] (no subject)

2009-03-23 Thread David

Jared White wrote:

 
**
*  I cant get a code to work for this bottom half,  Can 
anyone help me


***
**
*

***
**
*


See if this helps;
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] (no subject)

2009-03-24 Thread David
Padmanaban Ganesan wrote:
> Hello David,
>  
> Please try this . I hope this answered your question now.
>  
> SAM PRG:
> 
> def main():
> i=1
> while i <=10:
> j=1
> while j<=i:
> print  'Paddy' ,
> j=j+1
> print
> i=i+1
>  
> def rev():
> i=10
> while i >=1:
> print  'Paddy' ,
> print
> i=i-1
> main()
> rev ()
>  
> O/P:
> ---
>  
> Paddy
> Paddy Paddy
> Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy  Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy  Paddy  Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy  Paddy  Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy  Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy Paddy
> Paddy Paddy Paddy
> Paddy Paddy
> Paddy
>  
>  
> please let me know if you need any other details.
>  
> Ta,
> Paddy 
>  
> " The Secret of Creativity is knowing to  hide the source "
>
>  
>
>  
>  
Here is how I did it;

#!/usr/bin/python

for i in range(10):
print i*"*"
for i in range(10-1, -1, -1):
print i*"*"


-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


[Tutor] Adding key, value to Dictionary

2009-03-27 Thread David
I am trying to make a simple Todo program and I can not get the 
dictionary to update.

This works;

#!/usr/bin/python
key = 'Clean house'
value = (1,2,3,4)
todo = {key:value}
value = (5,6,7,8)
todo['Walk Dog'] = value
print todo

results
{'Walk Dog': (5, 6, 7, 8), 'Clean house': (1, 2, 3, 4)}
OK good

But I can not get this to update after the first time it is ran.

def get_todo():
todo = {}
key = raw_input('Enter Todo Title: ')
todo[key] = key
print '\n', key, 'has been added.'
print 'Next, enter date for Todo: '
curr_date = time.strftime('%Y %m %d', time.gmtime())
print 'Format as ', curr_date
yr = int(raw_input('\nEnter Year: '))
mt = int(raw_input('Enter Month: '))
dy = int(raw_input('Enter Day: '))
hr = int(raw_input('Enter Hour (24h): '))
mn = int(raw_input('Enter Minute (01-59): '))
value = [yr, mt, dy, hr, mn]
todo = {key:value}
todo[key] = value
print todo
response = raw_input('Do you want to add another Todo? (y/n) ')
if response == 'y':
get_todo()
else:
print 'Goodbye'

get_todo()

results

Enter Todo Title: Clean House

Clean House has been added.
Next, enter date for Todo:
Format as  2009 03 27

Enter Year: 2009
Enter Month: 3
Enter Day: 27
Enter Hour (24h): 13
Enter Minute (01-59): 28
{'Clean House': [2009, 3, 27, 13, 28]}
Do you want to add another Todo? (y/n) y
Enter Todo Title: Walk Dog

Walk Dog has been added.
Next, enter date for Todo:
Format as  2009 03 27

Enter Year: 2009
Enter Month: 3
Enter Day: 27
Enter Hour (24h): 14
Enter Minute (01-59): 35
{'Walk Dog': [2009, 3, 27, 14, 35]}
Do you want to add another Todo? (y/n)

Not so good:(



--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Adding key, value to Dictionary

2009-03-27 Thread David

David wrote:
I am trying to make a simple Todo program and I can not get the 
dictionary to update.

This works;

#!/usr/bin/python
key = 'Clean house'
value = (1,2,3,4)
todo = {key:value}
value = (5,6,7,8)
todo['Walk Dog'] = value
print todo

results
{'Walk Dog': (5, 6, 7, 8), 'Clean house': (1, 2, 3, 4)}
OK good


I also thought this would work if I did not start out with a blank 
dictionary;

def get_todo():
key = raw_input('Enter Todo Title: ')
print '\n', key, 'has been added.'
print 'Next, enter date for Todo: '
curr_date = time.strftime('%Y %m %d', time.gmtime())
print 'Format as ', curr_date
yr = int(raw_input('\nEnter Year: '))
mt = int(raw_input('Enter Month: '))
dy = int(raw_input('Enter Day: '))
hr = int(raw_input('Enter Hour (24h): '))
mn = int(raw_input('Enter Minute (01-59): '))
value = [yr, mt, dy, hr, mn]
todo = {key:value}
todo[key] = value
print todo
response = raw_input('Do you want to add another Todo? (y/n) ')
if response == 'y':
get_todo()
else:
print 'Goodbye'

get_todo()

same result

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Adding key, value to Dictionary

2009-03-27 Thread David

greg whittier wrote:

On Fri, Mar 27, 2009 at 1:31 PM, David  wrote:

But I can not get this to update after the first time it is ran.

def get_todo():
   todo = {}

moved todo{} outside of the function


This set todo to an empty dictionary each time you execute get_todo.


Ok I see it now.



todo = {key:value} again resets the value of todo.  You only need
todo[key]=value.


Yep, thanks


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Operational Error. --HELP

2009-03-31 Thread David

bijoy franco wrote:

I tried following query as well.

code:
infunction_curs.execute('SELECT * FROM table_book')

This also throws the same error

Bijoy


Why did you try that?

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


[Tutor] Append a dictionary value

2009-04-04 Thread David

I put together a todo program here;
http://linuxcrazy.pastebin.com/f74beaf78

And I am trying to add an option to edit the values which are date and 
time. Below I have gotten this far but now I need some help. looks like 
my attempt to use setdefault will not work. Please point me in the right 
direction my head has started to hurt :)

thanks
-david

#!/usr/bin/python
import time
import datetime
todo = {'Study Python':
(datetime.date(2009, 4, 1), datetime.time(12, 15)),
'Clean House':
(datetime.date(2009, 4, 4), datetime.time(15, 15)),
'Fix Python Code':
(datetime.date(2009, 3, 29), datetime.time(9, 1))}

for k, v in todo.iteritems():
print k, v[0],v[1]

answer = raw_input('\nWhich Todo do you want to edit? \nEnter >> ')
for k, v in todo.iteritems():
key = todo[answer]
current_date = key[0]
print 'Current Date and Time for', answer,'\n'
print 'Date: =', current_date
current_time = key[1]
print 'Time: =', current_time
print """

Enter D: Edit Date
Enter T: Edit Time
"""
new_value = raw_input('\nWhich value do you want to edit? ')
new_value = new_value.lower()
if new_value == 'd':
print 'Next, enter date for Todo: '
curr_date = time.strftime('%Y %m %d', time.gmtime())
print 'Format as ', curr_date
yr = int(raw_input('\nEnter Year: '))
mt = int(raw_input('Enter Month: '))
dy = int(raw_input('Enter Day: '))
datevalue = datetime.date(yr, mt, dy)
todo[answer] = datevalue, time
#todo.setdefault(answer,[current_date]).append(datevalue)
elif new_value == 't':
hr = int(raw_input('\nEnter Hour (24h): '))
mn = int(raw_input('Enter Minute (01-59): '))
sec = 0
hourvalue = datetime.time(hr, mn, sec)
todo[answer] = date, hourvalue
#todo.setdefault(answer,[current_time]).append(hourvalue)
else:
print 'big time error'

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Append a dictionary value

2009-04-04 Thread David

David wrote:

I put together a todo program here;
http://linuxcrazy.pastebin.com/f74beaf78

And I am trying to add an option to edit the values which are date and 
time. Below I have gotten this far but now I need some help. looks like 
my attempt to use setdefault will not work. Please point me in the right 
direction my head has started to hurt :)

thanks
-david
I guess because the value is a tuple that that can not be changed. So 
what I did is save the current values as variables and them del the 
dictionary key and make a new one with the saved variables, or new ones 
if edited.


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] Append a dictionary value

2009-04-04 Thread David

Sander Sweers wrote:


I do not understand what it is you want to do. Do you want to replace
the old date and time with the new? If so you already do this with
todo[answer] = datevalue, time. Why do you want to use setdefault?


I was confused, I thought it would add another value to the key not 
change the current one.



Why not use a datetime object?

todo = {'Study Python':
(datetime.datetime(2009, 4, 1,12,15)}

Greets
Sander



thank you

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: [Tutor] (no subject)

2009-04-06 Thread David

Sifis Sifakis wrote:

Hi,
I'm a student in Applied Informatics and i need to make a project in 
Python. More specificaly,i have to create a simple online bookstore 
using Python. 


I would use Google App Engine;

http://code.google.com/appengine/docs/python/gettingstarted/


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Consolidate reused code blocks

2009-04-08 Thread David

Hi Everyone,

I have a simple todo list program with functions to add, delete, edit 
and print out a list of todo's. I need to understand how to remove the 
same blocks of code I use in each function. Should I create a class for 
the same block of code I am including in each function? Here are two of 
the functions;


def main():
print '\nYour current Todo list is: \n'
if os.path.exists('todo.dat'):
try:
fname = open('todo.dat', 'rb')
data = cPickle.Unpickler(fname)
todo = data.load()
load_todo(todo)
for k, v in todo.iteritems():
print k, v[0], v[1]
finally:
fname.close()
menu()
else:
todo = {}
print "You have 0 todo's"
menu()

def del_todo():
if os.path.exists('todo.dat'):
try:
fname = open('todo.dat', 'rb')
data = cPickle.Unpickler(fname)
todo = data.load()
load_todo(todo)
finally:
fname.close()
else:
todo = {}

try:
print '\nYour current Todo list is: \n'
for k, v in todo.iteritems():
print k
answer = raw_input('\nWhich Todo do you want to remove? ')
del todo[answer]
print '\nDeleted Todo', answer
print '\nYour current Todo list is: \n'
for k, v in todo.iteritems():
print k, v[0],v[1]
load_todo(todo)
except KeyError, e:
print '\nError! Please enter the Todo to be removed.\n'
    print 'Case and spaces are important.'

Here is the whole thing :)
http://linuxcrazy.pastebin.com/f4206de5a

Thanks for your time,
-david

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Fwd: Re: Consolidate reused code blocks]

2009-04-08 Thread David


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
--- Begin Message ---

Kent Johnson wrote:

On Wed, Apr 8, 2009 at 8:38 PM, David  wrote:

Hi Everyone,

I have a simple todo list program with functions to add, delete, edit and
print out a list of todo's. I need to understand how to remove the same
blocks of code I use in each function. Should I create a class for the same
block of code I am including in each function?


No, you can make functions to contain common code. You are sort of on
the right track with your load_todo() function, though it should
really be called save_todo().


Here are two of the
functions;

def main():
   print '\nYour current Todo list is: \n'
   if os.path.exists('todo.dat'):
   try:
   fname = open('todo.dat', 'rb')
   data = cPickle.Unpickler(fname)
   todo = data.load()
   load_todo(todo)


Not sure why you call load_todo() here, it writes back to the file you
just read.

You could have a real load_todo() that looks like this:

def load_todo():
  if (os.path.exists('todo.dat')):
with open('todo.dat', 'rb') as fname: # with statement is simpler
than try/finally
  data = cPickle.Unpickler(fname)
  todo = data.load()
  else:
todo = {}
  return todo

Then your main() could look like this:

def main():
   print '\nYour current Todo list is: \n'
   todo = load_todo()
   if todo:
   for k, v in todo.iteritems():
   print k, v[0], v[1]
   else:
   print "You have 0 todo's"
   menu()

Kent


I have a load_todo(todo) now that dumps the working dictionary to the 
file on disk;

def load_todo(todo):
"""Loads the current todo list to disk."""
fname = open('todo.dat', 'w')
object = cPickle.Pickler(fname)
object.dump(todo)
fname.close()


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com

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


Re: [Tutor] Consolidate reused code blocks

2009-04-08 Thread David

Kent Johnson wrote:

On Wed, Apr 8, 2009 at 8:38 PM, David  wrote:

Hi Everyone,

I have a simple todo list program with functions to add, delete, edit and
print out a list of todo's. I need to understand how to remove the same
blocks of code I use in each function. Should I create a class for the same
block of code I am including in each function?


No, you can make functions to contain common code. You are sort of on
the right track with your load_todo() function, though it should
really be called save_todo().


Here are two of the
functions;

def main():
   print '\nYour current Todo list is: \n'
   if os.path.exists('todo.dat'):
   try:
   fname = open('todo.dat', 'rb')
   data = cPickle.Unpickler(fname)
   todo = data.load()
   load_todo(todo)


Not sure why you call load_todo() here, it writes back to the file you
just read.

You could have a real load_todo() that looks like this:

def load_todo():
  if (os.path.exists('todo.dat')):
with open('todo.dat', 'rb') as fname: # with statement is simpler
than try/finally
  data = cPickle.Unpickler(fname)
  todo = data.load()
  else:
todo = {}
  return todo

Then your main() could look like this:

def main():
   print '\nYour current Todo list is: \n'
   todo = load_todo()
   if todo:
   for k, v in todo.iteritems():
   print k, v[0], v[1]
   else:
   print "You have 0 todo's"
   menu()

Kent



Ok, I got it now, rename load_todo to save_todo, then create the load_todo.
thanks kent

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2009-04-11 Thread David

krayzie...@yahoo.com wrote:

Sent from my BlackBerry® device from Digicel

Don't have a BlackBerry, sorry can not help.
-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sender name in smtplib

2009-04-13 Thread David

George Wahid wrote:

I want to send an email from a google mail account so that the sender
name will be 'User Name' instead of 'usern...@gmail.com' in the inbox.
this is the code I use: (I'm using python 2.5)

import smtplib
g=smtplib.SMTP('smtp.googlemail.com')
g.ehlo();g.starttls();g.ehlo()
g.login('usern...@gmail.com','somepassword')
g.sendmail('User Name','usern...@gmail.com','From: User Name\r\nTo: 
usern...@gmail.com\r\nsubject: how r u ?\r\nfoobar')

{}

g.quit()


but this doesn't work, what should I do ?


Here is how I do it, may help;
http://dwabbott.com/code/index14.html

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] beginners resources list, Python education events

2009-04-16 Thread David

wesley chun wrote:

hey all,

i'm trying to collate a complete newbie-to-programming list of
resources and was wondering if you could help me fill in the holes...
thx in advance!


Hi wesley,

A couple I liked;
One Day of IDLE Toying
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
Dive Into Python
http://www.diveintopython.org/toc/index.html
A Python Course
http://www.upriss.org.uk/python/PythonCourse.html


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PDF to text conversion

2009-04-21 Thread David

bob gailer wrote:

Robert Berman wrote:

Hi,

I must convert a history file in PDF format that goes from May of 1988 
to current date.  Readings are taken twice weekly and consist of the 
date taken mm/dd/yy and the results appearing as a 10 character 
numeric + special characters sequence. This is obviously an easy setup 
for a very small database  application with the date as the key, the 
result string as the data.


My problem is converting the PDF file into a text file which I can 
then read and process. I do not see any free python libraries having 
this capacity. I did see a PDFPILOT program for Windows but this 
application is being developed on Linux and should also run on 
Windows; so I do not want to incorporate a Windows only application.

How about pyPdf;
http://pybrary.net/pyPdf/
And an example;
http://code.activestate.com/recipes/511465/

-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PDF to text conversion

2009-04-22 Thread David

Robert Berman wrote:

Dinesh,

I have pdftotext version 3.0.0.  I have decided to use this to go from 
PDF to text. It is not the ideal solution, but is is a certainly doable 
solution.


Thank you,

Robert

Dinesh B Vadhia wrote:
The best converter so far is pdftotext from 
http://www.glyphandcog.com/ who maintain an open source project at 
http://www.foolabs.com/xpdf/.
 
It's not a Python library but you can call pdftotext from with Python 
using os.system().  I used the pdftotext -layout option and that gave 
the best result.  hth.
 
dinesh
 

You can use subprocess;
#!/usr/bin/python

from subprocess import call
call(['pdftotext', 'test.pdf'])

-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Number cruncher

2009-04-22 Thread David

John Jenkinson wrote:
I need to write code that determines a students final grade based on the 
number of each type of assignment turned in with its corresponding 
weighted percentage.  There will be 15-20 inputs.  I have not reached 
this point in my learning of python, so I would like to request a 
resource that would help me for this project.
 
- John Jenkinson





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

If you want to start here;
http://pytut.infogami.com/beginners
When you get to 9 you will be able to do your lesson.
-david

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to run a .py file or load a module?

2009-04-26 Thread David

Norman Khine wrote:

On Mon, Apr 27, 2009 at 12:07 AM, Sander Sweers  wrote:

Here is another one for fun, you run it like
python countdown.py 10

#!/usr/bin/env python

import sys
from time import sleep

times = int(sys.argv[1]) # The argument given on the command line

def countdown(n):
try:
while n != 1:
n = n-1
print n
sleep(1)
finally:
print 'Blast Off!'

countdown(times)

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


[Tutor] Add newline's, wrap, a long string

2009-04-28 Thread David
I am getting information from .txt files and posting them in fields on a 
web site. I need to break up single strings so they are around 80 
characters then a new line because when I enter the info to the form on 
the website it has fields and it errors out with such a long string.


here is a sample of the code;

#!/usr/bin/python
import subprocess
import os

u_e = subprocess.Popen(
'grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut -d\\"-f2', 
shell=True, stdout=subprocess.PIPE,)

os.waitpid(u_e.pid, 0)
USE = u_e.stdout.read().strip()
L = len(USE)
print L
print USE

L returns 1337

Here is what USE returns;
http://linuxcrazy.pastebin.com/m2239816f

thanks
-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add newline's, wrap, a long string

2009-04-28 Thread David

vince spicer wrote:

first, grabbing output from an external command try:

import commands

USE = commands.getoutput('grep USE /tmp/comprookie2000/emege_info.txt 
|head -n1|cut -d\\"-f2')
 
then you can wrap strings,


import textwrap

Lines = textwrap.wrap(USE, 80) # return a list

so in short:

import commands, textwrap
data = textwrap.wrap(commands.getoutput('my command'), 80)



Vince





On Tue, Apr 28, 2009 at 3:43 PM, David <mailto:da...@abbottdavid.com>> wrote:


I am getting information from .txt files and posting them in fields
on a web site. I need to break up single strings so they are around
80 characters then a new line because when I enter the info to the
form on the website it has fields and it errors out with such a long
string.

here is a sample of the code;

#!/usr/bin/python
import subprocess
import os

u_e = subprocess.Popen(
'grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut
-d\\"-f2', shell=True, stdout=subprocess.PIPE,)
os.waitpid(u_e.pid, 0)
USE = u_e.stdout.read().strip()
L = len(USE)
print L
print USE

L returns 1337

Here is what USE returns;
http://linuxcrazy.pastebin.com/m2239816f

thanks
-david
-- 
Powered by Gentoo GNU/Linux

http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org <mailto:Tutor@python.org>
http://mail.python.org/mailman/listinfo/tutor



Thanks Vince,
I could not get command to work, but I did not try very hard;
["cut: the delimiter must be a single character Try `cut --help' for 
more", 'information. head: write error: Broken pipe']


But textwrap did the trick, here is what I came up with;

#!/usr/bin/python

import subprocess
import os
import textwrap
import string

def subopen():
u_e = subprocess.Popen(
'grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut 
-d\\" -f2',

shell=True, stdout=subprocess.PIPE,)
os.waitpid(u_e.pid, 0)
USE = u_e.stdout.read().strip()
L = textwrap.wrap(USE, 80) # return a list
Lines = string.join(L, '\n')
fname = 'usetest.txt'
fobj = open(fname, 'w')
fobj.write(Lines)
fobj.close

subopen()

Here is the output;
http://linuxcrazy.pastebin.com/m66105e3

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add newline's, wrap, a long string

2009-04-29 Thread David

Martin Walsh wrote:

... but, you don't need to use subprocess at all. How about (untested),

# grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut -d\" -f2
infof = open('/tmp/comprookie2000/emerge_info.txt')
for line in infof:
if 'USE' in line:
USE = line.split('"')[1]
break
else:
USE = ''
infof.close()



Thanks Martin works perfect. So I understand correctly, line.split('"') 
splits the list on " so [1] grabs after USE = " and up till [2] starts.





Just one more comment, string.join is deprecated, yet join is a method
of str objects. So ...

  Lines = '\n'.join(L)

... or use textwrap.fill which returns a string with the newlines
already in place ...

  Lines = textwrap.fill(USE, 80)

HTH,
Marty


Again thanks, I like the comments :)
-david

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add newline's, wrap, a long string

2009-04-29 Thread David

David wrote:

Martin Walsh wrote:




Just one more comment, string.join is deprecated, yet join is a method
of str objects. So ...

  Lines = '\n'.join(L)

... or use textwrap.fill which returns a string with the newlines
already in place ...

  Lines = textwrap.fill(USE, 80)

HTH,
Marty


Again thanks, I like the comments :)
-david



Ok here is what I have now;
#!/usr/bin/python

import textwrap

def get_use():
fname = open('/tmp/comprookie2000/emerge_info.txt')
for line in fname:
if 'USE' in line:
output = line.split('"')[1]
USE = textwrap.fill(output, 80)
break
else:
USE = ''
fname.close()

get_use()

Here is the whole program so far, what it does is it logs into a druple 
web site and posts. I would like to make it better, as you can see I do 
the same thing over and over. Also I don't think this is a python 
problem but I can only post one line or I get HTTP/1.1 417 Expectation 
Failed. I thought the problem was because it was one long string, but 
that is solved, may be it is looking for return/Enter to be pressed, not 
sure.


http://linuxcrazy.pastebin.com/m7689c088

thanks
-david


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add newline's, wrap, a long string

2009-04-29 Thread David

Alan Gauld wrote:


"Sander Sweers"  wrote


What you can do is define all the variables upfront. This way you can
get rid of the else. Below is an example how you can do this with only
looping once over the fle.


And you can put the variables as keys of a dictionary and avoid all the 
if tests:


data = {'CBUILD':None, 'ACCEPT_KEYWORDS: None,

   }


for line in fname:

 for keyphrase in data:

  if keyphrase in line:
  output = line.split('"')[1]
  data[keyphrase] = textwrap.fill(output, 80)




I don't know how else to describe it, that is so cool :)
[code]
#!/usr/bin/python

import textwrap
data = {'CBUILD':None, 'CFLAGS':None, 'MAKEOPTS':None}
def get_use():
fname = open('/tmp/comprookie2000/emerge_info.txt')
for line in fname:
for keyphrase in data:
if keyphrase in line:
output = line.split('"')[1]
data[keyphrase] = textwrap.fill(output, 80)
fname.close()

get_use()

CBUILD = data['CBUILD']
CFLAGS = data['CFLAGS']
MAKEOPTS = data['MAKEOPTS']


print 'CBUILD =',CBUILD
print 'CFLAGS =',CFLAGS
print 'MAKEOPTS =',MAKEOPTS


[output]
CBUILD = x86_64-pc-linux-gnu
CFLAGS = -march=opteron -O2 -pipe
MAKEOPTS = -j3

Thanks Alan Martin, Sander, hope I did it correctly.


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code Dosent work.

2009-05-03 Thread David

Jacob Mansfield wrote:
hi everyone, I'm a bit new here but i was wondering if someone could 
check some of my code, it's not doing quite what it's meant to.

thanks

Works without pygame;
filename, blank for none.

Welcome to databox V2.0.
 1. Searth the database.
 2. Add a record.
 3. Exit.
Please make a selection.
2
First name.
David

Second name.
William
Done.


Welcome to databox V2.0.
 1. Searth the database.
 2. Add a record.
 3. Exit.
Please make a selection.
1


David William

Why were you using pygame?


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] quick question to open(filename, 'r') vs. file(filename, 'r')

2009-05-04 Thread David
Dear list,

in different books I come across different syntax for dealing with
files. It seems that open(filename, 'r') and file(filename, 'r') are
used interchangeably, and I wonder what this is all about. Is there a
reason why Python allows such ambiguity here?

Cheers for a quick shot of enlightenment ;-)

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


[Tutor] Reset while loop

2009-05-05 Thread David

Hi, not even sure if I can ask this very smartly but we shall try:
I was playing around with trying to create a python program like tail -f 
as discussed on the list. i came up with this;


def tail_it(bufsize=8192, linesep=__import__('os').linesep):
f = None
if f == None:
f = open(tail_fname, 'rb')
f.seek(0, 2)
pos, tailsize = divmod(f.tell(), bufsize)
if tailsize == 0:
pos = max(0, pos-1)
pos *= bufsize
f.seek(pos)
lines = f.read().split(linesep)
x = len(lines)
x = x-2
print lines[x:]
f.close()
while True:
new_time = os.stat(tail_fname).st_mtime
if new_time > old_time:
f = open(tail_fname, 'rb')
f.seek(0, 2)
pos, tailsize = divmod(f.tell(), bufsize)
if tailsize == 0:
pos = max(0, pos-1)
pos *= bufsize
f.seek(pos)
lines = f.read().split(linesep)
x = len(lines)
x = x-2
print lines[x:]
time.sleep(sec_to_wait)
f.close()

[output]
['May  5 22:32:26 opteron su[5589]: pam_unix(su:session): session closed 
for user root', '']
['May  5 22:32:26 opteron su[5589]: pam_unix(su:session): session closed 
for user root', '']
['May  5 22:32:26 opteron su[5589]: pam_unix(su:session): session closed 
for user root', '']
['May  5 22:40:01 opteron cron[22996]: (root) CMD (test -x 
/usr/sbin/run-crons && /usr/sbin/run-crons )', '']
['May  5 22:40:01 opteron cron[22996]: (root) CMD (test -x 
/usr/sbin/run-crons && /usr/sbin/run-crons )', '']
['May  5 22:41:26 opteron ntpd[3571]: kernel time sync status change 
4001', '']
['May  5 22:41:26 opteron ntpd[3571]: kernel time sync status change 
4001', '']
['May  5 22:41:26 opteron ntpd[3571]: kernel time sync status change 
4001', '']
['May  5 22:41:26 opteron ntpd[3571]: kernel time sync status change 
4001', '']

[/output]

That was with sec_to_wait set at 30

The problem I am having is it will print something whatever sec_to_wait 
is set to even if the file's st_mtime is the same. I want it to only 
prine when the st_mtime has changed. I think I need to update the while 
loop and make old_time = new-time and start over but I need some 
direction to get started, thanks

-david

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reset while loop

2009-05-06 Thread David

Alan Gauld wrote:


"David"  wrote


I was playing around with trying to create a python program like tail 
-f as discussed on the list. i came up with this;


Alan, thanks for your time and great tips :)


import os

def get_tail(fname, bufsize, linesep):
f = open(fname, 'rb')
f.seek(0, 2)
pos, tailsize = divmod(f.tell(), bufsize)
if tailsize == 0:
pos = max(0, pos-1)
pos *= bufsize
f.seek(pos)
lines = f.read().split(linesep)
f.close()
return lines[-2:]


def tail_it(fname, bufsize=8192, linesep=os.linesep):
while True:
new_time = os.stat(tail_fname).st_mtime
if new_time > old_time:
time.sleep(sec_to_wait)
print get_tail (fname, bufsize, linesep)
old_time = new_time

I haven't tried it but that should be close to what you want.


This helps a lot because I can now see how the loop works. One of my 
problems is putting the pieces of code in the right places. It helps me 
understand when I can run the program and see the errors and output to 
make adjustments.



OTOH since you only use the last two lines why not miss all
that out and go straight to where you want to be with:

f.seek(-buffsize, os.SEEK_END)# goto one buffsize away from end
return f.read().split(linesep)[-2:]

I like it!

Here is what I came up with;

#!/usr/bin/python

"Python program similar to tail -f"
import os
import sys
import commands
import time

sec_to_wait = 60
fname = raw_input('Enter the log file to be monitored: ')

def usage():
"""Explains the program to the user"""
print \
"You will need to be root to monitor most log files."

def check_whoami():
"""Check if Root"""
if commands.getoutput('whoami') != 'root':
sys.exit('\nYou will need to be Root!\n')

def print_log_end(fname, bufsize, linesep):
f = open(fname, 'r')
f.seek(-bufsize, os.SEEK_END)# goto one buffsize away from end
log = f.read().split(linesep)[-8:]
for i in log:
print i
f.close()

def tail_it(fname, bufsize, linesep):
old_time = os.stat(fname).st_mtime
while True:
new_time = os.stat(fname).st_mtime
if new_time > old_time:
time.sleep(sec_to_wait)
updated = print_tail(fname, bufsize, linesep)
for i in updated:
print i
old_time = new_time

def print_tail(fname, bufsize, linesep):
f = open(fname, 'r')
f.seek(-bufsize, os.SEEK_END)# goto one buffsize away from end
return f.read().split(linesep)[-2:]
f.close()

if __name__ == "__main__":
print_log_end(fname, bufsize=8192, linesep=os.linesep)
check_whoami()
tail_it(fname, bufsize=8192, linesep=os.linesep)

[output]
Enter the log file to be monitored: /var/log/messages
May  6 16:00:01 opteron cron[24679]: (root) CMD (rm -f 
/var/spool/cron/lastrun/cron.hourly)
May  6 16:00:01 opteron run-crons[24685]: (root) CMD 
(/etc/cron.hourly/moodle)
May  6 16:00:01 opteron run-crons[24688]: (root) CMD 
(/etc/cron.hourly/vnstat)

May  6 16:03:06 opteron su[24712]: Successful su for root by david
May  6 16:03:06 opteron su[24712]: + pts/6 david:root
May  6 16:03:06 opteron su[24712]: pam_unix(su:session): session opened 
for user root by david(uid=1000)
May  6 16:10:01 opteron cron[24751]: (root) CMD (test -x 
/usr/sbin/run-crons && /usr/sbin/run-crons )


May  6 16:20:01 opteron cron[24788]: (root) CMD (test -x 
/usr/sbin/run-crons && /usr/sbin/run-crons )



--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reset while loop

2009-05-06 Thread David
When running the program cpu usage is 100%. Here is the part that is 
running;


def tail_it(fname, bufsize, linesep):
"""Update if monitored file time changes"""
old_time = os.stat(fname).st_mtime
while True:
new_time = os.stat(fname).st_mtime
if new_time > old_time:
time.sleep(sec_to_wait)
updated = return_tail(fname, bufsize, linesep)
for i in updated:
print i
old_time = new_time

It is waiting here;
new_time = os.stat(fname).st_mtime

Why would something like that happen and is there any way to fix it? The 
program is just for me to learn Python, if I wanted to tail a log file I 
would just use tail, but an understanding may help in the future.

thanks,
-david


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reset while loop

2009-05-06 Thread David

bob gailer wrote:



You call sleep only when the file is updated. As long as the file is not 
updated the loop runs continuously and therefore 100%.


and is there any way to fix it? 


move the sleep call out of the if, and put the update of old_time in the if

   while True:
   new_time = os.stat(fname).st_mtime
   if new_time > old_time:
   updated = return_tail(fname, bufsize, linesep)
   for i in updated:
   print i
   old_time = new_time
   time.sleep(sec_to_wait)


Thank You Bob

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code Dosent work.

2009-05-09 Thread David

Jacob Mansfield wrote:
not sure why i was using pygame, anyway the problem is with the saveing, 
press exit, the program will save to databox.txt, then start the program 
again giveing it the filename that it saved to, then look at the records.


Post the code you have now and I am sure someone can help point you in 
the right direction.

-david

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] paramiko again

2009-05-09 Thread David

Matt Herzog wrote:

Hello again.

This code comes straight from the http://oreilly.com/catalog/9780596515829/ 
book.

The only actual code I changed was s/get/put on the second to last line. The 
author says I ought to be able to do this and have it Just Work. There are 
several things I don't understand. Would be nice if the books' author was on 
this list so I could ask him directly. Heh.

The code runs but does not upload any files. I would rather be specifying the local dir on the source machine rather than path on the destination. 


1. How can paramiko know whether the dir_path is on the local vs remote system?
2. I can't find sftp.put or sftp.get in ipython. Are they part of paramiko? If 
not, where do they come from?

Thanks for any insight.

--- begin --
#!/usr/bin/env python 
import paramiko 
import os 
hostname = '192.168.1.15' 
port = 22 
username = 'revjimjones' 
password = 'C0ol4id3' 
dir_path = '/home/revjimjones/logs' 
if __name__ == "__main__": 
t = paramiko.Transport((hostname, port)) 
t.connect(username=username, password=password) 
sftp = paramiko.SFTPClient.from_transport(t) 
files = sftp.listdir(dir_path) 
for f in files: 
print 'Uploading', f 
sftp.put(os.path.join(dir_path, f), f) 
t.close() 


 end ---



Your going to have to read up on it. Download the source here;
http://github.com/robey/paramiko/downloads
Then look at the demos folder where you will see an example for sftp like;
# now, connect and use paramiko Transport to negotiate SSH2 across the 
connection

try:
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password, hostkey=hostkey)
sftp = paramiko.SFTPClient.from_transport(t)

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


[Tutor] Suggestions for while loop

2009-05-10 Thread David

Hi, I am going through Wesley Chun's book and this is Exercise 8-11;
Write a program to ask the user to input a list of names, format "Last 
Name" "comma" "First Name". Write a function that manages the input so 
that when/if the user types in the names in the wrong format the error 
is corrected, and keep track of the number of errors. When done sort the 
list.


Questions;

This;
answers = raw_input('Enter Name: ')
index = answers.find(',')

Does not seem to be a very good to me, how could I check for a comma 
between two words?


And This;
try:
total_names = int(raw_input('Enter Total Number of Names: '))
except ValueError:
print 'You must enter a number!'
total_names = int(raw_input('Enter Total Number of Names: '))

Does not handle the second input for exceptions.

thanks,
-david


#!/usr/bin/python
import string

names = []

def get_names():
wrong_format = 0
count = 0
try:
total_names = int(raw_input('Enter Total Number of Names: '))
except ValueError:
print 'You must enter a number!'
total_names = int(raw_input('Enter Total Number of Names: '))

while count < total_names:
print 'Format: LastName, First Name'
answers = raw_input('Enter Name: ')
index = answers.find(',')
answers = answers.title()
index = answers.find(',')
if index != -1:
names.append(answers)
count += 1
else:
wrong_format += 1
print '\nWrong Format!!!'
if wrong_format > 1:
print 'That is %i Fixing Format ...' % wrong_format
else:
print 'You have done this %i times, Fixing Format ...' 
% wrong_format

print 'Done, continue:\n'
answers = answers.split()
answers = string.join(answers, ', ')
names.append(answers)
count += 1

def show_names():
print 'Your Names Are: \n'
for i in sorted(names):
print i

def main():
get_names()
if names:
show_names()

if __name__ == "__main__":
main()

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Suggestions for while loop

2009-05-11 Thread David

Dave Angel wrote:



def getTotalNumber(prompt):
   while True:
   try:
   numstr = raw_input(prompt)
   n = int(numstr)
   if  0 < n < 50:#some validation
return n
   print "Number is not reasonable, try again"
  except ValueError:
   print "You must enter a number!"


Richard "Roadie Rich" Lovely wrote:


total_names = -1 # set an invalid initial value
while not 0 < total_names < 50: # loop while total_names has an invalid value
try:
# If this excepts, total_names is not changed.
total_names = int(raw_input('Enter Total Number of Names: '))
# if total_names now has a valid value, the loop exits.
except ValueError:
print 'You must enter a number!' # loop continues.


Thanks Dave and Richard,

And to run it is this correct

total_names = getTotalNumber('Enter Total Number of Names: ')


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simply moving files]

2009-05-12 Thread David

David wrote:




Subject:
[Tutor] simply moving files
From:
Matt Herzog 
Date:
Tue, 12 May 2009 13:51:36 -0400
To:
Python List 

To:
Python List 


On monday I posted the below code:

def schmove(src,dst):
... src = '/home/datasvcs/PIG/cjomeda_exp/'
... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/'
... listOfFiles = os.listdir(src)
... for filez in listOfFiles:
... os.system("mv"+ " " + src + " " + dst)

David Angel replied to my post and I guess I accidentally deleted his response. 
Today I found his response posted on mail-archive.com and tried some 
variations. They all failed.

David said, "Just use os.rename() if the dest is a directory, it'll move the file 
there."

Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " + src + " 
" + dst)" no files are coppied.

os.renames happily renames the source directory, but that's not what I want.

Any other suggestions?

-- Matt




I did not try Davids example but Kents works fine here;

#!/usr/bin/python
#Python 2.6.2
import os
src = '/home/david/test_src/'
dst = '/home/david/test/'
listofFiles = os.listdir(src)
for fnames in listofFiles:
os.system("mv %s/%s %s" % (src, fnames, dst))
results = os.listdir(dst)
print results

[results]
david [03:37 PM] opteron ~ $ ./tutor_mv.py
['fruit_loops.py', 'numberList.py', 'sumList.py']
david [03:42 PM] opteron ~ $ ls /home/david/test
fruit_loops.py  numberList.py  sumList.py


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Fwd: Re: simply moving files]]

2009-05-12 Thread David

Forwarded to the list, I would also like to understand the forward slash;
os.system("mv %s/%s %s" % (src, fnames, dst))
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
--- Begin Message ---
On Tue, May 12, 2009 at 03:50:00PM -0400, David wrote:
> David wrote:
> >
> >
> >
> >Subject:
> >[Tutor] simply moving files
> >From:
> >Matt Herzog 
> >Date:
> >Tue, 12 May 2009 13:51:36 -0400
> >To:
> >Python List 
> >
> >To:
> >Python List 
> >
> >
> >On monday I posted the below code:
> >
> >def schmove(src,dst):
> >... src = '/home/datasvcs/PIG/cjomeda_exp/'
> >... dst = '/home/datasvcs/PIG/cjomeda_exp_archive/'
> >... listOfFiles = os.listdir(src)
> >... for filez in listOfFiles:
> >... os.system("mv"+ " " + src + " " + dst)
> >
> >David Angel replied to my post and I guess I accidentally deleted his 
> >response. Today I found his response posted on mail-archive.com and tried 
> >some variations. They all failed.
> >
> >David said, "Just use os.rename() if the dest is a directory, it'll move 
> >the file there."
> >
> >Example: If I use: "os.rename(src, dst)" where I had "os.system("mv"+ " " 
> >+ src + " " + dst)" no files are coppied.
> >
> >os.renames happily renames the source directory, but that's not what I 
> >want.
> >
> >Any other suggestions?
> >
> >-- Matt
> >
> >
> >
> I did not try Davids example but Kents works fine here;
> 
> #!/usr/bin/python
> #Python 2.6.2
> import os
> src = '/home/david/test_src/'
> dst = '/home/david/test/'
> listofFiles = os.listdir(src)
> for fnames in listofFiles:
> os.system("mv %s/%s %s" % (src, fnames, dst))
> results = os.listdir(dst)
> print results

Actually, the above does EXACTLY what I want. I hope I did not seem accusatory 
in my previous post. I'm just under some pressure and had become frustrated. 
Maybe on the weekend I'll have time to understand the line: 

os.system("mv %s/%s %s" % (src, fnames, dst)) 

Many thanks. 

-- Matt
> 
> [results]
> david [03:37 PM] opteron ~ $ ./tutor_mv.py
> ['fruit_loops.py', 'numberList.py', 'sumList.py']
> david [03:42 PM] opteron ~ $ ls /home/david/test
> fruit_loops.py  numberList.py  sumList.py
> 
> 
> -- 
> Powered by Gentoo GNU/Linux
> http://linuxcrazy.com

-- 
I fear you speak upon the rack,
Where men enforced do speak anything.

- William Shakespeare


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


Re: [Tutor] simply moving files]]

2009-05-13 Thread David

Alan Gauld wrote:


"David"  wrote


Forwarded to the list, I would also like to understand the forward slash;
os.system("mv %s/%s %s" % (src, fnames, dst))


The slash separates the file path, src,  from the filename.

Thus if src is /foo/bar/baz
and fnames is spam

then %s/%s becomes

/foo/bar/baz/spam

Another way of doing the same thing would be with join:

'/'.join([src,fnames])

or for platform independance:

os.sep.join([src,fnames])

HTH,


Thank you Alan, you are a very good teacher, you should write a book :)

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Find files without __doc__ strings

2009-05-16 Thread David
I am doing an exercise in Wesley Chun's book. Find files in the standard 
 library modules that have doc strings. Then find the ones that don't, 
"the shame list". I came up with this to find the ones with;

#!/usr/bin/python
import os
import glob
import fileinput
import re

pypath = "/usr/lib/python2.6/"
fnames = glob.glob(os.path.join(pypath, '*.py'))

def read_doc():
pattern = re.compile('"""*\w')
for line in fileinput.input(fnames):
if pattern.match(line):
print 'Doc String Found: ', fileinput.filename(), line

read_doc()

There must have been an easier way :)

Now I have a problem, I can not figure out how to compare the fnames 
with the result fileinput.filename() and get a list of any that don,t 
have doc strings.


thanks
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Find files without __doc__ strings

2009-05-17 Thread David

spir wrote:

Le Sat, 16 May 2009 21:46:02 -0400,
David  s'exprima ainsi:

I am doing an exercise in Wesley Chun's book. Find files in the standard 
  library modules that have doc strings. Then find the ones that don't, 
"the shame list". I came up with this to find the ones with;

#!/usr/bin/python
import os
import glob
import fileinput
import re

pypath = "/usr/lib/python2.6/"
fnames = glob.glob(os.path.join(pypath, '*.py'))

def read_doc():
 pattern = re.compile('"""*\w')
 for line in fileinput.input(fnames):
 if pattern.match(line):
 print 'Doc String Found: ', fileinput.filename(), line

read_doc()


It seems to me that your approach is moderately wrong ;-)


There must have been an easier way :)


Not sure. As I see it the problem is slightly more complicated. A module doc is 
any triple-quoted string placed before any code. But it must be closed, too.
You'll have to skip blank and comment lines, then check whether the rest 
matches a docstring. It could be done with a single complicated pattern, but 
you could also go for it step by step.
Say I have a file 'dummysource.py' with the following text:
==
# !/usr/bin/env python
# coding: utf8

# comment
# ''' """

''' foo module
doc
'''
def foofunc():
''' foofuncdoc '''
pass
==

Then, the following doc-testing code
==
import re
doc = re.compile(r'(""".+?""")|(\'\'\'.+?\'\'\')', re.DOTALL)

def checkDoc(sourceFileName):
sourceFile = file(sourceFileName, 'r')
# move until first 'code' line
while True:
line = sourceFile.readline()
strip_line = line.strip()
print "|%s|" % strip_line
if (strip_line != '') and (not strip_line.startswith('#')):
break
# check doc (keep last line read!)
source = line + sourceFile.read()
result = doc.match(source)
if result is not None:
print "*** %s ***" % sourceFileName
print result.group()
return True
else:
return False

sourceFile = file("dummysource.py",'r')
print checkDoc(sourceFile)
==

will output:

==
|# !/usr/bin/env python|
|# coding: utf8|
||
|# comment|
|# ''' """|
||
|''' foo module|
*** dummysource.py ***
''' foo module
doc
'''
True
==

It's just for illustration; you can probably make things simpler or find a 
better way.

Now I have a problem, I can not figure out how to compare the fnames 
with the result fileinput.filename() and get a list of any that don,t 
have doc strings.


You can use a func like the above one to filter out (or in) files that answer 
yes/no to the test.
I would start with a list of all files, and just populate 2 new lists for "shame" and 
"fame" files ;-) according to the result of the test.

You could use list comprehension syntax, too:
fameFileNames = [fileName for fileName in fileNames if checkDoc(fileName)]
But if you do this for shame files too, then every file gets tested twice.


thanks


Denis
--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



Thanks Denis,
This seems to work OK;
#!/usr/bin/python
import os
import glob
import fileinput
import re

pypath = "/usr/lib/python2.6/"
fnames = glob.glob(os.path.join(pypath, '*.py'))
fnames.sort()
goodFiles = []

def shame_list():
pattern = re.compile(r'(^""")|(^\'\'\')', re.DOTALL)
for line in fileinput.input(fnames):
if pattern.match(line):
found = fileinput.filename()
goodFiles.append(found)
goodFiles.sort()
for item in fnames:
if item in goodFiles:
fnames.remove(item)
print 'Shame List: \n', fnames
shame_list()



Shame List:
['/usr/lib/python2.6/__phello__.foo.py', 
'/usr/lib/python2.6/collections.py', '/usr/lib/python2.6/md5.py', 
'/usr/lib/python2.6/pydoc_topics.py', '/usr/lib/python2.6/sha.py', 
'/usr/lib/python2.6/struct.py', '/usr/lib/python2.6/this.py']



--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Fwd: Re: Find files without __doc__ strings]

2009-05-18 Thread David

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

--- Begin Message ---
Lie Ryan wrote:
> David wrote:
>> spir wrote:
>>> Le Sat, 16 May 2009 21:46:02 -0400,
>>> David  s'exprima ainsi:
>>>
>>>> I am doing an exercise in Wesley Chun's book. Find files in the
>>>> standard   library modules that have doc strings. Then find the
>>>> ones that don't, "the shame list". I came up with this to find the
>>>> ones with;
>
> why not __import__() it then test whether its .__doc__ is None?
>
> def test(filename):
> if __import__(filename).__doc__ is None:
> shame_list.append(filename)
> else:
> fame_list.append(filename)
>
Thanks Spir and Lie,
How about;

#!/usr/bin/python

import os
import glob
import os.path

shame_list = []
fame_list = []
pypath = "/usr/lib/python2.5/"

def grab_files():
fnames = glob.glob(os.path.join(pypath, '*.py'))
fnames.sort()
sendall(fnames)

def sendall(fnames):
for filename in fnames:
filename = os.path.split(filename)
filename = filename[1]
filename = os.path.splitext(filename)
filename = filename[0]
test(filename)


def test(filename):
try:
if __import__(filename).__doc__ is None:
shame_list.append(filename)
else:
fame_list.append(filename)
except ImportError:
pass

grab_files()
print 'Shame List: ', shame_list

How can I do;
def sendall(fnames):
[snip]
More efficient.

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com


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


Re: [Tutor] Find files without __doc__ strings

2009-05-18 Thread David
Lie Ryan wrote:
> David wrote:
>> spir wrote:
>>> Le Sat, 16 May 2009 21:46:02 -0400,
>>> David  s'exprima ainsi:
>>>
>>>> I am doing an exercise in Wesley Chun's book. Find files in the
>>>> standard   library modules that have doc strings. Then find the
>>>> ones that don't, "the shame list". I came up with this to find the
>>>> ones with;
>
> why not __import__() it then test whether its .__doc__ is None?
>
> def test(filename):
> if __import__(filename).__doc__ is None:
> shame_list.append(filename)
> else:
> fame_list.append(filename)
>
Thanks Spir and Lie,
How about;

#!/usr/bin/python

import os
import glob
import os.path

shame_list = []
fame_list = []
pypath = "/usr/lib/python2.5/"

def grab_files():
fnames = glob.glob(os.path.join(pypath, '*.py'))
fnames.sort()
sendall(fnames)

def sendall(fnames):
for filename in fnames:
filename = os.path.split(filename)
filename = filename[1]
filename = os.path.splitext(filename)
filename = filename[0]
test(filename)


def test(filename):
try:
if __import__(filename).__doc__ is None:
shame_list.append(filename)
else:
fame_list.append(filename)
except ImportError:
pass

grab_files()
print 'Shame List: ', shame_list

How can I do;
def sendall(fnames):
[snip]
More efficient.

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

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


Re: [Tutor] web cam

2009-05-20 Thread David

Ricardo Aráoz wrote:

Hi, a friend of mine has asked me how difficult would it be to send web
cam images through python program as a hobby project.
Honestly, at this point I have no idea where does he want to put python
in the equation nor what does the project entail. So I'm asking for
pointers to :
a) Any already done projects in python
b) keywords to google for
c) what parts do you think I'll need to put together (web service,
client, browser) and which modules do you recommend.

I know this is a half baked question, just some pointers on where to
start from would be enough.

Thanks


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



You can upload still shots from the web cam with pycurl.

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sqlite3 format data from tables

2009-05-23 Thread David

I have a budget program I am using to learn from.
http://linuxcrazy.pastebin.com/f3b301daf

I can not figure out how to get the transaction details to return so 
that it looks nice. It returns like this now.


Your transaction History is: [(1, u'Food', -100), (2, u'Deposit', -200), 
(3, u'Deposit', 500), (4, u'Python Book', -50)]


Here is how it gets to that point;

def get_transactions(self):
ct=self.connection.cursor()
ct.execute("select * from transact;")
return ct.fetchall()

def report_transactions(self):
return self.database.get_transactions()

def display_transactions(self):
print "Your transaction History is:",self.bl.report_transactions()

self.menu[5]=("Transaction History",self.display_transactions)

Can I use the numbers 1,2,3,4 as a way to return the history?

Thanks, I hope I explained it correctly :)
-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3 format data from tables

2009-05-23 Thread David

David wrote:

I have a budget program I am using to learn from.
http://linuxcrazy.pastebin.com/f3b301daf

I can not figure out how to get the transaction details to return so 
that it looks nice. It returns like this now.


Your transaction History is: [(1, u'Food', -100), (2, u'Deposit', -200), 
(3, u'Deposit', 500), (4, u'Python Book', -50)]


Here is how it gets to that point;

def get_transactions(self):
ct=self.connection.cursor()
ct.execute("select * from transact;")
return ct.fetchall()

def report_transactions(self):
return self.database.get_transactions()

def display_transactions(self):
print "Your transaction History is:",self.bl.report_transactions()

self.menu[5]=("Transaction History",self.display_transactions)

Can I use the numbers 1,2,3,4 as a way to return the history?

Thanks, I hope I explained it correctly :)
-david

Ok this seems to work OK;
def display_transactions(self):
transactions = self.bl.report_transactions()
for data in transactions:
print "Transaction History: ", data[-2], data[-1]


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Post to wordpress

2009-05-23 Thread David

Jan Erik Moström wrote:

Hi,

I'm looking for a module or an example for how to post to a wordpress 
blog. I want to create a post and set:


+   title
+   content
+   category
+   tags
+   publish date

I've looked around and found

 (setting 
categories doesn't seem to work, don't know if tags/date is possible)


 (no code available)

 
(setting categories doesn't seem to work, don't know about tags/date)


 
(same as above)


Does anyone know if a library exists or some example of how to do this?

jem

I use pycurl to post to a drupal site;
http://linuxcrazy.pastebin.com/f6835c5f8
This may help to explain it;
http://madeuce.wordpress.com/2009/02/23/further-simplification-of-pycurl/

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3 format data from tables

2009-05-23 Thread David

Martin Walsh wrote:

David wrote:

David wrote:

I have a budget program I am using to learn from.
http://linuxcrazy.pastebin.com/f3b301daf

I can not figure out how to get the transaction details to return so
that it looks nice. It returns like this now.

Your transaction History is: [(1, u'Food', -100), (2, u'Deposit',
-200), (3, u'Deposit', 500), (4, u'Python Book', -50)]

Here is how it gets to that point;

def get_transactions(self):
ct=self.connection.cursor()
ct.execute("select * from transact;")
return ct.fetchall()

def report_transactions(self):
return self.database.get_transactions()

def display_transactions(self):
print "Your transaction History is:",self.bl.report_transactions()

self.menu[5]=("Transaction History",self.display_transactions)

Can I use the numbers 1,2,3,4 as a way to return the history?

Thanks, I hope I explained it correctly :)
-david

Ok this seems to work OK;
def display_transactions(self):
transactions = self.bl.report_transactions()
for data in transactions:
print "Transaction History: ", data[-2], data[-1]





It would be helpful if you showed the output you expect. Here is another
option ...

def display_transactions(self):
transactions = self.bl.report_transactions()
print "Your transaction History is:"
for n, k, v in transactions:
print ' %-15s %10.2f' % (k, v)

HTH,
Marty

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



Thanks very nice,

Your transaction History is:
 Food   -100.00
 Deposit-200.00
 Deposit 500.00
 Python Book -50.00
 Gift300.00

Also thank you Alan for your tips :)



def report_transactions(self):
return self.database.get_transactions()


Unless you intend doing something useful this function
is just an extra later of processing!


I got a kick out of it, helped me understand how the different 
function's and the classes work together, thats all, I found most of the 
code on the web and just patched it together to be honest :)



Can I use the numbers 1,2,3,4 as a way to return the history?


I don;t really understand what you mean by this bit?



Here is the data as it is returned from sqlite;
Your transaction History is: [(1, u'Food', -100), (2, u'Deposit', -200), 
(3, u'Deposit', 500), (4, u'Python Book', -50)]


I was wondering if the numbers could be used to return the contents of 
the tuple's.


Sometimes it is hard to ask a good question when I don't have a clue, 
thanks for your patience.


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using a list

2009-05-30 Thread David

Alan Gauld wrote:

"Doug Reid"  wrote


The tutorial I'm using is discussing list, tuples, and dictionaries.
...
four attributes: Strength,Stamina, Wisdom, and Dexterity.
The player should be able to spend points from the pool on
any attribute and should also be able to take points from
an attribute and put them back into the pool.


How would you describe a dictionary?
Can you see a way to apply it to the problem?




#list of attributes and their values
attributes=['dexterity=',dexterity ,'strength=',strength, 
'stamina=',stamina, 'wisdom=',wisdom]


It is a list but not of attributes. Its a list containing strings and
numbers alternating. The strings consist of an attribute name
and an equals sign. But you know about a collection type that
stores values against strings and allows you to retrieve those
values using the string as a key.


#creation loop
while creating:

choice=menu()
if choice=='0':
  print '\nThank you for using character creator.'
  end=raw_input('\n Press enter to end.')
  creating=False
elif choice=='1':#prints out list of attributes and their values
  for entry in attributes:
 print entry,

This will print

attribute=
value
attribute=
value

Not very pretty. But if you use a dictionary:

for item in dictionary:
   print item, '=', dictionary[item]

elif choice=='2':
allot=raw_input('''What attribute would you like to change?
Enter dex for dexterity, str for strength, etc. ''').lower()
if allot=='dex':
change=int(raw_input('How many points do you wish to allot? '))
attributes[1]=dexterity=+change
points=points-change
if allot=='str':
change=int(raw_input('How many points do you wish to allot? '))
attributes[3]=strength=+change

And this gets even more messy.
Again think how it would look with a dictionary...

I am also new to Python and never programed before. I use the questions 
from the Tutor list to learn. I put the attributes into dictionaries and 
 came up with a little game between the user and the computer. Thank 
you Doug for the question.

Here is my attempt;
http://linuxcrazy.pastebin.com/m31d02824

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using a list

2009-05-30 Thread David

David wrote:

Alan Gauld wrote:

"Doug Reid"  wrote


The tutorial I'm using is discussing list, tuples, and dictionaries.
...
four attributes: Strength,Stamina, Wisdom, and Dexterity.
The player should be able to spend points from the pool on
any attribute and should also be able to take points from
an attribute and put them back into the pool.


How would you describe a dictionary?
Can you see a way to apply it to the problem?




#list of attributes and their values
attributes=['dexterity=',dexterity ,'strength=',strength, 
'stamina=',stamina, 'wisdom=',wisdom]


It is a list but not of attributes. Its a list containing strings and
numbers alternating. The strings consist of an attribute name
and an equals sign. But you know about a collection type that
stores values against strings and allows you to retrieve those
values using the string as a key.


#creation loop
while creating:

choice=menu()
if choice=='0':
  print '\nThank you for using character creator.'
  end=raw_input('\n Press enter to end.')
  creating=False
elif choice=='1':#prints out list of attributes and their values
  for entry in attributes:
 print entry,

This will print

attribute=
value
attribute=
value

Not very pretty. But if you use a dictionary:

for item in dictionary:
   print item, '=', dictionary[item]

elif choice=='2':
allot=raw_input('''What attribute would you like to change?
Enter dex for dexterity, str for strength, etc. ''').lower()
if allot=='dex':
change=int(raw_input('How many points do you wish to allot? '))
attributes[1]=dexterity=+change
points=points-change
if allot=='str':
change=int(raw_input('How many points do you wish to allot? '))
attributes[3]=strength=+change

And this gets even more messy.
Again think how it would look with a dictionary...

I am also new to Python and never programed before. I use the questions 
from the Tutor list to learn. I put the attributes into dictionaries and 
 came up with a little game between the user and the computer. Thank you 
Doug for the question.

Here is my attempt;
http://linuxcrazy.pastebin.com/m31d02824


Duh, I had the counter wrong, here is a better one :)
http://linuxcrazy.pastebin.com/m2dc25067

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Class Tips

2009-05-30 Thread David

I took this program that determines a fertilizer application rate;

#!/usr/bin/python

rate = float(raw_input("Enter rate i.e. (0.5) : "))
n = float(raw_input("Enter N from bag i.e. (.14) : "))
app = rate / n
area = 43.560
acre = input("Enter total acre's to be treated: ")
bag = input("Enter bag weight: ")

print "You should apply", app * area * acre / bag, "bags."

And converted it to class/object to learn how they work. Just looking 
for some pointers, if I did it correctly etc.


#!/usr/bin/python

class FertRate:
def __init__(self, rate, nitrogen, acre, bag):
self.area = 43.560
self.app = rate / (nitrogen / 100.00)
self.acre = acre
self.bag = bag

def result(self):
result = self.app * self.area * self.acre / self.bag
print 'You should apply %0.2f bags.' % result

def main():
rate, nitrogen, acre, bag = get_inputs()
frate = FertRate(rate, nitrogen, acre, bag)
frate.result()

def get_inputs():
rate = float(raw_input('Enter Rate e.q., (0.5): '))
nitrogen = float(raw_input('Enter N From Bag e.q., (14): '))
acre = int(raw_input("Enter Total Acre's To Be Treated: "))
bag = int(raw_input('Enter Bag Weight: '))
return rate, nitrogen, acre, bag

main()

thanks,
-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class Tips

2009-05-30 Thread David

Alan Gauld wrote:


"David"  wrote


I took this program that determines a fertilizer application rate;
...
And converted it to class/object to learn how they work. Just looking 
for some pointers, if I did it correctly etc.


For such a small program its hard to see what else you could have done. 
Technically itys not too bad, I've made a couple of suggestions below. 
However, leaving the fact that its an excercise I'd say that really this 
is just a function rather than a class.



class FertRate:
def __init__(self, rate, nitrogen, acre, bag):
self.area = 43.560
self.app = rate / (nitrogen / 100.00)
self.acre = acre
self.bag = bag

def result(self):
result = self.app * self.area * self.acre / self.bag
print 'You should apply %0.2f bags.' % result


Its never a good idea to include printing in the same function as 
calculation. IT would be better to have two functions one to calculate 
and one to generate the printable output. (The actual printing is best 
done outside the class altogether, it improves the reusability. For 
example prints don't work in a GUI but a formatted string can be used.


But even if you keep it as one function at lest return the result as a 
string rather than print it




def main():
rate, nitrogen, acre, bag = get_inputs()
frate = FertRate(rate, nitrogen, acre, bag)


This could have just been:

frate = FertRate( get_inputs() )

which saves the need for the variables.


frate.result()


So if you took my advice about returning a string this becomes

print frate.result()

But as I say you could just have made FertRate a function:

print FertRate( get_inputs() )

and it would have been just as effective, classes really only start to 
be useful on slightly larger programs than this.



But as an example of using a class its nearly OK, just the tweak of the 
return value to think about - and that applies to the function version too!




Thanks Alan,

this works;
def main():
rate, nitrogen, acre, bag = get_inputs()
frate = FertRate(rate, nitrogen, acre, bag)
result = frate.result()
print 'You should apply %0.2f bags.' % result

but I get an error here;

def main():
frate = FertRate(get_inputs())
result = frate.result()
print 'You should apply %0.2f bags.' % result


Traceback (most recent call last):
  File "./fert_class.py", line 26, in 
main()
  File "./fert_class.py", line 15, in main
frate = FertRate(get_inputs())
TypeError: __init__() takes exactly 5 arguments (2 given)



--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class Tips

2009-05-31 Thread David

ALAN GAULD wrote:



but I get an error here;

def main():
frate = FertRate(get_inputs())




  File "./fert_class.py", line 15, in main
frate = FertRate(get_inputs())
TypeError: __init__() takes exactly 5 arguments (2 given)



Sorry my mistake. Because get_inputs() returns a tuple 
you have to tell the function to unpack it by placing an 
asterisk in front of the function call:


frate = FerrtRate( *get_inputs() )

That should work now.

Alan G.



Super, I had seen that in other programs and now I know why.
I have used;
def c(*args, **kwargs):
My understanding is 'args' is a tuple with all the positional arguments, 
kwargs is a dictionary with all the named arguments.


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class Tips

2009-05-31 Thread David

W W wrote:



One thing that's probably not in the scope of the program but really 
usually a good idea is error checking.

i.e.  this line:
rate = float(raw_input("Enter rate i.e. (0.5) : "))

could be converted to something like:

try:
rate = float(raw_input("Enter rate..."))
except ValueError:
print "Invalid input"
#Quit or loop until valid input is entered.

HTH,
Wayne
OK, this is what I came up with, how else could I do it so as not to use 
sys.exit() ?


#!/usr/bin/python
"""Determine the number of bags to use to fertilize
a given area given the application rate."""
from sys import exit

class FertRate:
def __init__(self, rate, nitrogen, acre, bag):
self.area = 43.560
self.app = rate / (nitrogen / 100.00)
self.acre = acre
self.bag = bag

def result(self):
result = self.app * self.area * self.acre / self.bag
return result

def main():
while True:
try:
frate = FertRate( *get_inputs() )
result = frate.result()
print 'You should apply %0.2f bags.' % result
exit()
except TypeError, UnboundLocalError:
pass

def get_inputs():
try:
print 'Rate: Pounds nitrogen per 1000 (square feet)'
rate = float(raw_input('Enter Rate i.e., (0.5): '))
print "Nitrogen: The first number of the fertilizer's analysis"
nitrogen = float(raw_input('Enter Nitrogen From Bag i.e., (14): '))
acre = int(raw_input("Enter Total Acre's To Be Treated i.e, 
(3): "))

bag = int(raw_input('Enter Bag Weight (lb): i.e., (50) '))
return rate, nitrogen, acre, bag
except ValueError:
print 'Invalid input!'
print 'You must enter a number!'

if __name__ == "__main__":
main()


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Spell checking source code?

2009-06-02 Thread David

ALAN GAULD wrote:


But that will check the whole file. The OP only wanted to spell
check the comments. Unless I'm missing something?


"Allen Fowler"  wrote 
Are there any utilities to help "spell check" source code?  (Docstrings, etc)



I came up with this;
[sample file]
#!/usr/bin/python

def doc_test():
"""Do notheing, but document it.

No, really, it doesn't do anything.
"""
pass
[test program]
#!/usr/bin/python
from doc_function_test import doc_test
from enchant.checker import SpellChecker

doc_string = doc_test.__doc__
doc_string = str(doc_string)
chkr = SpellChecker("en_US")
chkr.set_text(doc_string)
for err in chkr:
print "Error:", err.word

[results]
python spell_check_doc.py
Error: notheing




--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] my first gui]

2009-06-03 Thread David

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com

--- Begin Message ---
prasad rao wrote:
> Hello.
> I made my first mager gui program.I need your openions suggestions and
> improvements.
>  
Hi Prasad,
I get this error, I am using 2.5 on Linux;

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1403, in __call__
return self.func(*args)
  File "prasad_gui.py", line 20, in fshow
text.insert(END,('Total files in %s are %d
\n'%(entry1.get(),len(mf)))+ mystring(mf))
  File "prasad_gui.py", line 36, in mystring
for n,m in  enumerate(x,start=1):
TypeError: 'start' is an invalid keyword argument for this function

-- 
powered by Gentoo/GNU Linux
http://linuxcrazy.com


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


Re: [Tutor] my first gui]

2009-06-03 Thread David
David wrote:
>
> prasad rao wrote:
>   
>> Hello.
>> I made my first mager gui program.I need your openions suggestions and
>> improvements.
>>  
>> 
> Hi Prasad,
> I get this error, I am using 2.5 on Linux;
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1403, in __call__
> return self.func(*args)
>   File "prasad_gui.py", line 20, in fshow
> text.insert(END,('Total files in %s are %d
> \n'%(entry1.get(),len(mf)))+ mystring(mf))
>   File "prasad_gui.py", line 36, in mystring
> for n,m in  enumerate(x,start=1):
> TypeError: 'start' is an invalid keyword argument for this function
>
>   
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
Ok this works,

def mystring(x):
q=''
for n,m in  enumerate(x):
n + 1
o=str(n)+'.'+str(m)
q+=(o+'\n')
return q+'\n'

I took the liberty of editing the format;

#! usr\bin\python
from Tkinter import *
import os
import time
import glob

def myfiles (n='',m=''):
mf=[os.path.join(x,i)for x,y,z in os.walk(n) for i in z if
i.endswith(m)]
return mf

def fshow():
tclear()
x=entry1.get()
try:
value1,value2=x.split(',')
mf=myfiles(value1,value2)
text.insert(END,('Total files in %s are %d
\n'%(entry1.get(),len(mf)))+ mystring(mf))
except:
mf=myfiles(x)
text.insert(END,('Total files in %s are %d
\n'%(entry1.get(),len(mf)))+ mystring(mf))

def atime(x):
atime=time.strftime("%c",time.localtime(os.path.getatime(x)))
return atime
  
def mtime(x):
mtime=time.strftime("%c",time.localtime(os.path.getmtime(x)))
return mtime
   
def ctime(x):
ctime=time.strftime("%c",time.localtime(os.path.getctime(x)))
return ctime

def mystring(x):
q=''
for n,m in  enumerate(x):
n + 1
o=str(n)+'.'+str(m)
q+=(o+'\n')
return q+'\n'
 
def info():
tclear()
import glob,os
mf=''
md=''
mfl,mdl=[],[]   
mdd=glob.glob(entry1.get()+os.sep+'*')
for x in mdd:
if os.path.isfile(x)==True:
mfl.append(x)
else:mdl.append(x)
   mf+=mystring(mfl)
md+=mystring(mdl)
mf=("Total files in %s are %d \n\n"%(entry1.get(),len(mfl)))+mf
md=('Total directories in %s are %d
\n\n'%(entry1.get(),len(mdl)))+md
mf+='\n\n'
text.insert(END,mf+md)

def destroy():
root.destroy()

def eclear():
entry1.delete(0,END)
entry2.delete(0,END)
entry3.delete(0,END)
entry4.delete(0,END)

def tclear():
text.delete(1.0,END)

def ashow():
x=entry1.get()
try:
n,m=x.split(',')
value=atime(n)
except:
value=atime(x)
entry2.insert(0,value)

def mshow():
x=entry1.get()
try:
n,m=x.split(',')
value=mtime(n)
except:
value=mtime(x)
entry3.insert(0,value)

def cshow():
x=entry1.get()
try:
n,m=x.split(',')
value=ctime(n)
except:
value=ctime(x)
entry4.insert(0,value)

root = Tk()
  
frame1=Frame(root,relief='sunken',border=1)
frame1.pack(side='top',expand="true")

frame2=Frame(root,relief='sunken',border=1)
frame2.pack(side='top',expand="true")

frame3=Frame(root,relief='sunken',border=1)
frame3.pack(side='top',expand="true")

frame4=Frame(root,relief='sunken',border=1,)
frame4.pack(side='top',expand="true")

frame5=Frame(root,relief='sunken',border=1)
frame5.pack(side='top',expand="true")

label5=Label(frame1,text="Enter file path to get information about the
file \
or enter directory(or directory,fileextension) to get files init ",border=1)
label5.pack(side='top',fill='both')

b1=Button(frame2,text='quit',command=destroy,border=1)
b1.pack(side='left',padx=5,pady=5)

b2=Button(frame2,text='clear',command=eclear,border=1)
b2.pack(side='left',padx=5,pady=5)

b3=Button(frame2,text='accessed',command=ashow,border=1)
b3.pack(side='left',padx=5,pady=5)

b4=Button(frame2,text='modified',command=mshow,border=1)
b4.pack(side='left',padx=5,pady=5)

b5=Button(frame2,text='cr

[Tutor] What is this kind of loop called

2009-06-07 Thread David
In one of my questions to this list, Kent explained to me how to use a 
loop like this;


#!/usr/bin/python
from time import sleep

def get(numbers):
print 'Calling ', numbers
sleep(1)
print 'Connected '
sleep(1)

def call_numbers():
for i in range(9549355543, 9549355560):
numbers = i
get(numbers)
call_numbers()

Is there a technical name for a loop like this?
thanks
-david
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Fwd: Re: What is this kind of loop called]

2009-06-07 Thread David

Forwarding to the list, forgot again :(
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
--- Begin Message ---

bob gailer wrote:

David wrote:
In one of my questions to this list, Kent explained to me how to use a 
loop like this;


#!/usr/bin/python
from time import sleep

def get(numbers):
print 'Calling ', numbers
sleep(1)
print 'Connected '
sleep(1)

def call_numbers():
for i in range(9549355543, 9549355560):
numbers = i
get(numbers)
call_numbers()

Is there a technical name for a loop like this?


For loop? That is what I call it.


As usual I am not very clear, see how the call_numbers() for loop gets 
passes to the get(numbers) to do something else, that is what I was 
asking about.


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com

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


Re: [Tutor] smptlib question

2009-06-08 Thread David

Albert-jan Roskam wrote:

(sorry for posting this again, but something might have gone wrong)

Hi,

I made a very simple program to send everybody I know a change of address I am 
parsing the .msg files with another function, which returns a set called 
'recipients'.

The code below works, but it displays all recipients in the 'to' field. That 
is, in the Nth iteration, N recipients are shown. So the first mail has one 
recipient in the 'to' field, the second mail has the first and the second 
recipient, and so forth. I only want one recipient to be shown in the 'to' 
field. It's ugly and since I have a lot of email addresses to parse (4 years 
worth of emails!), it would become a very long list.

Pointers, anyone?

Thanks!
Albert-Jan
Python 2.5, Windows XP

import smtplib, email.utils
from email.mime.text import MIMEText

msg = MIMEText("""Dear reader:\n\nblah blaah blaah.\nSincerely,\nThe 
dude""")

sender = 'r...@stimpy.com'
recipients = ['happyha...@joy.com', 'y...@eediot.com]
for no, recipient in enumerate(recipients):
print "--> Sending message to: %s (%s of %s)" % (recipient, no+1, 
len(recipients))
msg['To'] = email.utils.formataddr((recipient, recipient))
print msg['To']
msg['From'] = email.utils.formataddr(('Cool dude', sender))
msg['Subject'] = 'Change of email address'

server = smtplib.SMTP("mysmtpserver.isp.com")
server.set_debuglevel(True)
try:
server.sendmail(sender, [recipient], msg.as_string())
finally:
server.quit()


  
___

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




Hi Albert,
I got this to work;

#!/usr/bin/python

import smtplib, email.utils
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.Utils import COMMASPACE, formatdate

def recipients():
recipients = ['happyha...@joy.com', 'y...@eediot.com]
for no, recipient in enumerate(recipients):
print "--> Sending message to: %s (%s of %s)" % (recipient, 
no+1, len(recipients))

message(recipient)

def message(recipient):
body = "Dear reader:\n\nblah blaah blaah.\nSincerely,\nThe dude"
send_mail([recipient], 'Change of email address', body)


def send_mail(send_to, subject, text, server="mail.stimpy.com"):
send_from = "r...@stimpy.com"
msg = MIMEMultipart()
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['From'] = send_from
msg['Subject'] = subject
msg.attach( MIMEText(text) )
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()

recipients()

--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gui further explained (The error in unreadable form)

2009-06-09 Thread David

Essah Mitges wrote:

What I am trying to do is start my pygame game from my pygame menuI do not think I am using the right code to do this I am trying to use the 
subprocess module to open a child window with the game inside of it but python doesn't like thatThe second thing that i'd like to know how I could 
list the content of a text file inside a pygame window(this is a different file)Traceback (most recent call last):  File "C:\Users\John 
Doe\Desktop\D-Day\back.py", line 47, in main()  File "C:\Users\John Doe\Desktop\D-Day\back.py", line 37, in mainelif 
sbut.clicked(k.pos):  File "C:\Users\John Doe\Desktop\D-day\but.py", line 200, in clickedsubprocess.Popen(["D-Day", 
"Destruction.py"])  File "C:\Python26\lib\subprocess.py", line 595, in __init__errread, errwrite)  File 
"C:\Python26\lib\subprocess.py", line 804, in _execute_childstartupinfo)WindowsError: [Error 2] The system cannot find the file 
specified
_
Attention all humans. We are your photos. Free us.
http://go.microsoft.com/?linkid=9666046
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor





--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help solving this problem

2009-06-10 Thread David

Raj Medhekar wrote:
I have been teaching myself Python using a book. The chapter I am on 
currently, covers branching, while loops and program planning. I am 
stuck on on of the challenges at the end of this chapter, and I was 
hoping to get some help with this. Here it is:


Write a program that flips a coin 100 times and the tells you the number 
of heads and tails.


I have tried to think about several ways to go about doing this but I 
have hit a wall. Even though I understand the general concept of 
branching and looping, I have been having trouble writing a program with 
these.  I look forward to your reply that will help me understand these 
structures better.


Sincerely,
Raj




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

I am learning also, I came up with;

#!/usr/bin/python

import random
random = random.Random()
choice = ['heads', 'tails']
head_wins = 0
tail_wins = 0

def coin_flip():
flip = random.choice(choice)
global head_wins
global tail_wins
if flip == 'heads':
head_wins += 1
elif flip == 'tails':
tail_wins += 1

def number_flips():
for i in range(100):
coin_flip()

number_flips()
print 'Head Total Wins =', head_wins
print 'Tail Total Wins =', tail_wins


--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need a solution.

2009-06-11 Thread David

Raj Medhekar wrote:
I have been having some difficulty modifying this program to where a 
player has limited number of guesses and if he fails to guess correctly 
within that number he is asked to "Try Again" The original program code 
and the code that I modified are given below. Thanks for your help.


Sincerely,
Raj

The Original program code:

# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it  and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100."
print "Try to guess it in as few attempts as possible.\n"

# set the initial values
the_number = random.randrange(100)+1
guess = int(raw_input("Take a guess:"))
tries = 1

#guessing loop
while guess != the_number:
if guess > the_number:
print "Lower..."
else:
print "Higher..."

guess = int(raw_input("Take a guess:"))
tries += 1

print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"

raw_input("\n\nPress the enter key to exit")


Hi Raj,
I am also learning Python and never did any real programming before, I 
have been attempting to learn about classes, this is my version, 
comments, suggestions always welcome.

-david

#!/usr/bin/python
from random import randrange
from sys import exit

class GuessNumber:
def __init__(self):
self.number = randrange(100)+1
self.count_tries = 1
self.total_tries = 5
def update_count(self):
self.count_tries += 1

def guess_number():
gn = GuessNumber()
number = gn.number
tries = gn.total_tries
attempts = gn.count_tries
update_count = gn.update_count()
guess = 'Take a guess: '
question = 'Try again? '
decision = 'Do you want to try again? y/n '
discription = \
"""\n\tWelcome to 'Guess My Number'!
I'm thinking of a number between 1 and 100.
Try to guess it in 5 attempts!\n
"""
print discription
answer = int(raw_input(guess))
while answer != number and attempts < tries:
if answer > number:
print 'Lower ...'
else:
print 'Higher ...'
update_count
print 'You have %i attempts left!' % (tries - attempts)
answer = int(raw_input(guess))
attempts += 1
if answer == number:
print 'You guessed it the number was', number
print 'And it only took you %i attempts' % attempts
choice = raw_input(decision)
if choice == 'y':
choice = choice.lower()
guess_number()
else:
exit()
else:
print 'You did not pick the number!'
print 'The number was', number
choice = raw_input(decision)
if choice == 'y':
choice = choice.lower()
guess_number()
else:
exit()

if __name__ == "__main__":
guess_number()





--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need a solution.

2009-06-11 Thread David

Randy Trahan wrote:
Well that didin't work I tried the program and it went into an infinite 
loop...is that the problem you were asking about?


On Fri, Jun 12, 2009 at 12:14 AM, Randy Trahan <mailto:mattie289...@gmail.com>> wrote:


Hi Raj,
 
The only thing I see is that under #guessing Loop you do not have ()

around the code; ie.
while (guess != the_number):
 if (guess > the_number):
print "Lower.."


 
On Fri, Jun 12, 2009 at 12:02 AM, David 
<mailto:da...@abbottdavid.com>> wrote:

Raj Medhekar wrote:

I have been having some difficulty modifying this program to
where a player has limited number of guesses and if he fails
to guess correctly within that number he is asked to "Try
Again" The original program code and the code that I
modified are given below. Thanks for your help.

Sincerely,
Raj

The Original program code:

# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it  and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100."
print "Try to guess it in as few attempts as possible.\n"

# set the initial values
the_number = random.randrange(100)+1
guess = int(raw_input("Take a guess:"))
tries = 1

#guessing loop
while guess != the_number:
   if guess > the_number:
   print "Lower..."
   else:
   print "Higher..."

   guess = int(raw_input("Take a guess:"))
   tries += 1

print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"

raw_input("\n\nPress the enter key to exit")

Hi Raj,
I am also learning Python and never did any real programming
before, I have been attempting to learn about classes, this is
my version, comments, suggestions always welcome.
-david

#!/usr/bin/python
from random import randrange
from sys import exit

class GuessNumber:
   def __init__(self):
   self.number = randrange(100)+1
   self.count_tries = 1
   self.total_tries = 5
   def update_count(self):
   self.count_tries += 1

def guess_number():
   gn = GuessNumber()
   number = gn.number
   tries = gn.total_tries
   attempts = gn.count_tries
   update_count = gn.update_count()
   guess = 'Take a guess: '
   question = 'Try again? '
   decision = 'Do you want to try again? y/n '
   discription = \
   """\n\tWelcome to 'Guess My Number'!
   I'm thinking of a number between 1 and 100.
   Try to guess it in 5 attempts!\n
   """
   print discription
   answer = int(raw_input(guess))
   while answer != number and attempts < tries:
   if answer > number:
   print 'Lower ...'
   else:
   print 'Higher ...'
   update_count
   print 'You have %i attempts left!' % (tries - attempts)
   answer = int(raw_input(guess))
   attempts += 1
   if answer == number:
   print 'You guessed it the number was', number
   print 'And it only took you %i attempts' % attempts
   choice = raw_input(decision)
   if choice == 'y':
   choice = choice.lower()
   guess_number()
   else:
   exit()
   else:
   print 'You did not pick the number!'
   print 'The number was', number
   choice = raw_input(decision)
   if choice == 'y':
   choice = choice.lower()
   guess_number()
   else:
   exit()

if __name__ == "__main__":
   guess_number()





-- 
Powered by Gentoo GNU/Linux

http://linuxcrazy.com <http://linuxcrazy.com/>
___
Tutor maillist  -  Tutor@python.org <mailto:Tutor@python.org>
http://mail.python.org/

  1   2   3   4   5   6   7   8   9   10   >