Re: [Tutor] Getting Running File's Name
Why would that be any different under Linux? sys.argv[0] Wim On 1/31/06, Hans Dushanthakumar [EMAIL PROTECTED] wrote: Under WinXP, the variable sys.argv[0] holds the script file name (including the path). Not sure, but it may work the same under Linux as well. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Bryan Carbonnell Sent: Tuesday, 31 January 2006 3:11 p.m. To: tutor@python.org Subject: [Tutor] Getting Running File's Name Can Python return the name of the current file's name? In other works, if I am running a Python file (MyPythonFile.py) is there a function that will return 'MyPythonFile.py'? This will be used in Linux if that matters. Thanks -- Bryan Carbonnell - [EMAIL PROTECTED] Warning: dates on calendar are closer than they appear. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Newbie question re. Functions
Hi,I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises.The challenge says:Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. The function looks like this:def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high): response = int(raw_input(question)) return responseThe author has not eluded to 'step values' in anyway that I can see in the proceeding chapters!HELP!-- Best Regards Jon Moore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Life after beginner
Hi Pat, My question is, what next? Is there some intermediate tutorials or books There are lots of more advanced books, usually focusing on a particular topic. Some examples include: Python and Tkinter programming by Grayson Python Programming on Win32 by Hammond Text Processing in Python by Mertz and there are others on XML, etc. Programming Python by Lutz is also fairly in-depth and the new third edition promises to be more so. (I intend to replace my first edition when it finally hits the streets!) And of course Dive into Python sits somewhere between beginner tutor and advanced specialist book. just writing a simple script I might miss. I really want to learn about in depth programming and programming style but I am far from an expert. But with all the languages I have learned (really touched on) C, C++ perl, Programming style covers two things: 1) Good fundamental programming rtechnique and 2) language idioms If you want to be a better programmer in general then you should consider reading some general programming books such as: Code Complete by McConnelk - Every programmer should read this Programming Pearls by Benley - likewise The Pragmattic Programmer by Hunt Thomas The Practice of Programming by Kernighan/Pike These all discuss general techniques for making programs more readable, maintainable and more efficient, regardless of language. (In fact most include examples in multiple languages) I want to be able to write large projects in python and carry that experience over to the other languages as well. So join a large project. Sourceforge has lots of opensource projects crying out for volunteers. You can start by writing documentation as a way of getting to know the system, then testing new releases, then doing bug fixes and finally coding new features. All contributions are welcomed. And you can see your software being used by the world at large. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Life after beginner
Pat Martin wrote: Hello, I have been reading about and playing with programming in python for awhile now. I have most of the basics down. I know what a tuple is, I know how to load modules, and I understand a fair amount of beginning programming theory. I have written some scripts for both home and work and have become fairly proficient at reading python code. My question is, what next? Is there some intermediate tutorials or books out there that I can start learning some real meat in the language? Things that just writing a simple script I might miss. I really want to learn about in depth programming and programming style but I am far from an expert. But with all the languages I have learned (really touched on) C, C++ perl, and python I seem to get to this point and then I am not sure where to go from here. I want to be able to write large projects in python and carry that experience over to the other languages as well. So any insight would be welcome. It sounds like you are looking for two different kinds of learning. First, you want a deeper knowledge of Python - what are the advanced features, how is Python really used? I found the book Python Cookbook to be a great intermediate step in my own learning - it is full of well-written, idiomatic Python code that shows you how experienced practitioners actually use the language. Second, you want to get better at the craft of programming. This is harder than learning Python and takes practice. Look at books that are not specifically Python oriented. As well as the books Danny and Alan recommend, I have some favorites listed here: http://personalpages.tds.net/~kent37/BookList.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
Jon Moore wrote: Hi, I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises. The challenge says: Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. The function looks like this: def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high): response = int(raw_input(question)) return response The author has not eluded to 'step values' in anyway that I can see in the proceeding chapters! I have the book and I don't understand what he is asking for in that question either. To me a 'step value' would be something that alters a sequence, for example the third argument to range() is a step value: help(range) Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) - list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. range(0, 6) [0, 1, 2, 3, 4, 5] range(0, 6, 2) [0, 2, 4] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
Hi Jon, Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. If its any consolation that doesn't really mean much to me either. I understand the concept of step value - range() takes one for example, check the docs. But how a step value would be used in this kind of user-input scenario I have no idea! def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high): response = int(raw_input(question)) return response The only possibility I can think of is that the step value is used to narrow the acceptable range each time round the loop. But given we don't necessarily tell the user what the range is that would be weird. We'd need to modify question as we go or something. On the assumption you aren't being marked on this I'd just make up your own mind what it should do and do it! :-) ...and treat it as a good example of a bad statement of requirements! Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy files
Alan,Thanks for that. Hopefully this now is easier to read. The only problem is that despite the fact that as the same user, I can manually change these files (so I must have the right file permissions ?) - the copying does not happening.def compare_files(file_name1, file_name2): x = filecmp.cmp (file_name1, file_name2) print x return xdef change_files(file_1, file_2): yesorno = raw_input("Do you want them to be the same Y or N ") yesorno = string.upper(yesorno) if yesorno == 'Y': try: shutil.copy(file_1, file_2) print "the copy part thinks it worked" except: print "it did not work" def did_it_work(file_1, file_2): #this is to debug the copy afterchange = compare_files("test1.txt","test3.txt" ) if afterchange == 'True': print "the copy went fine" else: print "problem with the copy" #main import shutil import string import filecmpx = compare_files("test1.txt","test3.txt" ) if x == False: print "test1 and test3 are different" change_files("test1.txt", "text3.txt") did_it_work("test1.txt", "text3.txt") else: x = compare_files("test2.txt","test3.txt" ) i! f x == False: print "test2 and test3 are different" change_files("test2.txt", "text3.txt") did_it_work("test2.txt", "text3.txt") print "program finished" Alan Gauld [EMAIL PROTECTED] wrote: David,Can I suggest you rethink your variable names?That might make it clearer what is happening. def compare_files(file_name1, file_name2): x = cmp (file_name1, file_name2) return xSeems fair enough except file_name1 and file_name2 are actually file *contents*!And in fact the function really just compares 2 strings. in fact it compares 2 anythings,It just returns the resulkt of cmp() so you could lose it entirely!
You might find it easier to use the filecmp.cmp() function which comparestwo files using their filenames as arguments. def open_files(file_name): file_is = open(file_name,'r') file_conts = file_is.read() return file_contsAnd "open_files" actually only opens one file and then returns it contents.So a name like "contents_of(filename)" would be more descriptive def change_files(file_1, file_2): yesorno = raw_input("Do you want them to be the same Y or N ") yesorno = string.upper(yesorno) if yesorno == 'Y': try: shutil.copy2(file_1, file_2) print "copy has been done " except: print "it did not work"The user prompt doesn't give the user much clue what he is agreeing tomake the same but otherwise this seems OK. I assume you have writeaccess to both files? #main file_name1 = open_files("test1.txt") file_name2 = open_files("test2.txt") file_name3 = open_files("test3.txt")the 3 variables above each contain not the *name* of the file but the contents. import shutil import string x = compare_files(file_name3, file_name1)x = cmp(f1,f2)would be just as useful. if x != 0: print "test1 and test3 are different" change_files("test1.txt", "text3.txt", file_name1)The function above has 2 parameters but you are passing 3 arguments.I'd expect Python to complain at that? Also the first two are filenamesbut the last is the contents of file1 else: file_name1 = "test2.txt"but here you overwrite the contents with the filename print file_name1and print "text2.txt"I'm not sure what thats trying to do? ! x = compare_files(file_name3, file_name2)again a simple cmp() would do the same job if x != 0: print "test2 and test3 are different" change_files("test2.txt", "text3.txt")Since you didn't mention an error I assume your program alwaysgoes down this path?Despite the confusing names it looks like the program must begoing down the second branch and trying to copy the two files.The only obvious thing I can think of is that the files do not havewrite permissions set appropriately?Not sure if that helps at all but the best I can do at 12:45am...:-)Alan G. To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
I guess I am not going mad then!I will skip this exercise and move on.ThanksJonOn 31/01/06, Alan Gauld [EMAIL PROTECTED] wrote:Hi Jon, Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1.If its any consolation that doesn't really mean much to me either.I understand the concept of step value - range() takes one forexample, check the docs. But how a step value would be used in this kind of user-input scenarioI have no idea!def ask_number(question, low, high):Ask for a number within the range response = Nonewhile response not in range(low, high):response =int(raw_input(question))return responseThe only possibility I can think of is that the step value is used tonarrow the acceptable range each time round the loop. But given we don't necessarily tell the user what the range is that would beweird. We'd need to modify question as we go or something.On the assumption you aren't being marked on this I'd justmake up your own mind what it should do and do it! :-) ...and treat it as a good example of a bad statement ofrequirements!Alan G-- Best RegardsJon Moore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Cannot run .py file from apache web server , Guidance requested
Hi I am trying to execute .py scripts from my apache web server , but it is not giving the results as how I run php files , it just displays the contents of the script , I am able to run and get results of PHP from the same loaction my sample-test.py file is as follows import cgi reshtml = '''Content-Type: text/html\n HTMLHEADTITLE Friends CGI Demo (dynamic screen) /TITLE/HEAD BODYH3Friends list for: I Joseph /I/H3 Your name is: BJohn /BP You have B 20/B friends. /BODY/HTML''' When I access this script from the url http://192.168.20.99/~john/ sample-test.py in the browser I see the contents of the file , not the result Is there any function similar to phpino() in python , so that I can test Guidance requested , Joseph John ___ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
Jon Moore wrote: Hi, I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises. The challenge says: Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. The function looks like this: def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high): response = int(raw_input(question)) return response The author has not eluded to 'step values' in anyway that I can see in the proceeding chapters! This lights my frustration fire. I wonder whether the author tested the book? When I worked for a training company I was asked to test a new on-line course on JCL. I demurred by saying But I don't know JCL.. The reply was that's exactly what we want! So a general recommendation to authors is to have a member of the target audience test the book. You Jon have done that but at some cost to you and those of us on this list. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
I know. Its hard enough for someone like me as it is without things like this complicating it!I have another one for the group, but I will save it for another day ;)I have been looking for contact details for the author to ask him what he was eluding to with the exercise, but to no avail. JonOn 31/01/06, Bob Gailer [EMAIL PROTECTED] wrote: Jon Moore wrote: Hi, I am still working my way through my 'Python for absolute beginners book' and have hit a brick wall with one of the end of chapter exercises. The challenge says: Improve the function ask_number() so that the function can be called with a step value. Make the default value of step 1. The function looks like this: def ask_number(question, low, high): Ask for a number within the range response = None while response not in range(low, high): response =int(raw_input(question)) return response The author has not eluded to 'step values' in anyway that I can see in the proceeding chapters!This lights my frustration fire. I wonder whether the author tested thebook?When I worked for a training company I was asked to test a new on-line course on JCL. I demurred by saying But I don't know JCL.. The replywas that's exactly what we want!So a general recommendation to authors is to have a member of the targetaudience test the book. You Jon have done that but at some cost to you and those of us on this list.-- Best RegardsJon Moore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cannot run .py file from apache web server , Guidance requested
Further delving leads to Apache Tutorial: Dynamic Content with CGI in the Apache Documentation. Under that is a section But it's still not working! ... you see ... The source code of your CGI program ...That means that you have not properly configured Apache to process your CGI program. Reread the section on configuring Apache cid:part1.04040807.02090606@alum.rpi.edu and try to find what you missed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] smtplib with yahoo smtp server
Hello everyone,I am working with a registration system for my website in mod_python. I needed to send mail to registered users for confirmation. Since I can't use my ISP's smtp server, I used yahoo's smtp server and my yahoo username and password to connect and send mail using this script (see below). But I get the following error. Traceback (most recent call last): File mail.py, line 12, in ? session = smtplib.SMTP(smtpserver) File /usr/lib/python2.4/smtplib.py, line 255, in __init__ addr = socket.gethostbyname(socket.gethostname())socket.gaierror: (-2, 'Name or service not known')I got this script from some website I can't remember and just changed some values to get it to work. Is is possible to send mail like this? Is there any other easy way to do this? Thanks for your time.--- import smtplib smtpserver = 'smtp.mail.yahoo.com' AUTHREQUIRED = 1 smtpuser = '[EMAIL PROTECTED]' smtppass = '[snip]' RECIPIENTS = ['[EMAIL PROTECTED]'] SENDER = '[EMAIL PROTECTED]' mssg = mod python session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)-- Intercodes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy files
The only problem is that despite the fact that as the same user, I can manually change these files (so I must have the right file permissions ?) Can you do it from within python at the prompt Use os.getcwd() to find out where you are Use os.chdir() to navigate Use os.listdir() to list the folder contents and use shutil.copy() to copy the files. Doing it manually from inside the prompt should show up any problems. You can even try the filecomp call from in there too... is a powerful tool. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
On Tue, 31 Jan 2006, Jon Moore wrote: I have been looking for contact details for the author to ask him what he was eluding to with the exercise, but to no avail. Hi Jon, I did find errata here: http://www.muskalipman.com/ptr_detail.cfm?group=Programmingall=1isbn=1-59200-073-8 (bottom of the page) but as far as contact information, I haven't been able to find anything. I do agree the challenege exercise as you've put it seems somewhat nonsensical. *grin* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Exit a child thread using threading.Thread() object
A quick question. I have started a child thread using the threading.Thread class. Is there any way to cleanly exit the child thread? What I mean by cleanly is for example if you use the thread.start_new() function to create a child thread, the function running in the child thread can call thread.exit() to terminate the thread. I could not find anything comparable in the Thread object's documentation. Thanks Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exit a child thread using threading.Thread() object
Bernard Lebel wrote: A quick question. I have started a child thread using the threading.Thread class. Is there any way to cleanly exit the child thread? What I mean by cleanly is for example if you use the thread.start_new() function to create a child thread, the function running in the child thread can call thread.exit() to terminate the thread. I could not find anything comparable in the Thread object's documentation. Both thread.start_new() and threading.Thread wrap a callable object in a new thread. For start_new(), the callable is a parameter passed to the function. For threading.Thread, the callable can be passed as an initialization parameter or by overriding Thread.run(). In any case, the thread runs until the wrapped method terminates, either by a normal function return or by raising an uncaught exception. The usual way to exit a thread is for the wrapped callable to return (just a normal function return). thread.exit() just raises SystemExit which terminates the callable with an uncaught exception. You could probably do the same in a Thread by raising SystemExit explicitly or calling sys.exit() (which raises SystemExit for you). But just returning normally from the callable is the usual way to exit a thread from within the thread. If you want to stop a thread from another thread it is harder. The cleanest way to do it is to set a flag that the running thread will check. There are several recipes in the online cookbook that show how to do this. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
So a general recommendation to authors is to have a member of the target audience test the book. You Jon have done that but at some cost to you and those of us on this list. One advantage of doing my book as a web site first was that I had plenty of testers before committing to print (over 100k visitors). Mind you the paper version still had plenty of mistakes but mostly those were typos... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
DannyMany thanks for that, I notice a few erratas that I am yet to come up against. This will save my sanity (well some of it)1JonOn 31/01/06, Danny Yoo [EMAIL PROTECTED] wrote: On Tue, 31 Jan 2006, Jon Moore wrote: I have been looking for contact details for the author to ask him what he was eluding to with the exercise, but to no avail.Hi Jon,I did find errata here: http://www.muskalipman.com/ptr_detail.cfm?group=Programmingall=1isbn=1-59200-073-8(bottom of the page) but as far as contact information, I haven't been able to find anything.I do agree the challenege exercise as you've put it seems somewhatnonsensical.*grin* -- Best RegardsJon Moore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
AlanAre you the author of Learn to Program Using Python: A Tutorial for Hobbyists, Self-starters and All Who Want to Learn the Art of Computer Programming? Is the book still available as a web site?JonOn 31/01/06, Alan Gauld [EMAIL PROTECTED] wrote: So a general recommendation to authors is to have a member of the target audience test the book. You Jon have done that but at some cost to you and those of us on this list.One advantage of doing my book as a web site first was that I had plentyof testers before committing to print (over 100k visitors). Mind you the paperversion still had plenty of mistakes but mostly those were typos...Alan G.-- Best RegardsJon Moore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting Running File's Name
On 31 Jan 2006 at 9:17, Rinzwind wrote: Why would that be any different under Linux? sys.argv[0] On 1/31/06, Hans Dushanthakumar [EMAIL PROTECTED] wrote: Under WinXP, the variable sys.argv[0] holds the script file name (including the path). Not sure, Wim/Hans, Thank you both. It worked perfectly. -- Bryan Carbonnell - [EMAIL PROTECTED] If you lend someone $20, and never see that person again, it was probably worth it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question re. Functions
Are you the author of Learn to Program Using Python: A Tutorial for Hobbyists, Self-starters and All Who Want to Learn the Art of Computer Programming? Yes. Is the book still available as a web site? Yes. It has been substantially rewritten sionce the book was done to cover more recent features of Python. But the basic structure and content is still the same. The book has 3 chapters whose copyright belongs to Addison Wesley and thus are not on the web site but OTOH the web site has several topics which were written after the book was published Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor