[Tutor] cylinder texture map?

2006-10-12 Thread Michael Shulman
Hello,

You guys gave fantastic advice for my last question about point in 
polygon testing, thanks.

New question;
I'd like to make a scrolling background for a game I'm working on.  I 
was thinking, since it's all in orthographic view, that a horizontal 
cylinder which rotates with a texture would simulate this very well.
I've never used textures before, and in all the sample code I see, they 
have polygons with defined points, so it's very straightforward to see 
what goes with what... but I don't see how to make the switch over to
the glut primitives.  Any samples/ insights would be awesome.

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


Re: [Tutor] SQL Queries For MySQL

2006-10-12 Thread Alan Gauld
> query = "SELECT * FROM DB WHERE NAME = %s" % (name)
> cursor.execute(query)

There can be security issues with this style, especially 
if the parameters can be modified by users - for example 
you read the values from a web page.

The cursor.execute() call has the ability to pass the parameters 
in directly, ie combining the two statements above into one. 
The details of how ypou do that varies between database 
drivers so you need to check the documents but I think for 
MySQL its almost an exact translation:

query = "SELECT * FROM DB WHERE NAME = %s"
cursor.execute(query, name)

If you search the ist archives you'll find a fairly long thread 
describing the whys/wherefores in much more depth.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

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


[Tutor] Why is random.choice so much slower than random.random()?

2006-10-12 Thread Dick Moores
Why is random.choice so much slower than random.random()? In fact, by 
a factor of 12! And randint(). Some 25 times slower than random(). Why?
(I know that random() is the basis for most of the other functions in 
the random module, and a look at random.py, though I don't complete 
understand it, gives me an idea what's going on with randint(), etc., still...)

C:\>python -m timeit  -s"from random import choice" "for x in range(1):
" " choice([0, 1])"
10 loops, best of 3: 22.8 msec per loop

C:\>python -m timeit  -s"from random import random" "for x in range(1):
" " random()"
1000 loops, best of 3: 1.84 msec per loop

C:\>python -m timeit  -s"from random import uniform" "for x in range(1)
:" " uniform(0, 1)"
100 loops, best of 3: 12.2 msec per loop

C:\>python -m timeit  -s"from random import randrange" "for x in range(1000
0):" " randrange(2)"
10 loops, best of 3: 25.3 msec per loop

C:\>python -m timeit  -s"from random import randint" "for x in range(1)
:" " randint(0, 1)"
10 loops, best of 3: 45.9 msec per loop


Anyway, if you are making a coin flipping program, with a great many 
flips and speed is important, it seems a good idea to avoid the 
otherwise obvious choice of choice().

coin = choice(["heads", "tails"]).

instead, use

value = random()
if value >= .5:
 coin = "heads"
else:
 coin = "tails"

I tested these in order, using the template in random.py (a copy of 
it of course):

Evaluating timeitRandom-1.py
100 loops, best of 3: 4.24 msec per loop
SystemExit:
 >>>
Evaluating timeitRandom-2.py
10 loops, best of 3: 27.9 msec per loop
SystemExit:
 >>>
(Thanks, Kent)

Even with all the extra baggage attached to it, random() is 6.6 times 
faster than choice with no baggage!

Dick Moores

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


Re: [Tutor] Why is random.choice so much slower than random.random()?

2006-10-12 Thread Luke Paireepinart
Dick Moores wrote:
> Why is random.choice so much slower than random.random()? In fact, by 
> a factor of 12! And randint(). Some 25 times slower than random(). Why?
> (I know that random() is the basis for most of the other functions in 
> the random module, and a look at random.py, though I don't complete 
> understand it, gives me an idea what's going on with randint(), etc., 
> still...)
>   
I haven't looked at the random code, but what I expect is happening is that
for random.choice(a)
you need to
1) get a random number
2) convert that random number into an index into your list.  eg. [0,1] 
any random number < .5 would be index 0.
recall that random goes from 0 to 1.
3) grab that item from the list and return it.

I'm guessing that step 2 and step 3 are why it takes a while, since 
these are probably implemented in Python.

for random.randint(a,b):
It might do
random.choice(range(a,b+1))
so there's the overhead of generating the range.

Course this is completely speculation and may be not true at all, but I 
thought I'd give it a shot :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is random.choice so much slower than random.random()?

2006-10-12 Thread Kent Johnson
Dick Moores wrote:
> Why is random.choice so much slower than random.random()? In fact, by 
> a factor of 12! And randint(). Some 25 times slower than random(). Why?
> (I know that random() is the basis for most of the other functions in 
> the random module, and a look at random.py, though I don't complete 
> understand it, gives me an idea what's going on with randint(), etc., 
> still...)
> 
> C:\>python -m timeit  -s"from random import choice" "for x in range(1):
> " " choice([0, 1])"
> 10 loops, best of 3: 22.8 msec per loop
> 
> C:\>python -m timeit  -s"from random import random" "for x in range(1):
> " " random()"
> 1000 loops, best of 3: 1.84 msec per loop
> 
> C:\>python -m timeit  -s"from random import uniform" "for x in range(1)
> :" " uniform(0, 1)"
> 100 loops, best of 3: 12.2 msec per loop
> 
> C:\>python -m timeit  -s"from random import randrange" "for x in range(1000
> 0):" " randrange(2)"
> 10 loops, best of 3: 25.3 msec per loop
> 
> C:\>python -m timeit  -s"from random import randint" "for x in range(1)
> :" " randint(0, 1)"
> 10 loops, best of 3: 45.9 msec per loop

Looking at the code and your numbers, my guess is that the time to make 
a Python function call on your computer is about 2 microseconds (20 msec 
/ 1). (I mean the entire overhead - looking up the function and 
actually calling it.)

random.randint() just calls random.randrange() after incrementing the 
upper limit. So the difference in times between these two is one 
addition and a function call.

randrange() does a little checking, then calls random(). The time 
difference is a little more than 20 msec, probably due to the argument 
checking.

> Anyway, if you are making a coin flipping program, with a great many 
> flips and speed is important, it seems a good idea to avoid the 
> otherwise obvious choice of choice().

And more generally, in a highly optimized loop, avoid function calls if 
possible, they are relatively expensive in Python.

Kent

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


[Tutor] python tutor

2006-10-12 Thread deandermo



can any one please help 
im looking for a personal tutor that can help me 
with learning python .
im finding it alien to me as i am a beginer 

ive tried numerous websites and i am still finding 
it stranfe to .
can anyone help me ??
many thanks dean dermody
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] tutor required

2006-10-12 Thread deandermo



please can you help me ?
i need a private tutor to learn me python , i know 
this may seem strange but im finding it really difficult to learn ,
ive very website there is 'and im just not learning 
, i would feel better iff i had someone teaching it me ,.
do you know of anyone who could help me out 
?
.please get in touch.
 many thanks dean 
dermody
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2006-10-12 Thread dean dermody

do you know of any private tutors to tach me python 
thank you 

Hotmail is evolving - be one of the first to try the  Windows Live™ Mail Beta 

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


[Tutor] Fwd: do you know how to do this

2006-10-12 Thread ALAN GAULD
Forwarding to the group...

--- anil maran <[EMAIL PROTECTED]> wrote:

> Date: Thu, 12 Oct 2006 01:46:44 -0700 (PDT)
> From: anil maran <[EMAIL PROTECTED]>
> Subject: do you know how to do this
> To: Alan Gauld <[EMAIL PROTECTED]>
> 
> The user, password and group are stored in a session on disk
> using 
> flup.middleware.session. You can change this to fit your needs
> like in 
> a database. I think someone have already extended the flup
> session with 
> a database store? 
> 
> Use the decorator function on your GET and POST method to set 
> authentication and provide which group are allowed. 
> 
> If auth is set to True and user/password/access did not match,
> a 
> redirect is made to /login. 
> 
> 
>  
> Anil
> 
> 
> 
> - Original Message 
> From: Alan Gauld <[EMAIL PROTECTED]>
> To: tutor@python.org
> Sent: Thursday, October 12, 2006 12:31:04 AM
> Subject: Re: [Tutor] SQL Queries For MySQL
> 
> 
> > query = "SELECT * FROM DB WHERE NAME = %s" % (name)
> > cursor.execute(query)
> 
> There can be security issues with this style, especially 
> if the parameters can be modified by users - for example 
> you read the values from a web page.
> 
> The cursor.execute() call has the ability to pass the
> parameters 
> in directly, ie combining the two statements above into one. 
> The details of how ypou do that varies between database 
> drivers so you need to check the documents but I think for 
> MySQL its almost an exact translation:
> 
> query = "SELECT * FROM DB WHERE NAME = %s"
> cursor.execute(query, name)
> 
> If you search the ist archives you'll find a fairly long
> thread 
> describing the whys/wherefores in much more depth.
> 
> HTH,
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


Send instant messages to your online friends http://uk.messenger.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python tutor

2006-10-12 Thread Alan Gauld
This list does not provide private tutors as such. But you can ask
questions about topics that you don't understand on  the web sites
(preferrably with a link to the page in question) and people will try
to clarify what is meant.

The advantages of the list approach are:

1) More tutors so more chance of one finding an explanation
you understand

2) The are other beginners on the list who may understand
your perspective better than an expert who may take for granted
certain assumptions that are not valid for a beginner.

3) Your learning experience gets shared to otherbgefginners who
may be struggling with the same issues.

The downside is that you have to be brave enough to publicly
ask questions thatyou think are probably too basic, however any
question is valid on this list. It is designed for beginners after 
all!

If you are really lucky some individuial suibscriber may offer one
on one coaching, or recommend a training course local to you.

Finally, I recommend that you tackle one web tutor/book at a time,
certainy not more than 2 in parallel to avoid getting confused
over terminology etc.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


"deandermo" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
can any one please help
im looking for a personal tutor that can help me with learning python 
.
im finding it alien to me as i am a beginer
ive tried numerous websites and i am still finding it stranfe to .
can anyone help me ??
many thanks dean dermody






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


Re: [Tutor] Why is random.choice so much slower than random.random()?

2006-10-12 Thread Dick Moores
At 04:33 AM 10/12/2006, Kent Johnson wrote:
>Looking at the code and your numbers, my guess is that the time to make
>a Python function call on your computer is about 2 microseconds (20 msec
>/ 1). (I mean the entire overhead - looking up the function and
>actually calling it.)

Hm. Does this test include the entire overhead?

C:\>python -m timeit  -r 3 -s"from random import random" "random()"
1000 loops, best of 3: 0.157 usec per loop

Dick



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


[Tutor] Help with basic user-data file

2006-10-12 Thread Asrarahmed Kadri
Folks,
 
I am trying to modify the userManagement program given in Core Python Programming. It uses a dictionary to store user-password information. The usernames are the keys and the passwords are the values. 
Now I want is to add a third element; last login time.
I want to store this information in a file so that the data is not lost once the program stops execution.
 
I am not sure of using time function in python..
Can anyone help with this issue??
 
REgards.
Asrar-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is random.choice so much slower than random.random()?

2006-10-12 Thread Kent Johnson
Dick Moores wrote:
> At 04:33 AM 10/12/2006, Kent Johnson wrote:
>> Looking at the code and your numbers, my guess is that the time to make
>> a Python function call on your computer is about 2 microseconds (20 msec
>> / 1). (I mean the entire overhead - looking up the function and
>> actually calling it.)
> 
> Hm. Does this test include the entire overhead?
> 
> C:\>python -m timeit  -r 3 -s"from random import random" "random()"
> 1000 loops, best of 3: 0.157 usec per loop

I don't know why that one is faster. Maybe because it is calling a 
function in C, or because there are no arguments? Someone else will have 
to answer that.

Kent

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


Re: [Tutor] SQL Queries For MySQL

2006-10-12 Thread johnf

On Thursday 12 October 2006 00:31, Alan Gauld wrote:
> > query = "SELECT * FROM DB WHERE NAME = %s" % (name)
> > cursor.execute(query)
>
> There can be security issues with this style, especially
> if the parameters can be modified by users - for example
> you read the values from a web page.
>
> The cursor.execute() call has the ability to pass the parameters
> in directly, ie combining the two statements above into one.
> The details of how ypou do that varies between database
> drivers so you need to check the documents but I think for
> MySQL its almost an exact translation:
>
> query = "SELECT * FROM DB WHERE NAME = %s"
> cursor.execute(query, name)
>
> If you search the ist archives you'll find a fairly long thread
> describing the whys/wherefores in much more depth.
>
> HTH,
Since the archive is large - could you provide the subject title.

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


Re: [Tutor] Help with basic user-data file

2006-10-12 Thread Rob Andrews
To keep the information, the simplest solution is simply to save it in
a text file that the program can load into memory when it starts up
again. For sensitive information like passwords, a little extra fuss
is generally merited.

When someone logs in, you can save a value like
time.strftime(time.ctime()) for a nice, human-readable time stamp.
Don't forget to "import time" first.

-Rob A.

On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
> Folks,
>
> I am trying to modify the userManagement program given in Core Python
> Programming. It uses a dictionary to store user-password information. The
> usernames are the keys and the passwords are the values.
> Now I want is to add a third element; last login time.
> I want to store this information in a file so that the data is not lost once
> the program stops execution.
>
> I am not sure of using time function in python..
> Can anyone help with this issue??
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about number of threads

2006-10-12 Thread shawn bright
Hey there,
i have an app that runs several processes as threads.
using the threading.Thread()

now, i have another app that does the same thing. Now, pretty soon, we
will be combining all the features of the two packages together into
one app. 

My question is, is there a limit on how many threads one GUI application can have running in the background ?
Most of them are sleeping most of the time. They wake up and do something every 10 seconds, 20 minutes, etc...

Any pitfalls out there i shoud know about ?

thanks

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


Re: [Tutor] Help with basic user-data file

2006-10-12 Thread Asrarahmed Kadri
It means there is no need of entering the data in the dictionary,??
 
How will I then implement the uniqueness of loginnames???
 
Thanks for the support.
regards,
Asrar 
On 10/12/06, Rob Andrews <[EMAIL PROTECTED]> wrote:
To keep the information, the simplest solution is simply to save it ina text file that the program can load into memory when it starts up
again. For sensitive information like passwords, a little extra fussis generally merited.When someone logs in, you can save a value liketime.strftime(time.ctime()) for a nice, human-readable time stamp.
Don't forget to "import time" first.-Rob A.On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:> Folks,>> I am trying to modify the userManagement program given in Core Python
> Programming. It uses a dictionary to store user-password information. The> usernames are the keys and the passwords are the values.> Now I want is to add a third element; last login time.> I want to store this information in a file so that the data is not lost once
> the program stops execution.>> I am not sure of using time function in python..> Can anyone help with this issue??___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with basic user-data file

2006-10-12 Thread Rob Andrews
When a login name is being created, you can pull a list of existing
login names from file, and run a check to see if it is in the list. If
the new name is in the list, have it kick back a message telling the
user to try another name.

Also, your program could suggest a new user name in such a case, or
even assign new users names of its choosing.

The dictionary data structure is handy for the program to use in very
efficiently matching user names with passwords. But you don't have to
store the dictionary in a file as a dictionary. It's possible to do
so, but often easier to use a delimited text file.

On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
> It means there is no need of entering the data in the dictionary,??
>
> How will I then implement the uniqueness of loginnames???
>
> Thanks for the support.
> regards,
> Asrar
>
>
> On 10/12/06, Rob Andrews <[EMAIL PROTECTED]> wrote:
> >
> > To keep the information, the simplest solution is simply to save it in
> > a text file that the program can load into memory when it starts up
> > again. For sensitive information like passwords, a little extra fuss
> > is generally merited.
> >
> > When someone logs in, you can save a value like
> > time.strftime(time.ctime()) for a nice, human-readable time stamp.
> > Don't forget to "import time" first.
> >
> > -Rob A.
> >
> > On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
> > > Folks,
> > >
> > > I am trying to modify the userManagement program given in Core Python
> > > Programming. It uses a dictionary to store user-password information.
> The
> > > usernames are the keys and the passwords are the values.
> > > Now I want is to add a third element; last login time.
> > > I want to store this information in a file so that the data is not lost
> once
> > > the program stops execution.
> > >
> > > I am not sure of using time function in python..
> > > Can anyone help with this issue??
> > ___
> > Tutor maillist  -   Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
> To HIM you shall return.


-- 
Blogging my outdoors obsession: http://trekkingbob.blogspot.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about number of threads

2006-10-12 Thread Kent Johnson
shawn bright wrote:
> Hey there,
> i have an app that runs several processes as threads.
> using the threading.Thread()
> 
> now, i have another app that does the same thing. Now, pretty soon, we 
> will be combining all the features of the two packages together into one 
> app.
> 
> My question is, is there a limit on how many threads one GUI application 
> can have running in the background ?
> Most of them are sleeping most of the time. They wake up and do 
> something every 10 seconds, 20 minutes, etc...

IIRC the number of threads is limited by memory - each thread requires 
some heap space for its stack, etc. I don't think you will have trouble 
until you have hundreds or thousands of threads.

For example on my computer this program prints 1031 before it exits with 
thread.error: can't start new thread:

import time
from threading import Thread, activeCount

def run():
 while 1:
 time.sleep(1)

while 1:
 print activeCount()
 t=Thread(target=run)
 t.setDaemon(1)
 t.start()

(The setDaemon() call lets the application exit normally when it gets an 
exception; otherwise it hangs with all the threads running.)

Kent

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


Re: [Tutor] SQL Queries For MySQL

2006-10-12 Thread Jason Massey
On 10/12/06, johnf <[EMAIL PROTECTED]> wrote:
On Thursday 12 October 2006 00:31, Alan Gauld wrote:> > query = "SELECT * FROM DB WHERE NAME = %s" % (name)> > cursor.execute(query)>> There can be security issues with this style, especially
> if the parameters can be modified by users - for example> you read the values from a web page.>> The cursor.execute() call has the ability to pass the parameters> in directly, ie combining the two statements above into one.
> The details of how ypou do that varies between database> drivers so you need to check the documents but I think for> MySQL its almost an exact translation:>> query = "SELECT * FROM DB WHERE NAME = %s"
> cursor.execute(query, name)>> If you search the ist archives you'll find a fairly long thread> describing the whys/wherefores in much more depth.>> HTH,Since the archive is large - could you provide the subject title.
ThanksJohn___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
Forgot to forward to the list...Check out this posting from Danny:
http://mail.python.org/pipermail/tutor/2003-April/022010.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: question about number of threads

2006-10-12 Thread shawn bright
-- Forwarded message --From: shawn bright <[EMAIL PROTECTED]>Date: Oct 12, 2006 9:15 AM
Subject: Re: [Tutor] question about number of threadsTo: Kent Johnson <[EMAIL PROTECTED]>oh, well then i do not have anything to worry about. I was 
talking about a move from 6 threads to 10. he he. Thanks for the advice
!

shawnOn 10/12/06, Kent Johnson <
[EMAIL PROTECTED]> wrote:
shawn bright wrote:> Hey there,> i have an app that runs several processes as threads.> using the threading.Thread()>> now, i have another app that does the same thing. Now, pretty soon, we
> will be combining all the features of the two packages together into one> app.>> My question is, is there a limit on how many threads one GUI application> can have running in the background ?
> Most of them are sleeping most of the time. They wake up and do> something every 10 seconds, 20 minutes, etc...IIRC the number of threads is limited by memory - each thread requiressome heap space for its stack, etc. I don't think you will have trouble
until you have hundreds or thousands of threads.For example on my computer this program prints 1031 before it exits withthread.error: can't start new thread:import timefrom threading import Thread, activeCount
def run(): while 1: time.sleep(1)while 1: print activeCount() t=Thread(target=run) t.setDaemon(1) t.start()(The setDaemon() call lets the application exit normally when it gets an
exception; otherwise it hangs with all the threads running.)Kent___Tutor maillist  -  
Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] SQL Queries For MySQL

2006-10-12 Thread Python
On Thu, 2006-10-12 at 06:19 -0700, johnf wrote:
> On Thursday 12 October 2006 00:31, Alan Gauld wrote:
> > > query = "SELECT * FROM DB WHERE NAME = %s" % (name)
> > > cursor.execute(query)
> >
> > There can be security issues with this style, especially
> > if the parameters can be modified by users - for example
> > you read the values from a web page.
> >
> > The cursor.execute() call has the ability to pass the parameters
> > in directly, ie combining the two statements above into one.
> > The details of how ypou do that varies between database
> > drivers so you need to check the documents but I think for
> > MySQL its almost an exact translation:
> >
> > query = "SELECT * FROM DB WHERE NAME = %s"
> > cursor.execute(query, name)
> >
> > If you search the ist archives you'll find a fairly long thread
> > describing the whys/wherefores in much more depth.
> >
> > HTH,
> Since the archive is large - could you provide the subject title.

http://www.google.com/search?hl=en&q=cursor.execute+tutor+python&btnG=Google+Search

The above google search should get you pretty close.  It is looking for:
cursor.execute tutor python

In particular, this link (from the first page)
http://www.mail-archive.com/tutor@python.org/msg15716.html
is probably part of the thread you want.

> 
> Thanks
> John
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp

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


[Tutor] how to check whether a file exists or not??

2006-10-12 Thread Asrarahmed Kadri
Hello,
 
Sorry, but this is a very basic questions...
Can you tell me how to check the existence of a file..
Also if a file exists, and we open it in a write mode, it would be truncated to zero length. So what is the way out of this??#
 
Regards,
 
Asrar-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to check whether a file exists or not??

2006-10-12 Thread Ziad Rahhal
On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
Hello,
 
Sorry, but this is a very basic questions...
Can you tell me how to check the existence of a file..
    to check if a file exists, you can use os.path.exists(path) 
    or look at http://python.org/doc/current/lib/module-os.path.html for more info
 Also if a file exists, and we open it in a write mode, it would be truncated to zero length. So what is the way out of this??#

 
Regards,
 
Asrar-- To HIM you shall return. 

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


Re: [Tutor] python tutor

2006-10-12 Thread Danny Yoo


> 1) More tutors so more chance of one finding an explanation you 
> understand

Another advantage that can't be overstated is that of checks-and-balances: 
if any one of the tutors here gives erroneous advice, the other tutors 
here will provide error-correction.  (I've had this happen for myself 
several times, and I'm grateful!)

Contrast this situation with depending on a single authority who might not 
necessarily know what he or she is talking about.  So there's a strength 
and reliability in a public forum like this that you won't easily find 
from private tutoring.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] do you know how to do this

2006-10-12 Thread Danny Yoo
>> Date: Thu, 12 Oct 2006 01:46:44 -0700 (PDT)
>> From: anil maran <[EMAIL PROTECTED]>
>> Subject: do you know how to do this
>> To: Alan Gauld <[EMAIL PROTECTED]>
>>
>> The user, password and group are stored in a session on disk using 
>> flup.middleware.session. You can change this to fit your needs like in 
>> a database. I think someone have already extended the flup session with 
>> a database store?
>>
>> Use the decorator function on your GET and POST method to set
>> authentication and provide which group are allowed.
>>
>> If auth is set to True and user/password/access did not match, a 
>> redirect is made to /login.

Anil, can you try to refocus your question?

You have to be more specific than "Do you know how to do this?" because 
that can invite really flippant answers like "Yes" or "No".  That's not 
going to be useful for you.  Instead, try focusing us on what problems 
you're having.

>From your message with Alan, I see a general problem statement with 
several requirements necessary for a solution.  It really looks like a 
homework assignment.  We are not allowed to go into a particular solution; 
we're going to have to limit ourselves to reduce the confusion you have 
with the problem, but that's it: you're going to have to do your own work 
on the problem.

Is there any part in your assignment that you don't understand?  Is there 
any part in there that you do understand?  Do you understand all the terms 
used in the problem?  At what point are you getting stuck?  Have you 
worked on any other problem that's similar to the one you're looking at 
now?

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


Re: [Tutor] cylinder texture map?

2006-10-12 Thread Danny Yoo


On Thu, 12 Oct 2006, Michael Shulman wrote:

> I'd like to make a scrolling background for a game I'm working on.  I
> was thinking, since it's all in orthographic view, that a horizontal
> cylinder which rotates with a texture would simulate this very well.


I have to admit I'm clueless about programming games.  You might want to 
ask a game developer forum for better advice.  There's also a few links 
on:

 http://pyopengl.sourceforge.net/documentation/

to several OpenGL tutorials, including:

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


Re: [Tutor] cylinder texture map?

2006-10-12 Thread Adam Bark
On 12/10/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
On Thu, 12 Oct 2006, Michael Shulman wrote:> I'd like to make a scrolling background for a game I'm working on.  I> was thinking, since it's all in orthographic view, that a horizontal> cylinder which rotates with a texture would simulate this very well.
I have to admit I'm clueless about programming games.  You might want toask a game developer forum for better advice.  There's also a few linkson: 
http://pyopengl.sourceforge.net/documentation/to several OpenGL tutorials, including: http://nehe.gamedev.net/
pygame.org and there mailing list might be helpful as well. The only thing I can think of for this is to use something like blender with an exact replica of the 3d object you plan to map to, unwrap it and make a uv mapping, ie you cut the 3d object up so it's flat draw the texture on then it fits perfectly when you apply it to the original object.
HTH
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] embedding lists in configuration files

2006-10-12 Thread William O'Higgins Witteman
I am looking for a way to use a plain text configuration file in a
Python program instead of hard-coded values.  The configuration data
currently is in the form of a couple of lists and some triple-quoted
strings.

I was looking at the ConfigParser module, but I cannot see how to use
this format to represent lists or triple-quoted strings.  Are there any
other suggestions?  Thanks.
-- 

yours,

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


[Tutor] Fwd: Help with basic user-data file

2006-10-12 Thread Rob Andrews
I'm forwarding this to the tutor list, as I'm swamped at work.

-- Forwarded message --
From: Asrarahmed Kadri <[EMAIL PROTECTED]>
Date: Oct 12, 2006 9:17 AM
Subject: Re: [Tutor] Help with basic user-data file
To: Rob Andrews <[EMAIL PROTECTED]>


Thanks.
Can you please also tell me how to check the existence of a file using
python builtin functions.


Regards,
Asrar


On 10/12/06, Rob Andrews <[EMAIL PROTECTED]> wrote:
> When a login name is being created, you can pull a list of existing
> login names from file, and run a check to see if it is in the list. If
> the new name is in the list, have it kick back a message telling the
> user to try another name.
>
> Also, your program could suggest a new user name in such a case, or
> even assign new users names of its choosing.
>
> The dictionary data structure is handy for the program to use in very
> efficiently matching user names with passwords. But you don't have to
> store the dictionary in a file as a dictionary. It's possible to do
> so, but often easier to use a delimited text file.
>
> On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
> > It means there is no need of entering the data in the dictionary,??
> >
> > How will I then implement the uniqueness of loginnames???
> >
> > Thanks for the support.
> > regards,
> > Asrar
> >
> >
> > On 10/12/06, Rob Andrews < [EMAIL PROTECTED]> wrote:
> > >
> > > To keep the information, the simplest solution is simply to save it in
> > > a text file that the program can load into memory when it starts up
> > > again. For sensitive information like passwords, a little extra fuss
> > > is generally merited.
> > >
> > > When someone logs in, you can save a value like
> > > time.strftime(time.ctime()) for a nice, human-readable time stamp.
> > > Don't forget to "import time" first.
> > >
> > > -Rob A.
> > >
> > > On 10/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
> > > > Folks,
> > > >
> > > > I am trying to modify the userManagement program given in Core Python
> > > > Programming. It uses a dictionary to store user-password information.
> > The
> > > > usernames are the keys and the passwords are the values.
> > > > Now I want is to add a third element; last login time.
> > > > I want to store this information in a file so that the data is not lost
> > once
> > > > the program stops execution.
> > > >
> > > > I am not sure of using time function in python..
> > > > Can anyone help with this issue??
> > > ___
> > > Tutor maillist  -   Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> >
> >
> >
> > --
> > To HIM you shall return.
>
>
> --
> Blogging my outdoors obsession: http://trekkingbob.blogspot.com/
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
To HIM you shall return.

-- 
Blogging my outdoors obsession: http://trekkingbob.blogspot.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] float object not callable error

2006-10-12 Thread Kristinn Didriksson
Hello,
I an completely new to programming and am trying to teach myself  
Python using Python Programming by John Zelle. Essentially I am an ex- 
tech writer trying to learn how to program.
My system: Mac OS X 10.4, Python 2.5, TextMate editor
Here is the problem:

I get 'float' object not callable error.

I thought this was a conversion error, but it seems to me that it may  
be something else. It will not print x and I don't understand why it  
will not do that. Any help is greatly appreciated.

This is the code below. When I got the error message initially, I  
tried to break it down into smaller bites so I could see the problem  
more clearly. I tried to figure this out myself, but not having any  
luck.

Regards,
Kristinn

# Calculate the area of a triangle. Input the lengths of the sides:  
a, b, c.
# Formulas: (s = a + b + c) / 2
# A = sqrt(s(s - a)(s -b)(s - c))

def main():
import math
a, b, c = input("Please enter the sides of the triangle separated by  
commas: ")
s = (float(a + b + c)/2)
print s #This is to test the first part of the algorithm--and it fails
x = (s(s -a)(s -b)(s -c))
print x
y = math.sqrt(x)
print y
#area = math.sqrt((s)(s - a)(s -b)(s-c)) --this is the formula that  
will not work
print "This is the area of the traingle: " + area

main()

# This algorithm has type conversion problems.
# Error message: 'float' object is not callable
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] float object not callable error

2006-10-12 Thread Danny Yoo
> Here is the problem:
>
> I get 'float' object not callable error.

Hi Kristinn,


Ah.  Ok.  The problem is a notational one.  You're reusing notation that 
you've learned from your math classes, that is, that:

 a b

informally represents the multiplication of numbers 'a' and 'b'. 
Furthermore, math notation allows the use of parens, so:

(a) (b)

a (b)

(a) b

all designate expressions that multiply two variables together in math.


However, Python does NOT support this particular math notation!  The 
reason is because it conflicts with the notation used for applying 
functions to arguments:

 f(x)

Computers are "stupid" and computer programming languages avoid using 
notations that can be ambiguously interpreted.  Math notation is pretty 
ambiguous sometimes, but that's usually not a problem because it's 
primarily used to communicate between humans who can tease out the meaning 
of the ambiguities.  But, again, computers are stupid, so the notation we 
use in programming is often a bit more fixed and inflexible.

In that context, take a look at the way you're notating multiplication.


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


Re: [Tutor] float object not callable error

2006-10-12 Thread Bob Gailer
Kristinn Didriksson wrote:
> Hello,
> I an completely new to programming and am trying to teach myself  
> Python using Python Programming by John Zelle. Essentially I am an ex- 
> tech writer trying to learn how to program.
> My system: Mac OS X 10.4, Python 2.5, TextMate editor
> Here is the problem:
>
> I get 'float' object not callable error.
>   
Please in future posts include the exception message (traceback). It 
pinpoints the line of code raising the exception. You did help us here 
by commenting the problem lines.
> I thought this was a conversion error, but it seems to me that it may  
> be something else. It will not print x and I don't understand why it  
> will not do that. Any help is greatly appreciated.
>
> This is the code below. When I got the error message initially, I  
> tried to break it down into smaller bites so I could see the problem  
> more clearly. I tried to figure this out myself, but not having any  
> luck.
>
> Regards,
> Kristinn
>
> # Calculate the area of a triangle. Input the lengths of the sides:  
> a, b, c.
> # Formulas: (s = a + b + c) / 2
> # A = sqrt(s(s - a)(s -b)(s - c))
>
> def main():
>   import math
>   a, b, c = input("Please enter the sides of the triangle separated by  
> commas: ")
>   s = (float(a + b + c)/2)
>   print s #This is to test the first part of the algorithm--and it fails
>   x = (s(s -a)(s -b)(s -c))
>   
In algebra multiplication is assumed when 2 items are adjacent. In most 
programming languages multiplication is expressed by some symbol. Python 
(as many languages) uses * for multiplication. Parentheses following a 
name assumes the name is a callable object (e.g. function). So change 
the above to:

x = s*(s -a)*(s -b)*(s -c)

Note I've also dropped the outside parentheses as (1) not necessary and 
(2) potentially confusing considering that outside parentheses are used 
to construct tuples and generators.
>   print x
>   y = math.sqrt(x)
>   print y
>   #area = math.sqrt((s)(s - a)(s -b)(s-c)) --this is the formula that  
> will not work
>   print "This is the area of the traingle: " + area
>   
> main()
>
> # This algorithm has type conversion problems.
> # Error message: 'float' object is not callable
FWIW the simplest example of the callable issue is:
 >>> 2(3)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'int' object is not callable
 >>> 2*3
6

>
>   


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] do you know how to do this

2006-10-12 Thread anil maran
Dear DannyTHanks for your prompt response. THis is not a homework problem, I m trying to learn how to do sessions logins
I m trying to do the following
1) have logins/passwords stored in postgresql, currently this is my
code, python+psycopg2 talking to postgresql running in backend.
if i.email != "" and i.password != "":
      algo = 'sha1'
      salt = sha.new(str(random.random())).hexdigest()[:5]
      hsh = sha.new(salt+i.password).hexdigest()
      password_algo_salt_hash = '%s$%s$%s' % (algo, salt, hsh)
  web.insert('users', email = i.email, password = password_algo_salt_hash, ip=web.ctx.ip, rawpassword=i.password)
  web.setcookie('username', i.email,2629743)#expires in a month

2) As you can
see I m not setting the cookie properly , I m just setting email as
cookie, So I want to set a proper hash of email time and cookie HOW DO I set a proper hash based cookie.a login page that takes a username and password, checks it  against a database, and then sets a cookie of (hash(secret,user,  time),user,time). Then there's a function that checks the cookie and  returns the user object if the hashes match. 
I m unable to figure out how to do this yet
Anil- Original Message From: Danny Yoo <[EMAIL PROTECTED]>To: [EMAIL PROTECTED]Cc: Tutor Sent: Thursday, October 12, 2006 10:17:14 AMSubject: do you know how to do this>> Date: Thu, 12 Oct 2006 01:46:44 -0700 (PDT)>> From: anil maran <[EMAIL PROTECTED]>>> Subject: do you know how to do this>> To: Alan Gauld <[EMAIL PROTECTED]> The user, password and group are stored in a session on disk using >> flup.middleware.session. You can change this to fit your needs like in >> a database. I think someone have already extended the flup session with >> a database
 store? Use the decorator function on your GET and POST method to set>> authentication and provide which group are allowed. If auth is set to True and user/password/access did not match, a >> redirect is made to /login.Anil, can you try to refocus your question?You have to be more specific than "Do you know how to do this?" because that can invite really flippant answers like "Yes" or "No".  That's not going to be useful for you.  Instead, try focusing us on what problems you're having.From your message with Alan, I see a general problem statement with several requirements necessary for a solution.  It really looks like a homework assignment.  We are not allowed to go into a particular solution; we're going to have to limit ourselves to reduce the confusion you have with the problem, but that's it: you're going to
 have to do your own work on the problem.Is there any part in your assignment that you don't understand?  Is there any part in there that you do understand?  Do you understand all the terms used in the problem?  At what point are you getting stuck?  Have you worked on any other problem that's similar to the one you're looking at now?Good luck.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with generating session id

2006-10-12 Thread anil maran
Hi guysI m trying to maintain Sessions for each user, and a session-id that needs to be stored in cookie. I m unable to figure out how to generate session-id that can be stored in a cookie and sync with a session.The problem is this everytime someone logs in check and see if they have session info that can be resumed or create a new session and store the session id in a cookie. Atleast this is my understanding, how do we sync up sessions + logins. Should I store the session id in a db. ThanksAnilHere is code I have worked on so far, does login with sessions no cookies yet;)#!/usr/bin/env python# -*- coding: utf-8 -*-import osimport webfrom flup.middleware.session import DiskSessionStore, SessionMiddlewareweb.internalerror = web.debugerror### URL
 MAPPING#urls = (    '/','index',    '/login','login',    '/logout','logout')### AUTHORIZATION STUFF#def dologin(user):    session = web.ctx.environ['com.saddi.service.session'].session    session['id'] = user.id    session['username'] = user.username    session['groups'] = user.groups    session['loggedin'] = 1def dologout():    session = web.ctx.environ['com.saddi.service.session'].session    session.invalidate()def initsession(session):    session['id'] = 0    session['username'] = ''    session['groups'] = ''    session['loggedin'] = 0def checkauth(session):    if session['loggedin'] == 1:    
 return True    return Falsedef checkaccess(auth=False, access=''):    def decorator(func):     def proxyfunc(self, *args, **kw):    service = web.ctx.environ['com.saddi.service.session']    session = service.session    if service.isSessionNew:    initsession(session)    if auth == True:    if not checkauth(session):    return
 web.redirect('/login')    if access != '':    groups = session['groups'].split(',')    if access not in groups:     return web.redirect('/login')    return func(self, *args, **kw)    return proxyfunc    return decorator### PAGES#class index:    @checkaccess(auth=True, access='admin')    def GET(self):    print web.ctx.environ    service =
 web.ctx.environ['com.saddi.service.session']    print ''    print service    session = web.ctx.environ['com.saddi.service.session'].session    print ' Session'    print session    web.render('index.html')class login:    @checkaccess()    def GET(self):    web.render('login.html')    @checkaccess()    def POST(self):    user = web.storify({    'id':1,    'username':'mark',    'password':'userss',    'groups':'admin'   
 })    inp = web.input()    if inp.username == user.username and inp.password == user.password:    dologin(user)    web.redirect('/')    else:    web.render('login.html')class logout:    @checkaccess()    def GET(self):    dologout()    web.redirect('/')### MIDDLEWARE FACTORIES#    def session_mw(app):    sessionStore = DiskSessionStore(storeDir="%s/sessions/" % os.getcwd(), timeout=5)    return
 SessionMiddleware(sessionStore, app)  Anil___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with generating session id

2006-10-12 Thread Luke Paireepinart
anil maran wrote:
> Hi guys
> I m trying to maintain Sessions for each user, and a session-id that 
> needs to be stored in cookie. I m unable to figure out how to generate 
> session-id that can be stored in a cookie and sync with a session.
> The problem is this
> everytime someone logs in check and see if they have session info that 
> can be resumed or create a new session and store the session id in a 
> cookie. Atleast this is my understanding, how do we sync up sessions + 
> logins. Should I store the session id in a db.
> Thanks
> Anil
> Here is code I have worked on so far, does login with sessions no 
> cookies yet;)
You need to think through the logic of what you're trying to do.
Often, the logistics of how a specific algo will be implemented take 
more thought and planning than the actual programming of it.
We here are essentially a programming help forum, for people who don't 
have a problem coming up with an algorithm (the hard part)
but just in implementing it (the easy part).

So asking us 'how do I do x' is almost definitely not going to get the 
kind of answer you want.

Consider what you're seeking.  It's not up to us to design an 
implementation for you.
There are many different ways you can sync up logins, there are multiple 
ways to store the session-id on the server.
It's up to you to come up with which way you want to do it, and start 
implementing it, and then we assist you if you have basic programming 
problems.
If you want to know about session-ids, what they're supposed to do, how 
to generate them, how to use cookies... all of these questions
are questions you would get better help by asking on a Webmaster forum.

What problem are you having specifically?
can you generate the session-id?
can you make a cookie with the session-id on the user's computer?
can you check their cookie when they login with whatever method you're 
using to keep track of sessions on your server?

Also,
what does @checkaccess() do?
is this a placeholder?
what is flup? what is flup.middleware? what is flup.middleware.session?
Your code doesn't do anything, does it?
it's just a definition of a bunch of methods.
Is this a library you wrote?
What kind of advice are you looking to get from showing us this?

HTH,
-Luke

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


Re: [Tutor] embedding lists in configuration files

2006-10-12 Thread Luke Paireepinart
William O'Higgins Witteman wrote:
> I am looking for a way to use a plain text configuration file in a
> Python program instead of hard-coded values.  The configuration data
> currently is in the form of a couple of lists and some triple-quoted
> strings.
>
> I was looking at the ConfigParser module, but I cannot see how to use
> this format to represent lists or triple-quoted strings.  Are there any
> other suggestions?  Thanks.
>   
I've never used configparser, but from what I read just now about it, it 
seems like this should work for lists:
#--- start INI file
[category]
list: element1,element2,element3,element4,element5
#end INI file

#your file
from ConfigParser import ConfigParser
config = ConfigParser()
config.read('sample.ini')

print "The COW says:  "
#the following line should generate a list from the comma-separated values.
print config.get("category","list").split(',')


#--- end your file

I can't install ConfigParser at the moment to test this, but I hope it 
works :)
Tell me if it does.
As for triple-quoted strings...
I'm not sure about that.
a little bit of googling seems to agree that you can't have multi-line 
strings.
I don't know that for a fact, though.

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


Re: [Tutor] Fwd: Help with basic user-data file

2006-10-12 Thread Kent Johnson
> From: Asrarahmed Kadri <[EMAIL PROTECTED]>
> Date: Oct 12, 2006 9:17 AM
> Subject: Re: [Tutor] Help with basic user-data file
> To: Rob Andrews <[EMAIL PROTECTED]>
> 
> 
> Thanks.
> Can you please also tell me how to check the existence of a file using
> python builtin functions.

If path is a string containing the full path to the file (absolute path 
or relative to the working dir) then use
import os
os.path.exists(path) # To see if the path represents *something* real
os.path.isfile(path) # check for a file specifically
os.path.isdir(path)  # check for a directory

Kent


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


Re: [Tutor] embedding lists in configuration files

2006-10-12 Thread Kent Johnson
William O'Higgins Witteman wrote:
> I am looking for a way to use a plain text configuration file in a
> Python program instead of hard-coded values.  The configuration data
> currently is in the form of a couple of lists and some triple-quoted
> strings.
> 
> I was looking at the ConfigParser module, but I cannot see how to use
> this format to represent lists or triple-quoted strings.  Are there any
> other suggestions?  Thanks.

ConfigObj supports lists and triple-quoted strings directly:
http://www.voidspace.org.uk/python/configobj.html

Kent

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


Re: [Tutor] how to check whether a file exists or not??

2006-10-12 Thread John Fouhy
On 13/10/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:
> Also if a file exists, and we open it in a write mode, it would be truncated
> to zero length. So what is the way out of this??#

You can open in append mode..

>>> f = open('foo', 'w')
>>> f.write('Hello ')
>>> f.close()
>>> f = open('foo', 'a')
>>> f.write('world!')
>>> f.close()
>>> f = open('foo', 'r')
>>> f.read()
'Hello world!'

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


[Tutor] wxPython book

2006-10-12 Thread Alan Gauld
I just noticed

WxPython in Action (Paperback) 
by Noel Rappin, Robin Dunn 

on Amazon.co.uk.

I wondered if anyone has got the book and would like 
to comment on it? One of the main reasions I stick with 
Tkinter is that I have Grayson's book as a reference.

If this is as useful for wxPython I might move my 
allegiance...

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SQL Queries For MySQL

2006-10-12 Thread johnf
On Thursday 12 October 2006 07:14, Jason Massey wrote:
> On 10/12/06, johnf <[EMAIL PROTECTED]> wrote:
> > On Thursday 12 October 2006 00:31, Alan Gauld wrote:
> > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name)
> > > > cursor.execute(query)
> > >
> > > There can be security issues with this style, especially
> > > if the parameters can be modified by users - for example
> > > you read the values from a web page.
> > >
> > > The cursor.execute() call has the ability to pass the parameters
> > > in directly, ie combining the two statements above into one.
> > > The details of how ypou do that varies between database
> > > drivers so you need to check the documents but I think for
> > > MySQL its almost an exact translation:
> > >
> > > query = "SELECT * FROM DB WHERE NAME = %s"
> > > cursor.execute(query, name)
> > >
> > > If you search the ist archives you'll find a fairly long thread
> > > describing the whys/wherefores in much more depth.
> > >
> > > HTH,
> >
> > Since the archive is large - could you provide the subject title.
> >
> > Thanks
> > John
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> Forgot to forward to the list...
>
> Check out this posting from Danny:
>
> http://mail.python.org/pipermail/tutor/2003-April/022010.html
OK from what I understand you are concerned with "SQL injection".  But I don't 
see the difference between the two statements preventing "SQL injection".  
Can someone explain.  

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


Re: [Tutor] embedding lists in configuration files

2006-10-12 Thread Alan Gauld
> Python program instead of hard-coded values.  The configuration data
> currently is in the form of a couple of lists and some triple-quoted
> strings.
>
> I was looking at the ConfigParser module, but I cannot see how to 
> use
> this format to represent lists or triple-quoted strings.  Are there 
> any
> other suggestions?  Thanks.

There are several possibilities:-
1)  the simplest is simply a lsingle line
with the values separated by some character - commas, colons,
hyphens, whatever doesn't appear in the data.

Then read the line as a string, split(char) it into its parts and 
convert
the parts to the appropriate types. Using commas may allow you
to leverage the CSV module.

2) Use a richer format, like XML which provides for very
complex structures and allows you to use a standard parser
like ElementTree to extract the data.

3) Write all values onm their own lines and add a marker to
separate lists. Then use a while loop to read in the lines until
you reach the marker.

Thee are other options too, but those should be enough
to get you going.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] wxPython book

2006-10-12 Thread wesley chun
> WxPython in Action (Paperback)
> by Noel Rappin, Robin Dunn

i'll probably be picking up a copy of it myself. i've seen positive
comments about the book.  more reviews available at Amazon US:
http://www.amazon.com/exec/obidos/ASIN/1932394621

there's also a wxWidgets book if you need to know the details.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
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
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trying to understand sys.getrefcount()

2006-10-12 Thread Tony Cappellini
I'm using Python 2.3.4After reading this in the docs


getrefcount(
object)
Return the reference count of the object. The count returned is 
generally one higher than you might expect, because it includes the (temporary) 
reference as an argument to getrefcount().I decided to try some experiments class junk(object):...     pass... >>> sys.getrefcount(junk)5>>> j1=junk()
>>> sys.getrefcount(junk)6sys.getrefcount(j1)2I understand why j1 is 1 higher than I expect, based on the docs, but why does getrefcount(junk) return 5 before any instances of class junk are made?

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


Re: [Tutor] wxPython book

2006-10-12 Thread Alan Gauld
Thanks Wes,

After posting it dawned on me that the US site might have more (any!)
reviews, and sure enough there is one mega review and several shorter
ones, none negative. I think I'll be buying...

The wxWidgets book I'll pass on, I have an old one from about 10
years ago (from when I was actively programming in C++) which explains
the logic behind the toolkit and the wxWidgets reference web pages
do all I need now, its really the Python aspects I want a book on.

Thanks again,

Alan G.


- Original Message - 
From: "wesley chun" <[EMAIL PROTECTED]>
To: "Alan Gauld" <[EMAIL PROTECTED]>
Cc: 
Sent: Thursday, October 12, 2006 11:38 PM
Subject: Re: [Tutor] wxPython book


>> WxPython in Action (Paperback)
>> by Noel Rappin, Robin Dunn
>
> i'll probably be picking up a copy of it myself. i've seen positive
> comments about the book.  more reviews available at Amazon US:
> http://www.amazon.com/exec/obidos/ASIN/1932394621
>
> there's also a wxWidgets book if you need to know the details.
>
> hope this helps!
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>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
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help me : Why this code is not working??

2006-10-12 Thread Asrarahmed Kadri
 
 
I have created two buttons. The code for button2 is not working as I want it to be. When I click button2, the application should exit, but it isnt. 
Can someone fix it??
from Tkinter import *from tkMessageBox import *
def callback():    showinfo('message','I am here...')
def QUIT():    ans = askyesno('Confirm','Do you really want to quit?')    if ans:    root.exit    else:    showinfo('Selection','You have decided to stay on')

root = Tk()win = Frame(root)win.pack()
button1 = Button(win,text='Hello',command=callback)button1.pack(side=LEFT)
button2 = Button(win,text='Quit',command=QUIT)button2.pack(side=RIGHT)
root.mainloop()-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me : Why this code is not working??

2006-10-12 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
>  
>  
> I have created two buttons. The code for button2 is not working as I 
> want it to be. When I click button2, the application should exit, but 
> it isnt.
> Can someone fix it??
>
> from Tkinter import *
> from tkMessageBox import *
>
> def callback():
> showinfo('message','I am here...')
>
> def QUIT():
> ans = askyesno('Confirm','Do you really want to quit?')
> if ans:
> root.exit
>
SEND US THE TRACEBACK :)
Don't just tell us that something doesn't work.
The traceback contains valuable information that tells you (or us) how 
to debug it.
In this case,the traceback was
#//
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
return self.func(*args)
  File "C:/Python24/temp.py", line 10, in QUIT
root.exit
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1654, in __getattr__
return getattr(self.tk, attr)
AttributeError: exit
#
Okay, so what do we see here?
Start reading from the bottom.
AttributeError: exit.
okay, so that means that we tried to access a method or a variable of a 
class,  and it wasn't  there.
It lacked that attribute.

Which class was it?
looking further up the stack, we see where we access 'exit.'
line 10, in QUIT:
root.exit

This means that whatever class root is an instance of doesn't have a 
method named exit.

Remember, the computer is stupid.  To the computer, 'exit' and 'quit' 
mean something as different
as 'root beer' and 'trash can' would to us.  The method you're trying to 
access is called 'quit', not 'exit'
That's your first problem.

The second problem you have, is that you're not calling this method, 
you're just accessing it, which doesn't really do anything.
What you'll want to do is
root.quit()

and not
root.quit

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


Re: [Tutor] SQL Queries For MySQL

2006-10-12 Thread Python
On Thu, 2006-10-12 at 14:46 -0700, johnf wrote:
> On Thursday 12 October 2006 07:14, Jason Massey wrote:
> > On 10/12/06, johnf <[EMAIL PROTECTED]> wrote:
> > > On Thursday 12 October 2006 00:31, Alan Gauld wrote:
> > > > > query = "SELECT * FROM DB WHERE NAME = %s" % (name)
> > > > > cursor.execute(query)
(snipped)
> > > > query = "SELECT * FROM DB WHERE NAME = %s"
> > > > cursor.execute(query, name)
(snipped)
> OK from what I understand you are concerned with "SQL injection".  But I 
> don't 
> see the difference between the two statements preventing "SQL injection".  

Suppose name = 'x"; DELETE FROM DB; SELECT COUNT(*) FROM DB; SELECT FROM DB 
WHERE NAME = "x'

The first version will simply build a string with the SQL command
interpolating name.  The where quote (") gets closed and semicolons
separate SQL commands.  The sequence of commands gets executed.  

The second version will escape the quotes and semicolons in the name
string.  You will simply try to match a rather odd looking name.  You
could do the escaping yourself before doing the string interpolation,
but the DB module is already set up to do the work for you.

> Can someone explain.  
> 
> John
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp

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


Re: [Tutor] Help me : Why this code is not working??

2006-10-12 Thread Asrarahmed Kadri
Thanks a lot.
It was quick.
I will send the traceback from now on.
 
-Asrar 
On 10/13/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
Asrarahmed Kadri wrote:>>> I have created two buttons. The code for button2 is not working as I
> want it to be. When I click button2, the application should exit, but> it isnt.> Can someone fix it??>> from Tkinter import *> from tkMessageBox import *>> def callback():
> showinfo('message','I am here...')>> def QUIT():> ans = askyesno('Confirm','Do you really want to quit?')> if ans:> root.exit>SEND US THE TRACEBACK :)
Don't just tell us that something doesn't work.The traceback contains valuable information that tells you (or us) howto debug it.In this case,the traceback was#//Exception in Tkinter callback
Traceback (most recent call last):File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__   return self.func(*args)File "C:/Python24/temp.py", line 10, in QUIT   root.exitFile "C:\Python24\lib\lib-tk\Tkinter.py", line 1654, in __getattr__
   return getattr(self.tk, attr)AttributeError: exit#Okay, so what do we see here?Start reading from the bottom.AttributeError: exit.okay, so that means that we tried to access a method or a variable of a
class,  and it wasn't  there.It lacked that attribute.Which class was it?looking further up the stack, we see where we access 'exit.'line 10, in QUIT:root.exitThis means that whatever class root is an instance of doesn't have a
method named exit.Remember, the computer is stupid.  To the computer, 'exit' and 'quit'mean something as differentas 'root beer' and 'trash can' would to us.  The method you're trying toaccess is called 'quit', not 'exit'
That's your first problem.The second problem you have, is that you're not calling this method,you're just accessing it, which doesn't really do anything.What you'll want to do isroot.quit()
and notroot.quitHTH,-Luke-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] tkinter tutorials

2006-10-12 Thread Amadeo Bellotti
I am currently interseted in learning tkinter and what beeter way then with a project so im making a python IDE and i was wondering if there were any good tutorials that are out there for tkinter and a book or 2 would be nice thank you

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


Re: [Tutor] tkinter tutorials

2006-10-12 Thread Danny Yoo


On Thu, 12 Oct 2006, Amadeo Bellotti wrote:

> I am currently interseted in learning tkinter and what beeter way then 
> with a project so im making a python IDE and i was wondering if there 
> were any good tutorials that are out there for tkinter and a book or 2 
> would be nice thank you


John Grayson's "Python and Tkinter Programming" is an excellent book on 
learning the Tkinter toolkit:

 http://www.manning.com/grayson/


You might also find the tutorial material on:

 http://wiki.python.org/moin/TkInter

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


[Tutor] How to write strings with new line character in a file

2006-10-12 Thread Asrarahmed Kadri
Folks,
 
I am trying to enter names in a file; each on a new line with this code, but not working:
 
done = 0
while not done:    str = raw_input("Enter login name:\t to quit type 'q': ")if str == 'q':    done = 1    else:  
   str = str + '\n'
   fd.write(str)
The traceback is as under:
 
Traceback (most recent call last):  File "scrap.py", line 38, in ?    fd.write(str)IOError: (0, 'Error')
 
Please help to rectify this error...-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] do you know how to do this

2006-10-12 Thread Danny Yoo

> a login page that takes a username and password, checks it against a 
> database, and then sets a cookie of (hash(secret,user, time),user,time).

Hi Anil,

Ok, separate the concerns about where the inputs are coming from.  It will 
seem weird, but just for the moment, forget completely about the web, and 
just concentrate on the inputs and outputs of this subproblem.


It sounds like you're trying to generate a string value, given a user name 
and value.  Conceptually, you can treat this as a simple function:

 def generate_login_cookie(username, password):
 """generate_login_cookie: string string -> string
 Creates a new login cookie that can be used to log in again."""
 ## fill me in.

This might not quite be right yet, but we're still looking at this from a 
high level.



> Then there's a function that checks the cookie and returns the user 
> object if the hashes match.

Ok, furthermore, it sounds like you want a function that takes a cookie 
string value and returns a User object if the hashes match.  Just for 
discussion's sake, let's call this login_with_cookie().

 def login_with_cookie(cookie_value):
 """login_with_cookie: string -> User, or None
 Given a string value generated with generate_login_cookie(),
 returns the associated user.  Otherwise, returns None."""
 ## fill me in

I have no idea what a User object is supposed to be, but I'll assume for 
the moment that this function is going to satisfy the following pseudocode 
requirement:

 if sometime in the past:

 c = generate_login_cookie(username, password):

 then:

 u = login_with_cookie(c)
 assert (u.username == username)

 should hold.  Furthermore, on any other arbitrary string s that hasn't
 been generated with generate_login_cookie(), we'd like to know that:

 assert (login_with_cookie(s) == None)

 because otherwise the login system would suck.  *grin*


We also know that generate_login_cookie() and login_with_cookie() must 
cooperate in some way that is persistent across time.  That's where your 
database is going to come into play: a database is going to be your 
persistent state.

I would recommend concentrating on getting those two functions working, 
because they have the nice property that you can actually code these out 
without having to go doing web-ish things.  More importantly, you should 
be able to unit-test something like this with ease.  (And you'd better 
test, considering how important login and authentication are!)


The part dealing with the web itself can be considered orthogonal.  If you 
get generate_login_cookie() and login_with_cookie() working ok, then your 
problem reduces down to: "How do I set a cookie in my web application?", 
and "How do I read a cookie from the user's request?" because you can use 
the above functions as helpers.  Then you have a much simpler problem on 
your hands.

The main difficulty that I think you're hitting is that you seem to try to 
juggle all your requirements at the same time.  So the main recommendation 
I can give is: decompose your problem.  Try not to solve it in one gulp: 
most problems are too big to handle all at once.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write strings with new line character in a file

2006-10-12 Thread Danny Yoo
>
> while not done:
>str = raw_input("Enter login name:\t to quit type 'q': ")
>if str == 'q':
>   done = 1
>else:
>   str = str + '\n'
>   fd.write(str)

Hi Asrarahmed,

What's 'fd'?  Where is it defined?

(I have a guess, but I'd rather that you show where fd is being defined 
explicitely.)



If you're still trying to drive DOS applications with popen(), I'd 
strongly encourage you to take a closer look at PExpect: you should be 
able to get it to work with a Cygwin-based environment.

 http://pexpect.sourceforge.net/

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


Re: [Tutor] wxPython book

2006-10-12 Thread Dennis O'Brien

There is a good interview on Python 411 last week with the authors of
the book.
http://www.awaretek.com/python/index.html

You can also find a few other shows about gui toolkits in Python.  This
is a great resource if you want to learn about Python while you commute.

--Dennis
 
- Original Message -Date: Thu, 12 Oct 2006 23:50:11 +0100
From: "Alan Gauld" <[EMAIL PROTECTED]>
Subject: Re: [Tutor] wxPython book
To: "wesley chun" <[EMAIL PROTECTED]>
Cc: tutor@python.org
Message-ID: <[EMAIL PROTECTED]>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
reply-type=response

Thanks Wes,

After posting it dawned on me that the US site might have more (any!)
reviews, and sure enough there is one mega review and several shorter
ones, none negative. I think I'll be buying...

The wxWidgets book I'll pass on, I have an old one from about 10 years
ago (from when I was actively programming in C++) which explains the
logic behind the toolkit and the wxWidgets reference web pages do all I
need now, its really the Python aspects I want a book on.

Thanks again,

Alan G.


- Original Message -
From: "wesley chun" <[EMAIL PROTECTED]>
To: "Alan Gauld" <[EMAIL PROTECTED]>
Cc: 
Sent: Thursday, October 12, 2006 11:38 PM
Subject: Re: [Tutor] wxPython book


>> WxPython in Action (Paperback)
>> by Noel Rappin, Robin Dunn
>
> i'll probably be picking up a copy of it myself. i've seen positive
> comments about the book.  more reviews available at Amazon US:
> http://www.amazon.com/exec/obidos/ASIN/1932394621
>
> there's also a wxWidgets book if you need to know the details.
>
> hope this helps!
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>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
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Responding to a request for input from a MS-DOS program

2006-10-12 Thread Jeffrey Kennedy
Hi Alan,

I think I might be trying to walk before I can crawl; for benefits of
other newbies, I'll summarise lessons learned so far.

Firstly, I spent ages trying to find out why the Python documentation
syntax for Popen, using stdin=PIPE, didn't work:

Traceback (most recent call last):
  File "", line 1, in -toplevel-
p1=subprocess.Popen("c:/temp/enter.bat", stdin = PIPE)
NameError: name 'PIPE' is not defined

Turns out it needs to be specified as stdin=subprocess.PIPE. Then spent
even longer trying to figure out why this command:

>>> p=subprocess.Popen("c:/temp/enter.bat", stdin=subprocess.PIPE)

gave this error:

Traceback (most recent call last):
  File "", line 1, in -toplevel-
p=subprocess.Popen("c:/temp/enter.bat", stdin=subprocess.PIPE)
  File "C:\Python24\lib\subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
  File "C:\Python24\lib\subprocess.py", line 607, in _get_handles
c2pwrite = self._make_inheritable(c2pwrite)
  File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable
DUPLICATE_SAME_ACCESS)
WindowsError: [Errno 6] The handle is invalid

(and stdout gives TypeError: an integer is required).
Google eventually helped me find out that it's a problem with the way
the IDLE Python GUI treats stdin and stdout rather than a problem in the
code (which is based on an example in your excellent tutorial).

I created a two-line DOS batch file to emulate what I'm trying to do.
The file (saved as 'enter.bat') is:
SET /P = Type '1' then press 'Enter'
SET /P = Type '2' then press 'Enter'

After typing the following lines into the Python command line editor,
enter.bat runs and takes over the command prompt (waiting for the first
input):
import subprocess
cmd='C:/temp/enter.bat'
p1=subprocess.Popen(cmd, stdin = subprocess.PIPE)

OUTPUT:
>>> p1=subprocess.Popen(cmd, stdin = subprocess.PIPE)
>>>
C:\Python24>SET /P = Type '1' then press 'Enter'
 Type '1' then press 'Enter'

I then tried the following:
subprocess.Popen(cmd, stdin = subprocess.PIPE).stdin.write('1\n')

This seems to work - the entry seems to be accepted, but the second
prompt from enter.bat now takes over the command prompt:
OUTPUT:
>>> subprocess.Popen(cmd, stdin = subprocess.PIPE).stdin.write('1\n')

>>> C:\Python24>SET /P = Type '1' then press 'Enter'
 Type '1' then press 'Enter'
C:\Python24>SET /P = Type '2' then press 'Enter'
 Type '2' then press 'Enter'

Am I on the right track? I suspect I need to use checks to make sure the
enter.bat program has responded before sending the input, but I'm trying
to get the basic commands right first.

Thanks again,

Jeff

Hi Jeff,

> I want to use Python to run an old MS-DOS program that doesn't
> accept arguments when launched. I have to open the program first,
> then it will ask me for the name of another program

> I want to bypass the human input, because I have over
> 100 files I want processed, and I can use Python to iterate through
> each file in turn

You need to look at the subprocess module and the examples that
replace the older popen functions.

You will find more info including examples of both popen and
subporocess in my tutorial under the OS topic in the
Applications Section

Since you are new to this you might want to read the whole topic,
or for more directed help scroll down to the Manipulating Processes
heading. Unfortunately I just noticed I don't give any excample of
writing to a process(in response to a prompt) which is something I
should fix...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write strings with new line character in a file

2006-10-12 Thread Bob Gailer
Asrarahmed Kadri wrote:
> Folks,
>  
> I am trying to enter names in a file; each on a new line with this 
> code, but not working:
>  
> done = 0
> *while not done:
> str = raw_input("Enter login name:\t to quit type 'q': ")
> if str == 'q':
> done = 1
> else:  *
> *   str = str + '\n'*
> *   fd.write(str)
> *
No can help without seeing the code that creates fd. Please post that.
> The traceback is as under:
>  
> Traceback (most recent call last):
>   File "scrap.py", line 38, in ?
> fd.write(str)
> IOError: (0, 'Error')
>  
> Please help to rectify this error...
> -- 
> To HIM you shall return.
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] Help with basic user-data file

2006-10-12 Thread Liam Clarke
Hi Asrarahmed,

There's a few questions in there, and unfortunately I don't have a copy 
of your book. But I'll try to answer them, and I'll change the order so 
that they build on each other.

 >I am not sure of using time function in python..

Depending on what you're trying to do, the simplest way is to just use 
the datetime module. http://docs.python.org/lib/module-datetime.html

 >>> import datetime
 >>> the_time_right_now = datetime.datetime.now()

This creates a datetime object. You can do all sorts of useful stuff 
with them, but for now, you probably just want to display the time. You 
can just

 >>> print the_time_right_now
2006-10-13 19:26:45.671000

But that may not be the most useful format. Datetime objects have a 
method called strftime(), and you can give it format strings as per the 
time module -
http://docs.python.org/lib/module-time.html to change the output. For 
instance.

 >>> print the_time_right_now
2006-10-13 19:26:45.671000

 >>> print the_time_now.strftime("%I:%M%p, %A %d %B %Y")
07:26PM, Friday 13 October 2006

In that case in the format string %I means hours in 1-12 format, %M is 
minutes, %p is AM/PM, %A is the full name of the day, %d is the day 
number, %B is the full month name and %Y is the full year.'

Have a play with it.
> I am trying to modify the userManagement program given in Core Python 
> Programming. It uses a dictionary to store user-password information. 
> The usernames are the keys and the passwords are the values.
> Now I want is to add a third element; last login time.

Okay. So what could do here is instead of having the password as a 
value, have a list or a dictionary as the value and store the password 
and login time in that.

For example:

 >>> userInfo = {}
 >>> userInfo['Liam'] = { 'password' : 'snooze', 'last_login_time': 
datetime.datetime.now()}

If you print userInfo, you'll see that it's saved a datetime object in 
there.
 >>> print userInfo
{'Liam': {'password': 'snooze', 'last_login_time': 
datetime.datetime(2006, 10, 13, 19, 34, 58, 437000)}}

You could then retrieve my password by

 >>> print userInfo['Liam']['password']
snooze

Or the datetime object you created with
 >>> print userInfo['Liam']['last_login_time']
2006-10-13 19:34:58.437000

> I want to store this information in a file so that the data is not 
> lost once the program stops execution.
You'd need to use the pickle module. (Or cPickle, which is marginally 
faster. They work the same, more or less)

 >>> import pickle

Pickle will turn objects into a stream of bytes, which you can save to a 
file. You can then reopen the file, and reload the objects.
So, once you've imported pickle, you need to open a file to write to. 
Make sure you open it in binary mode (So file mode will be "wb")

 >>> save_file = open("userInfo.pck", "wb")

You then use the pickle.dump() method to serialize the object -

 >>> pickle.dump(userInfo, save_file)

Make sure you close the file afterwards.

 >>> save_file.close()

Now, next time you start up -

 >>> import pickle

You use the pickle.load() method to get your object back. First thing is 
to open the file you saved it to, (open it in binary mode).

 >>> load_file = open("userInfo.pck", "rb")
 >>> userInfo = pickle.load(load_file)
 >>> load_file.close()
 >>> print userInfo
{'Liam': {'password': 'snooze', 'last_login_time': 
datetime.datetime(2006, 10, 13, 19, 34, 58, 437000)}}

Hope that helps.

Regards,

Liam Clarke

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