From bgailer at gmail.com Mon Aug 1 00:14:10 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 31 Jul 2011 18:14:10 -0400 Subject: [Tutor] How do I learn python for web development In-Reply-To: <725283150-1312144033-cardhu_decombobulator_blackberry.rim.net-569129859-@b1.c28.bise6.blackberry> References: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> <725283150-1312144033-cardhu_decombobulator_blackberry.rim.net-569129859-@b1.c28.bise6.blackberry> Message-ID: <4E35D3B2.4010202@gmail.com> PLEASE DO NOT HIJACK PRIOR MESSAGES. New thread? Start a new email. PLEASE DO NOT SEND A BUNCH OF IRREVELANT TEXT. Just what is relevant. On 7/31/2011 4:27 PM, eire1130 at gmail.com wrote: > There are several books om django. This is what you are looking for > > > Sent from my Verizon Wireless BlackBerry > > -----Original Message----- > From: "abdulhakim haliru" > Sender: tutor-bounces+eire1130=gmail.com at python.org > Date: Sun, 31 Jul 2011 20:22:30 > To: > Reply-To: abdulhakim.haliru at leproghrammeen.com > Subject: [Tutor] How do I learn python for web development > > Hi guys, > > I am really interested in switching from PHP to python but there don't appear to be a book for such. > > Can anyone advice me please. > > Abdulhakim. > Sent from my BlackBerry wireless device from MTN > > -----Original Message----- > From: tutor-request at python.org > Sender: tutor-bounces+abdulhakim.haliru=leproghrammeen.com at python.org > Date: Sun, 31 Jul 2011 07:01:56 > To: > Reply-To: tutor at python.org > Subject: Tutor Digest, Vol 89, Issue 92 > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: How to make tkMessage function to have duration > (Steven D'Aprano) > 2. Re: How to make tkMessage function to have duration (Emeka) > 3. newbie needs pypy setup tips (Tom Roche) > 4. Re: newbie needs pypy setup tips (eire1130 at gmail.com) > 5. Re: Mainloop conflict (Christopher King) > 6. Re: Mainloop conflict (Stefan Behnel) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 30 Jul 2011 21:25:27 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] How to make tkMessage function to have duration > Message-ID:<4E33EA27.50301 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Emeka wrote: >> Hello All, >> >> Say I have the below(code), .... I would want the message to last say 30 >> seconds and afterwards disappear. I won't want the user to be the one to >> enable it to disappear. >> >> Basically, what I want is to be able to show the user some message , and >> after some seconds, the message goes away > I *hate* it when applications do that. Just as I'm trying to read the > message, take a screen shot, or whatever, the message disappears. I > think that's one of the worst things you can do in an application. > > If the message isn't important enough to require it to stay visible > until the user explicitly closes it, then it shouldn't go into a dialog > in the first place. > > > -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Mon Aug 1 01:05:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Aug 2011 00:05:20 +0100 Subject: [Tutor] How do I learn python for web development In-Reply-To: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> References: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> Message-ID: <4E35DFB0.2080008@btinternet.com> abdulhakim haliru wrote: > Hi guys, > > I am really interested in switching from PHP to python > but there don't appear to be a book for such. > I don;t know of any books expressly for converting from PHP to P{ython web development but there is a lot of documentation on Python web development, plus several different frameworks to choose from. I've used TurboGears, and played with Django and Zope. There are dead tree books on all three, the most popular seems to be Django. There are other, simpler frameworks too like Pylons and CherryPy. Take a look at them, they all do pretty much the same things and all are easier to use than traditional CGI, although Python supports that too of course. HTH, Alan G. From alan.gauld at btinternet.com Mon Aug 1 01:05:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Aug 2011 00:05:20 +0100 Subject: [Tutor] How do I learn python for web development In-Reply-To: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> References: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> Message-ID: <4E35DFB0.2080008@btinternet.com> abdulhakim haliru wrote: > Hi guys, > > I am really interested in switching from PHP to python > but there don't appear to be a book for such. > I don;t know of any books expressly for converting from PHP to P{ython web development but there is a lot of documentation on Python web development, plus several different frameworks to choose from. I've used TurboGears, and played with Django and Zope. There are dead tree books on all three, the most popular seems to be Django. There are other, simpler frameworks too like Pylons and CherryPy. Take a look at them, they all do pretty much the same things and all are easier to use than traditional CGI, although Python supports that too of course. HTH, Alan G. From g.nius.ck at gmail.com Mon Aug 1 02:42:39 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Sun, 31 Jul 2011 20:42:39 -0400 Subject: [Tutor] Mailing list documentation In-Reply-To: <0ae946b0272de6e1eceefdd4488612c7@mighty.webmail.co.za> References: <0ae946b0272de6e1eceefdd4488612c7@mighty.webmail.co.za> Message-ID: Wow wow, way is a Sergey at might.co.za person doing a tutor response. And why can I see it if it isn't to me.. I'm sorry Sergey if this isn't something malicious, it just seems suspicious. On Sun, Jul 31, 2011 at 3:30 PM, Sergey wrote: > On Sun, 31 Jul 2011 14:22:41 -0400 Alexander Etter > wrote > > > Hello everyone, is there a page that contains documentation for this > mailing > > list? I've seen a few users top post and others advise against it; if > there > > isn't a page listing conventions let's create it and if there is what is > it's > > URL and how do you suggest users read it? > > Alexander > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > --- > tutor-request at python.org > Fri, 29 Jul 2011 19:52:43 +0200 (2 days, 1 hour ago) > > Welcome to the Tutor at python.org mailing list! This list is for folks > who want to ask (and/or answer) questions from folks who wish to learn > how to program with Python. Feel free to ask even the most basic of > questions -- that's what the list is for! > > For best results when asking a question on this list: - Try to write > some code to solve your problem - Show the code you have written - > Describe what the code does and what you want it to do - If the code > generates an error, copy and paste the entire error message, including > the traceback, into your email. - Tell us what OS and Python version > you are using. > > - Don't ask us to do your homework. - Don't assume we know what you > are talking about. If you are having trouble with a third-party > library, include a link to the library home page. > > When replying to a posting: - Use Reply All to reply to the entire > list - Don't top post - put your reply after the text to which you are > replying > > For all posts: - Format your email as plain text, not HTML > > > To post to this list, send your email to: > > tutor at python.org > > General information about the mailing list is at: > > http://mail.python.org/mailman/listinfo/tutor > > If you ever want to unsubscribe or change your options (eg, switch to > or from digest mode, change your password, etc.), visit your > subscription page at: > > http://mail.python.org/mailman/options/tutor/*************** > > You can also make such adjustments via email by sending a message to: > > Tutor-request at python.org > > with the word `help' in the subject or body (don't include the > quotes), and you will get back a message with instructions. > > You must know your password to change your options (including changing > the password, itself) or to unsubscribe. It is: > > *********************** > > Normally, Mailman will remind you of your python.org mailing list > passwords once every month, although you can disable this if you > prefer. This reminder will also include instructions on how to > unsubscribe or change your account options. There is also a button on > your options page that will email your current password to you. > > > ____________________________________________________________ > South Africas premier free email service - www.webmail.co.za > > For super low premiums, click here http://www.dialdirect.co.za/?vdn=15828 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Mon Aug 1 03:43:56 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Sun, 31 Jul 2011 21:43:56 -0400 Subject: [Tutor] Mailing list documentation In-Reply-To: References: <0ae946b0272de6e1eceefdd4488612c7@mighty.webmail.co.za> Message-ID: On Sun, Jul 31, 2011 at 8:42 PM, Christopher King wrote: > Wow wow, way is a Sergey at might.co.za person doing a tutor response. Assuming you mean _why_ (not _way_) , Sergey was simply quoting the introductory email we all get when we join, as it answered the original posters question. There is nothing of concern here. -- Brett Ritter / SwiftOne swiftone at swiftone.org From d at davea.name Mon Aug 1 03:55:55 2011 From: d at davea.name (Dave Angel) Date: Sun, 31 Jul 2011 21:55:55 -0400 Subject: [Tutor] Mailing list documentation In-Reply-To: References: <0ae946b0272de6e1eceefdd4488612c7@mighty.webmail.co.za> Message-ID: <4E3607AB.5000405@davea.name> On 07/31/2011 08:42 PM, Christopher King wrote: > Wow wow, way is a Sergey at might.co.za person doing a tutor response. And why > can I see it if it isn't to me.. I'm sorry Sergey if this > isn't something malicious, it just seems suspicious. > (You could try reading it, instead of just getting suspicious. one of the things it requests is "don't top-post". Put your response after the part you're quoting.) A simple google search finds a similar article dated from 2008, so I don't think it's a plot by Sergey. http://mail.python.org/pipermail/tutor/2008-March/060723.html As for why it comes to you, presumably that has something to do with you subscribing to the list. > -- DaveA From cwitts at compuscan.co.za Mon Aug 1 08:06:22 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 01 Aug 2011 08:06:22 +0200 Subject: [Tutor] How do I learn python for web development In-Reply-To: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> References: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry> Message-ID: <4E36425E.8010707@compuscan.co.za> On 2011/07/31 10:22 PM, abdulhakim haliru wrote: > Hi guys, > > I am really interested in switching from PHP to python but there don't appear to be a book for such. > > Can anyone advice me please. > > Abdulhakim. > Sent from my BlackBerry wireless device from MTN > You can try Python 3 Web Development Beginner's Guide http://www.packtpub.com/python-3-web-development-beginners-guide/book It's Python 3.x, CherryPy, jQuery, jQuery UI -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Mon Aug 1 19:48:44 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Mon, 01 Aug 2011 10:48:44 -0700 Subject: [Tutor] Question about sorting a list within a dictionary within a list Message-ID: <4E36E6FC.8080904@iandouglas.com> I'm using the Bono library for talking to EC2, and I'm getting a list of EC2 instances back in a list called "reservations". Each element in the list is a dictionary of information. One of those dictionary elements is a list called 'instances', and I only ever care about the first entry. That instances[0] value is a dictionary, which holds a key I want to use to sort the base "reservations" list. I found this helpful bit for sorting a list of dictionaries by a key within the dictionaries: http://stackoverflow.com/questions/72899/in-python-how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary ... this works great if you just have a list of dictionaries. I'm not sure how to go deeper within that to sort my data without iterating through the entire 'reservations' list and building an entirely new list. Maybe it would be easier, but I'm just curious if it's possible without messing with my main 'reservations' list. My current code looks like this: (it's a views.py file) from django.http import HttpResponse import boto.ec2 from operator import itemgetter def index(request): conn = boto.connect_ec2() reservations = conn.get_all_instances() # this is where I'm trying to sort everything res_sorted = sorted(reservations, key=itemgetter('launch_time')) output = '' output += '' output += '' output += '' output += '' output += '' output += '' output += '' output += '' for reservation in res_sorted: instance = reservation.instances[0] output += '' output += '' output += '' output += '' output += '' output += '' output += '' Ideally, I'd like to make each table column 'sortable' so the user can click on state/launched/etc (I may add more columns in the future), but I'm not sure how to search deeper within the 'reservations' list for the sorted() call to get at the 'launch_time' element within the instaces[0] dictionary. Also, I'm sure there are much better ways to do the display logic, but I'll tackle that another time. Thanks for any pointers, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From mediacus at gmail.com Mon Aug 1 20:13:51 2011 From: mediacus at gmail.com (=?ISO-8859-1?Q?Bj=F8rn=2DRoar_Eriksen?=) Date: Mon, 1 Aug 2011 20:13:51 +0200 Subject: [Tutor] get last 7 days string in a log file Message-ID: Hi I'm new to Python and I'm trying to write a script that's count restart of an application. The log file contains: 2009-03-06 18:20:26,423 User operation - start nanny 2009-03-06 18:20:26,423 User operation - start all services And 2009-03-06 18:20:26,423 User operation - start all services tells me that the application has been restarted. My script do count it, but I cant figure out how to code so it's only get from to day and 7 day's back. #Counts restart of an application count = 0 with open("c:/test/bre.log")as f: for line in f: if "User operation - start all services" in line: count += 1 #print line.strip() print 'Server restart: %s' % count -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Mon Aug 1 20:24:53 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Mon, 1 Aug 2011 23:54:53 +0530 Subject: [Tutor] get last 7 days string in a log file In-Reply-To: References: Message-ID: Hi, Let me understand the problem - Do you want to count the number of times the application was restarted between today and 7 days back? => If yes, then you will need to do some string manipulation to get the required dates. Then you will need to apply both the conditions to the line i.e. if the date is the required date and if the string contains what you want. i.e. if "2009-03-6" in line and : ... count += 1 You can apply this logic to each date and create a complex statement using OR to get the count. OR you can use the datetime object with proper formatting and check the existence of the condition. Do I understand your problem correctly? Regards Sumod 2011/8/1 Bj?rn-Roar Eriksen > Hi > > I'm new to Python and I'm trying to write a script that's count restart of > an application. The log file contains: > 2009-03-06 18:20:26,423 User operation - start nanny > 2009-03-06 18:20:26,423 User operation - start all services > And 2009-03-06 18:20:26,423 User operation - start all services tells me > that the application has been restarted. > > My script do count it, but I cant figure out how to code so it's only get > from to day and 7 day's back. > #Counts restart of an application > count = 0 > with open("c:/test/bre.log")as f: > for line in f: > if "User operation - start all services" in line: > count += 1 > #print line.strip() > print 'Server restart: %s' % count > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mediacus at gmail.com Mon Aug 1 21:01:43 2011 From: mediacus at gmail.com (=?utf-8?Q?Bj=C3=B8rn_Roar_Eriksen?=) Date: Mon, 1 Aug 2011 21:01:43 +0200 Subject: [Tutor] get last 7 days string in a log file In-Reply-To: References: Message-ID: <6D522706-08E4-4A99-B6C2-FA63CBFCFF5E@gmail.com> Yes, that is what I want to do. Kind Regard Bj?rn-Roar Den 1. aug. 2011 kl. 20:24 skrev spawgi at gmail.com: > Hi, > > Let me understand the problem > - Do you want to count the number of times the application was restarted between today and 7 days back? > => If yes, then you will need to do some string manipulation to get the required dates. Then you will need to apply both the conditions to the line i.e. if the date is the required date and if the string contains what you want. > i.e. if "2009-03-6" in line and : > ... count += 1 > You can apply this logic to each date and create a complex statement using OR to get the count. > OR you can use the datetime object with proper formatting and check the existence of the condition. > > Do I understand your problem correctly? > > Regards > Sumod > > > 2011/8/1 Bj?rn-Roar Eriksen > Hi > > I'm new to Python and I'm trying to write a script that's count restart of an application. The log file contains: > 2009-03-06 18:20:26,423 User operation - start nanny > 2009-03-06 18:20:26,423 User operation - start all services > And 2009-03-06 18:20:26,423 User operation - start all services tells me that the application has been restarted. > > My script do count it, but I cant figure out how to code so it's only get from to day and 7 day's back. > #Counts restart of an application > count = 0 > with open("c:/test/bre.log")as f: > for line in f: > if "User operation - start all services" in line: > count += 1 > #print line.strip() > print 'Server restart: %s' % count > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > http://spawgi.wordpress.com > We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Aug 1 22:03:18 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Aug 2011 22:03:18 +0200 Subject: [Tutor] Question about sorting a list within a dictionary within a list References: <4E36E6FC.8080904@iandouglas.com> Message-ID: ian douglas wrote: > I'm using the Bono library for talking to EC2, and I'm getting a list of > EC2 instances back in a list called "reservations". Each element in the > list is a dictionary of information. One of those dictionary elements is > a list called 'instances', and I only ever care about the first entry. > That instances[0] value is a dictionary, which holds a key I want to use > to sort the base "reservations" list. > > I found this helpful bit for sorting a list of dictionaries by a key > within the dictionaries: > http://stackoverflow.com/questions/72899/in-python-how-do-i-sort-a-list- of-dictionaries-by-values-of-the-dictionary > > ... this works great if you just have a list of dictionaries. I'm not > sure how to go deeper within that to sort my data without iterating > through the entire 'reservations' list and building an entirely new > list. Maybe it would be easier, but I'm just curious if it's possible > without messing with my main 'reservations' list. > > > My current code looks like this: (it's a views.py file) > > from django.http import HttpResponse > import boto.ec2 > from operator import itemgetter > > def index(request): > conn = boto.connect_ec2() > reservations = conn.get_all_instances() > > # this is where I'm trying to sort everything > res_sorted = sorted(reservations, key=itemgetter('launch_time')) > > output = '
StateLaunchedPublic HostnamePublic IPPrivate HostnamePrivate IP
' + instance.state + '' + instance.launch_time + '' + instance.public_dns_name + '' + instance.ip_address + '' + instance.private_dns_name + '' + instance.private_ip_address + '
' > output += '' > output += '' > output += '' > output += '' > output += '' > output += '' > output += '' > output += '' > for reservation in res_sorted: > instance = reservation.instances[0] > output += '' > output += '' > output += '' > output += '' > output += '' > output += '' > output += '' > > > Ideally, I'd like to make each table column 'sortable' so the user can > click on state/launched/etc (I may add more columns in the future), but > I'm not sure how to search deeper within the 'reservations' list for the > sorted() call to get at the 'launch_time' element within the instaces[0] > dictionary. > > Also, I'm sure there are much better ways to do the display logic, but > I'll tackle that another time. I cannot help you with the django or boto part. As to sorting lists: to do it inplace invoke the sort() method: reservations.sort(key=mykey) You can think of itemgetter("launch_time") as a function that creates the the following function on the fly: def mykey(item): return item["launch_time"] Judging from the code you provide you need def mykey(item): return item.instances[0].launch_time instead. If you want to be flexible about the actual attribute you can change that to attrname = ... def mykey(item): return getattr(item.instances[0], attrname) Djange probably offers a way to provide the desired attribute name via the request object. Your index() function would then become LEGAL_SORTKEYS = set(["launch_time", "ip_address"]) def index(request): conn = boto.connect_ec2() reservations = conn.get_all_instances() attrname = ... # your code if attrname in LEGAL_SORTKEYS: def mykey(item): return getattr(item.instances[0], attrname) reservations.sort(key=mykey) else: ... # provide an error message or just don't sort output = '
StateLaunchedPublic HostnamePublic IPPrivate HostnamePrivate IP
' + instance.state + '' + instance.launch_time + '' + instance.public_dns_name + '' + instance.ip_address + '' + instance.private_dns_name + '' + instance.private_ip_address + '
' output += '' ... From ian.douglas at iandouglas.com Mon Aug 1 22:05:07 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Mon, 01 Aug 2011 13:05:07 -0700 Subject: [Tutor] time zone conversion Message-ID: <4E3706F3.30700@iandouglas.com> Hi all, Been trying to wrap my head around some datetime vs time stuff with regards to parsing a string as a date plus time with a timezone offset. This is the string I'm given: 2010-01-22T00:14:33.000Z And I can use time.strptime to parse out its individual elements, but then I need to adjust that time, in UTC/Zulu to my local time zone. Here's what I'm currently trying: old_launch_time = '2010-01-22T00:14:33.000Z' os.environ['TZ'] = 'UTC' time.tzset() launch_time = time.strptime(old_launch_time, '%Y-%m-%dT%H:%M:%S.000Z') os.environ['TZ'] = 'US/Pacific' time.tzset() print 'old time: ' + old_launch_time print 'new time: ' + time.strftime("%Y-%m-%d %H:%M:%S", launch_time) output: old time: 2010-01-22T00:14:33.000Z new time: 2010-01-22 00:14:33 But the different tzset() calls are not adjusting based on the 7 or 8 hour difference. I know that all incoming dates/times are coming to me in UTC. I just can't seem to get a good handle on how to properly convert it to my own time zone. Thanks, Ian From ian.douglas at iandouglas.com Mon Aug 1 22:15:57 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Mon, 01 Aug 2011 13:15:57 -0700 Subject: [Tutor] Question about sorting a list within a dictionary within a list In-Reply-To: References: <4E36E6FC.8080904@iandouglas.com> Message-ID: <4E37097D.7010702@iandouglas.com> On 08/01/2011 01:03 PM, Peter Otten wrote: > ian douglas wrote: > >> I'm using the Bono library for talking to EC2, and I'm getting a list of >> >> I cannot help you with the django or boto part. Well, I suppose that using django/bono wasn't really relevant to the question. I appreciate the feedback though, I'll definitely keep it in mind for future projects. The sort() and mykey() stuff you proposed looked neat. I'll dig into that stuff more to see how it works when I finish this project. I appreciate the LEGAL_SORTKEYS bit too, it was on my to-do list as well. In the end, I ended up flattening things a little, instead of having a list of objects, and those objects holding a list of instances, and each of those instances being objects themselves: reservations_bulk = conn.get_all_instances() reservations_unsorted = [] ; for reservation in reservations_bulk: instance = reservation.instances[0].__dict__ reservations_unsorted.append(instance) reservations = sorted(reservations_unsorted, key=itemgetter('launch_time')) I'm sure there's an even cleaner way of doing the for loop too? I hadn't seen the __dict__ property before for objects, and that allowed me to just build a simple list of dictionaries, which I could then run through the itemgetter() solution I'd found on StackOverflow. Ian From __peter__ at web.de Mon Aug 1 22:49:51 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Aug 2011 22:49:51 +0200 Subject: [Tutor] Question about sorting a list within a dictionary within a list References: <4E36E6FC.8080904@iandouglas.com> <4E37097D.7010702@iandouglas.com> Message-ID: ian douglas wrote: > On 08/01/2011 01:03 PM, Peter Otten wrote: >> ian douglas wrote: >> >>> I'm using the Bono library for talking to EC2, and I'm getting a list of >>> >>> I cannot help you with the django or boto part. > > Well, I suppose that using django/bono wasn't really relevant to the > question. > > I appreciate the feedback though, I'll definitely keep it in mind for > future projects. The sort() and mykey() stuff you proposed looked neat. > I'll dig into that stuff more to see how it works when I finish this > project. I appreciate the LEGAL_SORTKEYS bit too, it was on my to-do > list as well. > > > In the end, I ended up flattening things a little, instead of having a > list of objects, and those objects holding a list of instances, and each > of those instances being objects themselves: > > reservations_bulk = conn.get_all_instances() > reservations_unsorted = [] ; > for reservation in reservations_bulk: > instance = reservation.instances[0].__dict__ > reservations_unsorted.append(instance) > reservations = sorted(reservations_unsorted, > key=itemgetter('launch_time')) > > I'm sure there's an even cleaner way of doing the for loop too? Untested: from operator import attrgetter, itemgetter from itertools import imap firsts = imap(itemgetter(0), conn.get_all_instances()) reservations = sorted(firsts, key=attrgetter("launch_time")) This gives you objects rather than the objects' __dict__s. From __peter__ at web.de Mon Aug 1 23:11:11 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Aug 2011 23:11:11 +0200 Subject: [Tutor] Question about sorting a list within a dictionary within a list References: <4E36E6FC.8080904@iandouglas.com> <4E37097D.7010702@iandouglas.com> Message-ID: Peter Otten wrote: > Untested: > > from operator import attrgetter, itemgetter > from itertools import imap > > firsts = imap(itemgetter(0), conn.get_all_instances()) > reservations = sorted(firsts, key=attrgetter("launch_time")) > > This gives you objects rather than the objects' __dict__s. Oops, I think I missed one level of indirection: firsts = (r.instances[0] for r in conn.get_all_instances()) reservations = sorted(firsts, key=attrgetter("launch_time")) From mnickey at gmail.com Tue Aug 2 00:05:30 2011 From: mnickey at gmail.com (Mike Nickey) Date: Mon, 1 Aug 2011 15:05:30 -0700 Subject: [Tutor] Accessing Specific Dictionary items Message-ID: Hi all, I'm trying to access and use specific items within a dictionary that is returned but am having issues in doing so. [{'city': 'Sunnyvale', 'region_name': 'CA', 'area_code': 408, 'metro_code': 'Santa Clara, CA', 'country_name': 'United States'}] How can I populate a list of many different returns so that I have a list that contains all the cities and in line with the item that is referenced. The first step is to populate the list unsorted as it needs to be in correlation to the item that it came from. Thanks for your help. -- ~MEN From eire1130 at gmail.com Tue Aug 2 00:12:59 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Mon, 1 Aug 2011 22:12:59 +0000 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: References: Message-ID: <2125203545-1312236780-cardhu_decombobulator_blackberry.rim.net-1393163250-@b1.c28.bise6.blackberry> I'm not sure I'm following. Could you give an example of expected input and expected output? Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Mike Nickey Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Mon, 1 Aug 2011 15:05:30 To: Subject: [Tutor] Accessing Specific Dictionary items Hi all, I'm trying to access and use specific items within a dictionary that is returned but am having issues in doing so. [{'city': 'Sunnyvale', 'region_name': 'CA', 'area_code': 408, 'metro_code': 'Santa Clara, CA', 'country_name': 'United States'}] How can I populate a list of many different returns so that I have a list that contains all the cities and in line with the item that is referenced. The first step is to populate the list unsorted as it needs to be in correlation to the item that it came from. Thanks for your help. -- ~MEN _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From ian.douglas at iandouglas.com Tue Aug 2 00:14:42 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Mon, 01 Aug 2011 15:14:42 -0700 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: References: Message-ID: <4E372552.9050702@iandouglas.com> On 08/01/2011 03:05 PM, Mike Nickey wrote: > Hi all, > > I'm trying to access and use specific items within a dictionary that > is returned but am having issues in doing so. > [{'city': 'Sunnyvale', 'region_name': 'CA', 'area_code': 408, > 'metro_code': 'Santa Clara, CA', 'country_name': 'United States'}] > > How can I populate a list of many different returns so that I have a > list that contains all the cities and in line with the item that is > referenced. > > The first step is to populate the list unsorted as it needs to be in > correlation to the item that it came from. > Thanks for your help. > Could you give us examples of what you want the list to look like? It will help us direct you to an answer. From spawgi at gmail.com Tue Aug 2 00:24:49 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Tue, 2 Aug 2011 03:54:49 +0530 Subject: [Tutor] time zone conversion In-Reply-To: <4E3706F3.30700@iandouglas.com> References: <4E3706F3.30700@iandouglas.com> Message-ID: Quick question - Is any daylight saving taken into consideration for this? On Tue, Aug 2, 2011 at 1:35 AM, ian douglas wrote: > Hi all, > > Been trying to wrap my head around some datetime vs time stuff with regards > to parsing a string as a date plus time with a timezone offset. > > This is the string I'm given: > > 2010-01-22T00:14:33.000Z > > And I can use time.strptime to parse out its individual elements, but then > I need to adjust that time, in UTC/Zulu to my local time zone. > > Here's what I'm currently trying: > > old_launch_time = '2010-01-22T00:14:33.000Z' > os.environ['TZ'] = 'UTC' > time.tzset() > launch_time = time.strptime(old_launch_time, > '%Y-%m-%dT%H:%M:%S.000Z') > os.environ['TZ'] = 'US/Pacific' > time.tzset() > print 'old time: ' + old_launch_time > print 'new time: ' + time.strftime("%Y-%m-%d %H:%M:%S", launch_time) > > output: > > old time: 2010-01-22T00:14:33.000Z > new time: 2010-01-22 00:14:33 > > But the different tzset() calls are not adjusting based on the 7 or 8 hour > difference. > > I know that all incoming dates/times are coming to me in UTC. I just can't > seem to get a good handle on how to properly convert it to my own time zone. > > Thanks, > Ian > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnickey at gmail.com Tue Aug 2 00:26:32 2011 From: mnickey at gmail.com (Mike Nickey) Date: Mon, 1 Aug 2011 15:26:32 -0700 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: <4E372552.9050702@iandouglas.com> References: <4E372552.9050702@iandouglas.com> Message-ID: The input being used is through pygeoip. Using this I am pulling the data by IP and from what I am reading this populates as a dictionary. Here is some of the output that I can show currently [{'city': 'Buena Park', 'region_name': 'CA', 'area_code': 714}, {'city': 'Wallingford', 'region_name': 'CT', 'area_code': 203}, {'city': 'Schenectady', 'region_name': 'NY', 'area_code': 518}, {'city': 'Athens', 'region_name': '35'}] I'd like to have an output similar to this: 'Buena Park', 'Wallingford', 'Schenectady','Athens' pulled by the "city" keys that are used in the returns. I think the easiest way to approach this would be simply to use the .append and populate a list but I don't know how to pull an item by key value from the dictionary returns. I hope this helps clear some confusion and thanks in advance. On Mon, Aug 1, 2011 at 15:14, ian douglas wrote: > On 08/01/2011 03:05 PM, Mike Nickey wrote: >> >> Hi all, >> >> I'm trying to access and use specific items within a dictionary that >> is returned but am having issues in doing so. >> [{'city': 'Sunnyvale', 'region_name': 'CA', 'area_code': 408, >> 'metro_code': 'Santa Clara, CA', 'country_name': 'United States'}] >> >> How can I populate a list of many different returns so that I have a >> list that contains all the cities and in line with the item that is >> referenced. >> >> The first step is to populate the list unsorted as it needs to be in >> correlation to the item that it came from. >> Thanks for your help. >> > > > Could you give us examples of what you want the list to look like? It will > help us direct you to an answer. > -- ~MEN From steve at pearwood.info Tue Aug 2 00:37:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Aug 2011 08:37:59 +1000 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: References: <4E372552.9050702@iandouglas.com> Message-ID: <4E372AC7.9090106@pearwood.info> Mike Nickey wrote: > The input being used is through pygeoip. > Using this I am pulling the data by IP and from what I am reading this > populates as a dictionary. > > Here is some of the output that I can show currently > [{'city': 'Buena Park', 'region_name': 'CA', 'area_code': 714}, > {'city': 'Wallingford', 'region_name': 'CT', 'area_code': 203}, > {'city': 'Schenectady', 'region_name': 'NY', 'area_code': 518}, > {'city': 'Athens', 'region_name': '35'}] > > I'd like to have an output similar to this: > 'Buena Park', 'Wallingford', 'Schenectady','Athens' pulled by the > "city" keys that are used in the returns. What do you mean, "the returns"? If all you want is a list of cities, that's easy: cities = [d['city'] for d in list_of_dicts] or if you prefer a more verbose way: cities = [] for d in list_of_dicts: cities.append(d['city']) To get the list sorted, just sort it afterwards: cities.sort() > I think the easiest way to > approach this would be simply to use the .append and populate a list > but I don't know how to pull an item by key value from the dictionary > returns. The same way you would pull an item by key from any other dict. -- Steven From eire1130 at gmail.com Tue Aug 2 02:28:06 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Tue, 2 Aug 2011 00:28:06 +0000 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: References: <4E372552.9050702@iandouglas.com> Message-ID: <1465184567-1312244887-cardhu_decombobulator_blackberry.rim.net-1333901828-@b1.c28.bise6.blackberry> Dictionaries are objects and you access their attributes through keys. So, let's say I had a dict: d = {'city':'plattsburgh'} I would thus access the attribute by doing this d['city'] You can store that value to a variable Or you can append to a list directly. l = [] for d in yourdict: l.append(d['city']) Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Mike Nickey Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Mon, 1 Aug 2011 15:26:32 To: ian douglas Cc: Subject: Re: [Tutor] Accessing Specific Dictionary items The input being used is through pygeoip. Using this I am pulling the data by IP and from what I am reading this populates as a dictionary. Here is some of the output that I can show currently [{'city': 'Buena Park', 'region_name': 'CA', 'area_code': 714}, {'city': 'Wallingford', 'region_name': 'CT', 'area_code': 203}, {'city': 'Schenectady', 'region_name': 'NY', 'area_code': 518}, {'city': 'Athens', 'region_name': '35'}] I'd like to have an output similar to this: 'Buena Park', 'Wallingford', 'Schenectady','Athens' pulled by the "city" keys that are used in the returns. I think the easiest way to approach this would be simply to use the .append and populate a list but I don't know how to pull an item by key value from the dictionary returns. I hope this helps clear some confusion and thanks in advance. On Mon, Aug 1, 2011 at 15:14, ian douglas wrote: > On 08/01/2011 03:05 PM, Mike Nickey wrote: >> >> Hi all, >> >> I'm trying to access and use specific items within a dictionary that >> is returned but am having issues in doing so. >> [{'city': 'Sunnyvale', 'region_name': 'CA', 'area_code': 408, >> 'metro_code': 'Santa Clara, CA', 'country_name': 'United States'}] >> >> How can I populate a list of many different returns so that I have a >> list that contains all the cities and in line with the item that is >> referenced. >> >> The first step is to populate the list unsorted as it needs to be in >> correlation to the item that it came from. >> Thanks for your help. >> > > > Could you give us examples of what you want the list to look like? It will > help us direct you to an answer. > -- ~MEN _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From mnickey at gmail.com Tue Aug 2 02:34:39 2011 From: mnickey at gmail.com (Mike Nickey) Date: Mon, 1 Aug 2011 17:34:39 -0700 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: <1465184567-1312244887-cardhu_decombobulator_blackberry.rim.net-1333901828-@b1.c28.bise6.blackberry> References: <4E372552.9050702@iandouglas.com> <1465184567-1312244887-cardhu_decombobulator_blackberry.rim.net-1333901828-@b1.c28.bise6.blackberry> Message-ID: Thank you all, I have found the assistance needed and the guidance here was wonderful. I needed to add a line in the middle that did a temporary storage for me before trying to append this to the list. It might not be the most elegant solution but it works. On Mon, Aug 1, 2011 at 17:28, wrote: > Dictionaries are objects and you access their attributes through keys. > > So, let's say I had a dict: d = {'city':'plattsburgh'} > > I would thus access the attribute by doing this > > d['city'] > > You can store that value to a variable > > Or you can append to a list directly. > > l = [] > > for d in yourdict: > ? ? l.append(d['city']) > > > Sent from my Verizon Wireless BlackBerry > > -----Original Message----- > From: Mike Nickey > Sender: tutor-bounces+eire1130=gmail.com at python.org > Date: Mon, 1 Aug 2011 15:26:32 > To: ian douglas > Cc: > Subject: Re: [Tutor] Accessing Specific Dictionary items > > The input being used is through pygeoip. > Using this I am pulling the data by IP and from what I am reading this > populates as a dictionary. > > Here is some of the output that I can show currently > [{'city': 'Buena Park', 'region_name': 'CA', 'area_code': 714}, > {'city': 'Wallingford', 'region_name': 'CT', 'area_code': 203}, > {'city': 'Schenectady', 'region_name': 'NY', 'area_code': 518}, > {'city': 'Athens', 'region_name': '35'}] > > I'd like to have an output similar to this: > 'Buena Park', 'Wallingford', 'Schenectady','Athens' pulled by the > "city" keys that are used in the returns. I think the easiest way to > approach this would be simply to use the .append and populate a list > but I don't know how to pull an item by key value from the dictionary > returns. > > I hope this helps clear some confusion and thanks in advance. > > > On Mon, Aug 1, 2011 at 15:14, ian douglas wrote: >> On 08/01/2011 03:05 PM, Mike Nickey wrote: >>> >>> Hi all, >>> >>> I'm trying to access and use specific items within a dictionary that >>> is returned but am having issues in doing so. >>> [{'city': 'Sunnyvale', 'region_name': 'CA', 'area_code': 408, >>> 'metro_code': 'Santa Clara, CA', 'country_name': 'United States'}] >>> >>> How can I populate a list of many different returns so that I have a >>> list that contains all the cities and in line with the item that is >>> referenced. >>> >>> The first step is to populate the list unsorted as it needs to be in >>> correlation to the item that it came from. >>> Thanks for your help. >>> >> >> >> Could you give us examples of what you want the list to look like? It will >> help us direct you to an answer. >> > > > > -- > ~MEN > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- ~MEN From bgailer at gmail.com Tue Aug 2 03:36:24 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 01 Aug 2011 21:36:24 -0400 Subject: [Tutor] Accessing Specific Dictionary items In-Reply-To: References: <4E372552.9050702@iandouglas.com> <1465184567-1312244887-cardhu_decombobulator_blackberry.rim.net-1333901828-@b1.c28.bise6.blackberry> Message-ID: <4E375498.3010406@gmail.com> On 8/1/2011 8:34 PM, Mike Nickey wrote: [snip] > > [{'city': 'Buena Park', 'region_name': 'CA', 'area_code': 714}, > {'city': 'Wallingford', 'region_name': 'CT', 'area_code': 203}, > {'city': 'Schenectady', 'region_name': 'NY', 'area_code': 518}, > {'city': 'Athens', 'region_name': '35'}] IMHO this is overkill. Consider instead using City-Region as the key and storing the pther attributes in a tuple. There is no need to have separate dictionaries or lots of repetitive keys: cities = { 'Buena Park CA': (414, 'Santa Clara, CA'), 'Wallingford'CT: (203),...} -- Bob Gailer 919-636-4239 Chapel Hill NC From kliateni at gmail.com Tue Aug 2 13:45:15 2011 From: kliateni at gmail.com (Karim) Date: Tue, 02 Aug 2011 13:45:15 +0200 Subject: [Tutor] Please code review. Message-ID: <4E37E34B.5080707@gmail.com> Hello, I need a generator to create the cellname in a excell (using pyuno) document to assign value to the correct cell. The following code does this but do you have some optimizations on it, for instance to get the alphabetic chars instead of hard-coding it. Cheers karim Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def _xrange_cellnames(rows, cols): ... """Internal iterator function to compute excell table cellnames.""" ... cellnames = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ... for row in xrange(1, rows+1): ... for char in cellnames.replace('', ' ').split()[:cols]: ... yield char + str(row) ... >>> list( _xrange_cellnames(rows=3,cols=4)) ['A1', 'B1', 'C1', 'D1', 'A2', 'B2', 'C2', 'D2', 'A3', 'B3', 'C3', 'D3'] From kliateni at gmail.com Tue Aug 2 14:53:38 2011 From: kliateni at gmail.com (Karim) Date: Tue, 02 Aug 2011 14:53:38 +0200 Subject: [Tutor] Please code review. In-Reply-To: References: <4E37E34B.5080707@gmail.com> <4E37EF35.2080403@gmail.com> Message-ID: <4E37F352.1090208@gmail.com> Thanks Martin, This is the generator expression version. I can use both function generator or generator expression version correction. Cheers Karim On 08/02/2011 02:47 PM, Martin Gracik wrote: > def get_cellnames2(rows, cols): > rows = range(1, rows + 1) > cols = string.ascii_uppercase[:cols] > return ('%s%s' % (col, row) for row in rows for col in cols) From paul at subsignal.org Tue Aug 2 14:04:45 2011 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Tue, 02 Aug 2011 14:04:45 +0200 Subject: [Tutor] Please code review. In-Reply-To: <4E37E34B.5080707@gmail.com> References: <4E37E34B.5080707@gmail.com> Message-ID: Am 02.08.2011 13:45, schrieb Karim: > > Hello, > > I need a generator to create the cellname in a excell (using pyuno) > document to assign value to > the correct cell. The following code does this but do you have some > optimizations > on it, for instance to get the alphabetic chars instead of hard-coding it. you can use: import string cellnames = string.ascii_uppercase not sure why you need the .replace().split() stuff... def _xrange_cellnames(rows, cols): cellnames = string.ascii_uppercase for row in xrange(1, rows+1): for char in cellnames[:rows]: yield char + str(row) cheers Paul > > Cheers > karim > > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> def _xrange_cellnames(rows, cols): > ... """Internal iterator function to compute excell table cellnames.""" > ... cellnames = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > ... for row in xrange(1, rows+1): > ... for char in cellnames.replace('', ' ').split()[:cols]: > ... yield char + str(row) > ... > >>> list( _xrange_cellnames(rows=3,cols=4)) > ['A1', 'B1', 'C1', 'D1', 'A2', 'B2', 'C2', 'D2', 'A3', 'B3', 'C3', 'D3'] > > From kliateni at gmail.com Tue Aug 2 16:19:05 2011 From: kliateni at gmail.com (Karim) Date: Tue, 02 Aug 2011 16:19:05 +0200 Subject: [Tutor] Please code review. In-Reply-To: References: <4E37E34B.5080707@gmail.com> <4E37F1D2.2090505@gmail.com> Message-ID: <4E380759.2020709@gmail.com> On 08/02/2011 03:59 PM, Peter Otten wrote: > Karim wrote: > >> values = ( (22.5,21.5,121.5), >> (5615.3,615.3,-615.3), >> (-2315.7,315.7,415.7) ) >> >> it = _xrange_cellnames(rows=len(value), cols=len(values[0])) >> >> table.getCellByName(it.next()).setValue(22.5) >> table.getCellByName(it.next()).setValue(5615.3) >> table.getCellByName(it.next()).setValue(-2315.7) > Some googling suggests that there exists a getCellByPosition() method. With > that the above would become (untested): > > for x, column in enumerate(values): > for y, value in enumerate(column): > table.getCellByPosition(x, y).setValue(value) Thanks for the tip I will check com.sun.star.text.TextTable API. Regards Karim From tgande at cisco.com Tue Aug 2 17:40:12 2011 From: tgande at cisco.com (Thirupathaiah Gande (tgande)) Date: Tue, 2 Aug 2011 10:40:12 -0500 Subject: [Tutor] python 2.3.4, how to use os.system and collect it's output to a file. Message-ID: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> Hi, I have Python 2.3.4. I want to use os.system command and collect a command's output to a file. But it is not collecting all the output. It is truncating.. Code is as below. cmd = "%s rl -comp %s@%s/%d >> %s" % (C_CMD, i, branch, x, temp_acme_rl_log) cmd_res = os.system( cmd ) What I am missing? Thanks gande -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Tue Aug 2 19:10:37 2011 From: timomlists at gmail.com (Timo) Date: Tue, 02 Aug 2011 19:10:37 +0200 Subject: [Tutor] python 2.3.4, how to use os.system and collect it's output to a file. In-Reply-To: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> References: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> Message-ID: <4E382F8D.8080503@gmail.com> On 02-08-11 17:40, Thirupathaiah Gande (tgande) wrote: > > Hi, > > I have Python 2.3.4. > Is there some reason for this? You probably should update to 2.7 if possible. Then have a look at the Subprocess module documentation. There are some examples which should get you on the way. Cheers, Timo > I want to use os.system command and collect a command?s output to a > file. But it is not collecting all the output. It is truncating.. > > Code is as below. > > cmd = "%s rl -comp %s@%s/%d >> %s" % (C_CMD, i, branch, x, > temp_acme_rl_log) > > cmd_res = os.system( cmd ) > > What I am missing? > > Thanks > > gande > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Aug 2 19:14:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Aug 2011 18:14:47 +0100 Subject: [Tutor] python 2.3.4, how to use os.system and collect it's output to a file. In-Reply-To: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> References: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> Message-ID: <4E383087.9080900@btinternet.com> On 02/08/11 16:40, Thirupathaiah Gande (tgande) wrote: > I want to use os.system command and collect a command?s output to a > file. But it is not collecting all the output. It is truncating.. no its not truncating anything, it is returning the exit code of the command, because thats what os.system does. You need to look at the Subprocess module to read/write to processes. The documentation shows many examples of usage, but if you have specific problems come back here. HTH, Alan G. From thudfoo at gmail.com Tue Aug 2 23:25:25 2011 From: thudfoo at gmail.com (xDog Walker) Date: Tue, 2 Aug 2011 14:25:25 -0700 Subject: [Tutor] python 2.3.4, how to use os.system and collect it's output to a file. In-Reply-To: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> References: <8BE8E0EE9AC921429C09E8EBF7EFB56B043BEBF5@XMB-RCD-208.cisco.com> Message-ID: <201108021425.25782.thudfoo@gmail.com> On Tuesday 2011 August 02 08:40, Thirupathaiah Gande (tgande) wrote: > Hi, > > > > I have Python 2.3.4. > > I want to use os.system command and collect a command's output to a > file. But it is not collecting all the output. It is truncating.. > > > > Code is as below. > > > > cmd = "%s rl -comp %s@%s/%d >> %s" % (C_CMD, i, branch, x, > temp_acme_rl_log) > > cmd_res = os.system( cmd ) > > > > What I am missing? > The stdlib has the commands module just for this sort of thing if your OS is Unix. -- I have seen the future and I am not in it. From thisisonlyatest at gmx.com Wed Aug 3 02:47:10 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Tue, 02 Aug 2011 20:47:10 -0400 Subject: [Tutor] When to use def __init__ when making a class? Message-ID: <4E389A8E.1000008@gmx.com> I have two questions: 1) When should I use "def __init__(self):" when I create a class? 2) Would these two classes have the same effect? class Name: def __init__(self): man = Marcus woman = Jasmine return self.man, self.woman class Name: man = Marcus woman = Jasmine return man, woman From swiftone at swiftone.org Wed Aug 3 03:09:01 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 2 Aug 2011 21:09:01 -0400 Subject: [Tutor] When to use def __init__ when making a class? In-Reply-To: <4E389A8E.1000008@gmx.com> References: <4E389A8E.1000008@gmx.com> Message-ID: On Tue, Aug 2, 2011 at 8:47 PM, brandon w wrote: > 1) ?When should I use "def __init__(self):" when I create a class? When you have any initialization to do. (in other words, when you want class instantiation to do more than simply give you an instance of the class. > 2) ?Would these two classes have the same effect? Neither of these two classes compile. You should try what you are asking before asking, it will lead you to better questions. Your examples show some misunderstanding about Python classes. 1) an __init__ method shouldn't return anything. The Class construction call will already return an instance of the class, __init__ is just about initialization. 2) A class definition likewise has no return value. 3) In your examples, Marcus and Jasmine are either intended to be strings (and should be quoted), or are variables you didn't provide. Here, try running these examples and see what you can figure out. Experiment with them a little, then come back with questions on what you observe. class Name: def __init__(self): self.man = "Marcus" self.woman = "Jasmine" instance = Name() print instance.man # Python 3 will use a different print syntax class Name: pass instance = Name() instance.man = "Fred" print instance.man -- Brett Ritter / SwiftOne swiftone at swiftone.org From steve at pearwood.info Wed Aug 3 03:25:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 03 Aug 2011 11:25:33 +1000 Subject: [Tutor] When to use def __init__ when making a class? In-Reply-To: <4E389A8E.1000008@gmx.com> References: <4E389A8E.1000008@gmx.com> Message-ID: <4E38A38D.6020905@pearwood.info> brandon w wrote: > I have two questions: > > 1) When should I use "def __init__(self):" when I create a class? Whenever you need something to happen when you create an instance. > 2) Would these two classes have the same effect? Technically, no, but in practice, you would find it hard to see the difference for the example given. But for slightly different examples, the difference would be astonishing. > class Name: > def __init__(self): > man = Marcus > woman = Jasmine > return self.man, self.woman Did you try the code before posting it? Three problems with it: (1) Firstly, Marcus and Jasmine are not built-in Python commands, so trying to execute man = Marcus raises NameError. You need to use quotation marks to turn it into a string. (2) Fixing that problem, man = "Marcus" doesn't do what you expect either, because it creates a local variable man and not an attribute. (3) Last but not least, the return result of __init__ is ignored, so even though you try to return self.man and self.women, nothing happens. Also, calling the class "Name" is a bad idea, because it doesn't have anything to do with what the class actually holds, which is a *pair* of names, one male and one female. This code should be written as: class Couple: def __init__(self): self.man = "Marcus" self.woman = "Jasmine" This creates a class where every instance has its own independent attributes man and woman. > class Name: > man = Marcus > woman = Jasmine > return man, woman Again, did you try this? If you did, you would discover it raises SyntaxError: you can't include a return statement inside a class, because it is meaningless. SyntaxError: 'return' outside function This should be written as class Couple: man = "Marcus" woman = "Jasmine" This creates a class where every instance shares the same pair of attributes. In this example, the difference is not very great, because strings cannot be modified in place. If you try to store a new value for the attribute, Python defaults to creating an independent instance attribute rather than changing the shared class attribute. Here is an example that may help show the difference: class TestAttributes: a = [1, 2, 3] # Shared, and mutable. def __init__(self): self.b = [1, 2, 3] # Not shared. Now, using this: >>> x = TestAttributes() # Create a new instance. >>> y = TestAttributes() # And another one. >>> >>> x.a [1, 2, 3] >>> y.a [1, 2, 3] >>> x.a.append(42) # Modify the SHARED list. >>> y.a # And all instances see the change! [1, 2, 3, 42] >>> >>> x.b [1, 2, 3] >>> x.b.append(999) # Modify the non-shared list. >>> x.b [1, 2, 3, 999] >>> y.b # Other instances are unchanged. [1, 2, 3] -- Steven From rdmoores at gmail.com Wed Aug 3 04:36:39 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 2 Aug 2011 19:36:39 -0700 Subject: [Tutor] Puzzled again Message-ID: Puzzled again. Why the error. Line 36 is the line just above "import os.path". I have many other functions in mycalc.py with examples formatted exactly the same way. def convertPath(path): ? ? """ ? ? Given a path with backslashes, return that path with forward slashes. ? ? By Steven D'Aprano ?07/31/2011 on Tutor list ? ? >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' ? ? >>> convertPath(path) ? ? 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' ? ? """ ? ? import os.path ? ? separator = os.path.sep ? ? if separator != '/': ? ? ? ? path = path.replace(os.path.sep, '/') ? ? return path >>> from mycalc import convertPath Traceback (most recent call last): ? File "", line 36, in Syntax Error: """: c:\Python32\lib\site-packages\mycalc.py, line 36-1 >>> What solved the problem and what didn't: This doesn't work: def convertPath(path): ? ? """ ? ? Given a path with backslashes, return that path with forward slashes. ? ? By Steven D'Aprano ?07/31/2011 on Tutor list ? ? >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' ? ? >>> convertPath(path) ? ? #'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' ? ? """ ? ? import os.path ? ? separator = os.path.sep ? ? if separator != '/': ? ? ? ? path = path.replace(os.path.sep, '/') ? ? return path Nor this: def convertPath(path): ? ? """ ? ? Given a path with backslashes, return that path with forward slashes. ? ? By Steven D'Aprano ?07/31/2011 on Tutor list ? ? #>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' ? ? #>>> convertPath(path) ? ? #'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' ? ? """ ? ? import os.path ? ? separator = os.path.sep ? ? if separator != '/': ? ? ? ? path = path.replace(os.path.sep, '/') ? ? return path But this does: def convertPath(path): ? ? """ ? ? Given a path with backslashes, return that path with forward slashes. ? ? By Steven D'Aprano ?07/31/2011 on Tutor list ? ? """ ? ? #>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' ? ? #>>> convertPath(path) ? ? #'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' ? ? import os.path ? ? separator = os.path.sep ? ? if separator != '/': ? ? ? ? path = path.replace(os.path.sep, '/') ? ? return path Thanks, Dick Moores From redacted@example.com Wed Aug 3 04:44:35 2011 From: redacted@example.com (Alexander Quest) Date: Tue, 2 Aug 2011 19:44:35 -0700 Subject: [Tutor] Indexing a list with nested tuples Message-ID: Hi guys- I'm having a problem with a list that has nested tuples: attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), ("dexterity", 0)] I've defined the list above with 4 items, each starting with a value of 0. The player enters how many points he or she wants to add to a given item. The selection menu is 1 - strength; 2 - health; 3 - wisdom; 4- dexterity. So the "selection" variable is actually 1 more than the index location of the intended item. So I have the following code: print("Added ", points, "to ", attributes[selection-1][0], "attribute.") My intent with this is to say that I've added this many points (however many) to the corresponding item in the list. So if the player selects "1", then selection = 1, but I subtract 1 from that (selection -1) to get the index value of that item in the list (in this case 0). Then I have [0] to indicate that I want to go to the second value within that first item, which is the point value. I get an error saying that list indices must be integers, not strings. I get a similar error even if I just put attributes[selection][0] without the minus 1. Also, it seems that the tuple within the list cannot be modified directly, so I can't add points to the original value of "0" that all 4 items start with. Is there a way to keep this nested list with tuples but be able to modify the point count for each item, or will it be better to create a dictionary or 2 separate lists (1 for the names "Strength, Health, Wisdom, Dexterity" and one for their starting values "0,0,0,0")? Any suggestions/help will be greatly appreciated!!! -Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Aug 3 05:26:50 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 02 Aug 2011 23:26:50 -0400 Subject: [Tutor] Indexing a list with nested tuples In-Reply-To: References: Message-ID: <4E38BFFA.6090600@gmail.com> On 8/2/2011 10:44 PM, Alexander Quest wrote: > Hi guys- I'm having a problem with a list that has nested tuples: > > attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), > ("dexterity", 0)] > > I've defined the list above with 4 items, each starting with a value > of 0. The player > enters how many points he or she wants to add to a given item. The > selection menu > is 1 - strength; 2 - health; 3 - wisdom; 4- dexterity. So the > "selection" variable is actually > 1 more than the index location of the intended item. So I have the > following code: > > print("Added ", points, "to ", attributes[selection-1][0], "attribute.") > > My intent with this is to say that I've added this many points > (however many) to the > corresponding item in the list. So if the player selects "1", then > selection = 1, but I subtract > 1 from that (selection -1) to get the index value of that item in the > list (in this case 0). Then I > have [0] to indicate that I want to go to the second value within that > first item, which is the > point value. I get an error saying that list indices must be integers, > not strings. I get a similar > error even if I just put attributes[selection][0] without the minus 1. > > Also, it seems that the tuple within the list cannot be modified > directly, so I can't add points to the original value of "0" that all > 4 items start with. Is there a way to keep this nested list with > tuples but be able to modify the point count for each item, or will it > be better to create a dictionary or 2 separate lists (1 for the names > "Strength, Health, Wisdom, Dexterity" and one > for their starting values "0,0,0,0")? Any suggestions/help will be > greatly appreciated!!! Thanks for inquiring. Some guidelines about questions: 1 - show us more code. in this case specifically how you obtain user input. 2 - show the complete traceback What does the error message tell you? Why would selection be a string rather than an integer? This has to do with how you obtain selection from the user. What Why did you expect to be able to alter the value of a tuple element? Tuples are immutable! Use a list instead. HTH -- Bob Gailer 919-636-4239 Chapel Hill NC From emekamicro at gmail.com Wed Aug 3 06:25:43 2011 From: emekamicro at gmail.com (Emeka) Date: Wed, 3 Aug 2011 05:25:43 +0100 Subject: [Tutor] Python scripts into executable Windows programss Message-ID: Hello All, I would want to convert Python scripts into executable Windows programs. I have already checked out py2exe, it seems like they support only Python 2.5. Mine is Python 2.7.7. Could anyone here help me out on this issue? ? Regards, Emeka -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Aug 3 06:59:51 2011 From: d at davea.name (Dave Angel) Date: Wed, 03 Aug 2011 00:59:51 -0400 Subject: [Tutor] Puzzled again In-Reply-To: References: Message-ID: <4E38D5C7.4090600@davea.name> On 08/02/2011 10:36 PM, Richard D. Moores wrote: > Puzzled again. Why the error. Line 36 is the line just above "import > os.path". I have many other functions in mycalc.py with examples > formatted exactly the same way. > > def convertPath(path): > """ > Given a path with backslashes, return that path with forward slashes. > > By Steven D'Aprano 07/31/2011 on Tutor list > >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' > >>> convertPath(path) > 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' > """ > import os.path > separator = os.path.sep > if separator != '/': > path = path.replace(os.path.sep, '/') > return path > >>>> from mycalc import convertPath > Traceback (most recent call last): > File "", line 36, in > Syntax Error: """: c:\Python32\lib\site-packages\mycalc.py, line 36-1 >>>> def convertPath(path): >>>> """ >>>> Given a path with backslashes, return that path with forward slashes. >>>> >>>> By Steven D'Aprano 07/31/2011 on Tutor list >>>> >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>>> >>> convertPath(path) >>>> 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' >>>> """ >>>> import os.path >>>> separator = os.path.sep >>>> if separator != '/': >>>> path = path.replace(os.path.sep, '/') When I paste that from your email into a file and run Python 2.7 on it, it behaves fine with no errors. That's in Linux. But the easiest explanation is that you perhaps used a funny character for your triple-quotes. And when you retyped them on a new line, you typed regular ones. For example, I've seen that sort of thing when someone wrote code in a Windows word processor that had "smart quotes." -- DaveA From qbits143 at gmail.com Wed Aug 3 07:08:18 2011 From: qbits143 at gmail.com (Ajith Gopinath) Date: Wed, 3 Aug 2011 10:38:18 +0530 Subject: [Tutor] python Module for Windows Active Directory In-Reply-To: <4E317A17.7060400@timgolden.me.uk> References: <067dbba75d8eba4cbfb7563a7cbcdd86@win-w8> <4E317A17.7060400@timgolden.me.uk> Message-ID: Sure Tim. Thanks for your help. Thanks and Regards Ajith Gopinath On Thu, Jul 28, 2011 at 8:32 PM, Tim Golden wrote: > On 28/07/2011 07:28, qbits143 at gmail.com wrote: > >> Hi, >> >> Which is the best package/module in Python to work with Windows Active >> Directory? >> >> I may need to create multiple OUs, set different users and computers and >> fill their individual attributes. Later i may need to modify/delete and >> then may need to check them for its availability. >> > > You could try my active_directory module: > > http://timgolden.me.uk/python/**active_directory.html > > although there's a much-improved version in development > (and actively used here at work). If you're interested, > look at: > > http://svn.timgolden.me.uk/**active_directory/branches/**rework/ > > TJG > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Aug 3 07:40:19 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 03 Aug 2011 07:40:19 +0200 Subject: [Tutor] Python scripts into executable Windows programss In-Reply-To: References: Message-ID: <4E38DF43.2040708@compuscan.co.za> On 2011/08/03 06:25 AM, Emeka wrote: > Hello All, > > I would want to convert Python scripts into executable Windows > programs. I have already checked out py2exe, it seems like they > support only Python 2.5. Mine is Python 2.7.7. Could anyone here help > me out on this issue? > ? > > Regards, > Emeka -- > /Satajanus Nig. Ltd > > > / > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor They do have support for Python 2.7, it's just the "latest version" on SF is listed as Py2.5 64bit. http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/ -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Wed Aug 3 08:07:01 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 2 Aug 2011 23:07:01 -0700 Subject: [Tutor] Puzzled again In-Reply-To: <4E38D5C7.4090600@davea.name> References: <4E38D5C7.4090600@davea.name> Message-ID: On Tue, Aug 2, 2011 at 21:59, Dave Angel wrote: > When I paste that from your email into a file and run Python 2.7 on it, it > behaves fine with no errors. ?That's in Linux. I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev 24721), Windows Vista, and Python 3.2.1. > But the easiest explanation is that you perhaps used a funny character for > your triple-quotes. ?And when you retyped them on a new line, you typed > regular ones. > > For example, I've seen that sort of thing when someone wrote code in a > Windows word processor that had "smart quotes." No, no funny characters with Wing. Thanks for your guess, Dave. But here's a try using the regular command line: C:\Windows\System32>python Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from mycalc import convertPath Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc.py", line 36 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 149-151: truncated \UXXXXXXX X escape >>> Dick From andreengels at gmail.com Wed Aug 3 08:39:54 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 3 Aug 2011 08:39:54 +0200 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> Message-ID: On Wed, Aug 3, 2011 at 8:07 AM, Richard D. Moores wrote: > On Tue, Aug 2, 2011 at 21:59, Dave Angel wrote: > > > When I paste that from your email into a file and run Python 2.7 on it, > it > > behaves fine with no errors. That's in Linux. > > I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev > 24721), Windows Vista, and Python 3.2.1. > > > But the easiest explanation is that you perhaps used a funny character > for > > your triple-quotes. And when you retyped them on a new line, you typed > > regular ones. > > > > For example, I've seen that sort of thing when someone wrote code in a > > Windows word processor that had "smart quotes." > > No, no funny characters with Wing. > > Thanks for your guess, Dave. > > But here's a try using the regular command line: > > C:\Windows\System32>python > Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit > (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from mycalc import convertPath > Traceback (most recent call last): > File "", line 1, in > File "C:\Python32\lib\site-packages\mycalc.py", line 36 > """ > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes > in position 149-151: truncated \UXXXXXXX > X escape > >>> > That says that there is some character in that line that is not valid Unicode. Remove the line (and perhaps the ones above and below it at the same time, in case it's around the line feed character(s)) and type it in again. It's likely to be as easy as that. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Wed Aug 3 09:04:12 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 3 Aug 2011 12:34:12 +0530 Subject: [Tutor] Python scripts into executable Windows programss In-Reply-To: References: Message-ID: For a seamless application development experience, you may want to consider these steps. 1. Use Eclipse-pydev to write your scripts 2. Use py2exe to convert into executable programs 3. Use Inno setup to create installers There is support for 2.6 and 2.7 with Python. Please see the news page - http://www.py2exe.org/index.cgi/News Hope this helps. Thanks and Regards, Sumod On Wed, Aug 3, 2011 at 9:55 AM, Emeka wrote: > Hello All, > > I would want to convert Python scripts into executable Windows programs. > I have already checked out py2exe, it seems like they support only Python > 2.5. Mine is Python 2.7.7. Could anyone here help me out on this issue? > ? > > Regards, > Emeka -- > *Satajanus Nig. Ltd > > > * > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Aug 3 09:12:54 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Aug 2011 09:12:54 +0200 Subject: [Tutor] Indexing a list with nested tuples References: Message-ID: Alexander Quest wrote: > Hi guys- I'm having a problem with a list that has nested tuples: > > attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), > ("dexterity", 0)] > > I've defined the list above with 4 items, each starting with a value of 0. > The player > enters how many points he or she wants to add to a given item. The > selection menu > is 1 - strength; 2 - health; 3 - wisdom; 4- dexterity. So the "selection" > variable is actually > 1 more than the index location of the intended item. So I have the > following code: > > print("Added ", points, "to ", attributes[selection-1][0], "attribute.") > > My intent with this is to say that I've added this many points (however > many) to the > corresponding item in the list. So if the player selects "1", then > selection = 1, but I subtract > 1 from that (selection -1) to get the index value of that item in the list > (in this case 0). Then I > have [0] to indicate that I want to go to the second value within that > first item, which is the > point value. I get an error saying that list indices must be integers, not > strings. I get a similar > error even if I just put attributes[selection][0] without the minus 1. > > Also, it seems that the tuple within the list cannot be modified directly, > so I can't add points to the original value of "0" that all 4 items start > with. Is there a way to keep this nested list with > tuples but be able to modify the point count for each item, or will it be > better to create a dictionary or 2 separate lists (1 for the names > "Strength, Health, Wisdom, Dexterity" and one > for their starting values "0,0,0,0")? Any suggestions/help will be greatly > appreciated!!! [I'm assuming you are using Python 3. If not replace input() with raw_input()] Let's investigate what happens when you enter an attribute index: >>> attribute_index = input("Choose attribute ") Choose attribute 2 >>> attribute_index '2' Do you note the '...' around the number? >>> attribute_index -= 1 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for -=: 'str' and 'int' It's actually a string, not an integer; therefore you have to convert it to an integer before you can do any math with it: >>> attribute_index = int(attribute_index) >>> attribute_index 2 >>> attribute_index -= 1 >>> attribute_index 1 Now let's try to change the second tuple: >>> attributes = [ ... ("strength", 0), ("health", 0), ("wisdom", 0), ("dexterity", 0)] >>> attributes[attribute_index] ('health', 0) >>> attributes[attribute_index][1] += 42 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment The error message is pretty clear, you cannot replace items of a tuple. You can either to switch to nested lists [["strength", 0], ["health", 0], ...] or replace the entire tuple with a new one: >>> name, value = attributes[attribute_index] >>> attributes[attribute_index] = name, value + 42 >>> attributes [('strength', 0), ('health', 42), ('wisdom', 0), ('dexterity', 0)] However, I think the pythonic way is to use a dictionary. If you want the user to input numbers you need a second dictionary to translate the numbers into attribute names: >>> attributes = dict(attributes) >>> lookup = {1: "strength", 2: "health", 3: "wisdom", 4: "dexterity"} >>> while True: ... index = input("index ") ... if not index: break ... amount = int(input("amount ")) ... name = lookup[int(index)] ... attributes[name] += amount ... index 1 amount 10 index 2 amount 20 index 3 amount 10 index 2 amount -100 index >>> attributes {'dexterity': 0, 'strength': 10, 'health': -38, 'wisdom': 10} Personally I would ask for attribute names directly. From d at davea.name Wed Aug 3 09:17:22 2011 From: d at davea.name (Dave Angel) Date: Wed, 03 Aug 2011 03:17:22 -0400 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> Message-ID: <4E38F602.8040404@davea.name> On 08/03/2011 02:07 AM, Richard D. Moores wrote: > On Tue, Aug 2, 2011 at 21:59, Dave Angel wrote: > >> When I paste that from your email into a file and run Python 2.7 on it, it >> behaves fine with no errors. That's in Linux. > > I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev > 24721), Windows Vista, and Python 3.2.1. > >> But the easiest explanation is that you perhaps used a funny character for >> your triple-quotes. And when you retyped them on a new line, you typed >> regular ones. >> >> For example, I've seen that sort of thing when someone wrote code in a >> Windows word processor that had "smart quotes." > > No, no funny characters with Wing. > > Thanks for your guess, Dave. > > But here's a try using the regular command line: > > C:\Windows\System32>python > Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit > (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> from mycalc import convertPath > Traceback (most recent call last): > File "", line 1, in > File "C:\Python32\lib\site-packages\mycalc.py", line 36 > """ > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes > in position 149-151: truncated \UXXXXXXX > X escape >>>> > > Dick > OK, so it's no longer a guess, it's a certainty. You can't get that error unless you have a non-ASCII character there. So take a look at the file with a hex viewer, and look at offset 149. Somewhere there's a character above hex 7f -- DaveA From emekamicro at gmail.com Wed Aug 3 09:22:12 2011 From: emekamicro at gmail.com (Emeka) Date: Wed, 3 Aug 2011 08:22:12 +0100 Subject: [Tutor] Python scripts into executable Windows programss In-Reply-To: References: Message-ID: Sumod, Thanks so much ... I was also looking for something like Inno. Emeka On Wed, Aug 3, 2011 at 8:04 AM, wrote: > For a seamless application development experience, you may want to consider > these steps. > 1. Use Eclipse-pydev to write your scripts > 2. Use py2exe to convert into executable programs > 3. Use Inno setup to create installers > > There is support for 2.6 and 2.7 with Python. Please see the news page - > http://www.py2exe.org/index.cgi/News > > Hope this helps. > > Thanks and Regards, > Sumod > > > On Wed, Aug 3, 2011 at 9:55 AM, Emeka wrote: > >> Hello All, >> >> I would want to convert Python scripts into executable Windows programs. >> I have already checked out py2exe, it seems like they support only Python >> 2.5. Mine is Python 2.7.7. Could anyone here help me out on this issue? >> ? >> >> Regards, >> Emeka -- >> *Satajanus Nig. Ltd >> >> >> * >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > http://spawgi.wordpress.com > We can do it and do it better. > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From mrinalini at edss.co.in Wed Aug 3 08:52:17 2011 From: mrinalini at edss.co.in (mrinalini at edss.co.in) Date: Wed, 03 Aug 2011 12:22:17 +0530 Subject: [Tutor] Dynamically linking python into my vc project - help required Message-ID: Hi, I am trying to embed python into my MFC application. I have done this before by statically linking to the python lib. But I want to change this now. The idea is to take the information from the registry for the installed version of python on the target machine. Then load python using loadlibrary call and use the functions from python using pointers to functions returned by GetProcAddress . For example - hModPython = AfxLoadLibrary("Python23.dll"); pFnPyRun_SimpleString *pFunction = NULL; pFnPy_Initialize *pPy_Initialize = NULL; pFunction = (pFnPyRun_SimpleString *)::GetProcAddress(hModPython, "PyRun_SimpleString"); pPy_Initialize = (pFnPy_Initialize *)::GetProcAddress(hModPython, "Py_Initialize"); try { pPy_Initialize(); if ( pFunction ) { (*pFunction)("import sys"); // call the code } else { AfxMessageBox("unable to access function from python23.dll.", MB_ICONSTOP|MB_OK); } } catch(...) { } And then I want to execute a python script through my MFC application - HANDLE hFile = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); DWORD dwSize = GetFileSize(hFile, NULL); DWORD dwRead; char *s = new char[dwSize +1]; ReadFile(hFile, s, dwSize, &dwRead, NULL); s[dwSize] = '\0'; CString wholefile(s); wholefile.Remove('\r'); wholefile+="\n"; CloseHandle(hFile); pFnPy_CompileString *pFPy_CompileString = (pFnPy_CompileString *)::GetProcAddress(hModPython, "Py_CompileString"); CString fl(file); PyObject* pCodeObject = pFPy_CompileString(wholefile.GetBuffer(0), fl.GetBuffer(0), Py_file_input); if (pCodeObject != NULL) { pFnPyEval_EvalCode *pFPyEval_EvalCode = (pFnPyEval_EvalCode *)::GetProcAddress(hModPython, "PyEval_EvalCode"); PyObject* pObject = pFPyEval_EvalCode((PyCodeObject*)pCodeObject, m_Dictionary, m_Dictionary); } I am facing two problems here , though I want to link to python dynamically I am required to include python.h for my code to compile the following declaration. PyObject* pCodeObject I tried copying some of the python definitions including PyObject into a header in my mfc app. Then it complies fine. but Py_CompileString call fails. so finally I am unable to run script from my MFC application by linking to python dynamically. How can this be done ? Please help. Is there a different approach to linking to python dynamically. Please could you write to me ? Thanks in advance, Mrinalini From alan.gauld at btinternet.com Wed Aug 3 10:11:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Aug 2011 09:11:18 +0100 Subject: [Tutor] Dynamically linking python into my vc project - help required In-Reply-To: References: Message-ID: <4E3902A6.8020001@btinternet.com> On 03/08/11 07:52, mrinalini at edss.co.in wrote: > Hi, > > I am trying to embed python into my MFC application. I have done this > before by statically linking to the python lib. But I want to change > this now. Hi, this mailing list is really for people trying to learn Python. This question is way more advanced than that! While you might get a reply here you will probably have more success on the main Python mailing list or even on the Python Windows list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Aug 3 10:45:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 03 Aug 2011 18:45:40 +1000 Subject: [Tutor] Puzzled again In-Reply-To: References: Message-ID: <4E390AB4.6000400@pearwood.info> Richard D. Moores wrote: > Puzzled again. Why the error. Line 36 is the line just above "import > os.path". I have many other functions in mycalc.py with examples > formatted exactly the same way. > > def convertPath(path): > """ > Given a path with backslashes, return that path with forward slashes. > > By Steven D'Aprano 07/31/2011 on Tutor list > >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' Are you aware that this is not a raw string? It's wrapped inside another non-raw string, so it is merely a sub-string containing the letters r single-quote C colon backslash-U etc. Now, as it turns out, backslash-U and friends don't have any special meanings, so it will work fine, but that's an accident of the characters in the path. If it were backslash-n (say) instead, things would be different. (P.S. the docstring itself can be a raw string. Just start it with r""" instead of """.) > >>> convertPath(path) > 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' > """ > import os.path > separator = os.path.sep > if separator != '/': > path = path.replace(os.path.sep, '/') > return path > >>>> from mycalc import convertPath > Traceback (most recent call last): > File "", line 36, in > Syntax Error: """: c:\Python32\lib\site-packages\mycalc.py, line 36-1 Is this the actual traceback you received? I would expect that importing mycalc.py would be fine, but that trying to run doctest over it *may* play up, probably with a SyntaxError. It works fine for me when I paste your code directly into an interactive session, and the docstring looks as expected: >>> print(convertPath.__doc__) Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 on Tutor list >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' In general, expect to have fun and games getting doctests to do the right thing with backslashes. The interaction of doctests (which uses exec under the hood) and backslashes is rather ugly. But I don't know if that's the problem here. Other than that, I'm afraid I can't reproduce your error. Perhaps there is some invisible character in the original file, such as a DOS "End of File" ctrl-Z, which was messing things up for you, you've eventually, and accidentally, deleted it. Because there's nothing obvious to explain why you get the error you get, or why it goes away when it does. -- Steven From steve at pearwood.info Wed Aug 3 11:02:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 03 Aug 2011 19:02:34 +1000 Subject: [Tutor] Puzzled again In-Reply-To: <4E390AB4.6000400@pearwood.info> References: <4E390AB4.6000400@pearwood.info> Message-ID: <4E390EAA.3080501@pearwood.info> Steven D'Aprano wrote: > Richard D. Moores wrote: >> Puzzled again. Why the error. Line 36 is the line just above "import >> os.path". I have many other functions in mycalc.py with examples >> formatted exactly the same way. >> >> def convertPath(path): >> """ >> Given a path with backslashes, return that path with forward slashes. >> >> By Steven D'Aprano 07/31/2011 on Tutor list >> >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' > > Are you aware that this is not a raw string? It's wrapped inside another > non-raw string, so it is merely a sub-string containing the letters r > single-quote C colon backslash-U etc. Now, as it turns out, backslash-U > and friends don't have any special meanings, so it will work fine, but *slaps head* Doh! No, I was wrong. \U DOES have a special meaning. It introduces an eight-character unicode escape sequence, but only in unicode strings. >>> u'\Users\Dick' File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-2: truncated \UXXXXXXXX escape This fails because the \U is not followed by any valid hex digits. So in Python 3, you should expect a different syntax error. -- Steven From grigor.kolev at gmail.com Wed Aug 3 11:12:38 2011 From: grigor.kolev at gmail.com (=?UTF-8?Q?=D0=93=D1=80=D0=B8=D0=B3=D0=BE=D1=80_=D0=9A=D0=BE=D0=BB?= =?UTF-8?Q?=D0=B5=D0=B2?=) Date: Wed, 03 Aug 2011 12:12:38 +0300 Subject: [Tutor] Using .po translation file Message-ID: <1312362758.27079.44.camel@dedal-laptop> Hi. Some one help me. Haw can I use .po translation file for my program. cat = gettext.Catalog(domain, localedir) what should be domain From dextrous85 at gmail.com Wed Aug 3 11:18:15 2011 From: dextrous85 at gmail.com (vishwajeet singh) Date: Wed, 3 Aug 2011 14:48:15 +0530 Subject: [Tutor] Using .po translation file In-Reply-To: <1312362758.27079.44.camel@dedal-laptop> References: <1312362758.27079.44.camel@dedal-laptop> Message-ID: 2011/8/3 ?????? ????? > Hi. > Some one help me. > Haw can I use .po translation file for my program. > > cat = gettext.Catalog(domain, localedir) > what should be domain > Domain is usually the name of po file it defaults to django and djangojs in some cases. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Wed Aug 3 11:18:30 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 3 Aug 2011 02:18:30 -0700 Subject: [Tutor] Puzzled again In-Reply-To: <4E38F602.8040404@davea.name> References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: Ooooops! I accidentally erased convertPath() from mycalc.py while trying out various things. It was my only copy of convertPath that had the docstring as posted, so I went to my initial post and copy-and-pasted it into mycalc.py. Now no problem: from Wing's shell: Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] Type "help", "copyright", "credits" or "license" for more information. >>> from mycalc import convertPath >>> So I'm no longer able to try the various things suggested by you guys. 10 thousand apologies. Dick From steve at pearwood.info Wed Aug 3 11:20:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 03 Aug 2011 19:20:45 +1000 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> Message-ID: <4E3912ED.8070509@pearwood.info> Richard D. Moores wrote: > But here's a try using the regular command line: > > C:\Windows\System32>python > Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit > (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> from mycalc import convertPath > Traceback (most recent call last): > File "", line 1, in > File "C:\Python32\lib\site-packages\mycalc.py", line 36 > """ > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes > in position 149-151: truncated \UXXXXXXX > X escape Ha ha, well I'm gratified that my prediction of the error you would receive under Python 3 is correct, but it doesn't really solve your problem under Python 2.7. What happens when you import the code using the standard Python2.7 interactive interpreter? I would expect that the truncated \UXXXXXXXX error will go away. If you're still getting the earlier SyntaxError, I would open the file in a hex editor and see what's there. I expect that there's something unexpected and invisible. I've seen this happen sometimes when copying and pasting from websites. For reasons that I'm sure make sense to web designers who haven't given it any thought, some websites put non-breaking spaces into source code, which plays merry hell with copying and pasting it because it looks to the naked eye like a normal space but isn't. I've also seen ctrl-Z end of file characters in source code, another invisible to the naked eye thing. Or so-called "high-ASCII" bytes. If you get an error like this: SyntaxError: Non-ASCII character '\\xe2' in file script.py on line 21, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details that's your problem. I don't trust errors given by IDEs, because they often play games with the source code and sometimes give misleading error messages. Whenever you have mysterious syntax errors you can't explain, bypass the IDE and go straight to the standard Python interactive interpreter. (Make sure you use the same version though.) -- Steven From steve at pearwood.info Wed Aug 3 11:22:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 03 Aug 2011 19:22:58 +1000 Subject: [Tutor] Using .po translation file In-Reply-To: <1312362758.27079.44.camel@dedal-laptop> References: <1312362758.27079.44.camel@dedal-laptop> Message-ID: <4E391372.8010408@pearwood.info> ?????? ????? wrote: > Hi. > Some one help me. > Haw can I use .po translation file for my program. This is not a standard part of Python. Is this a django thing? You should ask on a django forum. -- Steven From grigor.kolev at gmail.com Wed Aug 3 11:44:22 2011 From: grigor.kolev at gmail.com (=?UTF-8?Q?=D0=93=D1=80=D0=B8=D0=B3=D0=BE=D1=80_=D0=9A=D0=BE=D0=BB?= =?UTF-8?Q?=D0=B5=D0=B2?=) Date: Wed, 03 Aug 2011 12:44:22 +0300 Subject: [Tutor] Using .po translation file In-Reply-To: References: <1312362758.27079.44.camel@dedal-laptop> Message-ID: <1312364662.1817.6.camel@dedal-laptop> I do not understand I have bg.po file And try the following. import gettext instance = gettext.GNUTranslations(open('bg.po')) IOError: [Errno 0] Bad magic number: 'bg.po' and this instance = gettext.Catalog('bg.po') IOError: [Errno 2] No translation file found for domain: 'bg.po' ? 14:48 +0530 ?? 03.08.2011 (??), vishwajeet singh ??????: > > > 2011/8/3 ?????? ????? > Hi. > Some one help me. > Haw can I use .po translation file for my program. > > cat = gettext.Catalog(domain, localedir) > what should be domain > > Domain is usually the name of po file it defaults to django and > djangojs in some cases. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Vishwajeet Singh > +91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com > Twitter: http://twitter.com/vishwajeets | LinkedIn: > http://www.linkedin.com/in/singhvishwajeet From grigor.kolev at gmail.com Wed Aug 3 11:50:12 2011 From: grigor.kolev at gmail.com (=?UTF-8?Q?=D0=93=D1=80=D0=B8=D0=B3=D0=BE=D1=80_=D0=9A=D0=BE=D0=BB?= =?UTF-8?Q?=D0=B5=D0=B2?=) Date: Wed, 03 Aug 2011 12:50:12 +0300 Subject: [Tutor] Using .po translation file In-Reply-To: <4E391372.8010408@pearwood.info> References: <1312362758.27079.44.camel@dedal-laptop> <4E391372.8010408@pearwood.info> Message-ID: <1312365012.1817.11.camel@dedal-laptop> Otherwise I can do translation system. But it will be in its own way with dictionaries and shelve. But it will be difficult if someone decides to translate. po has its own editor. ? 19:22 +1000 ?? 03.08.2011 (??), Steven D'Aprano ??????: > ?????? ????? wrote: > > Hi. > > Some one help me. > > Haw can I use .po translation file for my program. > > > This is not a standard part of Python. Is this a django thing? You > should ask on a django forum. > > > > From spawgi at gmail.com Wed Aug 3 11:50:06 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 3 Aug 2011 15:20:06 +0530 Subject: [Tutor] Dynamically linking python into my vc project - help required In-Reply-To: <4E3902A6.8020001@btinternet.com> References: <4E3902A6.8020001@btinternet.com> Message-ID: +1 to Alan on this. Also, you may want to try stackoverflow.com for this question. Thanks and Regards, Sumod On Wed, Aug 3, 2011 at 1:41 PM, Alan Gauld wrote: > On 03/08/11 07:52, mrinalini at edss.co.in wrote: > >> Hi, >> >> I am trying to embed python into my MFC application. I have done this >> before by statically linking to the python lib. But I want to change >> this now. >> > > Hi, this mailing list is really for people trying to learn Python. > This question is way more advanced than that! While you might > get a reply here you will probably have more success on the main Python > mailing list or even on the Python Windows list. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Aug 3 14:52:56 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 03 Aug 2011 08:52:56 -0400 Subject: [Tutor] Indexing a list with nested tuples In-Reply-To: References: <4E38BFFA.6090600@gmail.com> Message-ID: <4E3944A8.3090208@gmail.com> On 8/2/2011 11:39 PM, Alexander Quest wrote: > Hey Bob- thanks for the reply. Here is a more complete part of that > code section (the ellipses are parts where I've deleted code because I > don't think it's important for this question): Please always reply-all so a copy goes to the list. Thanks for posting more code & traceback I forgot to mention earlier - tell us which version of Python you are using (this looks like version 3) You did not answer all my questions! How come? Please do so now. > > > _____________________________________________________________ > attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), > ("dexterity", 0)] > ..... > ..... > ..... > print( > """ > 1 - Strength > 2 - Health > 3 - Wisdom > 4 - Dexterity > > Any other key - Quit > """ > ) > selection = input("Selection: ") > if selection == "1" or selection == "2" or selection == "3" or > selection == "4": > print("You have ", points, "points available.") > how_many = input("How many would you like to add to > this attribute?: ") > while how_many < 0 or how_many > 30 or how_many == > "": # Because max points available is > 30, and entering less than 0 does not make sense. > print("Invalid entry. You have ", points, "points > available.") # If the user enters a > number less than 0, greater than 30, or just presses enter, it loops. > how_many = input("How many would you like to add > to this attribute?: ") > print("Added ", points, "to ", > attributes[selection-1][0], "attribute.") # > Here is where I try to add the number of points to the value, based on > what the user entered. > points = points - > how_many > # I subtract the number of points added from the total points available. > attributes[selection-1][1] += > how_many > # I add the number of points the user selected to the variable selected. > > > __________________________________________________________________________ > > > Here's the traceback I get: > > Traceback (most recent call last): > File "C:\Users\Alexander\Desktop\Python Practice\Ch05-2.py", line > 54, in > print("Added ", points, "to ", attributes[selection-1][0], > "attribute.") > TypeError: unsupported operand type(s) for -: 'str' and 'int' > _________________________________________________________________________ > > Thanks for any help. I understand that I can't change tuples directly, > but is there a way to change them indirectly (like saying > attribute.remove[x] and then saying attribute.append[x] with the new > variable? But this seems to take out both the string and the value, > when I only want to increase or decrease the value for one of the 4 > strings, strength, health, wisdom, or dexterity). DON'T USE TUPLES. WHY DO YOU INSIST ON THEM? > > > What does the error message( unsupported operand type(s) for -: > 'str' and 'int') tell you? > > Why would selection be a string rather than an integer? > > This has to do with how you obtain selection from the user. > > Why did you expect to be able to alter the value of a tuple > element? Tuples are immutable! Use a list instead. > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Wed Aug 3 17:50:28 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 3 Aug 2011 08:50:28 -0700 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: I wrote before that I had pasted the function (convertPath()) from my initial post into mycalc.py because I had accidentally deleted it from mycalc.py. And that there was no problem importing it from mycalc. Well, I was mistaken (for a reason too tedious to go into). There WAS a problem, the same one as before. I now have a hex editor, HxD (), and have some info to report. I've left convertPath() in mycalc.py, in importable form, and have been experimenting with it in a new module, mycalc2. The first run: def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 on Tutor list """ #>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' #>>> convertPath(path) #'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path gets C:\Windows\System32>python Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mycalc2 >>> Now I edit it back to its original problem form: def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 on Tutor list >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get C:\Windows\System32>python Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 10 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 144-146: truncated \UXXXXXXX X escape Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or the , 'T', 'u' of " Tutor" . A screen shot of HxD with this version of mycalc2.py open in it is at . You can see that I believe the offset integers are base-10 ints. I do hope that's correct, or I've done a lot of work for naught. Next I try def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 10 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 130-132: truncated \UXXXXXXX escape >>> where 130-132 are 20, 30, 37 or the , '0', '7' of " 07/31/2011". So I go with def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 10 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 118-120: truncated \UXXXXXXX escape Where 118-120 are 65, 6E, 20, or the 'e', 'n', of "Steven " I then delete that line, and go with def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 9 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 95-97: truncated \UXXXXXXXX escape where 95-97 are 64, 20, 73 or the 'd', , 's' of "forward slashes" So I delete "forward slashes" and go with def convertPath(path): """ Given a path with backslashes, return that path with >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 9 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 78-80: truncated \UXXXXXXXX escape where 78-80 are 20, 70, 61 or the , 'p', 'a' of "that path". I then delete that line, and the line above it, and go with def convertPath(path): """ >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 7 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 20-22: truncated \UXXXXXXXX escape where 20-22 are 68, 29, 3A or the 'h', ')', ':' of "def convertPath(path):" Obviously I can't delete those characters. If you read this far, I thank you. I know it is tedious. But what in the world is going on? Steven asked if convertPath was a problem for Python 2.7. So I put copied mycalc2.py to 2.7.1's site-packages folder and did: def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 on Tutor list """ #>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' #>>> convertPath(path) #'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path Gets C:\Windows\System32>C:\Python27\python Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mycalc2 >>> And as he predicted, def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 on Tutor list >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path C:\Windows\System32>C:\Python27\python Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mycalc2 >>> So no problems with convertPath() in 2.7.1 when imported. Dick From __peter__ at web.de Wed Aug 3 19:11:59 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Aug 2011 19:11:59 +0200 Subject: [Tutor] Puzzled again References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: Richard D. Moores wrote: > I wrote before that I had pasted the function (convertPath()) from my > initial post into mycalc.py because I had accidentally deleted it from > mycalc.py. And that there was no problem importing it from mycalc. > Well, I was mistaken (for a reason too tedious to go into). There WAS > a problem, the same one as before. Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." is fine, but when you put it into the docstring it is not a raw string within another string, it becomes just a sequence of characters that is part of the outer string. As such \U marks the beginning of a special way to define a unicode codepoint: >>> "\U00000041" 'A' As "sers\Dic", the eight characters following the \U in your docstring, are not a valid hexadecimal number you get an error message. The solution is standard procedure: escape the backslash or use a rawstring: Wrong: >>> """yadda r"C:\Users\Dick\..." yadda""" File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 10-12: truncated \UXXXXXXXX escape Correct: >>> """yadda r"C:\\Users\Dick\..." yadda""" 'yadda r"C:\\Users\\Dick\\..." yadda' Also correct: >>> r"""yadda r"C:\Users\Dick\..." yadda""" 'yadda r"C:\\Users\\Dick\\..." yadda' From rdmoores at gmail.com Wed Aug 3 19:48:09 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 3 Aug 2011 10:48:09 -0700 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: On Wed, Aug 3, 2011 at 10:11, Peter Otten <__peter__ at web.de> wrote: > Richard D. Moores wrote: > >> I wrote before that I had pasted the function (convertPath()) from my >> initial post into mycalc.py because I had accidentally deleted it from >> mycalc.py. And that there was no problem importing it from mycalc. >> Well, I was mistaken (for a reason too tedious to go into). There WAS >> a problem, the same one as before. > > Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." is > fine, but when you put it into the docstring it is not a raw string within > another string, it becomes just a sequence of characters that is part of the > outer string. As such \U marks the beginning of a special way to define a > unicode codepoint: > >>>> "\U00000041" > 'A' > > As "sers\Dic", the eight characters following the \U in your docstring, are > not a valid hexadecimal number you get an error message. > > The solution is standard procedure: escape the backslash or use a rawstring: > > Wrong: > >>>> """yadda r"C:\Users\Dick\..." yadda""" > ?File "", line 1 > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in > position 10-12: truncated \UXXXXXXXX escape > > Correct: > >>>> """yadda r"C:\\Users\Dick\..." yadda""" > 'yadda r"C:\\Users\\Dick\\..." yadda' > > Also correct: > >>>> r"""yadda r"C:\Users\Dick\..." yadda""" > 'yadda r"C:\\Users\\Dick\\..." yadda' Here's from my last post: ==================================== Now I edit it back to its original problem form: def convertPath(path): """ Given a path with backslashes, return that path with forward slashes. By Steven D'Aprano 07/31/2011 on Tutor list >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >>> convertPath(path) 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' """ import os.path separator = os.path.sep if separator != '/': path = path.replace(os.path.sep, '/') return path and get C:\Windows\System32>python Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mycalc2 Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\mycalc2.py", line 10 """ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 144-146: truncated \UXXXXXXX X escape Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or the , 'T', 'u' of " Tutor" . A screen shot of HxD with this version of mycalc2.py open in it is at . You can see that I believe the offset integers are base-10 ints. I do hope that's correct, or I've done a lot of work for naught. ==================================== So have I not used HxD correctly (my first time to use a hex reader)? If I have used it correctly, why do the reported problem offsets of 144-146 correspond to such innocuous things as 'T', 'u' and , and which come BEFORE the problems you and Steven point out? Dick From d at davea.name Wed Aug 3 21:04:49 2011 From: d at davea.name (Dave Angel) Date: Wed, 03 Aug 2011 15:04:49 -0400 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: <4E399BD1.5050001@davea.name> On 08/03/2011 01:48 PM, Richard D. Moores wrote: > On Wed, Aug 3, 2011 at 10:11, Peter Otten<__peter__ at web.de> wrote: > >> >> Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." is >> fine, but when you put it into the docstring it is not a raw string within >> another string, it becomes just a sequence of characters that is part of the >> outer string. As such \U marks the beginning of a special way to define a >> unicode codepoint: >> > Here's from my last post: > > ==================================== > Now I edit it back to its original problem form: > > def convertPath(path): > """ > Given a path with backslashes, return that path with forward slashes. > > By Steven D'Aprano 07/31/2011 on Tutor list > >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' > >>> convertPath(path) > 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' > """ > Traceback (most recent call last): > File "", line 1, in > File "C:\Python32\lib\site-packages\mycalc2.py", line 10 > """ > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes > in position 144-146: truncated \UXXXXXXX > X escape > > Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or the > , 'T', 'u' of " Tutor" . A screen shot of HxD with this > version of mycalc2.py open in it is at > . You can see that I believe the > offset integers are base-10 ints. I do hope that's correct, or I've > done a lot of work for naught. > ==================================== > > So have I not used HxD correctly (my first time to use a hex reader)? > If I have used it correctly, why do the reported problem offsets of > 144-146 correspond to such innocuous things as 'T', 'u' and, > and which come BEFORE the problems you and Steven point out? > This one is my fault, for pointing you to the hex viewer. Peter is correct. But the offset is relative to the beginning of the triple-quoted string. The problem has nothing to do with the encoding of the file itself, but instead just with the backslashes inside the triple-quoted string. Since you have a \U, the parser also expects 8 hex digits. The thing that threw me was that this particular symptom is specific to Python 3.x, which I don't normally use. The following line would have the same problem: mystring = "abc \Unexpected def" since the letters nexpecte don't spell out a valid hexcode. You would instead want mystring = r"abc \Unexpected def" -- DaveA From __peter__ at web.de Wed Aug 3 21:10:16 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Aug 2011 21:10:16 +0200 Subject: [Tutor] Puzzled again References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: Richard D. Moores wrote: > On Wed, Aug 3, 2011 at 10:11, Peter Otten <__peter__ at web.de> wrote: >> Richard D. Moores wrote: >> >>> I wrote before that I had pasted the function (convertPath()) from my >>> initial post into mycalc.py because I had accidentally deleted it from >>> mycalc.py. And that there was no problem importing it from mycalc. >>> Well, I was mistaken (for a reason too tedious to go into). There WAS >>> a problem, the same one as before. >> >> Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." >> is fine, but when you put it into the docstring it is not a raw string >> within another string, it becomes just a sequence of characters that is >> part of the outer string. As such \U marks the beginning of a special way >> to define a unicode codepoint: >> >>>>> "\U00000041" >> 'A' >> >> As "sers\Dic", the eight characters following the \U in your docstring, >> are not a valid hexadecimal number you get an error message. >> >> The solution is standard procedure: escape the backslash or use a >> rawstring: >> >> Wrong: >> >>>>> """yadda r"C:\Users\Dick\..." yadda""" >> File "", line 1 >> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in >> position 10-12: truncated \UXXXXXXXX escape >> >> Correct: >> >>>>> """yadda r"C:\\Users\Dick\..." yadda""" >> 'yadda r"C:\\Users\\Dick\\..." yadda' >> >> Also correct: >> >>>>> r"""yadda r"C:\Users\Dick\..." yadda""" >> 'yadda r"C:\\Users\\Dick\\..." yadda' > > Here's from my last post: > > ==================================== > Now I edit it back to its original problem form: > > def convertPath(path): > """ > Given a path with backslashes, return that path with forward slashes. > > By Steven D'Aprano 07/31/2011 on Tutor list > >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' > >>> convertPath(path) > 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' > """ > import os.path > separator = os.path.sep > if separator != '/': > path = path.replace(os.path.sep, '/') > return path > > and get > > C:\Windows\System32>python > Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit > (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import mycalc2 > Traceback (most recent call last): > File "", line 1, in > File "C:\Python32\lib\site-packages\mycalc2.py", line 10 > """ > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes > in position 144-146: truncated \UXXXXXXX > X escape > > Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or the > , 'T', 'u' of " Tutor" . A screen shot of HxD with this > version of mycalc2.py open in it is at > . You can see that I believe the > offset integers are base-10 ints. I do hope that's correct, or I've > done a lot of work for naught. > ==================================== > > So have I not used HxD correctly (my first time to use a hex reader)? > If I have used it correctly, why do the reported problem offsets of > 144-146 correspond to such innocuous things as 'T', 'u' and , > and which come BEFORE the problems you and Steven point out? Come on, put that r before the docstring def convertPath(path): r""" Given a path with backslashes, return that path with forward slashes. ... and see the problem go away. The numbers reported by Python are byte offsets within the string literal: >>> "\Uinvalidnumber" File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-2: truncated \UXXXXXXXX escape >>> "1\Uinvalidnumber" File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 1-3: truncated \UXXXXXXXX escape >>> "12\Uinvalidnumber" File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape >>> "123\Uinvalidnumber" File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 3-5: truncated \UXXXXXXXX escape From steve at pearwood.info Wed Aug 3 21:16:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 04 Aug 2011 05:16:59 +1000 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: <4E399EAB.10600@pearwood.info> Richard D. Moores wrote: > I wrote before that I had pasted the function (convertPath()) from my > initial post into mycalc.py because I had accidentally deleted it from > mycalc.py. And that there was no problem importing it from mycalc. > Well, I was mistaken (for a reason too tedious to go into). There WAS > a problem, the same one as before. Richard, too much information! Please try to be more concise in your posts. Try to find the *simplest* code that demonstrates the problem. E.g. instead of a 14 line function (including docstring) you should be able to demonstrate the problem with a TWO liner: def func(): """ text r'aaa\Userswxyzabcd' """ In Python 3, you will get a SyntaxError complaining about a truncated \UXXXXXXXX escape. This comes back to what I said earlier: r' inside another string does not start a raw string. (In much the same way that [ inside a string does not create a list.) \U instroduces a Unicode escape. Since docstrings are unicode in Python 3, and serswxyz are not valid hex digits, you get an error. To fix, you need to either make the whole docstring a raw string: r""" text r'aaa\Userswxyzabcd' """ or you need to escape the backslashes: """ text r'aaa\\Userswxyzabcd' """ You don't even need to use import to work with this. You can just copy and paste the string into an interactive interpreter: # Python 2: >>> s = """ text r'aaa\Userswxyzabcd' """ >>> print s text r'aaa\Userswxyzabcd' # Python 3: >>> s = """ text r'aaa\Userswxyzabcd' """ File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-13: truncated \UXXXXXXXX escape Remember: function docstrings are just ordinary strings. All the rules for strings apply equally to docstrings. You also report (in tedious detail!) apparent discrepancies between the offsets reported by Python when importing the file, and the actual content of the file at those offsets. I'm not even going to attempt to diagnose that. Without access to the exact source files, not copy and pasted into an email or a pastebin, there is no hope of diagnosing it. It would just be a major waste of time and energy. The most likely cause is that the version of the file you are importing is not the same as the version of the file you have open in the hex editor. E.g. suppose you open the file in the hex editor. Then you edit the file in your text editor, and save changes. Then you import it in Python, which reports the offsets according to the version of the file on disk. You look at the hex editor, but you're seeing the *old* version, before the changes. Unless the problem is *reproducible*, i.e. you can repeat it at will, there's no way of knowing for sure what happened. (Unless you have a time machine and can go back in time to see exactly you did.) Don't lose any sleep over this sort of thing. We've all done it. My favourite is when I'm making incremental edits to a file, but forget to reload() changes in the interactive interpreter correctly. Python ends up finding an error on (let's say) line 42, but by the time the error is reported, line 42 on disk has changed and so the traceback prints a completely irrelevant line. If you *can* reproduce the error at will, e.g. do this: (1) Take a source file in a known state; (2) Import the file into a *freshly started* Python interpreter; (3) Python reports an error on some line; (4) but the line doesn't seem to have anything to do with that error and repeat it as often as you like, then it would be worth sharing the file for further investigation, by attaching it to an email, not copying and pasting the text from it. Disclaimer: due to the way Python's parser works, sometimes a missing parenthesis or bracket will cause a syntax error on the line *following* the erroneous line. This is a known limitation. -- Steven From rdmoores at gmail.com Wed Aug 3 22:20:23 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 3 Aug 2011 13:20:23 -0700 Subject: [Tutor] Puzzled again In-Reply-To: <4E399EAB.10600@pearwood.info> References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> <4E399EAB.10600@pearwood.info> Message-ID: On Wed, Aug 3, 2011 at 12:16, Steven D'Aprano wrote: > Richard D. Moores wrote: >> >> I wrote before that I had pasted the function (convertPath()) from my >> initial post into mycalc.py because I had accidentally deleted it from >> mycalc.py. And that there was no problem importing it from mycalc. >> Well, I was mistaken (for a reason too tedious to go into). There WAS >> a problem, the same one as before. > > Richard, too much information! Please try to be more concise in your posts. > Try to find the *simplest* code that demonstrates the problem. Yes. Sorry. > E.g. instead of a 14 line function (including docstring) you should be able > to demonstrate the problem with a TWO liner: > > def func(): > ? ?""" text r'aaa\Userswxyzabcd' """ > > In Python 3, you will get a SyntaxError complaining about a truncated > \UXXXXXXXX escape. This comes back to what I said earlier: r' inside another > string does not start a raw string. (In much the same way that [ inside a > string does not create a list.) \U instroduces a Unicode escape. Since > docstrings are unicode in Python 3, and serswxyz are not valid hex digits, > you get an error. > > To fix, you need to either make the whole docstring a raw string: > > ? ?r""" text r'aaa\Userswxyzabcd' """ Yes! That works! I didn't understand that suggestion before, partly because I had the """ on a separate line, and was also confused by the "yadda"s. > or you need to escape the backslashes: > > ? ?""" text r'aaa\\Userswxyzabcd' """ Well, that's not so good, because it distorts the example I'm giving. Right? (Hey, I learned to put examples in my docstrings from you.) > You don't even need to use import to work with this. You can just copy and > paste the string into an interactive interpreter: > > # Python 2: >>>> s = """ text r'aaa\Userswxyzabcd' """ >>>> print s > ?text r'aaa\Userswxyzabcd' > > > # Python 3: >>>> s = """ text r'aaa\Userswxyzabcd' """ > ?File "", line 1 > SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in > position 11-13: truncated \UXXXXXXXX escape > > Remember: function docstrings are just ordinary strings. All the rules for > strings apply equally to docstrings. > > > You also report (in tedious detail!) apparent discrepancies between the > offsets reported by Python when importing the file, and the actual content > of the file at those offsets. I'm not even going to attempt to diagnose > that. Without access to the exact source files, not copy and pasted into an > email or a pastebin, there is no hope of diagnosing it. It would just be a > major waste of time and energy. > > The most likely cause is that the version of the file you are importing is > not the same as the version of the file you have open in the hex editor. No, I made sure that the 2 were the same. HxD has a refresh function, which I made sure to use (press F5). > E.g. suppose you open the file in the hex editor. Then you edit the file in > your text editor, and save changes. Then you import it in Python, which > reports the offsets according to the version of the file on disk. You look > at the hex editor, but you're seeing the *old* version, before the changes. > > Unless the problem is *reproducible*, i.e. you can repeat it at will, > there's no way of knowing for sure what happened. (Unless you have a time > machine and can go back in time to see exactly you did.) > > Don't lose any sleep over this sort of thing. We've all done it. My > favourite is when I'm making incremental edits to a file, but forget to > reload() changes in the interactive interpreter correctly. Python ends up > finding an error on (let's say) line 42, but by the time the error is > reported, line 42 on disk has changed and so the traceback prints a > completely irrelevant line. > > If you *can* reproduce the error at will, e.g. do this: > > (1) Take a source file in a known state; > (2) Import the file into a *freshly started* Python interpreter; I was always importing into a "freshly started" Python interpreter. > (3) Python reports an error on some line; > (4) but the line doesn't seem to have anything to do with that error > > and repeat it as often as you like, then it would be worth sharing the file > for further investigation, by attaching it to an email, not copying and > pasting the text from it. OK. I didn't know attachments were permitted on Tutor. But in looking at my Tutor archive in Gmail, I see that they are. Thanks. > Disclaimer: due to the way Python's parser works, sometimes a missing > parenthesis or bracket will cause a syntax error on the line *following* the > erroneous line. This is a known limitation. Happens often to me, because I tend to leave out a ')' or 2 at the end of a print() statement. Thanks for all your kind instruction and advice, Steven. Dick From rdmoores at gmail.com Wed Aug 3 22:30:13 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 3 Aug 2011 13:30:13 -0700 Subject: [Tutor] Puzzled again In-Reply-To: References: <4E38D5C7.4090600@davea.name> <4E38F602.8040404@davea.name> Message-ID: On Wed, Aug 3, 2011 at 12:10, Peter Otten <__peter__ at web.de> wrote: > Richard D. Moores wrote: > >> On Wed, Aug 3, 2011 at 10:11, Peter Otten <__peter__ at web.de> wrote: >>> Richard D. Moores wrote: >>> >>>> I wrote before that I had pasted the function (convertPath()) from my >>>> initial post into mycalc.py because I had accidentally deleted it from >>>> mycalc.py. And that there was no problem importing it from mycalc. >>>> Well, I was mistaken (for a reason too tedious to go into). There WAS >>>> a problem, the same one as before. >>> >>> Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." >>> is fine, but when you put it into the docstring it is not a raw string >>> within another string, it becomes just a sequence of characters that is >>> part of the outer string. As such \U marks the beginning of a special way >>> to define a unicode codepoint: >>> >>>>>> "\U00000041" >>> 'A' >>> >>> As "sers\Dic", the eight characters following the \U in your docstring, >>> are not a valid hexadecimal number you get an error message. >>> >>> The solution is standard procedure: escape the backslash or use a >>> rawstring: >>> >>> Wrong: >>> >>>>>> """yadda r"C:\Users\Dick\..." yadda""" >>> File "", line 1 >>> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in >>> position 10-12: truncated \UXXXXXXXX escape >>> >>> Correct: >>> >>>>>> """yadda r"C:\\Users\Dick\..." yadda""" >>> 'yadda r"C:\\Users\\Dick\\..." yadda' >>> >>> Also correct: >>> >>>>>> r"""yadda r"C:\Users\Dick\..." yadda""" >>> 'yadda r"C:\\Users\\Dick\\..." yadda' >> >> Here's from my last post: >> >> ==================================== >> Now I edit it back to its original problem form: >> >> def convertPath(path): >> ? ?""" >> ? ?Given a path with backslashes, return that path with forward slashes. >> >> ? ?By Steven D'Aprano ?07/31/2011 on Tutor list >> ? ?>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf' >> ? ?>>> convertPath(path) >> ? ?'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' >> ? ?""" >> ? ?import os.path >> ? ?separator = os.path.sep >> ? ?if separator != '/': >> ? ? ? ?path = path.replace(os.path.sep, '/') >> ? ?return path >> >> and get >> >> C:\Windows\System32>python >> Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit >> (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import mycalc2 >> Traceback (most recent call last): >> ?File "", line 1, in >> ?File "C:\Python32\lib\site-packages\mycalc2.py", line 10 >> ? ?""" >> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes >> in position 144-146: truncated \UXXXXXXX >> X escape >> >> Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or ?the >> , 'T', 'u' of ?" Tutor" . ?A screen shot of HxD with this >> version of mycalc2.py open in it is at >> . You can see that I believe the >> offset integers are base-10 ints. I do hope that's correct, or I've >> done a lot of work for naught. >> ==================================== >> >> So have I not used HxD correctly (my first time to use a hex reader)? >> If I have used it correctly, why do the reported problem offsets of >> 144-146 correspond to such innocuous things as 'T', 'u' and , >> and which come BEFORE the problems you and Steven point out? > > Come on, put that r before the docstring Yes! That works! Now I've got it. As I told Steven, I didn't understand that suggestion before, partly because I had the """ on a separate line, and was also confused by the "yadda"s. > def convertPath(path): > ? ?r""" > ? ?Given a path with backslashes, return that path with forward slashes. > ? ?... > > and see the problem go away. It did! >The numbers reported by Python are byte offsets > within the string literal: Ah, that explains the mystery. Thanks, Peter. Dick From redacted@example.com Thu Aug 4 00:57:33 2011 From: redacted@example.com (Alexander Quest) Date: Wed, 3 Aug 2011 15:57:33 -0700 Subject: [Tutor] Indexing a list with nested tuples In-Reply-To: References: Message-ID: Thanks Peter- I tried the replacement method where the entire tuple is replaced with a new one and that worked. Changing the "attribute_index" (or "selection" variable, as I called it) to an integer removed the int/str errors. -Alex On Wed, Aug 3, 2011 at 12:12 AM, Peter Otten <__peter__ at web.de> wrote: > Alexander Quest wrote: > > > Hi guys- I'm having a problem with a list that has nested tuples: > > > > attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), > > ("dexterity", 0)] > > > > I've defined the list above with 4 items, each starting with a value of > 0. > > The player > > enters how many points he or she wants to add to a given item. The > > selection menu > > is 1 - strength; 2 - health; 3 - wisdom; 4- dexterity. So the "selection" > > variable is actually > > 1 more than the index location of the intended item. So I have the > > following code: > > > > print("Added ", points, "to ", attributes[selection-1][0], "attribute.") > > > > My intent with this is to say that I've added this many points (however > > many) to the > > corresponding item in the list. So if the player selects "1", then > > selection = 1, but I subtract > > 1 from that (selection -1) to get the index value of that item in the > list > > (in this case 0). Then I > > have [0] to indicate that I want to go to the second value within that > > first item, which is the > > point value. I get an error saying that list indices must be integers, > not > > strings. I get a similar > > error even if I just put attributes[selection][0] without the minus 1. > > > > Also, it seems that the tuple within the list cannot be modified > directly, > > so I can't add points to the original value of "0" that all 4 items start > > with. Is there a way to keep this nested list with > > tuples but be able to modify the point count for each item, or will it be > > better to create a dictionary or 2 separate lists (1 for the names > > "Strength, Health, Wisdom, Dexterity" and one > > for their starting values "0,0,0,0")? Any suggestions/help will be > greatly > > appreciated!!! > > [I'm assuming you are using Python 3. If not replace input() with > raw_input()] > > Let's investigate what happens when you enter an attribute index: > > >>> attribute_index = input("Choose attribute ") > Choose attribute 2 > >>> attribute_index > '2' > > Do you note the '...' around the number? > > >>> attribute_index -= 1 > Traceback (most recent call last): > File "", line 1, in > TypeError: unsupported operand type(s) for -=: 'str' and 'int' > > It's actually a string, not an integer; therefore you have to convert it to > an integer before you can do any math with it: > > >>> attribute_index = int(attribute_index) > >>> attribute_index > 2 > >>> attribute_index -= 1 > >>> attribute_index > 1 > > Now let's try to change the second tuple: > > >>> attributes = [ > ... ("strength", 0), ("health", 0), ("wisdom", 0), ("dexterity", 0)] > >>> attributes[attribute_index] > ('health', 0) > >>> attributes[attribute_index][1] += 42 > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > The error message is pretty clear, you cannot replace items of a tuple. > You can either to switch to nested lists > > [["strength", 0], ["health", 0], ...] > > or replace the entire tuple with a new one: > > >>> name, value = attributes[attribute_index] > >>> attributes[attribute_index] = name, value + 42 > >>> attributes > [('strength', 0), ('health', 42), ('wisdom', 0), ('dexterity', 0)] > > However, I think the pythonic way is to use a dictionary. If you want the > user to input numbers you need a second dictionary to translate the numbers > into attribute names: > > >>> attributes = dict(attributes) > >>> lookup = {1: "strength", 2: "health", 3: "wisdom", 4: "dexterity"} > >>> while True: > ... index = input("index ") > ... if not index: break > ... amount = int(input("amount ")) > ... name = lookup[int(index)] > ... attributes[name] += amount > ... > index 1 > amount 10 > index 2 > amount 20 > index 3 > amount 10 > index 2 > amount -100 > index > >>> attributes > {'dexterity': 0, 'strength': 10, 'health': -38, 'wisdom': 10} > > Personally I would ask for attribute names directly. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From redacted@example.com Thu Aug 4 01:05:22 2011 From: redacted@example.com (Alexander Quest) Date: Wed, 3 Aug 2011 16:05:22 -0700 Subject: [Tutor] Indexing a list with nested tuples In-Reply-To: <4E3944A8.3090208@gmail.com> References: <4E38BFFA.6090600@gmail.com> <4E3944A8.3090208@gmail.com> Message-ID: Hi Bob- thanks for the reply again. I apologize about not "replying all" last time- still getting in the habit of doing this. I am using Python version 3.1. As far as tuples are concerned, I don't NEED to use them, but I am trying to get some practice with them. This is because I am following an instructional book that is discussing nested tuples within lists. The way I get the "selection" variable from the user is just by typing the following: selection = input("Selection: ") I'm not sure why it reads it initially as a string, but I later included the line selection = int(selection), which solved the int/str problem. Also, I was about to switch to dictionaries or just lists without tuples, but another poster above stated that I could just replace the entire tuple item within the list, which technically would not be changing the tuple, so it worked out. The only problem I have now is trying to sort the 4 attributes based on their numerical value, not their alphabetical value. But when I type in attributes.sort(reverse=True), it sorts them alphabetically because the name of the attribute is 1st in the list, and its value is 2nd. Here it is again for reference: attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), ("dexterity", 0)] Sorry if this is a bit confusing. Thanks for your help and tips so far Bob. -Alex On Wed, Aug 3, 2011 at 5:52 AM, bob gailer wrote: > On 8/2/2011 11:39 PM, Alexander Quest wrote: > > Hey Bob- thanks for the reply. Here is a more complete part of that code > section (the ellipses are parts where I've deleted code because I don't > think it's important for this question): > > > Please always reply-all so a copy goes to the list. > > Thanks for posting more code & traceback > > I forgot to mention earlier - tell us which version of Python you are using > (this looks like version 3) > > You did not answer all my questions! How come? Please do so now. > > > > _____________________________________________________________ > attributes = [("strength", 0), ("health ", 0), ("wisdom ", 0), > ("dexterity", 0)] > ..... > ..... > ..... > print( > """ > 1 - Strength > 2 - Health > 3 - Wisdom > 4 - Dexterity > > Any other key - Quit > """ > ) > selection = input("Selection: ") > if selection == "1" or selection == "2" or selection == "3" or selection == > "4": > print("You have ", points, "points available.") > how_many = input("How many would you like to add to this > attribute?: ") > while how_many < 0 or how_many > 30 or how_many == > "": # Because max points available is 30, and > entering less than 0 does not make sense. > print("Invalid entry. You have ", points, "points > available.") # If the user enters a number > less than 0, greater than 30, or just presses enter, it loops. > how_many = input("How many would you like to add to > this attribute?: ") > print("Added ", points, "to ", attributes[selection-1][0], > "attribute.") # Here is where I try to add the > number of points to the value, based on what the user entered. > points = points - > how_many > # I subtract the number of points added from the total points available. > attributes[selection-1][1] += > how_many # I > add the number of points the user selected to the variable selected. > > > __________________________________________________________________________ > > > Here's the traceback I get: > > Traceback (most recent call last): > File "C:\Users\Alexander\Desktop\Python Practice\Ch05-2.py", line 54, in > > print("Added ", points, "to ", attributes[selection-1][0], > "attribute.") > TypeError: unsupported operand type(s) for -: 'str' and 'int' > _________________________________________________________________________ > > Thanks for any help. I understand that I can't change tuples directly, but > is there a way to change them indirectly (like saying attribute.remove[x] > and then saying attribute.append[x] with the new variable? But this seems to > take out both the string and the value, when I only want to increase or > decrease the value for one of the 4 strings, strength, health, wisdom, or > dexterity). > > > DON'T USE TUPLES. WHY DO YOU INSIST ON THEM? > > > >> What does the error message( unsupported operand type(s) for -: 'str' and >> 'int') tell you? > > > Why would selection be a string rather than an integer? > > > This has to do with how you obtain selection from the user. >> >> Why did you expect to be able to alter the value of a tuple element? >> Tuples are immutable! Use a list instead. >> >> > -- > Bob Gailer919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Thu Aug 4 01:16:39 2011 From: ldl08 at gmx.net (David) Date: Thu, 04 Aug 2011 01:16:39 +0200 Subject: [Tutor] calculation in string operations Message-ID: <4E39D6D7.6030103@gmx.net> Hello everybody, I got an error message that surprises me. I know how to solve the problem (couple of parentheses will do), but I would expect Python to run as the code is presented below. After all, my_weight is a number that can be multiplied by a float. I would expect Python to evaluate the expression after the (final) operator and then having it inserted into the string. So I guess my question is this: what is the path that Python follows in its string formatting operations? Thanks for your insights, David [code] my_weight = 80 # kg # 1 kg equals 2.20462262 pounds print "My weight in pounds is %d" % my_weight * 2.20462262 [/code] python weight.py Traceback (most recent call last): File "weight.py", line 4, in print "My weight in pounds is %d" % my_weight * 2.20462262 TypeError: can't multiply sequence by non-int of type 'float' From alan.gauld at btinternet.com Thu Aug 4 02:20:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Aug 2011 01:20:42 +0100 Subject: [Tutor] calculation in string operations In-Reply-To: <4E39D6D7.6030103@gmx.net> References: <4E39D6D7.6030103@gmx.net> Message-ID: <4E39E5DA.8050004@btinternet.com> On 04/08/11 00:16, David wrote: > After all, my_weight is a number that can be multiplied by a float. > I would expect Python to evaluate the expression after the (final) > operator and then having it inserted into the string. But it doesn't because the % format operator has a higher precedence. So it sees the line as (string % value) * number But you want string % (value * number) So you need parens to force it to see things your way. > print "My weight in pounds is %d" % my_weight * 2.20462262 > > python weight.py > Traceback (most recent call last): > File "weight.py", line 4, in > print "My weight in pounds is %d" % my_weight * 2.20462262 > TypeError: can't multiply sequence by non-int of type 'float' -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 4 02:20:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Aug 2011 01:20:42 +0100 Subject: [Tutor] calculation in string operations In-Reply-To: <4E39D6D7.6030103@gmx.net> References: <4E39D6D7.6030103@gmx.net> Message-ID: <4E39E5DA.8050004@btinternet.com> On 04/08/11 00:16, David wrote: > After all, my_weight is a number that can be multiplied by a float. > I would expect Python to evaluate the expression after the (final) > operator and then having it inserted into the string. But it doesn't because the % format operator has a higher precedence. So it sees the line as (string % value) * number But you want string % (value * number) So you need parens to force it to see things your way. > print "My weight in pounds is %d" % my_weight * 2.20462262 > > python weight.py > Traceback (most recent call last): > File "weight.py", line 4, in > print "My weight in pounds is %d" % my_weight * 2.20462262 > TypeError: can't multiply sequence by non-int of type 'float' -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sander.sweers at gmail.com Thu Aug 4 02:22:55 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 4 Aug 2011 02:22:55 +0200 Subject: [Tutor] calculation in string operations In-Reply-To: <4E39D6D7.6030103@gmx.net> References: <4E39D6D7.6030103@gmx.net> Message-ID: On 4 August 2011 01:16, David wrote: > I got an error message that surprises me. I know how to solve the > problem (couple of parentheses will do), but I would expect Python to > run as the code is presented below. > After all, my_weight is a number that can be multiplied by a float. > I would expect Python to evaluate the expression after the (final) > operator and then having it inserted into the string. > > So I guess my question is this: what is the path that Python follows in > its string formatting operations? It had my stumped at first but then I saw what was happening. After some experimentation it seems that string formatting first converts my_weight to a string and then multiplies it. And multiplying a string with a float is not possible. Greets Sander From thisisonlyatest at gmx.com Thu Aug 4 02:49:47 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Wed, 03 Aug 2011 20:49:47 -0400 Subject: [Tutor] When to use def __init__ when making a class? In-Reply-To: References: <4E389A8E.1000008@gmx.com> Message-ID: <4E39ECAB.6040506@gmx.com> On 08/02/2011 09:09 PM, Brett Ritter wrote: > On Tue, Aug 2, 2011 at 8:47 PM, brandon w wrote: > >> 1) When should I use "def __init__(self):" when I create a class? >> > When you have any initialization to do. (in other words, when you > want class instantiation to do more than simply give you an instance > of the class. > > >> 2) Would these two classes have the same effect? >> > Neither of these two classes compile. You should try what you are > asking before asking, it will lead you to better questions. > > Your examples show some misunderstanding about Python classes. > > 1) an __init__ method shouldn't return anything. The Class > construction call will already return an instance of the class, > __init__ is just about initialization. > 2) A class definition likewise has no return value. > 3) In your examples, Marcus and Jasmine are either intended to be > strings (and should be quoted), or are variables you didn't provide. > > Here, try running these examples and see what you can figure out. > Experiment with them a little, then come back with questions on what > you observe. > > class Name: > def __init__(self): > self.man = "Marcus" > self.woman = "Jasmine" > > instance = Name() > print instance.man # Python 3 will use a different print syntax > > class Name: > pass > > instance = Name() > instance.man = "Fred" > print instance.man > > I see that the name Fred was assigned to "instance.man" in the example that you gave. I did forget to put the quotes around the names to make them strings. I thought that those would compile. I just wanted to understand the reason why people would use "def __init__(self):" so that I know when to use it. Thank you for your help. From thisisonlyatest at gmx.com Thu Aug 4 03:19:40 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Wed, 03 Aug 2011 21:19:40 -0400 Subject: [Tutor] When to use def __init__ when making a class? In-Reply-To: <4E38A38D.6020905@pearwood.info> References: <4E389A8E.1000008@gmx.com> <4E38A38D.6020905@pearwood.info> Message-ID: <4E39F3AC.7060403@gmx.com> On 08/02/2011 09:25 PM, Steven D'Aprano wrote: > brandon w wrote: >> I have two questions: >> >> 1) When should I use "def __init__(self):" when I create a class? > > Whenever you need something to happen when you create an instance. > > >> 2) Would these two classes have the same effect? > > Technically, no, but in practice, you would find it hard to see the > difference for the example given. But for slightly different examples, > the difference would be astonishing. > > > >> class Name: >> def __init__(self): >> man = Marcus >> woman = Jasmine >> return self.man, self.woman > > Did you try the code before posting it? > > Three problems with it: > > (1) Firstly, Marcus and Jasmine are not built-in Python commands, so > trying to execute man = Marcus raises NameError. You need to use > quotation marks to turn it into a string. > > (2) Fixing that problem, man = "Marcus" doesn't do what you expect > either, because it creates a local variable man and not an attribute. > > (3) Last but not least, the return result of __init__ is ignored, so > even though you try to return self.man and self.women, nothing happens. > > Also, calling the class "Name" is a bad idea, because it doesn't have > anything to do with what the class actually holds, which is a *pair* > of names, one male and one female. > > > This code should be written as: > > > class Couple: > def __init__(self): > self.man = "Marcus" > self.woman = "Jasmine" > > > This creates a class where every instance has its own independent > attributes man and woman. > > >> class Name: >> man = Marcus >> woman = Jasmine >> return man, woman > > > Again, did you try this? If you did, you would discover it raises > SyntaxError: you can't include a return statement inside a class, > because it is meaningless. > > SyntaxError: 'return' outside function > > This should be written as > > class Couple: > man = "Marcus" > woman = "Jasmine" > > > This creates a class where every instance shares the same pair of > attributes. > > > > In this example, the difference is not very great, because strings > cannot be modified in place. If you try to store a new value for the > attribute, Python defaults to creating an independent instance > attribute rather than changing the shared class attribute. > > > Here is an example that may help show the difference: > > > class TestAttributes: > a = [1, 2, 3] # Shared, and mutable. > def __init__(self): > self.b = [1, 2, 3] # Not shared. > > > Now, using this: > > > >>> x = TestAttributes() # Create a new instance. > >>> y = TestAttributes() # And another one. > >>> > >>> x.a > [1, 2, 3] > >>> y.a > [1, 2, 3] > >>> x.a.append(42) # Modify the SHARED list. > >>> y.a # And all instances see the change! > [1, 2, 3, 42] > >>> > >>> x.b > [1, 2, 3] > >>> x.b.append(999) # Modify the non-shared list. > >>> x.b > [1, 2, 3, 999] > >>> y.b # Other instances are unchanged. > [1, 2, 3] > > > > > I see. Thank you very much for the example that you have given me. This is clear and concise. I did forget to put the quotes around the names Marcus and Jasmine. I learn something new everyday.... From armvrt at gmail.com Thu Aug 4 21:52:25 2011 From: armvrt at gmail.com (Shwinn Ricci) Date: Thu, 4 Aug 2011 15:52:25 -0400 Subject: [Tutor] General method for creating a partitioned window Message-ID: Say I want one half of a 720 x 480 window be dedicated for creating a 2-D structure, and the other half for a 3-D structure. There would be a line 1 or 2 pixels thick straight down the window that would divide the two sectors. How does one go about doing this without creating two separate GUI window frames? I do not have my code with me right now, I can post as soon as I have access to it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 5 01:37:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Aug 2011 00:37:26 +0100 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: References: Message-ID: <4E3B2D36.5010003@btinternet.com> On 04/08/11 20:52, Shwinn Ricci wrote: > Say I want one half of a 720 x 480 window be dedicated for creating a > 2-D structure, and the other half for a 3-D structure. There would be a > line 1 or 2 pixels thick straight down the window that would divide the > two sectors. How does one go about doing this without creating two > separate GUI window frames? I do not have my code with me right now, I > can post as soon as I have access to it. You need to give yus more detail. This kind of thing is very GUI frame-work specific. Are you using Tkinter? wxPython?, Cocoa on MacOSX? They are all different. And because you want to do graphics you also need to tell us what graphics toolkit you are using? OpenGL? Something else? Or are you trying to script Blender or Maya or some other 2D/3D modelling tool? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 5 01:37:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Aug 2011 00:37:26 +0100 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: References: Message-ID: <4E3B2D36.5010003@btinternet.com> On 04/08/11 20:52, Shwinn Ricci wrote: > Say I want one half of a 720 x 480 window be dedicated for creating a > 2-D structure, and the other half for a 3-D structure. There would be a > line 1 or 2 pixels thick straight down the window that would divide the > two sectors. How does one go about doing this without creating two > separate GUI window frames? I do not have my code with me right now, I > can post as soon as I have access to it. You need to give yus more detail. This kind of thing is very GUI frame-work specific. Are you using Tkinter? wxPython?, Cocoa on MacOSX? They are all different. And because you want to do graphics you also need to tell us what graphics toolkit you are using? OpenGL? Something else? Or are you trying to script Blender or Maya or some other 2D/3D modelling tool? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Steve.Flynn at capita.co.uk Fri Aug 5 13:01:19 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Fri, 5 Aug 2011 12:01:19 +0100 Subject: [Tutor] "Object designer" applications - are there any? Message-ID: I'm about to embark on a project in Python (primarily in order to learn the language and equally importantly, to make my life easier at work). I'm an IBM MVS Operations Analyst by trade by recently I've been spending more and more time working on Data Migrations; legacy systems in VSAM files, ADABAS, DB2, Oracle, SQL Server, Sybase and most recently we're about to start off on Tandem, which should be interesting! Anyway, nearly all of this work, at some point, involves me reading a Data Dictionary for the source system and converting it to an Oracle table definition. More often than not this DDL is in text form and I convert it to Oracle DDL such as Create Table wibble ( clientref NUMBER(10) not null, bthdte NUMBER(5) not null, natinr_no VARCHAR2(16) not null, etc ) It struck me that if I write a "read in Sybase DDL and spit out Oracle DDL" routine and so forth, I'd get a lot of reuse out of it. However, I've not done much OOP at all and consequently, my object design skills are somewhat non-existent. Whilst I have a rough idea of what my properties my "table" object will have I was looking for something to help me design it - something which I can say "this is a table object, it has a name and multiple columns. Columns have a type, a width (which may be further comprised of scale and precision or just an integer depending on the column type) and a "nullable" flag.). Oh, and there may be multiple columns... so maybe a column should be an object too... etc. Anyone know if there are any such kinds of programs out there already (freeware please - I'll be doing this off my own back so funds are tight for commercial software). Failing that, does anyone use something for this kind of thing already, Visio maybe or a spreadsheet. Maybe just notepad or a post-it? Perhaps most people just design their objects on paper and let the code do the documentation for them... I don't know as I've never done this before. It doesn't strike me as being a complicated project at first glance - all it's doing is translating structured DDL into structured Oracle DDL, but I'd like to get my first principles correct so that I don't end up 3 weeks in and realise I've made a fundament design flaw ("Crap - I didn't think of anything to describe table indexes" or "Hmm - views.... is a "view" just another "table" or should I describe a view in the SQL it'll actually use, so it's just a piece of text.... and how does that translate to a materialized view" and so forth...) and have to re-do chunks... or maybe I do want to do that, to make sure I get my design nailed before a line of code is ground out. I'm open to suggestions on what useful tools are out there to make my learning experience easier, more pleasant and satisfying - if that involves the back of fag packets, so be it. :) -- Steve Flynn Technical Architect Tel 01242 670864 ? CLPS Elixir Project Office Capita Life?& Pensions Services S4, The Grange Bishops Cleeve GL52 8XX ? www.capita-lps.co.uk Part of the Capita Group plc - www.capita.co.uk Capita Life & Pensions Services Limited is registered in England No 4359665 Capita Life & Pensions Regulated Services Limited is registered in England No 2424853 Registered Office: 71 Victoria Street, Westminster, London, SW1H 0XA This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From cwitts at compuscan.co.za Fri Aug 5 14:09:36 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 05 Aug 2011 14:09:36 +0200 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: References: Message-ID: <4E3BDD80.9000706@compuscan.co.za> On 2011/08/05 01:01 PM, Flynn, Stephen (L & P - IT) wrote: > > > It struck me that if I write a "read in Sybase DDL and spit out Oracle DDL" routine and so forth, I'd get a lot of reuse out of it. However, I've not done much OOP at all and consequently, my object design skills are somewhat non-existent. Whilst I have a rough idea of what my properties my "table" object will have I was looking for something to help me design it - something which I can say "this is a table object, it has a name and multiple columns. Columns have a type, a width (which may be further comprised of scale and precision or just an integer depending on the column type) and a "nullable" flag.). Oh, and there may be multiple columns... so maybe a column should be an object too... etc. > > Anyone know if there are any such kinds of programs out there already (freeware please - I'll be doing this off my own back so funds are tight for commercial software). Failing that, does anyone use something for this kind of thing already, Visio maybe or a spreadsheet. Maybe just notepad or a post-it? > > > You could take a look at SQLAlchemy [1] and possibly the migrate [2] portion of it for schema management. It supports connectivity for both Sybase and Oracle as well as being able to generate the DDL [3] [1] http://www.sqlalchemy.org/docs/ [2] http://packages.python.org/sqlalchemy-migrate/versioning.html#experimental-commands [3] http://www.sqlalchemy.org/trac/wiki/FAQ#HowcanIgettheCREATETABLEDROPTABLEoutputasastring -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Fri Aug 5 14:40:05 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Fri, 5 Aug 2011 13:40:05 +0100 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: <4E3BDD80.9000706@compuscan.co.za> References: <4E3BDD80.9000706@compuscan.co.za> Message-ID: I'll certainly give it a look-see - thanks Christian I'm going to end up writing converters anyway, as at some point I'm going to be given (for example) a COBOL copybook for a file and have to translate that into an Oracle table version (actually I already have tools to do this, but if I'm going to be learning python via a project, I might as well do it properly). S. ________________________________ From: Christian Witts [mailto:cwitts at compuscan.co.za] Sent: Friday, August 05, 2011 1:10 PM To: Flynn, Stephen (L & P - IT) Cc: Tutor List Subject: Re: [Tutor] "Object designer" applications - are there any? On 2011/08/05 01:01 PM, Flynn, Stephen (L & P - IT) wrote: It struck me that if I write a "read in Sybase DDL and spit out Oracle DDL" routine and so forth, I'd get a lot of reuse out of it. However, I've not done much OOP at all and consequently, my object design skills are somewhat non-existent. Whilst I have a rough idea of what my properties my "table" object will have I was looking for something to help me design it - something which I can say "this is a table object, it has a name and multiple columns. Columns have a type, a width (which may be further comprised of scale and precision or just an integer depending on the column type) and a "nullable" flag.). Oh, and there may be multiple columns... so maybe a column should be an object too... etc. Anyone know if there are any such kinds of programs out there already (freeware please - I'll be doing this off my own back so funds are tight for commercial software). Failing that, does anyone use something for this kind of thing already, Visio maybe or a spreadsheet. Maybe just notepad or a post-it? You could take a look at SQLAlchemy [1] and possibly the migrate [2] portion of it for schema management. It supports connectivity for both Sybase and Oracle as well as being able to generate the DDL [3] [1] http://www.sqlalchemy.org/docs/ [2] http://packages.python.org/sqlalchemy-migrate/versioning.html#experiment al-commands [3] http://www.sqlalchemy.org/trac/wiki/FAQ#HowcanIgettheCREATETABLEDROPTABL Eoutputasastring -- Christian Witts Python Developer Click here to report this email as spam. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 5 15:15:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Aug 2011 14:15:35 +0100 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: References: Message-ID: <4E3BECF7.201@btinternet.com> On 05/08/11 12:01, Flynn, Stephen (L & P - IT) wrote: > Anyway, nearly all of this work, at some point, involves me reading a Data Dictionary > for the source system and converting it to an Oracle table definition. > More often than not this DDL is in text form and I convert it to Oracle DDL such as > > Create Table wibble > ( clientref NUMBER(10) not null, > bthdte NUMBER(5) not null, > natinr_no VARCHAR2(16) not null, > etc > ) > > It struck me that if I write a "read in Sybase DDL and spit out Oracle DDL" routine > and so forth, I'd get a lot of reuse out of it. > However, I've not done much OOP at all I'm not sure you need OOP for this. As you say a "routine" ie a function might be all you need along with some data structures - probably dictionaries to define the translations needed. > Perhaps most people just design their objects on paper and let > the code do the documentation for them... It depends on the complexity. For a big project (say >25 classes) I'd use a UML design tool like IBM RSA (Rational Rose as was) or Borland Together. But for small projects Visio/Power[point and some documentation in the code would suffice. And for very small designs (2 or 3 classes) it would just be the code! Biut for this it seems that a simple function to generte the DDL based on an input translation table should be feasible, with no objects required. (You could use objects of course if you really want but I don't think they're necessary, or even particularly helpful, in this case. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 5 15:15:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Aug 2011 14:15:35 +0100 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: References: Message-ID: <4E3BECF7.201@btinternet.com> On 05/08/11 12:01, Flynn, Stephen (L & P - IT) wrote: > Anyway, nearly all of this work, at some point, involves me reading a Data Dictionary > for the source system and converting it to an Oracle table definition. > More often than not this DDL is in text form and I convert it to Oracle DDL such as > > Create Table wibble > ( clientref NUMBER(10) not null, > bthdte NUMBER(5) not null, > natinr_no VARCHAR2(16) not null, > etc > ) > > It struck me that if I write a "read in Sybase DDL and spit out Oracle DDL" routine > and so forth, I'd get a lot of reuse out of it. > However, I've not done much OOP at all I'm not sure you need OOP for this. As you say a "routine" ie a function might be all you need along with some data structures - probably dictionaries to define the translations needed. > Perhaps most people just design their objects on paper and let > the code do the documentation for them... It depends on the complexity. For a big project (say >25 classes) I'd use a UML design tool like IBM RSA (Rational Rose as was) or Borland Together. But for small projects Visio/Power[point and some documentation in the code would suffice. And for very small designs (2 or 3 classes) it would just be the code! Biut for this it seems that a simple function to generte the DDL based on an input translation table should be feasible, with no objects required. (You could use objects of course if you really want but I don't think they're necessary, or even particularly helpful, in this case. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From python at bdurham.com Fri Aug 5 15:26:42 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 05 Aug 2011 09:26:42 -0400 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: References: <4E3BDD80.9000706@compuscan.co.za> Message-ID: <1312550802.12127.2159822357@webmail.messagingengine.com> Stephen, You might check out the SQL management tools from Embarcadero. They may provide some of the conversion capabilities you are looking for. And they generate beautiful documentation. Perhaps you could wrap the features of this product with Python scripts to acheive your goals? Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Fri Aug 5 15:37:11 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Fri, 5 Aug 2011 14:37:11 +0100 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: <4E3BECF7.201@btinternet.com> References: <4E3BECF7.201@btinternet.com> Message-ID: > > However, I've not done much OOP at all > > I'm not sure you need OOP for this. As you say a "routine" ie a function > might be all you need along with some data structures - probably > dictionaries to define the translations needed. I suspect you're correct Alan, but as I'm using this an a learning exercise for the language it seemed too good an opportunity to miss - I can relate a table to an "object" in my head quite easily - just need to know how to do it in Python... S. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From robert.sjoblom at gmail.com Fri Aug 5 15:46:18 2011 From: robert.sjoblom at gmail.com (=?utf-8?Q?Robert_Sj=C3=B6blom?=) Date: Fri, 5 Aug 2011 15:46:18 +0200 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: References: Message-ID: > It struck me that if I write a "read in Sybase DDL and spit out Oracle DDL" routine and so forth, I'd get a lot of reuse out of it. However, I've not done much OOP at all and consequently, my object design skills are somewhat non-existent. Whilst I have a rough idea of what my properties my "table" object will have I was looking for something to help me design it - something which I can say "this is a table object, it has a name and multiple columns. Columns have a type, a width (which may be further comprised of scale and precision or just an integer depending on the column type) and a "nullable" flag.). Oh, and there may be multiple columns... so maybe a column should be an object too... etc. > > Anyone know if there are any such kinds of programs out there already (freeware please - I'll be doing this off my own back so funds are tight for commercial software). Failing that, does anyone use something for this kind of thing already, Visio maybe or a spreadsheet. Maybe just notepad or a post-it? > > Perhaps most people just design their objects on paper and let the code do the documentation for them... I don't know as I've never done this before. > > It doesn't strike me as being a complicated project at first glance - all it's doing is translating structured DDL into structured Oracle DDL, but I'd like to get my first principles correct so that I don't end up 3 weeks in and realise I've made a fundament design flaw ("Crap - I didn't think of anything to describe table indexes" or "Hmm - views.... is a "view" just another "table" or should I describe a view in the SQL it'll actually use, so it's just a piece of text.... and how does that translate to a materialized view" and so forth...) and have to re-do chunks... or maybe I do want to do that, to make sure I get my design nailed before a line of code is ground out. > > > I'm open to suggestions on what useful tools are out there to make my learning experience easier, more pleasant and satisfying - if that involves the back of fag packets, so be it. :) I'm typing this on a phone, so I'll keep it short. There are two great books that could be useful: "Head First Object-Oriented Analysis & Design" and "Python 3 Object Oriented Programming". Head First assumes knowledge of java but is useful for learning OO (though some keywords are different, most code is understandable if you know python), wjile Python 3 is very dry and technical, but really goes in-depth with OO programming and the philosophies behind it (the first chapter really helped me wrap my head around OO and inheritance and encapsulation and what have you). As for diagrams I believe UML is sufficient and there are resources abound online for that, and Visio can easily handle UML standards. best regards, Robert S. From alan.gauld at btinternet.com Fri Aug 5 17:34:10 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 5 Aug 2011 16:34:10 +0100 (BST) Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: References: <4E3BECF7.201@btinternet.com> Message-ID: <1312558450.9907.YahooMailRC@web86702.mail.ird.yahoo.com> > > I'm not sure you need OOP for this. > I suspect you're correct Alan, but as I'm using this an a learning > exercise for the language it seemed too good an opportunity to miss That's fine so long as we understand why you are going down the OOP route. > can relate a table to an "object" in my head quite easily - just need to > know how to do it in Python... OK, So if you can conceptualise a table what are the operations you would perform on it? It sounds like you want to - add columns - from a definition file/document? - generate DDL based on current structure? - export a definition document? - Maybe autopopulate the definition from a given database connection? So the use case nmay be something like: Create a table connected to the old database. The table sucks up the metadata from the database and auto-populates itself with columns(which might be another class with name, type,size type details) Create a new Table object targeted at the new database (which might not exist yet?) If the table can't auto-populate then feed it the oold table object which it queries for a description. The new table then populates its own definition. Finally get the new table to generate the DDL and populate the new database. You might want different table classes each based on different databases, so they populate themselves based on the specific meta language and spit out a common description format. They cn then generate their own dialect of DDL too... Does that seem like a starter? But really, when working with objects it helps to sit back and think through how you want to use them from the outside rather than thinking about what they look like inside. That way the internals will reflect what's actually needed for the usage rather than some random model of what might be needed. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Fri Aug 5 18:14:40 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Fri, 5 Aug 2011 11:14:40 -0500 Subject: [Tutor] Python loop isn't working Message-ID: Hello list! I have a python script which works with other libraries in order to create maps. The script looks for an extension in a specific directory and with mapnik makes the thumbnails. The module works fine from Python command line and Pyton IDLE, but I need this program to run from MS-DOS, when I added the try statement it started to fail. Module runs but doesn't do what I need. Console shows: C:\Python26>shp2png.py C:\\ .png Iniciando... Listo What am I doing wrong? import mapnik import os,fnmatch, sys from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr directorio = sys.argv[1] extension = sys.argv[2] try: if len(sys.argv) == 3: print 'Iniciando...' file_list = [] folders = None for root, folders, files in os.walk( directorio+'\\' ): for filename in fnmatch.filter(files, extension): file_list.append(os.path.join(root, filename)) for row, filepath in enumerate(file_list, start=1): dir(LineSymbolizer().stroke) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp continue layer = shapeData.GetLayer() defn = layer.GetLayerDefn() geo = defn.GetGeomType() (ruta, filename) = os.path.split(filepath) archivo = os.path.splitext(filename) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#EBEBEB') s = mapnik.Style() r=mapnik.Rule() if geo == 3 or geo == -2147483645: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") try: lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." except RuntimeError, e: print 'Shapefile invalida' continue elif geo == 2 or geo == -2147483646: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") try: lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." except RuntimeError, e: print 'Shapefile invalida' continue elif geo == 1 or geo == -2147483647: print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) blue.allow_overlap = True s=mapnik.Style() r=mapnik.Rule() r.symbols.append(blue) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") try: lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "La imagen " +i+ " fue creada." except RuntimeError, e: print 'Shapefile invalida' continue else: print "Algo fallo y no entro a ninguna de las geometrias" print "Listo" else: print "Tus argumentos no son correctos" except IndexError: print "Tus argumentos no son correctos" -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Aug 5 18:40:48 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 05 Aug 2011 09:40:48 -0700 Subject: [Tutor] Python loop isn't working In-Reply-To: References: Message-ID: On 8/5/2011 9:14 AM Susana Iraiis Delgado Rodriguez said... > > Hello list! > I have a python script which works with other libraries in order to > create maps. The script looks for an extension in a specific directory > and with mapnik makes the thumbnails. > The module works fine from Python command line and Pyton IDLE, but I > need this program to run from MS-DOS, when I added the try statement it > started to fail. Module runs but doesn't do what I need. Console shows: > > C:\Python26>shp2png.py C:\\ .png > Iniciando... > Listo > > What am I doing wrong? > First, get rid of the encompassing try: except block so you can see any actual errors instead of trapping them. Place print statements at various points to test and confirm values. Read up on pdb.set_trace() to assist when prints don't quite help enough. Start your diagnostics from there and post the the actual traceback results when you get stuck. Emile > import mapnik > import os,fnmatch, sys > from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer > from osgeo import ogr,gdal,osr > > directorio = sys.argv[1] > extension = sys.argv[2] drop this... > try: outdent this... > if len(sys.argv) == 3: > print 'Iniciando...' > file_list = [] > folders = None > for root, folders, files in os.walk( directorio+'\\' ): > for filename in fnmatch.filter(files, extension): > file_list.append(os.path.join(root, filename)) throw a print statement here to confirm that file_list has valid contents (I suspect not) > for row, filepath in enumerate(file_list, start=1): > dir(LineSymbolizer().stroke) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > continue > layer = shapeData.GetLayer() > defn = layer.GetLayerDefn() > geo = defn.GetGeomType() > (ruta, filename) = os.path.split(filepath) > archivo = os.path.splitext(filename) > i = archivo[0]+'.png' > > m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") > m.background = mapnik.Color('#EBEBEB') > s = mapnik.Style() > r=mapnik.Rule() > > if geo == 3 or geo == -2147483645: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") > try: > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > except RuntimeError, e: > print 'Shapefile invalida' > continue > > elif geo == 2 or geo == -2147483646: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") > try: > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > except RuntimeError, e: > print 'Shapefile invalida' > continue > > elif geo == 1 or geo == -2147483647: > print "Trabajando mapa "+ruta+"\\"+filename+" con > geometria "+ str(geo) > blue = > mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) > blue.allow_overlap = True > s=mapnik.Style() > r=mapnik.Rule() > r.symbols.append(blue) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") > try: > lyr.datasource = > mapnik.Shapefile(base=ruta,file=archivo[0]) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "La imagen " +i+ " fue creada." > except RuntimeError, e: > print 'Shapefile invalida' > continue > else: > print "Algo fallo y no entro a ninguna de las geometrias" > print "Listo" > else: > print "Tus argumentos no son correctos" ... and drop this > except IndexError: > print "Tus argumentos no son correctos" > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kliateni at gmail.com Fri Aug 5 18:45:58 2011 From: kliateni at gmail.com (=?utf-8?B?a2xpYXRlbmlAZ21haWwuY29t?=) Date: Fri, 05 Aug 2011 18:45:58 +0200 Subject: [Tutor] =?utf-8?q?Re_=3A__Python_loop_isn=27t_working?= Message-ID: <4e3c1e48.10c6e30a.0ec4.ffff99b4@mx.google.com> Can you try to split it into fonctions Because it is hard to read it. Envoy? depuis mon HTC ----- Reply message ----- De : "Susana Iraiis Delgado Rodriguez" Pour?: Objet : [Tutor] Python loop isn't working Date : ven., ao?t 5, 2011 18:14 Hello list! I have a python script which works with other libraries in order to create maps. The script looks for an extension in a specific directory and with mapnik makes the thumbnails. The module works fine from Python command line and Pyton IDLE, but I need this program to run from MS-DOS, when I added the try statement it started to fail. Module runs but doesn't do what I need. Console shows: C:\Python26>shp2png.py C:\\ .png Iniciando... Listo What am I doing wrong? import mapnik import os,fnmatch, sys from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer from osgeo import ogr,gdal,osr directorio = sys.argv[1] extension = sys.argv[2] try: ??? if len(sys.argv) == 3:??? ??? ??? print 'Iniciando...' ??? ??? file_list = [] ??? ??? folders = None ??? ??? for root, folders, files in os.walk( directorio+'\\' ): ??? ??? ??? for filename in fnmatch.filter(files, extension): ??? ??? ??? ??? file_list.append(os.path.join(root, filename)) ??? ??? for row, filepath in enumerate(file_list, start=1): ??? ??? ??? dir(LineSymbolizer().stroke) ??? ??? ??? shapeData = ogr.Open(filepath) ??? ??? ??? shp = 'Error al abrir el archivo' +filepath ??? ??? ??? if shapeData is None: ??? ??? ??? ??? print shp ??? ??? ??? ??? continue ??? ??? ??? layer = shapeData.GetLayer() ??? ??? ??? defn = layer.GetLayerDefn() ??? ??? ??? geo = defn.GetGeomType() ??? ??? ??? (ruta, filename) = os.path.split(filepath) ??? ??? ??? archivo = os.path.splitext(filename) ??? ??? ??? i = archivo[0]+'.png' ??????? ??? ??? ??? m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") ??? ??? ??? m.background = mapnik.Color('#EBEBEB') ??? ??? ??? s = mapnik.Style() ??? ??? ??? r=mapnik.Rule() ??????????????? ??? ??? ??? if geo == 3 or geo == -2147483645: ??? ??? ??? ??? print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) ??? ??? ??? ??? r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B'))) ??? ??? ??? ??? r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9)) ??? ??? ??? ??? s.rules.append(r) ??? ??? ??? ??? m.append_style('My Style',s) ??? ??? ??? ??? lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") ??? ??? ??? ??? try: ??? ??? ??? ??? ??? lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) ??? ??? ??? ??? ??? lyr.styles.append('My Style') ??? ??? ??? ??? ??? m.layers.append(lyr) ??? ??? ??? ??? ??? m.zoom_to_box(lyr.envelope()) ??? ??? ??? ??? ??? mapnik.render_to_file(m,i, 'png') ??? ??? ??? ??? ??? print "La imagen " +i+ " fue creada." ??? ??? ??? ??? except RuntimeError, e: ??? ??? ??? ??? ??? print 'Shapefile invalida' ??? ??? ??? ??? ??? continue??? ??? ??? ??? ??? ?? ??? ??? ??? elif geo == 2 or geo == -2147483646: ??? ??? ??? ??? print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) ??? ??? ??? ??? r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9)) ??? ??? ??? ??? s.rules.append(r) ??? ??? ??? ??? m.append_style('My Style',s) ??? ??? ??? ??? lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") ??? ??? ??? ??? try: ??? ??? ??? ??? ??? lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) ??? ??? ??? ??? ??? lyr.styles.append('My Style') ??? ??? ??? ??? ??? m.layers.append(lyr) ??? ??? ??? ??? ??? m.zoom_to_box(lyr.envelope()) ??? ??? ??? ??? ??? mapnik.render_to_file(m,i, 'png') ??? ??? ??? ??? ??? print "La imagen " +i+ " fue creada." ??? ??? ??? ??? except RuntimeError, e: ??? ??? ??? ??? ??? print 'Shapefile invalida' ??? ??? ??? ??? ??? continue??? ??? ??? ??? ??? ??? elif geo == 1 or geo == -2147483647: ??? ??? ??? ??? print "Trabajando mapa "+ruta+"\\"+filename+" con geometria "+ str(geo) ??? ??? ??? ??? blue = mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50) ??? ??? ??? ??? blue.allow_overlap = True ??? ??? ??? ??? s=mapnik.Style() ??? ??? ??? ??? r=mapnik.Rule() ??? ??? ??? ??? r.symbols.append(blue) ??? ??? ??? ??? s.rules.append(r) ??? ??? ??? ??? m.append_style('My Style',s) ??? ??? ??? ??? lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") ??? ??? ??? ??? try: ??? ??? ??? ??? ??? lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) ??? ??? ??? ??? ??? lyr.styles.append('My Style') ??? ??? ??? ??? ??? m.layers.append(lyr) ??? ??? ??? ??? ??? m.zoom_to_box(lyr.envelope()) ??? ??? ??? ??? ??? mapnik.render_to_file(m,i, 'png') ??? ??? ??? ??? ??? print "La imagen " +i+ " fue creada." ??? ??? ??? ??? except RuntimeError, e: ??? ??? ??? ??? ??? print 'Shapefile invalida' ??? ??? ??? ??? ??? continue??? ??? ??? ??? ??? ??? else: ??? ??? ??? ??? print "Algo fallo y no entro a ninguna de las geometrias" ??? ??? print "Listo" ??? else: ??? ??? ??? print "Tus argumentos no son correctos" except IndexError: ??? print "Tus argumentos no son correctos" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 5 19:20:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Aug 2011 18:20:57 +0100 Subject: [Tutor] Python loop isn't working In-Reply-To: References: Message-ID: <4E3C2679.7010807@btinternet.com> On 05/08/11 17:14, Susana Iraiis Delgado Rodriguez wrote: > The module works fine from Python command line and Pyton IDLE, but I > need this program to run from MS-DOS, when I added the try statement it > started to fail. Module runs but doesn't do what I need. Console shows: > > C:\Python26>shp2png.py C:\\ .png > Iniciando... > Listo > > What am I doing wrong? What makes you think it doesn't work? The first pruint is near the start of your code, the last near the end. So your program appears to have run. What else were you expecting to see happen? What is different when you run it from "Python command line"? In practice there should be no difference between you typing C:\Python26>shp2png.py C:\\ .png and typing C:\Python26> python shp2png.py C:\\ .png Or are you doing something at the Python >>> prompt? If so what? How are you "running" it when it works? Alan G. From alan.gauld at btinternet.com Fri Aug 5 19:20:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Aug 2011 18:20:57 +0100 Subject: [Tutor] Python loop isn't working In-Reply-To: References: Message-ID: <4E3C2679.7010807@btinternet.com> On 05/08/11 17:14, Susana Iraiis Delgado Rodriguez wrote: > The module works fine from Python command line and Pyton IDLE, but I > need this program to run from MS-DOS, when I added the try statement it > started to fail. Module runs but doesn't do what I need. Console shows: > > C:\Python26>shp2png.py C:\\ .png > Iniciando... > Listo > > What am I doing wrong? What makes you think it doesn't work? The first pruint is near the start of your code, the last near the end. So your program appears to have run. What else were you expecting to see happen? What is different when you run it from "Python command line"? In practice there should be no difference between you typing C:\Python26>shp2png.py C:\\ .png and typing C:\Python26> python shp2png.py C:\\ .png Or are you doing something at the Python >>> prompt? If so what? How are you "running" it when it works? Alan G. From tim at johnsons-web.com Fri Aug 5 21:25:08 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Aug 2011 11:25:08 -0800 Subject: [Tutor] Converting from a single module to a package Message-ID: <20110805192508.GI14664@johnsons-web.com> I'm been coding in python now for close to 10 years. one of the modules that I have composed for re-use has gotten pretty big: It is implemented as import tlib as std I am thinking about 'downsizing' this module and breaking it up into smaller components, thus a package. And I would like to do this without a lot of code revisions. I would welcome references to URLs on this topic. thanks -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From g.nius.ck at gmail.com Fri Aug 5 21:36:11 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 5 Aug 2011 15:36:11 -0400 Subject: [Tutor] Indexing a list with nested tuples In-Reply-To: References: Message-ID: On Tue, Aug 2, 2011 at 10:44 PM, Alexander Quest wrote: > > have [0] to indicate that I want to go to the second value within that > first item, which is the > point value > Actually [0] is the first element. I would go with [1]. -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Fri Aug 5 21:53:27 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 5 Aug 2011 15:53:27 -0400 Subject: [Tutor] Converting from a single module to a package In-Reply-To: <20110805192508.GI14664@johnsons-web.com> References: <20110805192508.GI14664@johnsons-web.com> Message-ID: To make a package, you make a folder named what you want to name the package, for example: virus_toolkit. Then you make a file in it called __init__.py. This is what you import if you import the virus_toolkit. You usually put documentation and general functions in this I believe (I'm not 100% sure on package etiquette.) Then you put various modules inside the folder, such as brute force, worms, and Trojan_horse. Then you can do from virus_toolkit import worms, and such, or if you want to unleash a full out attack and import them all, do from virus_toolkit import *. On Fri, Aug 5, 2011 at 3:25 PM, Tim Johnson wrote: > I'm been coding in python now for close to 10 years. one of the > modules that I have composed for re-use has gotten pretty big: > > It is implemented as > > import tlib as std > > I am thinking about 'downsizing' this module and breaking it up into > smaller components, thus a package. And I would like to do this > without a lot of code revisions. > > I would welcome references to URLs on this topic. > > thanks > -- > Tim > tim at johnsons-web dot com or akwebsoft dot com > http://www.akwebsoft.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Fri Aug 5 21:58:59 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 5 Aug 2011 15:58:59 -0400 Subject: [Tutor] [Python-ideas] multiple intro statements [was: combine for/with statement] In-Reply-To: <87pqklhmsv.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312388460.7526.19.camel@Gutsy> <87pqklhmsv.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: I give +0. I'm sure that it could come in use somewhere, as long as it isn't used everywhere. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Sat Aug 6 01:22:47 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Aug 2011 15:22:47 -0800 Subject: [Tutor] Converting from a single module to a package In-Reply-To: References: <20110805192508.GI14664@johnsons-web.com> Message-ID: <20110805232247.GA572@johnsons-web.com> * Christopher King [110805 12:03]: > To make a package, you make a folder named what you want to name the > package, for example: virus_toolkit. Then you make a file in it called > __init__.py. This is what you import if you import the virus_toolkit. You > usually put documentation and general functions in this I believe (I'm not > 100% sure on package etiquette.) Then you put various modules inside the > folder, such as brute force, worms, and Trojan_horse. Then you can do from > virus_toolkit import worms, and such, or if you want to unleash a full out > attack and import them all, do from virus_toolkit import *. > Thanks Christopher. Your take on the issue is pretty much the same as mine. However, my question is really how to make the transition from a single module to a package with the least amount of code changes. I'm guessing that I'm going to have to bite the bullet on this one. Example: # current way import tlib as std .... std.htmlButton(*arglist) # New way, after transition import tlib as std std.html.button(*arglist) #OR import html from tlib html.button(*arglist) #... oh well. Probably best to leave the original as is, for backwards compatibility. cheers -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From redacted@example.com Sat Aug 6 01:32:09 2011 From: redacted@example.com (Alexander Quest) Date: Fri, 5 Aug 2011 16:32:09 -0700 Subject: [Tutor] Indexing a list with nested tuples In-Reply-To: References: Message-ID: My bad- meant to say [1]. Thanks. -Alexander On Fri, Aug 5, 2011 at 12:36 PM, Christopher King wrote: > > > On Tue, Aug 2, 2011 at 10:44 PM, Alexander Quest wrote: >> >> have [0] to indicate that I want to go to the second value within that >> first item, which is the >> point value >> > Actually [0] is the first element. I would go with [1]. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Aug 6 01:38:29 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 05 Aug 2011 16:38:29 -0700 Subject: [Tutor] Converting from a single module to a package In-Reply-To: <20110805232247.GA572@johnsons-web.com> References: <20110805192508.GI14664@johnsons-web.com> <20110805232247.GA572@johnsons-web.com> Message-ID: On 8/5/2011 4:22 PM Tim Johnson said... > * Christopher King [110805 12:03]: >> To make a package, you make a folder named what you want to name the >> package, for example: virus_toolkit. Then you make a file in it called >> __init__.py. This is what you import if you import the virus_toolkit. You >> usually put documentation and general functions in this But you can provide for both methods if in tlib.__init__ you provide for backward compatibility. > # current way > import tlib as std > .... > std.htmlButton(*arglist) > > # New way, after transition > import tlib as std in tlib.__init__, include the following: import html htmlButton = html.button > std.html.button(*arglist) > #OR > import html from tlib > html.button(*arglist) Emile From tim at johnsons-web.com Sat Aug 6 03:55:06 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 5 Aug 2011 17:55:06 -0800 Subject: [Tutor] Converting from a single module to a package In-Reply-To: References: <20110805192508.GI14664@johnsons-web.com> <20110805232247.GA572@johnsons-web.com> Message-ID: <20110806015506.GB572@johnsons-web.com> * Emile van Sebille [110805 15:51]: > On 8/5/2011 4:22 PM Tim Johnson said... > >* Christopher King [110805 12:03]: > >>To make a package, you make a folder named what you want to name the > >>package, for example: virus_toolkit. Then you make a file in it called > >>__init__.py. This is what you import if you import the virus_toolkit. You > >>usually put documentation and general functions in this > > > But you can provide for both methods if in tlib.__init__ you provide > for backward compatibility. > > > > # current way > > import tlib as std > > .... > > std.htmlButton(*arglist) > > > > # New way, after transition > > import tlib as std > > in tlib.__init__, include the following: > > import html > htmlButton = html.button Yes. That's what I'm talking about. Thank you Emile. :) -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From timomlists at gmail.com Sat Aug 6 12:17:55 2011 From: timomlists at gmail.com (Timo) Date: Sat, 06 Aug 2011 12:17:55 +0200 Subject: [Tutor] Converting from a single module to a package In-Reply-To: References: <20110805192508.GI14664@johnsons-web.com> <20110805232247.GA572@johnsons-web.com> Message-ID: <4E3D14D3.6090002@gmail.com> On 06-08-11 01:38, Emile van Sebille wrote: > On 8/5/2011 4:22 PM Tim Johnson said... >> * Christopher King [110805 12:03]: >>> To make a package, you make a folder named what you want to name the >>> package, for example: virus_toolkit. Then you make a file in it called >>> __init__.py. This is what you import if you import the >>> virus_toolkit. You >>> usually put documentation and general functions in this > > > But you can provide for both methods if in tlib.__init__ you provide > for backward compatibility. > > >> # current way >> import tlib as std >> .... >> std.htmlButton(*arglist) >> >> # New way, after transition >> import tlib as std > > in tlib.__init__, include the following: > > import html > htmlButton = html.button And print a deprecation warning when people use it like this. That way you let them know this method could be removed in a next version. See the warnings module. Cheers, Timo > >> std.html.button(*arglist) >> #OR >> import html from tlib >> html.button(*arglist) > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From norman at khine.net Sat Aug 6 13:32:17 2011 From: norman at khine.net (Norman Khine) Date: Sat, 6 Aug 2011 13:32:17 +0200 Subject: [Tutor] adding dictionary value at position [-1] Message-ID: hello, i know that there are no indexes/positions in a python dictionary, what will be the most appropriate way to do this: addresses = {} for result in results.get_documents(): addresses[result.name] = result.title # we add a create new address option, this needs to be the last value addresses['create-new-address'] = 'Create new address!' # {"address-one": "Address One", "create-new-address": "Create new address!", "address-two": "Address Two"} return dumps(addresses) so that when i return the 'dumps(addresses)', i would like the 'create-new-address' to be always at the last position. any advise much appreciated. norman -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From rafadurancastaneda at gmail.com Sat Aug 6 13:59:47 2011 From: rafadurancastaneda at gmail.com (=?UTF-8?B?UmFmYWVsIER1csOhbiBDYXN0YcOxZWRh?=) Date: Sat, 06 Aug 2011 13:59:47 +0200 Subject: [Tutor] adding dictionary value at position [-1] In-Reply-To: References: Message-ID: <4E3D2CB3.9090808@gmail.com> Resending to list, since I click reply instead of reply to list, I'm sorry Norman since you are receiving twice: If you need an order item, use a list, so you can use a dictionary containing an ordered list of dictionaries. I think you want do somthing like this: import json addresses = {} addresses['values'] = [] values = [1, 2, 3] for index,value in enumerate(values): addresses['values'].append({index: value}) print(json.dumps(addresses)) Output will be: {"values": [{"0": 1}, {"1": 2}, {"2": 3}]} On 06/08/11 13:32, Norman Khine wrote: > hello, > i know that there are no indexes/positions in a python dictionary, > what will be the most appropriate way to do this: > > addresses = {} > for result in results.get_documents(): > addresses[result.name] = result.title > # we add a create new address option, this needs to be > the last value > addresses['create-new-address'] = 'Create new address!' > > # {"address-one": "Address One", "create-new-address": > "Create new address!", "address-two": "Address Two"} > > return dumps(addresses) > > > so that when i return the 'dumps(addresses)', i would like the > 'create-new-address' to be always at the last position. > > any advise much appreciated. > > norman > From d at davea.name Sat Aug 6 14:07:08 2011 From: d at davea.name (Dave Angel) Date: Sat, 06 Aug 2011 08:07:08 -0400 Subject: [Tutor] adding dictionary value at position [-1] In-Reply-To: References: Message-ID: <4E3D2E6C.4080806@davea.name> On 08/06/2011 07:32 AM, Norman Khine wrote: > hello, > i know that there are no indexes/positions in a python dictionary, > what will be the most appropriate way to do this: > > addresses = {} > for result in results.get_documents(): > addresses[result.name] = result.title > # we add a create new address option, this needs to be > the last value > addresses['create-new-address'] = 'Create new address!' > > # {"address-one": "Address One", "create-new-address": > "Create new address!", "address-two": "Address Two"} > > return dumps(addresses) > > > so that when i return the 'dumps(addresses)', i would like the > 'create-new-address' to be always at the last position. > > any advise much appreciated. > > norman > We can assume this is a fragment of a function, since it ends with a return. You don't say what this function is supposed to return, and you don't supply the source for dumps(). So, applying my crystal ball and figuring you want a list, just write dumps so it puts the create-new-address entry at the end. You could ensure that by changing the name create-new-address to zzz-create-new-address, and simply doing a sort. Or you could simply return return dumps(addresses) + "Create new address" and not put it into the dictionary at all. -- DaveA From norman at khine.net Sat Aug 6 15:18:47 2011 From: norman at khine.net (Norman Khine) Date: Sat, 6 Aug 2011 15:18:47 +0200 Subject: [Tutor] adding dictionary value at position [-1] In-Reply-To: <4E3D2E6C.4080806@davea.name> References: <4E3D2E6C.4080806@davea.name> Message-ID: hello, thanks for the replies On Sat, Aug 6, 2011 at 2:07 PM, Dave Angel wrote: > On 08/06/2011 07:32 AM, Norman Khine wrote: >> >> hello, >> i know that there are no indexes/positions in a python dictionary, >> what will be the most appropriate way to do this: >> >> ? ? ? ? ? ? ? ? addresses = {} >> ? ? ? ? ? ? ? ? for result in results.get_documents(): >> ? ? ? ? ? ? ? ? ? ? addresses[result.name] = result.title >> ? ? ? ? ? ? ? ? # we add a create new address option, this needs to be >> the last value >> ? ? ? ? ? ? ? ? addresses['create-new-address'] = 'Create new address!' >> >> ? ? ? ? ? ? ? ?# {"address-one": "Address One", "create-new-address": >> "Create new address!", "address-two": "Address Two"} >> >> ? ? ? ? ? ? ? ? return dumps(addresses) >> >> >> so that when i return the 'dumps(addresses)', i would like the >> 'create-new-address' to be always at the last position. >> >> any advise much appreciated. >> >> norman >> > We can assume this is a fragment of a function, since it ends with a return. > > You don't say what this function is supposed to return, and you don't supply > the source for dumps(). the function returns: {"address-one": "Address One", "create-new-address": "Create new address!", "zzz-address-two": "ZZZ Address Two"} > > So, applying my crystal ball and figuring you want a list, just write dumps > so it puts the create-new-address entry at the end. ?You could ensure that > by changing the name create-new-address to zzz-create-new-address, and > simply doing a sort. ?Or you could simply return > ? return dumps(addresses) + "Create new address" > > and not put it into the dictionary at all. > -- > > DaveA > > -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From tlinnet at gmail.com Sat Aug 6 15:59:33 2011 From: tlinnet at gmail.com (=?ISO-8859-1?Q?Troels_Emtek=E6r_Linnet?=) Date: Sat, 6 Aug 2011 15:59:33 +0200 Subject: [Tutor] Basic web form interaction with http://propka.ki.ku.dk/ Message-ID: Dear Python users. I am an semi-experienced in python, but totally new on the web interactions. I have been working with scripts to the protein program Pymol, which can be extended with python script. I hope that some of you can help me with an interaction script to http://propka.ki.ku.dk/. I hope that some of you can show be a basic python script to load the suitable python modules and interacting with the web form. The main idea is, to load a protein structure in pymol. Then writing a pymol/python script that saves the stucture of the protein into a .pdb file. Then open http://propka.ki.ku.dk/, send the .pdb file, wait 1-2 minutes for the result, and capture the result. I hope that some of you can show be the basics steps, to interact with the web form. Best Troels -------------- next part -------------- An HTML attachment was scrubbed... URL: From mat.korycinski at gmail.com Sat Aug 6 16:14:57 2011 From: mat.korycinski at gmail.com (=?ISO-8859-2?Q?Mateusz_Koryci=F1ski?=) Date: Sat, 6 Aug 2011 16:14:57 +0200 Subject: [Tutor] Basic web form interaction with http://propka.ki.ku.dk/ In-Reply-To: References: Message-ID: Hi, Have You tried something similar to interface used in BioPython? I think U could get solution by reading code for connection with databases like Entrez. Maybe this will give you some ideas. Do you want your script to download pdb file from PDB database? Or you want only sending and receiving from propka? Cheers, Mateusz 2011/8/6 Troels Emtek?r Linnet > Dear Python users. > > I am an semi-experienced in python, but totally new on the web > interactions. > I have been working with scripts o the protein program Pymol, which can be > extended with python script. > > I hope that some of you can help me with an interaction script to > http://propka.ki.ku.dk/. > I hope that some of you can show be a basic python script to load the > suitable python modules and interacting > with the web form. > > The main idea is, to load a protein structure in pymol. > Then writing a pymol/python script that saves the stucture of the protein > into a .pdb file. > Then open http://propka.ki.ku.dk/, send the .pdb file, wait 1-2 minutes > for the result, and capture the result. > > I hope that some of you can show be the basics steps, to interact with the > web form. > > Best > Troels > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Pozdrawiam, Mateusz Koryci?ski -------------- next part -------------- An HTML attachment was scrubbed... URL: From tlinnet at gmail.com Sat Aug 6 16:44:32 2011 From: tlinnet at gmail.com (=?ISO-8859-1?Q?Troels_Emtek=E6r_Linnet?=) Date: Sat, 6 Aug 2011 16:44:32 +0200 Subject: [Tutor] Basic web form interaction with http://propka.ki.ku.dk/ In-Reply-To: References: Message-ID: Hi Mateus. No, I was certainly not aware of BioPython. What a nice project. I will check it out. No, the script should not download a .pdb file. The idea is, that a "researcher/student" sits with his/hers favorite protein in pymol and would like to know the pKa value of his/hers favorite amino acids. The student "probably" has only pymol installed, and would not like to install to many other python packages. Maybe the student can't, because it is a university computer. With this web-interaction script, the students activate the script, with: get_pka Molecule, residue The script saves the molecule to a .pdb file. Interact with the propka web site, send the file, wait 1 minute, grep for the line with the amino acid, and parse it back to pymol, so the student can see the pKa. To big benefit with this, is that the student does not have to handle to hard installations of scripts/programs or the manual way. And the student knows, that the pKa prediction is from the newest software available. If the student get greedy, he/she starts writing a pymol script that alter the pdb structure in pymol, and receive the new pKa value for each structural change. The downside, is of course the "waiting" time for the server response. Best Troels Troels Emtek?r Linnet Karl-Liebknecht-Stra?e 53, 2 RE 04107 Leipzig, Tyskland Mobil: +49 1577-8944752 2011/8/6 Mateusz Koryci?ski > Hi, > > Have You tried something similar to interface used in BioPython? I think U > could get solution by reading code for connection with databases like > Entrez. Maybe this will give you some ideas. > > Do you want your script to download pdb file from PDB database? Or you want > only sending and receiving from propka? > > > Cheers, > Mateusz > > 2011/8/6 Troels Emtek?r Linnet > >> Dear Python users. >> >> I am an semi-experienced in python, but totally new on the web >> interactions. >> I have been working with scripts o the protein program Pymol, which can be >> extended with python script. >> >> >> I hope that some of you can help me with an interaction script to >> http://propka.ki.ku.dk/. >> I hope that some of you can show be a basic python script to load the >> suitable python modules and interacting >> with the web form. >> >> The main idea is, to load a protein structure in pymol. >> Then writing a pymol/python script that saves the stucture of the protein >> into a .pdb file. >> Then open http://propka.ki.ku.dk/, send the .pdb file, wait 1-2 minutes >> for the result, and capture the result. >> >> I hope that some of you can show be the basics steps, to interact with the >> web form. >> >> Best >> Troels >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Pozdrawiam, > Mateusz Koryci?ski > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mat.korycinski at gmail.com Sat Aug 6 17:24:30 2011 From: mat.korycinski at gmail.com (=?ISO-8859-2?Q?Mateusz_Koryci=F1ski?=) Date: Sat, 6 Aug 2011 17:24:30 +0200 Subject: [Tutor] Basic web form interaction with http://propka.ki.ku.dk/ In-Reply-To: References: Message-ID: Hi, IMHO, first of all you should check if server admins allow automatic connection outside web browser. Maybe they do and there a simple way to connect and they will tell you how (for example how query should look like as a command for software installed on server). I just check and they have link to source code and some scripts - check this out, maybe there are scripts for sending query? About libraries - I don't really know how it looks like in Windows, but in Linux (I am working mostly with it) you can download libraries to home folder and import them to script directly from directory. Or you can export new path to show python where it should look for libraries. In this case you don't need root privileges. If it's bioinformatics classes you should ask department admin to install biopython. It have libraries to handle pdb files so it could be very helpful. Cheers, Mateusz 2011/8/6 Troels Emtek?r Linnet > Hi Mateus. > > No, I was certainly not aware of BioPython. What a nice project. I will > check it out. > > No, the script should not download a .pdb file. > The idea is, that a "researcher/student" sits with his/hers favorite > protein in pymol and would like to know the pKa value > of his/hers favorite amino acids. > > The student "probably" has only pymol installed, and would not like to > install to many other python packages. > Maybe the student can't, because it is a university computer. > > With this web-interaction script, the students activate the script, with: > get_pka Molecule, residue > > The script saves the molecule to a .pdb file. Interact with the propka web > site, send the file, wait 1 minute, grep for the line > with the amino acid, and parse it back to pymol, so the student can see the > pKa. > > To big benefit with this, is that the student does not have to handle to > hard installations of scripts/programs or the manual way. > And the student knows, that the pKa prediction is from the newest software > available. > If the student get greedy, he/she starts writing a pymol script that alter > the pdb structure in pymol, and receive the new pKa value for each > structural change. > The downside, is of course the "waiting" time for the server response. > > Best > Troels > > > > Troels Emtek?r Linnet > Karl-Liebknecht-Stra?e 53, 2 RE > 04107 Leipzig, Tyskland > Mobil: +49 1577-8944752 > > > > 2011/8/6 Mateusz Koryci?ski > >> Hi, >> >> Have You tried something similar to interface used in BioPython? I think U >> could get solution by reading code for connection with databases like >> Entrez. Maybe this will give you some ideas. >> >> Do you want your script to download pdb file from PDB database? Or you >> want only sending and receiving from propka? >> >> >> Cheers, >> Mateusz >> >> 2011/8/6 Troels Emtek?r Linnet >> >>> Dear Python users. >>> >>> I am an semi-experienced in python, but totally new on the web >>> interactions. >>> I have been working with scripts o the protein program Pymol, which can >>> be extended with python script. >>> >>> >>> I hope that some of you can help me with an interaction script to >>> http://propka.ki.ku.dk/. >>> I hope that some of you can show be a basic python script to load the >>> suitable python modules and interacting >>> with the web form. >>> >>> The main idea is, to load a protein structure in pymol. >>> Then writing a pymol/python script that saves the stucture of the protein >>> into a .pdb file. >>> Then open http://propka.ki.ku.dk/, send the .pdb file, wait 1-2 minutes >>> for the result, and capture the result. >>> >>> I hope that some of you can show be the basics steps, to interact with >>> the web form. >>> >>> Best >>> Troels >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> >> -- >> Pozdrawiam, >> Mateusz Koryci?ski >> > > -- Pozdrawiam, Mateusz Koryci?ski -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 6 17:49:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 06 Aug 2011 16:49:44 +0100 Subject: [Tutor] adding dictionary value at position [-1] In-Reply-To: References: Message-ID: <4E3D6298.4080708@btinternet.com> On 06/08/11 12:32, Norman Khine wrote: > hello, > i know that there are no indexes/positions in a python dictionary, > what will be the most appropriate way to do this: > > addresses = {} > for result in results.get_documents(): > addresses[result.name] = result.title > addresses['create-new-address'] = 'Create new address!' > return dumps(addresses) > > so that when i return the 'dumps(addresses)', i would like the > 'create-new-address' to be always at the last position. Translating that into English, what I think you want is: You want to print a dictionary (or return a string representation?) such that the last thing added to the dictionary is the last thing listed? Or, do you want the string representation to have all of the items in the order they were inserted? Or do you want the string representation to always have the specific 'create_new_address' listed last regardless of where it was originally inserted? And do you really want just a string representation in this order or do you really want the data stored and accessible in that order? (In which case don't use a dictionary!) I guess the real question is why you need the dictionary in the first place? Dictionaries facilitate random access to your data based on key values. Is that a necessary feature of your application? If so use a dictionary but consider adding an index value to the data(*). You can then sort the dictionary based on that index. If you don;t need the random access aspect then store the data in a list of (key,value) tuples instead. (*)One way to add an index is: def insert_in_dict(d,key,val): d[key] = (len(d), val) Obviously you need to drop the index when accessing the real values: def get_real_val(d,key): return d[key][1] And you could even clean all that up by creating a class derived from dict. You can then sort the dictionary by providing a key function to extract the index to sorted() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Sat Aug 6 18:18:07 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 06 Aug 2011 18:18:07 +0200 Subject: [Tutor] adding dictionary value at position [-1] References: <4E3D6298.4080708@btinternet.com> Message-ID: Alan Gauld wrote: > On 06/08/11 12:32, Norman Khine wrote: >> hello, >> i know that there are no indexes/positions in a python dictionary, >> what will be the most appropriate way to do this: >> >> addresses = {} >> for result in results.get_documents(): >> addresses[result.name] = result.title >> addresses['create-new-address'] = 'Create new address!' >> return dumps(addresses) >> >> so that when i return the 'dumps(addresses)', i would like the >> 'create-new-address' to be always at the last position. > > Translating that into English, what I think you want is: > > You want to print a dictionary (or return a string representation?) such > that the last thing added to the dictionary is the last thing listed? > Or, do you want the string representation to have all of the items in > the order they were inserted? > > Or do you want the string representation to always have the specific > 'create_new_address' listed last regardless of where it was originally > inserted? > > And do you really want just a string representation in this order or do > you really want the data stored and accessible in that order? (In which > case don't use a dictionary!) > > I guess the real question is why you need the dictionary in the first > place? Dictionaries facilitate random access to your data based on key > values. Is that a necessary feature of your application? If so use a > dictionary but consider adding an index value to the data(*). You can > then sort the dictionary based on that index. If you don;t need the > random access aspect then store the data in a list of (key,value) tuples > instead. > > (*)One way to add an index is: > > def insert_in_dict(d,key,val): > d[key] = (len(d), val) > > Obviously you need to drop the index when accessing the real values: > > def get_real_val(d,key): > return d[key][1] > > And you could even clean all that up by creating a class derived from > dict. In Python 2.7 there is already such a class: collections.OrderedDict: >>> from collections import OrderedDict >>> up = OrderedDict.fromkeys("abc") >>> down = OrderedDict.fromkeys("cba") >>> up OrderedDict([('a', None), ('b', None), ('c', None)]) >>> down OrderedDict([('c', None), ('b', None), ('a', None)]) From g.nius.ck at gmail.com Sat Aug 6 20:24:36 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Sat, 6 Aug 2011 14:24:36 -0400 Subject: [Tutor] [Python-ideas] Access to function objects In-Reply-To: References: Message-ID: On Sat, Aug 6, 2011 at 4:10 AM, David Townshend wrote: > > def counter(add) as func: > if not hasattr(func, 'count'): > func.count = 0 > func.count += 1 > print(func.count) > You already can do that without an as statment. >>> def counter(add): if not hasattr(counter, 'count'): counter.count = 0 counter.count += 1 return counter.count >>> counter('You ever notice how this parameter is never used anyway?') Output: 1 >>> counter('Oh well') Output: 2 -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Sun Aug 7 02:52:02 2011 From: questions.anon at gmail.com (questions anon) Date: Sun, 7 Aug 2011 10:52:02 +1000 Subject: [Tutor] gzip Message-ID: Hi All, I am trying to decompress at gzipped netcdf file and place the decompressed file in the same folder without the *.gz extension. I am using gzip. If I use the following code nothing happens. import gzip filepath="D:/test/surfacetemp.nc.gz" compresseddata=gzip.open(filepath, "rb") file_content=compresseddata.read() How can I output the decompressed file? something like: output=file_content.write(filepath[:-3]) thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sun Aug 7 03:22:56 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 7 Aug 2011 02:22:56 +0100 Subject: [Tutor] gzip In-Reply-To: References: Message-ID: On 7 August 2011 01:52, questions anon wrote: > How can I output the decompressed file? something like: > output=file_content.write(filepath[:-3]) > > See here: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files And here: http://docs.python.org/library/stdtypes.html#file.write Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Sun Aug 7 05:42:07 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 7 Aug 2011 05:42:07 +0200 Subject: [Tutor] commandline unable to read numbers? Message-ID: I have a quite odd problem, and I've come across it before but probably ignored it at the time because I had other concerns. I've tried googling for the answer but haven't really come closer to solving it. This is what happens: C:\[path]\nester>C:\Python32\python.ex e setup.py register running register running check We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: 1 Please choose one of the four options! We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: No matter what I enter it will loop back. It seems my commandline can't read numbers? The other time I noticed it was while working on a notebook example: class Menu: """Display a menu and respond to choices when run.""" def __init__(self): self.notebook = Notebook() self.choices = { "1": self.show_notes, "2": self.search_notes, "3": self.add_note, "4": self.modify_note, "5": self.quit } def display_menu(self): print(""" Notebook Menu 1. Show All Notes 2. Search Notes 3. Add Note 4. Modify Note 5. Quit """) def run(self): """Display the menu and respond to choices.""" while True: self.display_menu() choice = input("Enter an option: ") action = self.choices.get(choice) if action: action() else: print("{0} is not a valid choice.".format(choice)) This code works in IDLE, so I know it's nothing in the actual code that's a problem, but when I run it in commandline it will just repeat "is not a valid choice." Note that it does this no matter what I actually enter, it won't actually get any kind of input except the enter key. So I suppose it's a problem with input() (I'm using python 3.2 btw). Anyone have any insights? -- best regards, Robert S. From steve at pearwood.info Sun Aug 7 07:00:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 07 Aug 2011 15:00:16 +1000 Subject: [Tutor] commandline unable to read numbers? In-Reply-To: References: Message-ID: <4E3E1BE0.2020107@pearwood.info> Robert Sjoblom wrote: > I have a quite odd problem, and I've come across it before but > probably ignored it at the time because I had other concerns. I've > tried googling for the answer but haven't really come closer to > solving it. > This is what happens: > C:\[path]\nester>C:\Python32\python.ex > e setup.py register > running register > running check > We need to know who you are, so please choose either: > 1. use your existing login, > 2. register as a new user, > 3. have the server generate a new password for you (and email it to you), or > 4. quit > Your selection [default 1]: > 1 > Please choose one of the four options! Looks like a bug in the setup.py script. You should report it to the author of the package. Have you tried just pressing enter without entering anything? > No matter what I enter it will loop back. It seems my commandline > can't read numbers? The other time I noticed it was while working on a > notebook example: [...] > This code works in IDLE, so I know it's nothing in the actual code > that's a problem, Apart from the fact that it is incomplete and won't run as given, it seems fine. > but when I run it in commandline it will just repeat > "is not a valid choice." Note that it does this no matter what I > actually enter, it won't actually get any kind of input except the > enter key. So I suppose it's a problem with input() (I'm using python > 3.2 btw). Anyone have any insights? You're not telling us how you're running it from the command line. My guess is that when you try, you're ending up with a different version of Python, namely Python 2.x, where input() has different semantics. Try putting print("choice = ", choice, type(choice)) immediately after the call to input in your code, and seeing what it prints. My guess is that it will claim choice is a int instead of a string. -- Steven From emailkgnow at gmail.com Sun Aug 7 10:05:51 2011 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 7 Aug 2011 11:05:51 +0300 Subject: [Tutor] tkinter issue in python 3 Message-ID: Hi all, I'm studying this tutorialabout tkinter, but it that it's code in a 2.X. I'm using the following code in python 3, but when i hit quite in the resulting widget it hangs. I've tried modifying the things I know about to no avail. Can anyone help? Here's my code: from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button=Button(frame, text='Quit', fg='red', command=frame.quit) self.button.pack(side=LEFT) self.hi_there=Button(frame, text='hello', command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print('hi there, everyone') root=Tk() app = App(root) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Aug 7 13:04:08 2011 From: d at davea.name (Dave Angel) Date: Sun, 07 Aug 2011 07:04:08 -0400 Subject: [Tutor] commandline unable to read numbers? In-Reply-To: <4E3E1BE0.2020107@pearwood.info> References: <4E3E1BE0.2020107@pearwood.info> Message-ID: <4E3E7128.9040502@davea.name> On 08/07/2011 01:00 AM, Steven D'Aprano wrote: > Robert Sjoblom wrote: >> I have a quite odd problem, and I've come across it before but >> probably ignored it at the time because I had other concerns. I've >> tried googling for the answer but haven't really come closer to >> solving it. >> This is what happens: >> C:\[path]\nester>C:\Python32\python.ex >> e setup.py register >> running register >> running check >> We need to know who you are, so please choose either: >> 1. use your existing login, >> 2. register as a new user, >> 3. have the server generate a new password for you (and email it to >> you), or >> 4. quit >> Your selection [default 1]: >> 1 >> Please choose one of the four options! > > Looks like a bug in the setup.py script. You should report it to the > author of the package. > > Have you tried just pressing enter without entering anything? > > >> No matter what I enter it will loop back. It seems my commandline >> can't read numbers? The other time I noticed it was while working on a >> notebook example: > [...] >> This code works in IDLE, so I know it's nothing in the actual code >> that's a problem, > > Apart from the fact that it is incomplete and won't run as given, it > seems fine. > > >> but when I run it in commandline it will just repeat >> "is not a valid choice." Note that it does this no matter what I >> actually enter, it won't actually get any kind of input except the >> enter key. So I suppose it's a problem with input() (I'm using python >> 3.2 btw). Anyone have any insights? > > You're not telling us how you're running it from the command line. My > guess is that when you try, you're ending up with a different version > of Python, namely Python 2.x, where input() has different semantics. > > Try putting > > print("choice = ", choice, type(choice)) > > immediately after the call to input in your code, and seeing what it > prints. My guess is that it will claim choice is a int instead of a > string. > > One other thing to test is to print sys.version at the beginning of your program. That will confirm Steven's hypothesis that you have two different versions of Python. (Clearly, you'll also need to import sys) -- DaveA From __peter__ at web.de Sun Aug 7 13:16:58 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Aug 2011 13:16:58 +0200 Subject: [Tutor] tkinter issue in python 3 References: Message-ID: Khalid Al-Ghamdi wrote: > I'm studying this > tutorialabout > tkinter, but it that it's code in a 2.X. > > I'm using the following code in python 3, but when i hit quite in the > resulting widget it hangs. I've tried modifying the things I know about to > no avail. Can anyone help? > > Here's my code: > > from tkinter import * > > class App: > def __init__(self, master): > frame = Frame(master) > frame.pack() > > self.button=Button(frame, text='Quit', fg='red', > command=frame.quit) self.button.pack(side=LEFT) > > self.hi_there=Button(frame, text='hello', command=self.say_hi) > self.hi_there.pack(side=LEFT) > > def say_hi(self): > print('hi there, everyone') > > root=Tk() > app = App(root) > root.mainloop() There is nothing suspicious in the above code. If you are running it from within IDLE, try again from the commandline. From __peter__ at web.de Sun Aug 7 13:28:26 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Aug 2011 13:28:26 +0200 Subject: [Tutor] commandline unable to read numbers? References: Message-ID: Robert Sjoblom wrote: > I have a quite odd problem, and I've come across it before but > probably ignored it at the time because I had other concerns. I've > tried googling for the answer but haven't really come closer to > solving it. > This is what happens: > C:\[path]\nester>C:\Python32\python.ex > e setup.py register > running register > running check > We need to know who you are, so please choose either: > 1. use your existing login, > 2. register as a new user, > 3. have the server generate a new password for you (and email it to you), > or 4. quit > Your selection [default 1]: > 1 > Please choose one of the four options! > We need to know who you are, so please choose either: > 1. use your existing login, > 2. register as a new user, > 3. have the server generate a new password for you (and email it to you), > or 4. quit > Your selection [default 1]: > > No matter what I enter it will loop back. It seems my commandline > can't read numbers? The other time I noticed it was while working on a > notebook example: > > class Menu: > """Display a menu and respond to choices when run.""" > def __init__(self): > self.notebook = Notebook() > self.choices = { > "1": self.show_notes, > "2": self.search_notes, > "3": self.add_note, > "4": self.modify_note, > "5": self.quit > } > > def display_menu(self): > print(""" > Notebook Menu > > 1. Show All Notes > 2. Search Notes > 3. Add Note > 4. Modify Note > 5. Quit > """) > > def run(self): > """Display the menu and respond to choices.""" > while True: > self.display_menu() > choice = input("Enter an option: ") > action = self.choices.get(choice) > if action: > action() > else: > print("{0} is not a valid choice.".format(choice)) > > This code works in IDLE, so I know it's nothing in the actual code > that's a problem, but when I run it in commandline it will just repeat > "is not a valid choice." Note that it does this no matter what I > actually enter, it won't actually get any kind of input except the > enter key. So I suppose it's a problem with input() (I'm using python > 3.2 btw). Anyone have any insights? I think you are on the right track: Python 3.2's input() has a nasty bug on Windows (http://bugs.python.org/issue11272). If you repeat the following in your interactive interpreter (invoked from the commmandline) >>> input() 123 '123' and see '123\r' instead of just '123' you are affected. I believe the bug is fixed in 3.2.1, so the easiest solution to your problem would be to switch to that version. From robert.sjoblom at gmail.com Sun Aug 7 16:35:34 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 7 Aug 2011 16:35:34 +0200 Subject: [Tutor] commandline unable to read numbers? (Steven D'Aprano) Message-ID: > Robert Sjoblom wrote: >> I have a quite odd problem, and I've come across it before but >> probably ignored it at the time because I had other concerns. I've >> tried googling for the answer but haven't really come closer to >> solving it. >> This is what happens: >> C:\[path]\nester>C:\Python32\python.ex >> e setup.py register >> running register >> running check >> We need to know who you are, so please choose either: >> ?1. use your existing login, >> ?2. register as a new user, >> ?3. have the server generate a new password for you (and email it to you), or >> ?4. quit >> Your selection [default 1]: >> 1 >> Please choose one of the four options! > > Looks like a bug in the setup.py script. You should report it to the > author of the package. > > Have you tried just pressing enter without entering anything? Yes, and it goes back to "We need to know who you are, so please choose either:" The setup.py in question is the distutils.core one (from distutils.core import setup). >> No matter what I enter it will loop back. It seems my commandline >> can't read numbers? The other time I noticed it was while working on a >> notebook example: > [...] >> This code works in IDLE, so I know it's nothing in the actual code >> that's a problem, > > Apart from the fact that it is incomplete and won't run as given, it > seems fine. I only copied the relevant part, but here's the entire code if necessary: http://pastebin.com/PkB6P5fk >> but when I run it in commandline it will just repeat >> "is not a valid choice." Note that it does this no matter what I >> actually enter, it won't actually get any kind of input except the >> enter key. So I suppose it's a problem with input() (I'm using python >> 3.2 btw). Anyone have any insights? > > You're not telling us how you're running it from the command line. My > guess is that when you try, you're ending up with a different version of > Python, namely Python 2.x, where input() has different semantics. I run it like this: C:\Python32\python.exe setup.py register (or in the case of menu.py: C:\Python32\python.exe menu.py) -- which, when started, prints: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\>C:\Python32\python.exe Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> > > Try putting > > print("choice = ", choice, type(choice)) > > immediately after the call to input in your code, and seeing what it > prints. My guess is that it will claim choice is a int instead of a string. I thought so too at first, but that's not the issue: C:\Python32\python.exe menu.py Notebook Menu 1. Show All Notes 2. Search Notes 3. Add Note 4. Modify Note 5. Quit Enter an option: 1 is not a valid choice. -- best regards, Robert S. From dreyemi at gmail.com Sun Aug 7 17:37:24 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 7 Aug 2011 16:37:24 +0100 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack Message-ID: Hello all, Please I need help figuring out this permutation. I have a dict like this: x = "{'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 3456}", "{'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}"; #loop through and get the keys of each for k,v in x: keys = dict(x).keys() print keys I get ValueError: too many values to unpack Any help will be much appreciated. Regards -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sun Aug 7 18:17:21 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 07 Aug 2011 09:17:21 -0700 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: References: Message-ID: <4E3EBA91.7030801@alchemy.com> On 07-Aug-11 08:37, Kayode Odeyemi wrote: > Hello all, > > Please I need help figuring out this permutation. > > I have a dict like this: > > x = "{'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': > 3456}", "{'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, > 'tel': 34510}"; First of all, that's not a dict. It's just a tuple of strings. so, when you say: > #loop through and get the keys of each > for k,v in x: You'll get one iteration, where k=the first string and v=the second. However, you ignore k and v in all the code that follows, so I'm really confused what you're trying to do here. > keys = dict(x).keys() Now you try to create a dict out of a tuple of strings, which won't quite work as written but in principle would only have created a dictionary with the first string as the key, and the second as value, not nested dictionaries. The dict() constructor really expects to see a sequence of key/value pairs, so it's going to take your sequence x as a list of two such pairs, and then raise an exception because the strings are not key/value pairs. This would succeed if you said keys = dict((x,)).keys() perhaps, but it's still not at all what you're trying to accomplish. > print keys Note that you are re-assigning the value of keys each time through the loop but printing its last value after the loop exits. Is that what you intended? You're expecting Python to take a string that looks like Python source code and know that you want it to be interpreted as source code. Instead of using string values, use actual Python syntax directly, like: x = { 'pk': 1L, 'model': 'trans', 'fields': { 'updated': 2011, 'tel': 3456 } } -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From knacktus at googlemail.com Sun Aug 7 18:40:16 2011 From: knacktus at googlemail.com (Knacktus) Date: Sun, 07 Aug 2011 18:40:16 +0200 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: References: Message-ID: <4E3EBFF0.9050504@googlemail.com> Am 07.08.2011 17:37, schrieb Kayode Odeyemi: > Hello all, > > Please I need help figuring out this permutation. > > I have a dict like this: > > x = "{'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': > 3456}", "{'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, > 'tel': 34510}"; This is not a dict, it's a tuple of two strings. (By the way, the ";" is only needed if you would want to place several statements in one line, which you shouldn't do.) A tuple of dicts would be: x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 3456}}, {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}} Note the additional closing "}" for each entry. You can loop over the entries of your tuple and check the type: for entry in x: print type(entry) Now you can extend this loop and loop over the keys and values for each entry: for entry in x: for key, value in entry.items(): print key print value If key is "fields" then value is another dictionary. So if you wish you could also get the entries of those dicts explicitly: for entry in x: for key, value in entry.items(): print key if key == "fields": for field_key, field_value in value.items(): print " %s" % field_key print " %s" % field_value else: print " %s" % value For string formatting used here see: http://docs.python.org/library/stdtypes.html#string-formatting-operations HTH, Jan > > #loop through and get the keys of each > for k,v in x: > keys = dict(x).keys() > print keys > > I get ValueError: too many values to unpack > > Any help will be much appreciated. > > Regards > > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Sun Aug 7 18:45:54 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 07 Aug 2011 09:45:54 -0700 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: <4E3EBA91.7030801@alchemy.com> References: <4E3EBA91.7030801@alchemy.com> Message-ID: <4E3EC142.1000205@alchemy.com> On 07-Aug-11 09:17, Steve Willoughby wrote: > First of all, that's not a dict. It's just a tuple of strings. > so, when you say: > >> #loop through and get the keys of each >> for k,v in x: > > You'll get one iteration, where k=the first string and v=the second. > However, you ignore k and v in all the code that follows, so I'm really > confused what you're trying to do here. I just noticed I glossed over a key point, for that to work you'd need x to be a sequence of such tuples. As it stands there, you'll get an error because each element of x is a single string, so it can't pull two values out of each of them. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From steve at pearwood.info Sun Aug 7 19:25:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 08 Aug 2011 03:25:42 +1000 Subject: [Tutor] commandline unable to read numbers? (Steven D'Aprano) In-Reply-To: References: Message-ID: <4E3ECA96.5000408@pearwood.info> Robert Sjoblom wrote: [...] > > Have you tried just pressing enter without entering anything? > Yes, and it goes back to "We need to know who you are, so please > choose either:" The setup.py in question is the distutils.core one > (from distutils.core import setup). It sounds like Peter Otten has the solution: it's a bug in input on Windows systems. Follow the instructions in his post. -- Steven From robert.sjoblom at gmail.com Sun Aug 7 21:56:05 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 7 Aug 2011 21:56:05 +0200 Subject: [Tutor] commandline unable to read numbers? Message-ID: > I think you are on the right track: Python 3.2's input() has a nasty bug on > Windows (http://bugs.python.org/issue11272). If you repeat the following in > your interactive interpreter (invoked from the commmandline) > >>>> input() > 123 > '123' > > and see '123\r' instead of just '123' you are affected. I believe the bug is > fixed in 3.2.1, so the easiest solution to your problem would be to switch > to that version. Well that's what I get ('123\r'); installing 3.2.1 fixed it. setup.py works, as does menu.py (except the search function, but that's a different problem). Thank you (and everyone else who put time and effort into trying to solve this)! -- best regards, Robert S. From questions.anon at gmail.com Mon Aug 8 01:57:51 2011 From: questions.anon at gmail.com (questions anon) Date: Mon, 8 Aug 2011 09:57:51 +1000 Subject: [Tutor] gzip In-Reply-To: References: Message-ID: Thank you, I didn't realise that was all I needed. Moving on to the next problem: I would like to loop through a number of directories and decompress each *.gz file and leave them in the same folder but the code I have written only seems to focus on the last folder. Not sure where I have gone wrong. Any feedback will be greatly appreciated. import gzip import os MainFolder=r"D:/DSE_work/temp_samples/" for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: outputfolder=os.path.join(path,dir) print "the path and dirs are:", outputfolder for gzfiles in files: print gzfiles if gzfiles[-3:]=='.gz': print 'dealing with gzfiles:', dir, gzfiles f_in=os.path.join(outputfolder,gzfiles) print f_in compresseddata=gzip.GzipFile(f_in, "rb") newFile=compresseddata.read() f_out=open(f_in[:-3], "wb") f_out.write(newFile) On Sun, Aug 7, 2011 at 11:22 AM, Walter Prins wrote: > > > On 7 August 2011 01:52, questions anon wrote: > >> How can I output the decompressed file? something like: >> output=file_content.write(filepath[:-3]) >> >> > See here: > http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files > And here: > http://docs.python.org/library/stdtypes.html#file.write > > Walter > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Mon Aug 8 10:18:06 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Mon, 8 Aug 2011 09:18:06 +0100 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: <4E3EC142.1000205@alchemy.com> References: <4E3EBA91.7030801@alchemy.com> <4E3EC142.1000205@alchemy.com> Message-ID: Thanks so much. This is exactly what I'm looking for. In addition, since fields is obviously a dict, I won't want to have to display it's keys repeatedly. Is there a way to get the keys once, have it displayed and used as columns, then it's values are displayed beneath it. Something like: updated tel 2011 3456 2011 34510 right now, I'm having it displayed as updated 2011 tel 3456 updated 2011 tel 34510 I am having the fields being written using a writer like this: x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 3456}}, {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}} writer = csv.writer(response) for entry in x: for key, value in entry.items(): print key if key == "fields": for field_key, field_value in value.items(): d = [field_key] #a list of sequence x = [field_value] writer.writerow(d) writer.writerow(x) else: print " %s" % value On Sun, Aug 7, 2011 at 5:45 PM, Steve Willoughby wrote: > On 07-Aug-11 09:17, Steve Willoughby wrote: > > First of all, that's not a dict. It's just a tuple of strings. >> so, when you say: >> >> #loop through and get the keys of each >>> for k,v in x: >>> >> >> You'll get one iteration, where k=the first string and v=the second. >> However, you ignore k and v in all the code that follows, so I'm really >> confused what you're trying to do here. >> > > I just noticed I glossed over a key point, for that to work you'd need x to > be a sequence of such tuples. As it stands there, you'll get an error > because each element of x is a single string, so it can't pull two values > out of each of them. > > > -- > Steve Willoughby / steve at alchemy.com > "A ship in harbor is safe, but that is not what ships are built for." > PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Aug 8 10:34:15 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 08 Aug 2011 10:34:15 +0200 Subject: [Tutor] gzip In-Reply-To: References: Message-ID: questions anon, 08.08.2011 01:57: > Thank you, I didn't realise that was all I needed. > Moving on to the next problem: > I would like to loop through a number of directories and decompress each > *.gz file and leave them in the same folder but the code I have written only > seems to focus on the last folder. Not sure where I have gone wrong. > Any feedback will be greatly appreciated. > > > import gzip > import os > > MainFolder=r"D:/DSE_work/temp_samples/" > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > outputfolder=os.path.join(path,dir) > print "the path and dirs are:", outputfolder > for gzfiles in files: > print gzfiles > if gzfiles[-3:]=='.gz': > print 'dealing with gzfiles:', dir, gzfiles > f_in=os.path.join(outputfolder,gzfiles) > print f_in > compresseddata=gzip.GzipFile(f_in, "rb") > newFile=compresseddata.read() > f_out=open(f_in[:-3], "wb") > f_out.write(newFile) Note how "outputfolder" is set and reset in the first inner loop, *before* starting the second inner loop. Instead, build the output directory name once, without looping over the directories (which, as far as I understand your intention, you can ignore completely). Also, see the shutils module. It has a method that efficiently copies data between open file(-like) objects. With that, you can avoid reading the whole file into memory. Stefan From steve at alchemy.com Mon Aug 8 10:41:25 2011 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 08 Aug 2011 01:41:25 -0700 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: References: <4E3EBA91.7030801@alchemy.com> <4E3EC142.1000205@alchemy.com> Message-ID: <4E3FA135.3030704@alchemy.com> On 08-Aug-11 01:18, Kayode Odeyemi wrote: > Thanks so much. This is exactly what I'm looking for. In addition, since > fields is obviously a dict, I won't want to have to display it's keys > repeatedly. Is there a way to get the keys once, have it displayed and > used as columns, then it's values are displayed beneath it. Something like: > > updated tel > 20113456 > 201134510 Sure. You have to make the assumption that all the dictionaries in your list x have the same keys, or iterate over all of them, making a master list of all the keys you found. Either way, once you have the list of the keys you want to display, print them out once as column headings, then iterate over the list, printing each key's value in the same order each time. Another approach, if it seems like you're stuffing a lot of data into complex dictionary structures, is to turn this into a class. That way you can define the attributes of each object and even implement a print() method (or at least define __str__() and/or __repr__() methods) to print each object sensibly. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From dreyemi at gmail.com Mon Aug 8 11:20:37 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Mon, 8 Aug 2011 10:20:37 +0100 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: <4E3FA135.3030704@alchemy.com> References: <4E3EBA91.7030801@alchemy.com> <4E3EC142.1000205@alchemy.com> <4E3FA135.3030704@alchemy.com> Message-ID: > > Either way, once you have the list of the keys you want to display, print > them out once as column headings My concern is how do I print them out as columns, since writer.writerows is currently lining them out as rows (\n) Is there a function available for me to do this or do I have to construct the column structure myself, possibly leveraging the tab character or just basically construct a while loop and append spaces to each keys found? Thanks On Mon, Aug 8, 2011 at 9:41 AM, Steve Willoughby wrote: > Either way, once you have the list of the keys you want to display, print > them out once as column headings -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Mon Aug 8 11:12:39 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Mon, 8 Aug 2011 10:12:39 +0100 Subject: [Tutor] "Object designer" applications - are there any? In-Reply-To: <1312558450.9907.YahooMailRC@web86702.mail.ird.yahoo.com> References: <4E3BECF7.201@btinternet.com> <1312558450.9907.YahooMailRC@web86702.mail.ird.yahoo.com> Message-ID: Yup - sounds more like what the final version of my little project will do. At the moment, I'm more interested in taking each specific database's version of it's DDL and converting it to an Oracle version of that DDL, so initially it's not much more than a text converter which reads in text describing Sybase tables and spits out DDL describing Oracle tables. I'll spend a day working out my objects, their methods and properties, get that all nailed and begin the fun and games in translating my headspace into Python. I'll inevitably hassling you people as and when I get stuck or want some advice on the best way to proceed, so I guess by the end of it, you'll all be as sick of this as I will be. Share the misery... S ________________________________ From: ALAN GAULD [mailto:alan.gauld at btinternet.com] Sent: Friday, August 05, 2011 4:34 PM To: Flynn, Stephen (L & P - IT); tutor at python.org Subject: Re: [Tutor] "Object designer" applications - are there any? > > I'm not sure you need OOP for this. > I suspect you're correct Alan, but as I'm using this an a learning > exercise for the language it seemed too good an opportunity to miss That's fine so long as we understand why you are going down the OOP route. > can relate a table to an "object" in my head quite easily - just need to > know how to do it in Python... OK, So if you can conceptualise a table what are the operations you would perform on it? It sounds like you want to - add columns - from a definition file/document? - generate DDL based on current structure? - export a definition document? - Maybe autopopulate the definition from a given database connection? So the use case nmay be something like: Create a table connected to the old database. The table sucks up the metadata from the database and auto-populates itself with columns(which might be another class with name, type,size type details) Create a new Table object targeted at the new database (which might not exist yet?) If the table can't auto-populate then feed it the oold table object which it queries for a description. The new table then populates its own definition. Finally get the new table to generate the DDL and populate the new database. You might want different table classes each based on different databases, so they populate themselves based on the specific meta language and spit out a common description format. They cn then generate their own dialect of DDL too... Does that seem like a starter? But really, when working with objects it helps to sit back and think through how you want to use them from the outside rather than thinking about what they look like inside. That way the internals will reflect what's actually needed for the usage rather than some random model of what might be needed. HTH, Alan G. Click here to report this email as spam. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Mon Aug 8 15:00:23 2011 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 08 Aug 2011 06:00:23 -0700 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: References: <4E3EBA91.7030801@alchemy.com> <4E3EC142.1000205@alchemy.com> <4E3FA135.3030704@alchemy.com> Message-ID: <4E3FDDE7.9050708@alchemy.com> On 08-Aug-11 02:20, Kayode Odeyemi wrote: > Either way, once you have the list of the keys you want to display, > print them out once as column headings > > > My concern is how do I print them out as columns, since writer.writerows > is currently lining them out as rows (\n) > Is there a function available for me to do this or do I have to > construct the column structure myself, possibly leveraging > the tab character or just basically construct a while loop and append > spaces to each keys found? I would suggest using the string format() method to lay out the columns as you want them. You could use tab, but if your data values vary much, you'll get inconsistent results (i.e., if one row's value goes past the next tab stop). You'll want to create your own for loop to iterate over the (possibly sorted) list of values, printing each row the way you want it. > > Thanks > > On Mon, Aug 8, 2011 at 9:41 AM, Steve Willoughby > wrote: > > Either way, once you have the list of the keys you want to display, > print them out once as column headings > > > > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From eyeplum at gmail.com Mon Aug 8 17:22:19 2011 From: eyeplum at gmail.com (=?UTF-8?B?5p2O6b6R?=) Date: Mon, 8 Aug 2011 23:22:19 +0800 Subject: [Tutor] Missing in web.py and nosetests Message-ID: Hi all, I'm new in python and is learning about testing my little web.py app with nosetests. When the app is running in the web browser, it's ok. And the terminal returns something like "127.0.0.1:51936 - - [08/Aug/2011 23:00:37] "HTTP/1.1 GET /hello" - 200 OK" But when I'm trying to test the app with nosetests, it always goes wrong. As I look into the Tracebacks, I guess this is caused by the templates I've used in my app. But I'm not sure what should I do to make the nosetests running right. Hope some one can tell me what to do next. Thanks. PS: The Tracebacks looks like below: > $ nosetests > Traceback (most recent call last): > File "/Library/Python/2.7/site-packages/web/application.py", line 236, in > process > return self.handle() > File "/Library/Python/2.7/site-packages/web/application.py", line 227, in > handle > return self._delegate(fn, self.fvars, args) > File "/Library/Python/2.7/site-packages/web/application.py", line 409, in > _delegate > return handle_class(cls) > File "/Library/Python/2.7/site-packages/web/application.py", line 384, in > handle_class > return tocall(*args) > File "/Users/eyeplum/python/projects/gothonweb/bin/app.py", line 14, in > GET > return render.hello_form() > File "/Library/Python/2.7/site-packages/web/template.py", line 1009, in > __getattr__ > t = self._template(name) > File "/Library/Python/2.7/site-packages/web/template.py", line 1006, in > _template > return self._load_template(name) > File "/Library/Python/2.7/site-packages/web/template.py", line 993, in > _load_template > raise AttributeError, "No template named " + name > AttributeError: No template named hello_form > F > ====================================================================== > FAIL: tests.app_tests.test_index > ---------------------------------------------------------------------- > Traceback (most recent call last): > File > "/Library/Python/2.7/site-packages/nose-1.1.1-py2.7.egg/nose/case.py", line > 197, in runTest > self.test(*self.arg) > File "/Users/eyeplum/python/projects/gothonweb/tests/app_tests.py", line > 12, in test_index > assert_response(resp) > File "/Users/eyeplum/python/projects/gothonweb/tests/tools.py", line 6, > in assert_response > assert status in resp.status, "Expected response %r not in %r" % > (status, resp.status) > AssertionError: Expected response '200' not in '500 Internal Server Error' > ---------------------------------------------------------------------- > Ran 1 test in 0.083s > FAILED (failures=1) And the book I'm learning: http://learnpythonthehardway.org/book/ex51.html -- Li Yan -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Aug 8 17:48:18 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 8 Aug 2011 11:48:18 -0400 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack In-Reply-To: <4E3FDDE7.9050708@alchemy.com> References: <4E3EBA91.7030801@alchemy.com> <4E3EC142.1000205@alchemy.com> <4E3FA135.3030704@alchemy.com> <4E3FDDE7.9050708@alchemy.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA75614E6@EMARC112VS01.exchad.jpmchase.net> >I would suggest using the string format() method to lay out the columns >as you want them. You could use tab, but if your data values vary much, >you'll get inconsistent results (i.e., if one row's value goes past the >next tab stop). You'll want to create your own for loop to iterate over >the (possibly sorted) list of values, printing each row the way you want it. +1 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Mon Aug 8 21:02:26 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Aug 2011 05:02:26 +1000 Subject: [Tutor] Missing in web.py and nosetests In-Reply-To: References: Message-ID: <4E4032C2.4040707@pearwood.info> ?? wrote: > Hi all, > > I'm new in python and is learning about testing my little web.py app with > nosetests. > > When the app is running in the web browser, it's ok. And the terminal > returns something like "127.0.0.1:51936 - - [08/Aug/2011 23:00:37] "HTTP/1.1 > GET /hello" - 200 OK" > > But when I'm trying to test the app with nosetests, it always goes wrong. As > I look into the Tracebacks, I guess this is caused by the templates I've > used in my app. But I'm not sure what should I do to make the nosetests > running right. This is a forum for learning Python, not nose, or your web templating system. We can try to help, but you may have better luck on a dedicated nose forum, or on the main python-list at python.org mailing list (also available on Usenet comp.lang.python). I don't actually use nose, so it is hard for me to interpret the tracebacks you give. My *guess* is that you are reporting one test *error* (a test that fails because your code is broken) plus one test *failure* (a test which just fails). The first traceback you give seems to be an unexpected error: >> File "/Library/Python/2.7/site-packages/web/template.py", line 993, in >> _load_template >> raise AttributeError, "No template named " + name >> AttributeError: No template named hello_form >> F Do you actually have a template called "hello_form"? If not, then my *guess* is that this is an *error* (even though it prints F) because you don't actually have a template called hello_form. The second traceback seems to be a failing test: >> AssertionError: Expected response '200' not in '500 Internal Server Error' Your test expects a 500 Internal Server Error, but you actually get a 200 OK response. So your test is wrong: it fails for no good reason. But I am not an expert on nose. I might be interpreting these tracebacks completely wrong. Aside: I can't find anything in the nose docs which explain how to read the test output except in the trivial case that all the tests pass. http://packages.python.org/nose/index.html -- Steven From questions.anon at gmail.com Tue Aug 9 01:40:40 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 9 Aug 2011 09:40:40 +1000 Subject: [Tutor] gzip In-Reply-To: References: Message-ID: Thank you and I will look into shutils, below is the code that did work: import gzip import os MainFolder=r"E:/data" for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for gzfiles in files: if gzfiles[-3:]=='.gz': print "dealing with gzfiles:", gzfiles compressedfiles=os.path.join(path,gzfiles) f_in=gzip.GzipFile(compressedfiles, "rb") newFile=f_in.read() f_out=open(compressedfiles[:-3], "wb") f_out.write(newFile) print "end of processing" On Mon, Aug 8, 2011 at 6:34 PM, Stefan Behnel wrote: > questions anon, 08.08.2011 01:57: > > Thank you, I didn't realise that was all I needed. >> Moving on to the next problem: >> I would like to loop through a number of directories and decompress each >> *.gz file and leave them in the same folder but the code I have written >> only >> seems to focus on the last folder. Not sure where I have gone wrong. >> Any feedback will be greatly appreciated. >> >> >> import gzip >> import os >> >> MainFolder=r"D:/DSE_work/temp_**samples/" >> >> for (path, dirs, files) in os.walk(MainFolder): >> for dir in dirs: >> outputfolder=os.path.join(**path,dir) >> print "the path and dirs are:", outputfolder >> for gzfiles in files: >> print gzfiles >> if gzfiles[-3:]=='.gz': >> print 'dealing with gzfiles:', dir, gzfiles >> f_in=os.path.join(**outputfolder,gzfiles) >> print f_in >> compresseddata=gzip.GzipFile(**f_in, "rb") >> newFile=compresseddata.read() >> f_out=open(f_in[:-3], "wb") >> f_out.write(newFile) >> > > Note how "outputfolder" is set and reset in the first inner loop, *before* > starting the second inner loop. Instead, build the output directory name > once, without looping over the directories (which, as far as I understand > your intention, you can ignore completely). > > Also, see the shutils module. It has a method that efficiently copies data > between open file(-like) objects. With that, you can avoid reading the whole > file into memory. > > Stefan > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eyeplum at gmail.com Tue Aug 9 01:49:54 2011 From: eyeplum at gmail.com (=?UTF-8?B?5p2O6b6R?=) Date: Tue, 9 Aug 2011 07:49:54 +0800 Subject: [Tutor] Missing in web.py and nosetests In-Reply-To: <4E4032C2.4040707@pearwood.info> References: <4E4032C2.4040707@pearwood.info> Message-ID: Thanks Steven. Sorry for trying to discuss nose or templates here :( Do you actually have a template called "hello_form"? If not, then my *guess* > is that this is an *error* (even though it prints F) because you don't > actually have a template called hello_form. Yes, I have this template, and the app runs well when I manually testing it in a web browser. So I guess the promblem might be that the nose testing system need some kind of special operations to make it know where the template is(but actually I do have a *render = web.template.render("templates/", base="layout" *in my app which declares the place of the template). Think I need to read more on those topics~_~ Thanks. On Tue, Aug 9, 2011 at 3:02 AM, Steven D'Aprano wrote: > ?? wrote: > >> Hi all, >> >> I'm new in python and is learning about testing my little web.py app with >> nosetests. >> >> When the app is running in the web browser, it's ok. And the terminal >> returns something like "127.0.0.1:51936 - - [08/Aug/2011 23:00:37] >> "HTTP/1.1 >> GET /hello" - 200 OK" >> >> But when I'm trying to test the app with nosetests, it always goes wrong. >> As >> I look into the Tracebacks, I guess this is caused by the templates I've >> used in my app. But I'm not sure what should I do to make the nosetests >> running right. >> > > > This is a forum for learning Python, not nose, or your web templating > system. We can try to help, but you may have better luck on a dedicated nose > forum, or on the main python-list at python.org mailing list (also available > on Usenet comp.lang.python). > > > I don't actually use nose, so it is hard for me to interpret the tracebacks > you give. My *guess* is that you are reporting one test *error* (a test that > fails because your code is broken) plus one test *failure* (a test which > just fails). > > > The first traceback you give seems to be an unexpected error: > > > File "/Library/Python/2.7/site-**packages/web/template.py", line 993, in >>> _load_template >>> raise AttributeError, "No template named " + name >>> AttributeError: No template named hello_form >>> F >>> >> > Do you actually have a template called "hello_form"? If not, then my > *guess* is that this is an *error* (even though it prints F) because you > don't actually have a template called hello_form. > > > The second traceback seems to be a failing test: > > > AssertionError: Expected response '200' not in '500 Internal Server Error' >>> >> > Your test expects a 500 Internal Server Error, but you actually get a 200 > OK response. So your test is wrong: it fails for no good reason. > > > But I am not an expert on nose. I might be interpreting these tracebacks > completely wrong. > > > Aside: > > I can't find anything in the nose docs which explain how to read the test > output except in the trivial case that all the tests pass. > > http://packages.python.org/**nose/index.html > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- ?? | Li Yan http://about.me/eyeplum -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Aug 9 02:02:55 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Aug 2011 10:02:55 +1000 Subject: [Tutor] Missing in web.py and nosetests In-Reply-To: References: <4E4032C2.4040707@pearwood.info> Message-ID: <4E40792F.9090908@pearwood.info> ?? wrote: > Thanks Steven. > > Sorry for trying to discuss nose or templates here :( No need to be sorry, it isn't forbidden, but you may have more success asking help elsewhere. >> Do you actually have a template called "hello_form"? If not, then my *guess* >> is that this is an *error* (even though it prints F) because you don't >> actually have a template called hello_form. > > Yes, I have this template, and the app runs well when I manually testing it > in a web browser. So I guess the promblem might be that the nose testing > system need some kind of special operations to make it know where the > template is(but actually I do have a *render = > web.template.render("templates/", base="layout" *in my app which declares > the place of the template). Then my guess is that the difference might be because you are calling the nose tests from a different working directory than the web browser sees. Can you get the app to display os.getcwd(), and then write a test that compares the working directory as seen by nose to the working directory as seen by the web app? Or change the template location to be an absolute pathname. Also check the permissions on the templates. Perhaps the template is readable by whatever user is running the web server, but not by whatever user is running the nose tests. All these suggestions are wild guesses, you understand. Good luck. -- Steven From brown.helen at yahoo.com Tue Aug 9 03:00:36 2011 From: brown.helen at yahoo.com (Helen Brown) Date: Mon, 8 Aug 2011 18:00:36 -0700 (PDT) Subject: [Tutor] Reprojection tool for vector datasets Message-ID: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> I am such a novice at this but I have gotten to a place where I am stuck. The attachment is what I have done so far but it also has an error for indentation. I will be working on that to. I have place comment as to what I want the modules to do but that is as far as I can go. Can someone lead me to the finish line ? I have four datasets and they are supposed to be reproject to NAD 1983 UTM Zone 10. Plus I can not have any hard code. Please explain how I can understand this better. Thanks to the Python Lovers -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Reprojection.py Type: application/octet-stream Size: 2092 bytes Desc: not available URL: From jiayuaw at yahoo.com.sg Tue Aug 9 03:48:20 2011 From: jiayuaw at yahoo.com.sg (Jia-Yu Aw) Date: Tue, 9 Aug 2011 09:48:20 +0800 (SGT) Subject: [Tutor] How to use __iter__ Message-ID: <1312854500.30561.YahooMailNeo@web77909.mail.sg1.yahoo.com> Hi all I've been learning Classes and have read the documentation on __iter__ but still don't understand how it works. I have two pieces of code: the first is def __iter__, the second is using __iter__. Instead of being an iterator, I'm just using this is a function, which I think is incorrect. Can somebody explain __iter__ and, if it's related, next()? This is the first. But unlike what it says in the triple quotes, I return a whole list instead of a single shape: ? ? def __iter__(self): ? ? ? ? """ ? ? ? ? Return an iterator that allows you to iterate over the set of ? ? ? ? shapes, one shape at a time ? ? ? ? """ ? ? ? ? import copy ? ? ? ? setCopy = copy.copy(self.set) ? ? ? ? shapeList = [] ? ? ? ? while len(setCopy) > 0: ? ? ? ? ? ? try: ? ? ? ? ? ? ? ? y = setCopy[0] ? ? ? ? ? ? ? ? shapeList.append(y) ? ? ? ? ? ? ? ? setCopy.remove(y) ? ? ? ? ? ? except StopIteration: ? ? ? ? ? ? ? ? break ? ? ? ? return shapeList The second, how I've used __iter__: def findLargest(shapes): ? ? """ ? ? Returns a tuple containing the elements of ShapeSet with the ? ? ? ?largest area. ? ? shapes: ShapeSet ? ? """ ? ? ## TO DO ? ?? ? ? areaList = [] ? ? areaDict = {} ? ? largestDict = {} ? ?? ? ? shapeList = shapes.__iter__() ? ? for s in shapeList: ? ? ? ? areaDict[s] = s.area() ? ? ? ? areaList.append(s.area()) ? ? ? ?? ? ? largestArea = max(areaList) ? ? areaList = [] #re-initialize areaList, cleaning it ? ? import copy ? ? dictCopy = copy.copy(areaDict) ? ?? ? ? for a in areaDict: ? ? ? ? if areaDict[a] != largestArea: ? ? ? ? ? ? del dictCopy[a] ? ? return tuple(dictCopy) Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From eyeplum at gmail.com Tue Aug 9 08:27:01 2011 From: eyeplum at gmail.com (=?UTF-8?B?5p2O6b6R?=) Date: Tue, 9 Aug 2011 14:27:01 +0800 Subject: [Tutor] Missing in web.py and nosetests In-Reply-To: <4E40792F.9090908@pearwood.info> References: <4E4032C2.4040707@pearwood.info> <4E40792F.9090908@pearwood.info> Message-ID: Thanks again. I add "print os.getcwd()" inside* app.py* and *app_test.py(the nosetests script) *and find they are different. In app.py, the working dir is the whole directory including all subdirectories, but in app_test.py the working dir is the tests directory only. I guess it's due to the working mechanism of the nosetests... I also checked the permissions of those files, and they are all readable for everyone :( But I guess the problem is at the path of the template, the nosetests may have a different way to know the template path. (But when I change the pathname to be a absolute path, the nose goes wrong, and even the browser can't see the webpage :( ). I also tried to add a* __init__.py* file into the templates directory, but nothing different happens...(there is only 500 and AttributeError, "No template named " + name) the projects skeleton: /gothonweb /bin __init__.py app.py /templates index.html hello_form.html /tests __init__.py app_tests.py tools.py On Tue, Aug 9, 2011 at 8:02 AM, Steven D'Aprano wrote: > ?? wrote: > >> Thanks Steven. >> >> Sorry for trying to discuss nose or templates here :( >> > > No need to be sorry, it isn't forbidden, but you may have more success > asking help elsewhere. > > > > Do you actually have a template called "hello_form"? If not, then my >>> *guess* >>> is that this is an *error* (even though it prints F) because you don't >>> actually have a template called hello_form. >>> >> >> Yes, I have this template, and the app runs well when I manually testing >> it >> in a web browser. So I guess the promblem might be that the nose testing >> system need some kind of special operations to make it know where the >> template is(but actually I do have a *render = >> web.template.render("**templates/", base="layout" *in my app which >> declares >> the place of the template). >> > > > Then my guess is that the difference might be because you are calling the > nose tests from a different working directory than the web browser sees. Can > you get the app to display os.getcwd(), and then write a test that compares > the working directory as seen by nose to the working directory as seen by > the web app? Or change the template location to be an absolute pathname. > > Also check the permissions on the templates. Perhaps the template is > readable by whatever user is running the web server, but not by whatever > user is running the nose tests. > > All these suggestions are wild guesses, you understand. > > > Good luck. > > > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- ?? | Li Yan -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 9 08:56:37 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Aug 2011 08:56:37 +0200 Subject: [Tutor] How to use __iter__ References: <1312854500.30561.YahooMailNeo@web77909.mail.sg1.yahoo.com> Message-ID: Jia-Yu Aw wrote: > How to use __iter__ > Von: > Jia-Yu Aw > Antwortadresse: > Jia-Yu Aw > Datum: > Dienstag, 9. August 2011 03:48:20 > An: > tutor at python.org > Gruppen: > gmane.comp.python.tutor > Hi all > > I've been learning Classes and have read the documentation on __iter__ but still don't understand how it works. I have two pieces of code: the first is def __iter__, the second is using __iter__. Instead of being an iterator, I'm just using this is a function, which I think is incorrect. Can somebody explain __iter__ and, if it's related, next()? An "iterable" is an object that has an with an __iter__() method. The __iter__() method is supposed to return an "iterator", i. e. an object with a next() method. The next() method is then called repeatedly until a next() call raises a StopIteration. You can think of for item in items: do_something_with(item) as syntactic sugar for it = items.__iter__() while True: try: item = it.next() except StopIteration: break do_something_with(item) With that in mind > This is the first. But unlike what it says in the triple quotes, I return a whole list instead of a single shape: > > def __iter__(self): > """ > Return an iterator that allows you to iterate over the set of > shapes, one shape at a time > """ > import copy > setCopy = copy.copy(self.set) > shapeList = [] > while len(setCopy) > 0: > try: > y = setCopy[0] > shapeList.append(y) > setCopy.remove(y) > except StopIteration: > break > return shapeList your __iter__() method would become class MyIter(object): def __init__(self, items): self.items = list(items) def next(self): if len(self.items) == 0: raise StopIteration return self.items.pop(0) class MyIterable(object): # ... def __iter__(self): return MyIter(self.set) However, this is a clumsy way to implement an iterable. One alternative takes advantage of the fact that Python already knows how to iterate over a set. class MyIterable(object): def __iter__(self): for item in self.set: yield item Here the "yield" statement turns __iter__() from a function into a "generator". Every call of a generator creates a new iterator, i. e. an object with a next() method. Every next() call proceeds execution of the generator's body until it reaches a yield. Once the end of the body is reached next() will raise Stopiterations forever: >>> def f(): ... yield 1 ... yield 2 ... >>> g = f() >>> g.next() 1 >>> g.next() 2 >>> g.next() Traceback (most recent call last): File "", line 1, in StopIteration >>> g.next() Traceback (most recent call last): File "", line 1, in StopIteration A final simplification would be class MyIterable(object): def __iter__(self): return iter(self.set) > The second, how I've used __iter__: > > def findLargest(shapes): > """ > Returns a tuple containing the elements of ShapeSet with the > largest area. > shapes: ShapeSet > """ > ## TO DO > > areaList = [] > areaDict = {} > largestDict = {} Don't do that: > shapeList = shapes.__iter__() > for s in shapeList: The for-loop implicitly invokes the __iter__() method. Just loop over the original object: for s in shapes: > areaDict[s] = s.area() > areaList.append(s.area()) > > largestArea = max(areaList) > areaList = [] #re-initialize areaList, cleaning it > > import copy > dictCopy = copy.copy(areaDict) > for a in areaDict: > if areaDict[a] != largestArea: > del dictCopy[a] > > return tuple(dictCopy) Side note: you are copying data way to much. Don't! Most occurences of copy() only serve to help an experienced Pythonista identify newbie code ;) As an inspiration here's an alternative implementation: def find_largest(shapes): largest_area = max(shape.area() for shape in shapes) return [shape for shape in shapes if shape.area() == largest_area] From __peter__ at web.de Tue Aug 9 09:10:00 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Aug 2011 09:10 +0200 Subject: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack References: <4E3EBA91.7030801@alchemy.com> <4E3EC142.1000205@alchemy.com> Message-ID: Kayode Odeyemi wrote: > Thanks so much. This is exactly what I'm looking for. In addition, since > fields is obviously a dict, I won't want to have to display it's keys > repeatedly. Is there a way to get the keys once, have it displayed and > used as columns, then it's values are displayed beneath it. Something > like: > > updated tel > 2011 3456 > 2011 34510 > > right now, I'm having it displayed as > > updated > 2011 > tel > 3456 > updated > 2011 > tel > 34510 > > I am having the fields being written using a writer like this: > > x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': > 3456}}, > {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}} > writer = csv.writer(response) > > for entry in x: > for key, value in entry.items(): > print key > if key == "fields": > for field_key, field_value in value.items(): > d = [field_key] #a list of sequence > x = [field_value] > writer.writerow(d) > writer.writerow(x) > else: > print " %s" % value You are doing too much at once. You are only interested in the "fields" dictionary, so I recommend that you extract that first: items = [ {'pk': 1, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 3456}}, {'pk': 2, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 34510}} ] rows = [item["fields"] for item in items] Now the data structure has become simpler, just a list of dictionaries, you can think about how you generate the output. One way, the str.format() method, was already mentioned: >>> for row in rows: ... print "{updated}\t{tel}".format(**row) ... 2011 3456 2011 34510 If you want to continue to use the csv module you should use the DictWriter: >>> import csv, sys >>> fieldnames = rows[0].keys() >>> writer = csv.DictWriter(sys.stdout, fieldnames) >>> writer.writeheader() updated,tel >>> writer.writerows(rows) 2011,3456 2011,34510 From robert.johansson at math.umu.se Tue Aug 9 09:44:49 2011 From: robert.johansson at math.umu.se (Robert Johansson) Date: Tue, 9 Aug 2011 09:44:49 +0200 Subject: [Tutor] function remember calls? Message-ID: <61310E38B60C8F4AB59757E88A3C96771092E31562@UMDAC-CCR2.ad.umu.se> Hi all, This is my attempt to generate all pairs of relatively prime pairs of nonnegative integers (n, m) such that n + m <= N, using the Stern-Brocot tree. def rp_bounded_sum(n, i = 0, p = (0, 1), q = (1, 1), S = set([(0, 1), (1, 1)])): # Returns a set S with all relatively prime pairs (a, b) # such that 0 <= a <= b and a + b <= n. r = p[0] + q[0], p[1] + q[1] if r[0] + r[1] <= n: S.add(r) rp_bounded_sum(n, 1, p, r, S) rp_bounded_sum(n, 1, r, q, S) if not i: return S Strangely, (to me) it seems that the function remembers the set S between different calls: >>> T=rp_bounded_sum(200) >>> len(T) 6117 >>> T=rp_bounded_sum(100) >>> len(T) 6117 Why? I modified it to def rp_bounded_sum(n, i = 0, p = (0, 1), q = (1, 1), S = set()): # Returns a set S with all relatively prime pairs (a, b) # such that 0 <= a <= b and a + b <= n. if not i: S = set([(0, 1), (1, 1)]) r = p[0] + q[0], p[1] + q[1] if r[0] + r[1] <= n: S.add(r) rp_bounded_sum(n, 1, p, r, S) rp_bounded_sum(n, 1, r, q, S) if not i: return S Now it works fine but I don't understand why the first example fails. I'm not very pleased with any of these two solutions so I would be grateful for any suggestions of improvements. I use Python 2.7.2 under Windows 7 and I ran this in Python shell in IDLE. Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 9 10:05:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Aug 2011 09:05:18 +0100 Subject: [Tutor] function remember calls? In-Reply-To: <61310E38B60C8F4AB59757E88A3C96771092E31562@UMDAC-CCR2.ad.umu.se> References: <61310E38B60C8F4AB59757E88A3C96771092E31562@UMDAC-CCR2.ad.umu.se> Message-ID: <4E40EA3E.7040308@btinternet.com> On 09/08/11 08:44, Robert Johansson wrote: > def rp_bounded_sum(n, i = 0, p = (0, 1), q = (1, 1), S = set([(0, 1), > (1, 1)])): > Strangely, (to me) it seems that the function remembers the set S > between different calls: That's correct. Python evaluates the default parameter value once at function definition time so every call to the function uses the same default object value. This often catches out newbies but should be considered a 'feature of the language' rather than a bug - it's existence enables some useful techniques which would not otherwise be possible :-) If you check the documentation on default parameters you will find more details. hth, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 9 10:05:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Aug 2011 09:05:18 +0100 Subject: [Tutor] function remember calls? In-Reply-To: <61310E38B60C8F4AB59757E88A3C96771092E31562@UMDAC-CCR2.ad.umu.se> References: <61310E38B60C8F4AB59757E88A3C96771092E31562@UMDAC-CCR2.ad.umu.se> Message-ID: <4E40EA3E.7040308@btinternet.com> On 09/08/11 08:44, Robert Johansson wrote: > def rp_bounded_sum(n, i = 0, p = (0, 1), q = (1, 1), S = set([(0, 1), > (1, 1)])): > Strangely, (to me) it seems that the function remembers the set S > between different calls: That's correct. Python evaluates the default parameter value once at function definition time so every call to the function uses the same default object value. This often catches out newbies but should be considered a 'feature of the language' rather than a bug - it's existence enables some useful techniques which would not otherwise be possible :-) If you check the documentation on default parameters you will find more details. hth, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 9 10:09:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Aug 2011 09:09:56 +0100 Subject: [Tutor] Reprojection tool for vector datasets In-Reply-To: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> References: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> Message-ID: <4E40EB54.9050306@btinternet.com> On 09/08/11 02:00, Helen Brown wrote: > ...I have place > comment as to what I want the modules to do but that is as far as I can > go. Can someone lead me to the finish line ? The problem is that your code is wholly reliant on the classes that you are using and unless you find somebody who is familiar witht those classes it is unlikely we can suggest much of help. Based on the comments your basic logic appears to be ok, but how you turn the comments into reality depemds on the classes and their available operations. You need to study those classes and any associated documentation/sample code. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 9 10:09:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Aug 2011 09:09:56 +0100 Subject: [Tutor] Reprojection tool for vector datasets In-Reply-To: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> References: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> Message-ID: <4E40EB54.9050306@btinternet.com> On 09/08/11 02:00, Helen Brown wrote: > ...I have place > comment as to what I want the modules to do but that is as far as I can > go. Can someone lead me to the finish line ? The problem is that your code is wholly reliant on the classes that you are using and unless you find somebody who is familiar witht those classes it is unlikely we can suggest much of help. Based on the comments your basic logic appears to be ok, but how you turn the comments into reality depemds on the classes and their available operations. You need to study those classes and any associated documentation/sample code. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Tue Aug 9 10:16:03 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Aug 2011 10:16:03 +0200 Subject: [Tutor] function remember calls? References: <61310E38B60C8F4AB59757E88A3C96771092E31562@UMDAC-CCR2.ad.umu.se> Message-ID: Robert Johansson wrote: > This is my attempt to generate all pairs of relatively prime pairs of > nonnegative integers (n, m) such that n + m <= N, using the Stern-Brocot > tree. > > def rp_bounded_sum(n, i = 0, p = (0, 1), q = (1, 1), S = set([(0, 1), (1, > 1)])): > # Returns a set S with all relatively prime pairs (a, b) > # such that 0 <= a <= b and a + b <= n. > r = p[0] + q[0], p[1] + q[1] > if r[0] + r[1] <= n: > S.add(r) > rp_bounded_sum(n, 1, p, r, S) > rp_bounded_sum(n, 1, r, q, S) > if not i: > return S Default values for function arguments are shared across function invocations. If you have mutable defaults, e. g. a list or set, and modify that default value during the function call the modifications will be visible the next time you invoke the function. A simple example: >>> def f(x, items=[]): ... items.append(x) ... return items ... >>> f(1) [1] >>> f(2) [1, 2] >>> f(3) [1, 2, 3] >>> f(1, [42]) [42, 1] >>> f(4) [1, 2, 3, 4] The standard idiom to avoid this issue is to use a special default value to signal that the argument was not provided. In most cases that special value is None: >>> def f(x, items=None): ... if items is None: ... items = [] # if no list was provided make a new one ... items.append(x) ... return items ... >>> f(1) [1] >>> f(2) [2] >>> f(3) [3] >>> f(1, [42]) [42, 1] >>> f(4) [4] From steve at pearwood.info Tue Aug 9 13:06:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Aug 2011 21:06:32 +1000 Subject: [Tutor] Reprojection tool for vector datasets In-Reply-To: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> References: <1312851636.61993.YahooMailNeo@web46303.mail.sp1.yahoo.com> Message-ID: <4E4114B8.2060306@pearwood.info> Helen Brown wrote: > I am such a novice at this but I have gotten to a place where I am > stuck. The attachment is what I have done so far but it also has an > error for indentation. I will be working on that to. I have place > comment as to what I want the modules to do but that is as far as I > can go. Can someone lead me to the finish line ? I have four datasets > and they are supposed to be reproject to NAD 1983 UTM Zone 10. Plus I > can not have any hard code. I don't understand what you mean by "I can not have any hard code". The first thing I would do is get rid of the try...except clause. You have this: try: [lots and lots of indented code] except: # Report an error messages arcpy.AddMessage("This project is incomplete") #Report any error messages that the projection might have generated arcpy.AddMessage(arcpy.GetMessages()) This is a bad design, because it hides genuine programming bugs and changes them to say "This project is incomplete". How useless is that? If your code has a bug, you need to see what the bug is before you can fix it. So I recommend you do this: (1) Take all the lines between "try" and "except" and outdent them back to the margin. (2) Delete the line "try". (3) Delete the line "except". (4) Comment out the four lines following "except" ## Report an error messages #arcpy.AddMessage("This project is incomplete") ##Report any error messages that the projection might have generated #arcpy.AddMessage(arcpy.GetMessages()) (rather than delete them, because you may have to add them back in later). Now run the code and see what errors you get, if any, and fix them. You'll almost certainly get lots of errors, but only one at a time, fortunately! Read the error messages, try to understand what they are telling you, and try to fix them. And don't be shy about coming back for assistance. -- Steven From tlinnet at gmail.com Tue Aug 9 15:34:28 2011 From: tlinnet at gmail.com (=?ISO-8859-1?Q?Troels_Emtek=E6r_Linnet?=) Date: Tue, 9 Aug 2011 15:34:28 +0200 Subject: [Tutor] Python mechanize: Auto follow meta refresh? Message-ID: Hi. I try to to make a python interaction with the form on: http://propka.ki.ku.dk/ I just try to set: version='v3.1' and PDBID='4AKE' After the click and sending the form it stops. It should automatically refresh. Here is my code: import mechanize, sys, time, os url = "http://propka.ki.ku.dk/" version = "v3.1" PDBID = "4AKE" verbose = 'yes' server_wait = 1.0 br = mechanize.Browser() br.addheaders = [('User-agent', 'pythonMechanizeClient')] ### The things was added according to: http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/ ### Dont know what they do. br.set_handle_equiv(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Turn on debugging messages br.set_debug_http(True) #br.set_debug_redirects(True) #br.set_debug_responses(True) openpage = br.open(url) readpage = openpage.read() if verbose == 'yes': print br.title(); print br.geturl() #print readpage # To get available forms forms = [f.name for f in br.forms()] if verbose == 'yes': print forms ## Select first form br.select_form(name=forms[0]) ## Print the parameters of the 'version' RadioControl button and current value if verbose == 'yes': print br.find_control(name='version'); print br.find_control(name='version').value ## Change the parameters of the 'version' radio button and then reprint the new value br.form['version'] = [version] if verbose == 'yes': print br.find_control(name='version').value# ## Print the parameters of the 'PDBID' TextControl button and current value if verbose == 'yes': print br.find_control(name='PDBID'); print br.find_control(name='PDBID').value ## Change the parameters of the 'PDBID' TextControl and then reprint the new value br.form["PDBID"] = PDBID if verbose == 'yes': print br.find_control(name='PDBID').value ## Now reprint the current selected form, so we see that we have the right values. if verbose == 'yes': print br.form ## Two ways of submitting is tested #br.submit() req = br.click(type="submit", nr=0) ### Have to pass by a mechanize exception. Thats the reason for the why True ### The error was due to: #br.open(req) ##### mechanize._response.httperror_seek_wrapper: HTTP Error refresh: The HTTP server returned a redirect error that would lead to an infinite loop. ##### The last 30x error message was: ##### OK while True: try: br.open(req) break ### If there is raised an exception, we make a break. except: print("Waiting %s seconds for server"%server_wait) time.sleep(server_wait) break print br.geturl() print br.title() print br.response().read() ## Looking at some results in link format for l in br.links(): print l #for l in br.links(url_regex='stockrt'): # print l * It returns:* PROPKA Progress

PROPKA Progress

The PROPKA server is generating your results - this page will automatically refresh every 1 seconds.

Thank you for your patience!

Server Progress:

Elapsed Time: 19.00 seconds
Server Information:

Server load: 1.72 (1min) 0.86 (5min) 0.41 (15min)
Server time: Tue Aug 9 15:33:56 2011
*And it should be send forward to a result page afterwards. *I think it is because I got exception error. ##### mechanize._response.httperror_seek_wrapper: HTTP Error refresh: The HTTP server returned a redirect error that would lead to an infinite loop. ##### The last 30x error message was: ##### OK and I stop after this exception error. Is there a way to prolong the allowance for refreshing? Troels Emtek?r Linnet Karl-Liebknecht-Stra?e 53, 2 RE 04107 Leipzig, Tyskland Mobil: +49 1577-8944752 -------------- next part -------------- An HTML attachment was scrubbed... URL: From armvrt at gmail.com Tue Aug 9 16:44:48 2011 From: armvrt at gmail.com (Shwinn Ricci) Date: Tue, 9 Aug 2011 10:44:48 -0400 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: <4E3B2D36.5010003@btinternet.com> References: <4E3B2D36.5010003@btinternet.com> Message-ID: I am using wxPython and OpenGL, although I would prefer to run a script in Maya, but this does not seem efficient for what I want to do, since maya only allows for 3-D visualization, not simultaneous 2-D/3-D viewing (i.e., side-by-side) On Thu, Aug 4, 2011 at 7:37 PM, Alan Gauld wrote: > On 04/08/11 20:52, Shwinn Ricci wrote: > >> Say I want one half of a 720 x 480 window be dedicated for creating a >> 2-D structure, and the other half for a 3-D structure. There would be a >> line 1 or 2 pixels thick straight down the window that would divide the >> two sectors. How does one go about doing this without creating two >> separate GUI window frames? I do not have my code with me right now, I >> can post as soon as I have access to it. >> > > You need to give yus more detail. This kind of thing is very GUI frame-work > specific. Are you using Tkinter? wxPython?, Cocoa on MacOSX? > > They are all different. > > And because you want to do graphics you also need to tell us what graphics > toolkit you are using? OpenGL? Something else? > > Or are you trying to script Blender or Maya or some other 2D/3D modelling > tool? > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From armvrt at gmail.com Tue Aug 9 17:29:01 2011 From: armvrt at gmail.com (Shwinn Ricci) Date: Tue, 9 Aug 2011 11:29:01 -0400 Subject: [Tutor] precision? Message-ID: When comparing a given value with a database of values, but allowing for freedom due to variation at say, the thousandth digit, how does one generalize the precision to this degree? I don't want to truncate, so is there a round() function that takes into account what decimal place the value (database value) needs to be rounded to? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Aug 9 17:37:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Aug 2011 01:37:24 +1000 Subject: [Tutor] precision? In-Reply-To: References: Message-ID: <4E415434.1050905@pearwood.info> Shwinn Ricci wrote: > When comparing a given value with a database of values, but allowing for > freedom due to variation at say, the thousandth digit, how does one > generalize the precision to this degree? I don't want to truncate, so is > there a round() function that takes into account what decimal place the > value (database value) needs to be rounded to? Thousandth digit??? Python doesn't support floating point numbers with a thousand digits! I think about seventeen is about the limit. Yes, there is a round function: >>> x = 123.45678 >>> y = 123.45731 >>> x == y False >>> round(x, 3) == round(y, 3) True -- Steven From cfuller084 at thinkingplanet.net Tue Aug 9 17:44:27 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 9 Aug 2011 10:44:27 -0500 Subject: [Tutor] precision? In-Reply-To: References: Message-ID: <201108091044.28268.cfuller084@thinkingplanet.net> There's the one that comes with Python: http://docs.python.org/library/functions.html#round You should consider working with integers, though. Multiply all the values by 1000 and drop the fractional part. Cheers On Tuesday 09 August 2011, Shwinn Ricci wrote: > When comparing a given value with a database of values, but allowing for > freedom due to variation at say, the thousandth digit, how does one > generalize the precision to this degree? I don't want to truncate, so is > there a round() function that takes into account what decimal place the > value (database value) needs to be rounded to? From knacktus at googlemail.com Tue Aug 9 18:21:37 2011 From: knacktus at googlemail.com (Knacktus) Date: Tue, 09 Aug 2011 18:21:37 +0200 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: References: <4E3B2D36.5010003@btinternet.com> Message-ID: <4E415E91.5030504@googlemail.com> Am 09.08.2011 16:44, schrieb Shwinn Ricci: > > I am using wxPython and OpenGL, although I would prefer to run a script > in Maya, but this does not seem efficient for what I want to do, since > maya only allows for 3-D visualization, not simultaneous 2-D/3-D viewing > (i.e., side-by-side) > > > > On Thu, Aug 4, 2011 at 7:37 PM, Alan Gauld > wrote: > > On 04/08/11 20:52, Shwinn Ricci wrote: > > Say I want one half of a 720 x 480 window be dedicated for > creating a > 2-D structure, and the other half for a 3-D structure. There > would be a > line 1 or 2 pixels thick straight down the window that would > divide the > two sectors. How does one go about doing this without creating two > separate GUI window frames? You would need one frame (or widget) with an opengl context with 2 independent viewports. I don't think that's supported by any framework. You probably have to use two widgets. But that's no problem, as long as you can use layouts and styles to get the desired appearance of the two widgets (i.e. to make them appear as one). I do not have my code with me right > now, I > can post as soon as I have access to it. > > > You need to give yus more detail. This kind of thing is very GUI > frame-work specific. Are you using Tkinter? wxPython?, Cocoa on MacOSX? > > They are all different. > > And because you want to do graphics you also need to tell us what > graphics toolkit you are using? OpenGL? Something else? > > Or are you trying to script Blender or Maya or some other 2D/3D > modelling tool? > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _________________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/__mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Aug 9 19:23:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Aug 2011 18:23:10 +0100 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: References: <4E3B2D36.5010003@btinternet.com> Message-ID: <4E416CFE.8020801@btinternet.com> On 09/08/11 15:44, Shwinn Ricci wrote: > > I am using wxPython and OpenGL, I don't know anything about how OpenGL works with wxPython. However in general one of the following strategies should work: 1) Create composite panel containing two child panels side by side. Create your graphics in the child panels using the OpenGL library. 2) Create a single panel and general two images using OpenGL and then blit those two images side by side on the panel. Hopefully somebody with more OpenGL experience can give more direct help... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Tue Aug 9 19:08:20 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 9 Aug 2011 13:08:20 -0400 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: <4E415E91.5030504@googlemail.com> References: <4E3B2D36.5010003@btinternet.com> <4E415E91.5030504@googlemail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA766DCA1@EMARC112VS01.exchad.jpmchase.net> > Say I want one half of a 720 x 480 window be dedicated for > creating a > 2-D structure, and the other half for a 3-D structure. There > would be a > line 1 or 2 pixels thick straight down the window that would > divide the > two sectors. How does one go about doing this without creating two > separate GUI window frames? See SplitterWindow http://www.wxpython.org/docs/api/wx.SplitterWindow-class.html OR http://www.wxpython.org/docs/api/wx.lib.splitter.MultiSplitterWindow-class.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue Aug 9 19:23:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Aug 2011 18:23:10 +0100 Subject: [Tutor] General method for creating a partitioned window In-Reply-To: References: <4E3B2D36.5010003@btinternet.com> Message-ID: <4E416CFE.8020801@btinternet.com> On 09/08/11 15:44, Shwinn Ricci wrote: > > I am using wxPython and OpenGL, I don't know anything about how OpenGL works with wxPython. However in general one of the following strategies should work: 1) Create composite panel containing two child panels side by side. Create your graphics in the child panels using the OpenGL library. 2) Create a single panel and general two images using OpenGL and then blit those two images side by side on the panel. Hopefully somebody with more OpenGL experience can give more direct help... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From questions.anon at gmail.com Wed Aug 10 05:11:11 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 10 Aug 2011 13:11:11 +1000 Subject: [Tutor] inserting degrees symbol in plot title Message-ID: I am creating a number of plots of temperature in degrees celsius and I would like the title of the plot to have - C? Through a search I found a way to print the symbol degree_symbol = unichr(176).encode("latin-1") print degree_symbol but when I add this to my plot title I receive a huge error (see below). I have also tried copying (from word) and pasting the symbol into my title (like I did at the beginning of this email) but this also receives a huge error! Any feedback will be greatly appreciated. Traceback (most recent call last): File "D:\My Dropbox\Python_code\analysis_netcdf_subplots.py", line 75, in plt.show() File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 74, in __call__ manager.show() File "C:\Python27\lib\site-packages\matplotlib\backends\backend_wx.py", line 1557, in show self.canvas.draw() File "C:\Python27\lib\site-packages\matplotlib\backends\backend_wxagg.py", line 59, in draw FigureCanvasAgg.draw(self) File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 394, in draw self.figure.draw(self.renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 798, in draw func(*args) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 1946, in draw a.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\text.py", line 526, in draw bbox, info = self._get_layout(renderer) File "C:\Python27\lib\site-packages\matplotlib\text.py", line 305, in _get_layout clean_line, ismath = self.is_math_text(line) File "C:\Python27\lib\site-packages\matplotlib\text.py", line 989, in is_math_text if cbook.is_math_text(s): File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 1793, in is_math_text s = unicode(s) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 19: ordinal not in range(128) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Aug 10 05:16:59 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 09 Aug 2011 20:16:59 -0700 Subject: [Tutor] inserting degrees symbol in plot title In-Reply-To: References: Message-ID: <4E41F82B.4090704@alchemy.com> On 09-Aug-11 20:11, questions anon wrote: > I am creating a number of plots of temperature in degrees celsius and I > would like the title of the plot to have - C? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 19: > ordinal not in range(128) Putting the Unicode character in your program is one thing, but what library functions you pass that data to is a factor, too. Without knowing anything about matplotlib, my guess from the exception you quoted here is that the library is expecting ASCII characters below 128, so that function won't accept the special character. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From __peter__ at web.de Wed Aug 10 10:39:07 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Aug 2011 10:39:07 +0200 Subject: [Tutor] precision? References: <4E415434.1050905@pearwood.info> Message-ID: Steven D'Aprano wrote: > Shwinn Ricci wrote: >> When comparing a given value with a database of values, but allowing for >> freedom due to variation at say, the thousandth digit, how does one >> generalize the precision to this degree? I don't want to truncate, so is >> there a round() function that takes into account what decimal place the >> value (database value) needs to be rounded to? > > Thousandth digit??? Python doesn't support floating point numbers with a > thousand digits! I think about seventeen is about the limit. Not only that. The idea of n-digit precision is flawed because assuming an actual value of 1.00000 0.999 is closer than 1.01 but the latter has two correct digits and the former has none. > Yes, there is a round function: > > > >>> x = 123.45678 > >>> y = 123.45731 > >>> x == y > False > >>> round(x, 3) == round(y, 3) > True I prefer abs(x-y) < eps for similar reasons as stated above. 1.8 is as close to 1.4 as 1.0, but round(1.8) != round(1.4) whereas round(1.4) == round(1.0). From wprins at gmail.com Wed Aug 10 11:41:35 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 10 Aug 2011 10:41:35 +0100 Subject: [Tutor] precision? In-Reply-To: References: <4E415434.1050905@pearwood.info> Message-ID: Hi Steven D'Aprano wrote: > > Thousandth digit??? Python doesn't support floating point numbers with a > > thousand digits! I think about seventeen is about the limit. > ... except of course if you're using an arbitrary precision math package like mpmath or bigfloat. (I would've thought the fact that the original poster even mentions 1000 digits of accuracy might imply that they're actually using such a library - It would've been better if they'd been slightly more forthcoming with information about exactly what they're using and prevented us having to assume and guess, of course.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 10 18:43:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Aug 2011 17:43:08 +0100 Subject: [Tutor] precision? In-Reply-To: References: <4E415434.1050905@pearwood.info> Message-ID: <4E42B51C.5020003@btinternet.com> On 10/08/11 10:41, Walter Prins wrote: > Hi > > Steven D'Aprano wrote: > > Thousandth digit??? Python doesn't support floating point numbers > ... except of course if you're using an arbitrary precision math package > like mpmath or bigfloat. (I would've thought the fact that the original > poster even mentions 1000 digits of accuracy might imply that they're > actually using such a library I suspect the OP meant the 3rd decimal place - as in, the first is the tenth, the second the hundredth and the third is the thousandth... But I'm guessing... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Aug 10 18:43:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Aug 2011 17:43:08 +0100 Subject: [Tutor] precision? In-Reply-To: References: <4E415434.1050905@pearwood.info> Message-ID: <4E42B51C.5020003@btinternet.com> On 10/08/11 10:41, Walter Prins wrote: > Hi > > Steven D'Aprano wrote: > > Thousandth digit??? Python doesn't support floating point numbers > ... except of course if you're using an arbitrary precision math package > like mpmath or bigfloat. (I would've thought the fact that the original > poster even mentions 1000 digits of accuracy might imply that they're > actually using such a library I suspect the OP meant the 3rd decimal place - as in, the first is the tenth, the second the hundredth and the third is the thousandth... But I'm guessing... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From armvrt at gmail.com Wed Aug 10 19:43:54 2011 From: armvrt at gmail.com (Shwinn Ricci) Date: Wed, 10 Aug 2011 13:43:54 -0400 Subject: [Tutor] visualizing a point on a 3-dimensional surface Message-ID: Say I have a point that I want to visualize by placing a small marker there on the surface of an object. However, what if it's a 3-dimensional object? Would you just use a 3-D coordinate system and then use a rotatable camera script to wheel around and get a better view of the point? -------------- next part -------------- An HTML attachment was scrubbed... URL: From armvrt at gmail.com Wed Aug 10 21:16:27 2011 From: armvrt at gmail.com (Shwinn Ricci) Date: Wed, 10 Aug 2011 15:16:27 -0400 Subject: [Tutor] converting string to float Message-ID: I am reading values from excel using xlrd and using a variable to store them in (as part of a loop), as such: position = sheet.cell(j, i).value however, I want to convert position to a floating point number, as the actual cell value is in the form of X.XXX (where X = digits). When I try float(position) I get a ValueError saying that the string could not be converted to a float. What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwilsbach at gmail.com Wed Aug 10 21:23:10 2011 From: kwilsbach at gmail.com (Ken) Date: Wed, 10 Aug 2011 15:23:10 -0400 Subject: [Tutor] converting string to float In-Reply-To: References: Message-ID: Not sure since a simple float("1.111") worked for me try type() to see what your variable is being returned as. On Wed, Aug 10, 2011 at 3:16 PM, Shwinn Ricci wrote: > I am reading values from excel using xlrd and using a variable to store > them in (as part of a loop), as such: > > position = sheet.cell(j, i).value > > however, I want to convert position to a floating point number, as the > actual cell value is in the form of X.XXX (where X = digits). When I try > float(position) I get a ValueError saying that the string could not be > converted to a float. What am I doing wrong? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- -Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed Aug 10 21:23:36 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 10 Aug 2011 15:23:36 -0400 Subject: [Tutor] converting string to float In-Reply-To: References: Message-ID: On Wed, Aug 10, 2011 at 3:16 PM, Shwinn Ricci wrote: > I am reading values from excel using xlrd and using a variable to store > them in (as part of a loop), as such: > > position = sheet.cell(j, i).value > > however, I want to convert position to a floating point number, as the > actual cell value is in the form of X.XXX (where X = digits). When I try > float(position) I get a ValueError saying that the string could not be > converted to a float. What am I doing wrong? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Have you tried printing the value to see what position actually holds? If it has an apostrophe or something or something, you're not going to be able to convert. Also, as always, you should post the entire trace. It could be helpful here, for example: >>> x = '1. 1 ' >>> float(x) Traceback (most recent call last): File "", line 1, in float(x) ValueError: invalid literal for float(): 1. 1 >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Aug 11 01:20:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 11 Aug 2011 09:20:36 +1000 Subject: [Tutor] converting string to float In-Reply-To: References: Message-ID: <4E431244.8090108@pearwood.info> Shwinn Ricci wrote: > however, I want to convert position to a floating point number, as the > actual cell value is in the form of X.XXX (where X = digits). When I try > float(position) I get a ValueError saying that the string could not be > converted to a float. What am I doing wrong? Inspect the string by printing it with repr() and see what is actually there. e.g. print repr(position) float(position) -- Steven From steve at pearwood.info Thu Aug 11 01:22:22 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 11 Aug 2011 09:22:22 +1000 Subject: [Tutor] visualizing a point on a 3-dimensional surface In-Reply-To: References: Message-ID: <4E4312AE.6030105@pearwood.info> Shwinn Ricci wrote: > Say I have a point that I want to visualize by placing a small marker there > on the surface of an object. However, what if it's a 3-dimensional object? > Would you just use a 3-D coordinate system and then use a rotatable camera > script to wheel around and get a better view of the point? This has nothing to do with Python and would be best asked on a forum about 3D rendering software. But my guess for the answer is, Yes. (What else could you do?) -- Steven From questions.anon at gmail.com Thu Aug 11 03:57:02 2011 From: questions.anon at gmail.com (questions anon) Date: Thu, 11 Aug 2011 11:57:02 +1000 Subject: [Tutor] numpy.mean across multiple netcdf files Message-ID: I have many ncfiles each containing one month of hourly temperature data. I have worked out how to loop through a number of ncfiles and calculate the mean for each file at a particular time and even plot this and output as a *.png. What I am unsure of is how to calculate the mean at a particular time for all files. Do I somehow output the mean for each folder and then calculate the mean of all the means? Or is there some way to loop through and calculate it directly? Below is the code I have working that calculates the mean for each file. Any help will be greatly appreciated!! from netCDF4 import Dataset import numpy as N MainFolder=r"D:/temp_samples/" print MainFolder for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TSFC=ncfile.variables['T_SFC'][4::24,:,:] #this chooses a particular time for each day for the whole month LAT=ncfile.variables['latitude'][:] LON=ncfile.variables['longitude'][:] TIME=ncfile.variables['time'][:] fillvalue=ncfile.variables['T_SFC']._FillValue ncfile.close() #calculate summary stats TSFCmean=N.mean(TSFC, axis=0) print "The TSFCmean array is:", TSFCmean # there is a lot more code that follows this to plot the mean for each ncfile but I have cut that out as I think it is irrelevant to my question -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Thu Aug 11 08:48:15 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 10 Aug 2011 23:48:15 -0700 Subject: [Tutor] numpy.mean across multiple netcdf files In-Reply-To: References: Message-ID: <82B2C27D-5A95-435B-B488-C7D34A32C6E9@gmail.com> Hello Anonymous Questioner, First - you will probably be told this isn't the correct email list for this question - this is a general python tutorial list, while your question is numpy specific, so if this doesn't help, you should probably look to another email list. There are a couple general comments to make regarding your question. Basically, you want to load all the data into one big numpy array. Currently, it seems your data array has 3 indices, from this line > TSFC=ncfile.variables['T_SFC'][4::24,:,:] you can make a larger array with one more index, where the new index runs over files. So instead of looping over the files as you do, you can use the loop to build the larger array. I am sure there is a more elegant way to do this, but here is something that is along the lines of what you want > big_array = [] > for ncfile in files: > big_array.append(ncfile.variables['T_SFC'][4::24,:,:]) if all of your data you are taking from each file is the same size for all the files, then you can declare the whole thing an array > big_array = N.array(big_array) and then you can take averages very easily by specifying which index, or indices you want to average over. If life is not so kind, and your files are of different sizes, then you have to be more careful. But to give a precise answer to your problem would require knowledge of what your data files actually look like. Also, a bit of caution with averaging (in case you are unfamiliar). Say you have 5 data sets, and each one has a different amount of data in it. If you first take the average of each set, you can not simply take the average of those sets to produce the global average. You have to weight each set by the amount of data you averaged. Say the length of the sets are [N0,N1,N2,N3,N4] with average values [a0,a1,a2,a3,a4], then to produce the global average, you need to take avg = (1 / (N0+N1+N2+N3+N4) ) * (N0*a0 + N1*a1 + N2*a2 + N3*a3 + N4*a4) a few lines of algebra can demonstrate this produces the average you would get by combining all the data in all the sets and taking one big average. Regards, Andre On Aug 10, 2011, at 6:57 PM, questions anon wrote: > I have many ncfiles each containing one month of hourly temperature data. > I have worked out how to loop through a number of ncfiles and calculate the mean for each file at a particular time and even plot this and output as a *.png. > What I am unsure of is how to calculate the mean at a particular time for all files. > Do I somehow output the mean for each folder and then calculate the mean of all the means? Or is there some way to loop through and calculate it directly? > Below is the code I have working that calculates the mean for each file. Any help will be greatly appreciated!! > > from netCDF4 import Dataset > import numpy as N > > MainFolder=r"D:/temp_samples/" > print MainFolder > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > print dir > path=path+'/' > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", ncfile > ncfile=os.path.join(path,ncfile) > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > TSFC=ncfile.variables['T_SFC'][4::24,:,:] #this chooses a particular time for each day for the whole month > LAT=ncfile.variables['latitude'][:] > LON=ncfile.variables['longitude'][:] > TIME=ncfile.variables['time'][:] > fillvalue=ncfile.variables['T_SFC']._FillValue > ncfile.close() > > #calculate summary stats > TSFCmean=N.mean(TSFC, axis=0) > print "The TSFCmean array is:", TSFCmean > > # there is a lot more code that follows this to plot the mean for each ncfile but I have cut that out as I think it is irrelevant to my question > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From oberoc at gmail.com Thu Aug 11 12:33:04 2011 From: oberoc at gmail.com (Tino Dai) Date: Thu, 11 Aug 2011 06:33:04 -0400 Subject: [Tutor] Something in my .pythonrc broke my shell Message-ID: Hi Everybody, I'm using sontak's environment to give me a IDE in vim. He also crafted some code in the .pythonrc. Problem is, it broken my keyboard. The letter b not longer displays when I'm in the python shell (2.6.5 - linux), but everything is fine when enter the shell using the -E flag. Is there a simple way to track down this problem in the .pythonrc? Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Thu Aug 11 13:07:36 2011 From: oberoc at gmail.com (Tino Dai) Date: Thu, 11 Aug 2011 07:07:36 -0400 Subject: [Tutor] Something in my .pythonrc broke my shell In-Reply-To: References: Message-ID: On Thu, Aug 11, 2011 at 6:44 AM, Wolf Halton wrote: > Tino, > Copy the contents of your .pythonrc here so we can see what is going on. > Wolf > > I pastebin'ed it: http://pastebin.com/tdsK9JtK -Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Fri Aug 12 08:04:49 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 12 Aug 2011 07:04:49 +0100 Subject: [Tutor] Using type Message-ID: Hello All, I need help here, type(item) == [].__class__:. What is the idiomatic way of doing it? def myflatten(my_data): gut = [] for item in my_data: if type(item) == [].__class__: gut = gut + myflatten ( item) else: gut.append(item) return gut print myflatten(goo) -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 12 09:47:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Aug 2011 08:47:08 +0100 Subject: [Tutor] Using type In-Reply-To: References: Message-ID: <4E44DA7C.3040401@btinternet.com> On 12/08/11 07:04, Emeka wrote: > Hello All, > > I need help here, type(item) == [].__class__:. What is the idiomatic way > of doing it? if type(item) == type([])... or in this case if type(item) == list... But probably preferrable to using type is to use isinstance: if isinstance(item, list)... And even more preferable still is don't check the type at all but just try the operation try: item.doSomething() except AttributeError: doSomethingElse(item) But that isn't always appropriate. > def myflatten(my_data): > gut = [] > for item in my_data: > if type(item) == [].__class__: > gut = gut + myflatten ( item) > else: > gut.append(item) > return gut In this particular case you presumably want to be able to use any iterable object as an argument. So it might be better written as: def myflatten(my_data): gut = [] for item in my_data: try: iter(item) # test for iterability gut = gut + myflatten(item) except TypeError: gut.append(item) return gut -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 12 09:47:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Aug 2011 08:47:08 +0100 Subject: [Tutor] Using type In-Reply-To: References: Message-ID: <4E44DA7C.3040401@btinternet.com> On 12/08/11 07:04, Emeka wrote: > Hello All, > > I need help here, type(item) == [].__class__:. What is the idiomatic way > of doing it? if type(item) == type([])... or in this case if type(item) == list... But probably preferrable to using type is to use isinstance: if isinstance(item, list)... And even more preferable still is don't check the type at all but just try the operation try: item.doSomething() except AttributeError: doSomethingElse(item) But that isn't always appropriate. > def myflatten(my_data): > gut = [] > for item in my_data: > if type(item) == [].__class__: > gut = gut + myflatten ( item) > else: > gut.append(item) > return gut In this particular case you presumably want to be able to use any iterable object as an argument. So it might be better written as: def myflatten(my_data): gut = [] for item in my_data: try: iter(item) # test for iterability gut = gut + myflatten(item) except TypeError: gut.append(item) return gut -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Aug 12 11:08:26 2011 From: d at davea.name (Dave Angel) Date: Fri, 12 Aug 2011 05:08:26 -0400 Subject: [Tutor] Using type In-Reply-To: <4E44DA7C.3040401@btinternet.com> References: <4E44DA7C.3040401@btinternet.com> Message-ID: <4E44ED8A.8090901@davea.name> On 08/12/2011 03:47 AM, Alan Gauld wrote: > On 12/08/11 07:04, Emeka wrote: >> Hello All, >> >> I need help here, type(item) == [].__class__:. What is the idiomatic way >> of doing it? > > if type(item) == type([])... > > or in this case > > if type(item) == list... > > But probably preferrable to using type is to use isinstance: > > if isinstance(item, list)... > > And even more preferable still is don't check the type at > all but just try the operation > > try: > item.doSomething() > except AttributeError: > doSomethingElse(item) > > > But that isn't always appropriate. > >> def myflatten(my_data): >> gut = [] >> for item in my_data: >> if type(item) == [].__class__: >> gut = gut + myflatten ( item) >> else: >> gut.append(item) >> return gut > > In this particular case you presumably want to be > able to use any iterable object as an argument. > So it might be better written as: > > def myflatten(my_data): > gut = [] > for item in my_data: > try: > iter(item) # test for iterability > gut = gut + myflatten(item) > except TypeError: > gut.append(item) > return gut > > This is exactly the way I'd think about this problem. But I'd also point out the differences between the three. if type(x) == list is the most concise way to express the original relationship. if you want to be able to also handle any type that's derived from list, use isinstance(). If you want to be able to handle any iterable, use the final form. It'll work on lists and tuples, for simple examples. But beware that when you iterate through strings, the individual characters are also strings, and this function will fail with an error like: RuntimeError: maximum recursion depth exceeded -- DaveA From alan.gauld at btinternet.com Fri Aug 12 11:31:54 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 12 Aug 2011 10:31:54 +0100 (BST) Subject: [Tutor] Using type In-Reply-To: <4E44ED8A.8090901@davea.name> References: <4E44DA7C.3040401@btinternet.com> <4E44ED8A.8090901@davea.name> Message-ID: <1313141514.45858.YahooMailRC@web86703.mail.ird.yahoo.com> > It'll work on lists and tuples, for simple examples. But beware that > when you iterate through strings, the individual characters are also > strings, and this function will fail with an error like: > RuntimeError: maximum recursion depth exceeded Oh, good catch Dave. So you'd want to add an explicit check for a string. And in fact you probably don't want to "flatten" a string into individual characters anyway! Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Aug 12 12:07:06 2011 From: d at davea.name (Dave Angel) Date: Fri, 12 Aug 2011 06:07:06 -0400 Subject: [Tutor] Using type In-Reply-To: <1313141514.45858.YahooMailRC@web86703.mail.ird.yahoo.com> References: <4E44DA7C.3040401@btinternet.com> <4E44ED8A.8090901@davea.name> <1313141514.45858.YahooMailRC@web86703.mail.ird.yahoo.com> Message-ID: <4E44FB4A.7040203@davea.name> On 08/12/2011 05:31 AM, ALAN GAULD wrote: > > >> It'll work on lists and tuples, for simple examples. But beware that >> when you iterate through strings, the individual characters are also >> strings, and this function will fail with an error like: >> RuntimeError: maximum recursion depth exceeded > > Oh, good catch Dave. > > So you'd want to add an explicit check for a string. > And in fact you probably don't want to "flatten" a string into > individual characters anyway! > > Alan G. > I agree with you about probably not wanting to flatten a string. So I'd add an isinstance() for strings and unicode. But the following is an interesting problem. I like duck typing in general. But I dislike having negative isinstance() checks just for such a case. For example, one might remember to check for a string, but not unicode or byte, which have the same problem. Not to mention a user written iterable that might also behave the same way. For many functions, I'd simply document which types it's known to work for, and let the caller beware. But infinite recursion is a particularly nasty failure mode. Any suggestions how to solve a problem of this kind without having an explicit list of exceptions? The usual rule for avoiding infinite recursion is to assure that each recursion "reduces" the problem in some way, so that the termination condition can be assured. The following is the best I could come up to implement that. It refuses to recurse if the iterable won't change. def flatten(my_data): gut = [] for item in my_data: try: iter(item) # test for iterability if len(item) == 1 and item == item[0]: gut.append(item) else: gut = gut + flatten(item) except TypeError: gut.append(item) return gut -- DaveA From g.nius.ck at gmail.com Fri Aug 12 20:03:18 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 12 Aug 2011 14:03:18 -0400 Subject: [Tutor] Using type In-Reply-To: <4E44FB4A.7040203@davea.name> References: <4E44DA7C.3040401@btinternet.com> <4E44ED8A.8090901@davea.name> <1313141514.45858.YahooMailRC@web86703.mail.ird.yahoo.com> <4E44FB4A.7040203@davea.name> Message-ID: > > try: > iter(item) # test for iterability > if len(item) == 1 and item == item[0]: > gut.append(item) > else: > gut = gut + flatten(item) > > except TypeError: > gut.append(item) > I wouldn't put the what you want to do if there is no error in the try statement. It makes it appear like your checking for an error in all the code. I would do. try: iter(item) # test for iterability except TypeError: gut.append(item) else: if len(item) == 1 and item == item[0]: ##By the way, why do you have this if statment gut.append(item) else: gut = gut + flatten(item) Oh ya out of curiosity, what is the flatten func for? -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Fri Aug 12 22:21:36 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 12 Aug 2011 21:21:36 +0100 Subject: [Tutor] Using type In-Reply-To: References: <4E44DA7C.3040401@btinternet.com> <4E44ED8A.8090901@davea.name> <1313141514.45858.YahooMailRC@web86703.mail.ird.yahoo.com> <4E44FB4A.7040203@davea.name> Message-ID: Chris, I was just fooling around and I wanted to do something for myself before going to bed the other night. func myflatten will turn say [ 34 [90] [12] 1] into [34 90 12 1]. Just like its name sounds. Emeka On Fri, Aug 12, 2011 at 7:03 PM, Christopher King wrote: > try: >> iter(item) # test for iterability >> if len(item) == 1 and item == item[0]: >> gut.append(item) >> else: >> gut = gut + flatten(item) >> >> except TypeError: >> gut.append(item) >> > I wouldn't put the what you want to do if there is no error in the > try statement. It makes it appear like your checking for an error in all the > code. I would do. > > try: > iter(item) # test for iterability > except TypeError: > gut.append(item) > else: > if len(item) == 1 and item == item[0]: ##By the way, why do you > have this if statment > > gut.append(item) > else: > gut = gut + flatten(item) > > Oh ya out of curiosity, what is the flatten func for? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnshtb at gmail.com Fri Aug 12 22:54:02 2011 From: mnshtb at gmail.com (Michael Scharf) Date: Fri, 12 Aug 2011 16:54:02 -0400 Subject: [Tutor] Where to direct non-language questions? Message-ID: Hi List, I'm am not quite at the point of needing this, but where would I go to ask a question like "Why is the OpenCalais Python API not returning all fields when I do x or y" or "Has anyone built their own Python API for OpenCalais"? Stack Overflow? Or is there something Python-specific? Thank you, Mike From mnshtb at gmail.com Fri Aug 12 23:53:33 2011 From: mnshtb at gmail.com (Michael Scharf) Date: Fri, 12 Aug 2011 17:53:33 -0400 Subject: [Tutor] Where to direct non-language questions? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7951A86@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7951A86@EMARC112VS01.exchad.jpmchase.net> Message-ID: Sent: Friday, August 12, 2011 3:54 PM Hi List, I'm am not quite at the point of needing this, but where would I go to ask a question like "Why is the OpenCalais Python API not returning all fields when I do x or y" ?or "Has anyone built their own Python API for OpenCalais"? ?Stack Overflow? Or is there something Python-specific? Thank you, Mike ============================================== On Fri, Aug 12, 2011 at 5:36 PM, Prasad, Ramit wrote: With 3rd party tools/APIs, asking the 3rd party is usually the most effective. I would probably post those questions to: http://www.opencalais.com/forum Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 ============================================== Ramit, Thank you. Mike From ramit.prasad at jpmorgan.com Fri Aug 12 23:36:04 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 12 Aug 2011 17:36:04 -0400 Subject: [Tutor] Where to direct non-language questions? In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7951A86@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Michael Scharf Sent: Friday, August 12, 2011 3:54 PM To: tutor at python.org Subject: [Tutor] Where to direct non-language questions? Hi List, I'm am not quite at the point of needing this, but where would I go to ask a question like "Why is the OpenCalais Python API not returning all fields when I do x or y" or "Has anyone built their own Python API for OpenCalais"? Stack Overflow? Or is there something Python-specific? Thank you, Mike ============================================== With 3rd party tools/APIs, asking the 3rd party is usually the most effective. I would probably post those questions to: http://www.opencalais.com/forum _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Sat Aug 13 01:05:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Aug 2011 00:05:36 +0100 Subject: [Tutor] Where to direct non-language questions? In-Reply-To: References: Message-ID: <4E45B1C0.6080008@btinternet.com> On 12/08/11 21:54, Michael Scharf wrote: > .... where would I go to ask a question like In general start with the most specific source you can find. So if the tool/library has a mailing list or web forum ask there first - or possibly email the author. If there is no such forum try the main Python list comp.lang.python on usenet or the equivalent mailing list (they are just different representations of the same messages). If that fails then move up a level again to some of the more general mailing lists for your OS or perhaps a generic programming web site, but you had better have done your homework/searches first or you can expect to be flamed!! But nowadays most libraries have at least an author email link or a web forum/wiki/blog of some sort, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Aug 13 01:05:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Aug 2011 00:05:36 +0100 Subject: [Tutor] Where to direct non-language questions? In-Reply-To: References: Message-ID: <4E45B1C0.6080008@btinternet.com> On 12/08/11 21:54, Michael Scharf wrote: > .... where would I go to ask a question like In general start with the most specific source you can find. So if the tool/library has a mailing list or web forum ask there first - or possibly email the author. If there is no such forum try the main Python list comp.lang.python on usenet or the equivalent mailing list (they are just different representations of the same messages). If that fails then move up a level again to some of the more general mailing lists for your OS or perhaps a generic programming web site, but you had better have done your homework/searches first or you can expect to be flamed!! But nowadays most libraries have at least an author email link or a web forum/wiki/blog of some sort, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Aug 13 09:58:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Aug 2011 17:58:24 +1000 Subject: [Tutor] Where to direct non-language questions? In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7951A86@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E462EA0.9050206@pearwood.info> Michael Scharf wrote: > Sent: Friday, August 12, 2011 3:54 PM > > Hi List, > > I'm am not quite at the point of needing this, but where would I go to > ask a question like "Why is the OpenCalais Python API not returning > all fields when I do x or y" or "Has anyone built their own Python > API for OpenCalais"? Stack Overflow? Or is there something > Python-specific? Something as specific as the first question is best asked on whatever forum the OpenCalais Python library makes available: a mailing list, a bug tracker, the author's personal email, an IRC channel. The second question should be asked on whatever forums specialise in OpenCalais. Failing that, you could try comp.lang.python, which tends to have a lot more people that here. If you don't have access to Usenet, it is also available on python-list at python.org. -- Steven From thisisonlyatest at gmx.com Sat Aug 13 22:08:40 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sat, 13 Aug 2011 16:08:40 -0400 Subject: [Tutor] Tkinter: no module named messagebox Message-ID: <4E46D9C8.1060501@gmx.com> I have tried to follow the tutorial I found here: Python 2.7 Tutorial http://www.youtube.com/watch?v=uh6AdDX7K7U This is what I have done so far: #!/usr/bin/python from Tkinter import * import Tkinter.MessageBox myapp = Tk() myapp.title("This is the gui title") myapp.geometry("500x500+600+600") myapp.mainloop() I run it like this: $ python tktest.py I am getting the error message: Traceback (most recent call last): File "tkwindow.py", line 12, in import Tkinter.MessageBox ImportError: No module named MessageBox And then after changing the uppercase to lowercase this: Traceback (most recent call last): File "tkwindow.py", line 12, in import Tkinter.messagebox ImportError: No module named messagebox How do I find the modules in Tkinter? I am running Python 2.6.6. It may be a little older and not have the messagebox module. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Aug 13 22:49:42 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 Aug 2011 22:49:42 +0200 Subject: [Tutor] Tkinter: no module named messagebox References: <4E46D9C8.1060501@gmx.com> Message-ID: brandon w wrote: > I have tried to follow the tutorial I found here: > > Python 2.7 Tutorial > http://www.youtube.com/watch?v=uh6AdDX7K7U > > This is what I have done so far: > > #!/usr/bin/python > > from Tkinter import * > import Tkinter.MessageBox > > myapp = Tk() > myapp.title("This is the gui title") > myapp.geometry("500x500+600+600") > myapp.mainloop() > > I run it like this: > > $ python tktest.py > > I am getting the error message: > > Traceback (most recent call last): > File "tkwindow.py", line 12, in > import Tkinter.MessageBox > ImportError: No module named MessageBox > > And then after changing the uppercase to lowercase this: > > Traceback (most recent call last): > File "tkwindow.py", line 12, in > import Tkinter.messagebox > ImportError: No module named messagebox > > > How do I find the modules in Tkinter? The simplest approach is probably to explore your file system: Step 1: where's Tkinter? $ python -c 'import Tkinter, os; print os.path.dirname(Tkinter.__file__)' /usr/lib/python2.6/lib-tk Step 2: explore the neighbourhood $ find `python -c 'import Tkinter, os; print os.path.dirname(Tkinter.__file__)'` -iname '*messagebox*.py' /usr/lib/python2.6/lib-tk/tkMessageBox.py Step 3: we have a candidate; let's verify: $ python >>> import tkMessageBox >>> dir(tkMessageBox) ['ABORT', 'ABORTRETRYIGNORE', 'CANCEL', 'Dialog', 'ERROR', 'IGNORE', 'INFO', 'Message', 'NO', 'OK', 'OKCANCEL', 'QUESTION', 'RETRY', 'RETRYCANCEL', 'WARNING', 'YES', 'YESNO', 'YESNOCANCEL', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_show', 'askokcancel', 'askquestion', 'askretrycancel', 'askyesno', 'askyesnocancel', 'showerror', 'showinfo', 'showwarning'] >>> tkMessageBox.askyesno("does that help you?") True Of course you could also consult some documentation. I usually google for tkinter new mexico. http://infohost.nmt.edu/tcc/help/pubs/tkinter/dialogs.html#tkMessageBox > I am running Python 2.6.6. It may be a little older and not have the > messagebox module. I think tkMessageBox has been moved to tkinter.messagebox in Python 3. From thisisonlyatest at gmx.com Sat Aug 13 23:06:26 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sat, 13 Aug 2011 17:06:26 -0400 Subject: [Tutor] Tkinter: no module named messagebox In-Reply-To: References: <4E46D9C8.1060501@gmx.com> Message-ID: <4E46E752.3030901@gmx.com> On 08/13/2011 04:49 PM, Peter Otten wrote: > `python -c 'import Tkinter, os; print > os.path.dirname(Tkinter.__file__)'` Thanks dude. That is some really useful information. That will help me for future coding. I found that I needed to use "from tkMessageBox import *" to get it to work. From alan.gauld at btinternet.com Sat Aug 13 23:29:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Aug 2011 22:29:46 +0100 Subject: [Tutor] Testing, please ignore Message-ID: Testing from new Ubuntu install... problems with Thunderbird settings... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From je.rees at virgin.net Sat Aug 13 23:56:44 2011 From: je.rees at virgin.net (Jon) Date: Sat, 13 Aug 2011 22:56:44 +0100 Subject: [Tutor] Python Message-ID: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> Could you link me to some beginners tutorials/idle codes thank you. From alan.gauld at btinternet.com Sun Aug 14 02:30:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Aug 2011 01:30:56 +0100 Subject: [Tutor] Python In-Reply-To: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> References: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> Message-ID: On 13/08/11 22:56, Jon wrote: > Could you link me to some beginners tutorials/idle codes thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Just go to the python.org web site and follow the links to documentation for beginners. There are lots of tutorials listed for total newbies through to experienced programmers converting to Python. There are also how-to guides for common topics etc. If you have specific questions come back here. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From thisisonlyatest at gmx.com Sun Aug 14 03:35:26 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sat, 13 Aug 2011 21:35:26 -0400 Subject: [Tutor] Python In-Reply-To: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> References: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> Message-ID: <4E47265E.3080500@gmx.com> On 08/13/2011 05:56 PM, Jon wrote: > Could you link me to some beginners tutorials/idle codes thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Check out some Youtube videos too. derekbanas http://www.youtube.com/watch?v=UQi-L-_chcc theNewBoston http://www.youtube.com/watch?v=4Mf0h3HphEA From steve at pearwood.info Sun Aug 14 05:14:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Aug 2011 13:14:33 +1000 Subject: [Tutor] Python In-Reply-To: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> References: <6BB083FF-830D-4BFB-A7DA-30A6CE98B634@virgin.net> Message-ID: <4E473D99.4050404@pearwood.info> Jon wrote: > Could you link me to some beginners tutorials/idle codes thank you. http://duckduckgo.com/?q=python+beginners+tutorial (Check out the very first link provided.) -- Steven From wolf.halton at gmail.com Sun Aug 14 05:34:30 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Sat, 13 Aug 2011 23:34:30 -0400 Subject: [Tutor] Add lines to middle of text file Message-ID: Is there a way to add text to an arbitrary place in a text file? NewAddition="this important directive. " Open config.config Add new line above "# this marker text in config.config" Insert $NewAddition in blank line created above. Save config.config Close config.config <\pseudocode> I am automating adding servers to nagios monitoring. I already have the part that creates the new server.cfg file. This was a fairly simple bash script. I am planning to write it in python instead, so i can let the administrator choose the services to enable in a series of if statements, rather than having to hand-edit the resultant file. I need my script to add this filename to the main nagios.cfg list of read files, but it isn't going to work to do it as a straightforward append... Unless I can append it to a serverlist file and insert that file into nagios.cfg at the proper position... -------------- next part -------------- An HTML attachment was scrubbed... URL: From thisisonlyatest at gmx.com Sun Aug 14 05:40:20 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sat, 13 Aug 2011 23:40:20 -0400 Subject: [Tutor] Tkinter: no module named messagebox In-Reply-To: References: <4E46D9C8.1060501@gmx.com> Message-ID: <4E4743A4.2030804@gmx.com> On 08/13/2011 04:49 PM, Peter Otten wrote: > brandon w wrote: > > >> I have tried to follow the tutorial I found here: >> >> Python 2.7 Tutorial >> http://www.youtube.com/watch?v=uh6AdDX7K7U >> >> This is what I have done so far: >> >> #!/usr/bin/python >> >> from Tkinter import * >> import Tkinter.MessageBox >> >> myapp = Tk() >> myapp.title("This is the gui title") >> myapp.geometry("500x500+600+600") >> myapp.mainloop() >> >> I run it like this: >> >> $ python tktest.py >> >> I am getting the error message: >> >> Traceback (most recent call last): >> File "tkwindow.py", line 12, in >> import Tkinter.MessageBox >> ImportError: No module named MessageBox >> >> And then after changing the uppercase to lowercase this: >> >> Traceback (most recent call last): >> File "tkwindow.py", line 12, in >> import Tkinter.messagebox >> ImportError: No module named messagebox >> >> >> How do I find the modules in Tkinter? >> > The simplest approach is probably to explore your file system: > > Step 1: where's Tkinter? > > $ python -c 'import Tkinter, os; print os.path.dirname(Tkinter.__file__)' > /usr/lib/python2.6/lib-tk > > Step 2: explore the neighbourhood > > $ find `python -c 'import Tkinter, os; print > os.path.dirname(Tkinter.__file__)'` -iname '*messagebox*.py' > /usr/lib/python2.6/lib-tk/tkMessageBox.py > > Step 3: we have a candidate; let's verify: > > $ python > > >>>> import tkMessageBox >>>> dir(tkMessageBox) >>>> > ['ABORT', 'ABORTRETRYIGNORE', 'CANCEL', 'Dialog', 'ERROR', 'IGNORE', 'INFO', > 'Message', 'NO', 'OK', 'OKCANCEL', 'QUESTION', 'RETRY', 'RETRYCANCEL', > 'WARNING', 'YES', 'YESNO', 'YESNOCANCEL', '__builtins__', '__doc__', > '__file__', '__name__', '__package__', '_show', 'askokcancel', > 'askquestion', 'askretrycancel', 'askyesno', 'askyesnocancel', 'showerror', > 'showinfo', 'showwarning'] > >>>> tkMessageBox.askyesno("does that help you?") >>>> > True > > Of course you could also consult some documentation. I usually google for > tkinter new mexico. > http://infohost.nmt.edu/tcc/help/pubs/tkinter/dialogs.html#tkMessageBox > > >> I am running Python 2.6.6. It may be a little older and not have the >> messagebox module. >> > I think tkMessageBox has been moved to tkinter.messagebox in Python 3. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I have tried # 1. with another command but all I get is an error messages. $ python -c 'import time, os; print os.path.dirname(time.__doc__)' # This one gave no output. $ python -c 'import time, strftime, os; print os.path.dirname(strftime.__doc__)' Traceback (most recent call last): File "", line 1, in ImportError: No module named strftime $ python -c 'import os; from time import strftime; print os.path.dirname(strftime.__file__)' Traceback (most recent call last): File "", line 1, in AttributeError: 'builtin_function_or_method' object has no attribute '__file__' $ python -c 'import time, os; print os.path.dirname(time.__file__)' Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/posixpath.py", line 119, in dirname i = p.rfind('/') + 1 AttributeError: 'NoneType' object has no attribute 'rfind' $ python -c 'import time, os; print os.path.dirname(time.__package__)' more errors I am obviously doing something wrong. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Aug 14 06:38:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Aug 2011 14:38:38 +1000 Subject: [Tutor] Add lines to middle of text file In-Reply-To: References: Message-ID: <4E47514E.4000405@pearwood.info> Wolf Halton wrote: > Is there a way to add text to an arbitrary place in a text file? If you are using the OpenVMS operating system, or a VAX computer, then yes. The operating system natively supports inserting data into the middle of a file. If you are using Windows, Linux, Unix, Mac OS (classic or X), or just about every other operating system I've ever come across, no. Files support only overwriting or appending at the end of the file. This is why many file formats use fixed-width fields. You can seek to the position you want and overwrite a field with the new data. [...] > I need my script to add this filename to the main nagios.cfg list of read > files, but it isn't going to work to do it as a straightforward append... > Unless I can append it to a serverlist file and insert that file into > nagios.cfg at the proper position... The usual way to do that is to read the file into memory, insert the new data, then write the file back over the top of the old file. This could be as simple as this: text = open('nagios.cfg').read() text = modify(text) open('nagios.cfg', 'w').write(text) although for a production application, you would need error handling code to ensure things are as safe as possible. E.g.: text = open('nagios.cfg').read() text = modify(text) shutil.copy('nagios.cfg', 'nagios.cfg~') # save a backup copy open('nagios.cfg', 'w').write(text) Even that is pretty light on the error handling -- good enough for a quick and dirty script, but not for a professional quality application. -- Steven From thisisonlyatest at gmx.com Sun Aug 14 07:11:26 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sun, 14 Aug 2011 01:11:26 -0400 Subject: [Tutor] tkinter.TclError Message-ID: <4E4758FE.7060705@gmx.com> Here is the code: #!/usr/bin/python from Tkinter import * from tkMessageBox import * def iClicked(): radioValue = relStatus.get() tkMessageBox.showinfo("You clicked", radioValue) return def chLabel(): name = "Thank you for clicking me. " + your_name.get() labelText.set(name) your_name.delete(0, END) your_name.insert(0, "My name is Simon.") return myapp = Tk() myapp.title("This is the gui title") myapp.geometry("500x500+600+600") labelText = StringVar() labelText.set("Click button") label0 = Label(myapp, textvariable=labelText, height=4) label0.pack() chkbx = IntVar() chkbx0 = Checkbutton(myapp, variable=chkbx, text="Hungry?") chkbx0.pack() a_name = StringVar() your_name = Entry(myapp, textvariable=a_name) your_name.pack() # Once this section is commented out the window opens but without the radio buttons. # I have attempted many variations of the two lines. relStatus = StringVar() relStatus.set(None) #radio0 = Radiobutton(myapp, text="had breakfast", value="had breakfast", variable=relStatus, commmand=iClicked).pack(anchor=W) #radio0 = Radiobutton(myapp, text="did not eat breakfast", value="did not eat breakfast", variable=relStatus, commmand=iClicked).pack(anchor=W) #radio1 = Radiobutton(myapp, master=None, text="had breakfast", value="had breakfast", variable=relStatus, commmand=iClicked).pack() #radio1 = Radiobutton(myapp, master=None, text="did not eat breakfast", value="did not eat breakfast", variable=relStatus, commmand=iClicked).pack() #radio1 = Radiobutton(myapp, text="had breakfast", value="had breakfast", variable=relStatus, commmand=iClicked).pack() #radio1 = Radiobutton(myapp, text="did not eat breakfast", value="did not eat breakfast", variable=relStatus, commmand=iClicked).pack() #radio0 = Radiobutton(master, text="had breakfast", value="had breakfast", variable=myapp, commmand=iClicked).pack() #radio0 = Radiobutton(master, text="did not eat breakfast", value="did not eat breakfast", variable=myapp, commmand=iClicked).pack() radio1 = Radiobutton(master=myapp, text="had breakfast", value="had breakfast", variable=relStatus, commmand=iClicked).pack() radio1 = Radiobutton(master=myapp, text="did not eat breakfast", value="did not eat breakfast", variable=relStatus, commmand=iClicked).pack() # Something is wrong with the two lines above? button0 = Button(myapp, text="Click me", width=20, command=chLabel) button0.pack(side='bottom', padx=15, pady=15) myapp.mainloop() Here is the error: $ python tktest.py *Traceback (most recent call last): File "tkwindow.py", line 54, in radio1 = Radiobutton(master=myapp, text="had breakfast", value="had breakfast", variable=relStatus, commmand=iClicked).pack() File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 2732, in __init__ Widget.__init__(self, master, 'radiobutton', cnf, kw) File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1935, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: unknown option "-commmand"* -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Aug 14 08:29:13 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Aug 2011 08:29:13 +0200 Subject: [Tutor] Tkinter: no module named messagebox References: <4E46D9C8.1060501@gmx.com> <4E4743A4.2030804@gmx.com> Message-ID: brandon w wrote: > On 08/13/2011 04:49 PM, Peter Otten wrote: >>> How do I find the modules in Tkinter? >>> >> The simplest approach is probably to explore your file system: >> >> Step 1: where's Tkinter? >> >> $ python -c 'import Tkinter, os; print os.path.dirname(Tkinter.__file__)' >> /usr/lib/python2.6/lib-tk > I have tried # 1. with another command but all I get is an error messages. > > $ python -c 'import time, os; print os.path.dirname(time.__doc__)' # > This one gave no output. You typed time.__doc__ instead of time.__file__. With the latter you'd get an AttributeError because the time module is implemented in C. > $ python -c 'import time, strftime, os; print > os.path.dirname(strftime.__doc__)' > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named strftime Well you cannot import a module that doesn't exist... > $ python -c 'import os; from time import strftime; print > os.path.dirname(strftime.__file__)' > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'builtin_function_or_method' object has no attribute > '__file__' > > $ python -c 'import time, os; print os.path.dirname(time.__file__)' > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/posixpath.py", line 119, in dirname > i = p.rfind('/') + 1 > AttributeError: 'NoneType' object has no attribute 'rfind' > > $ python -c 'import time, os; print os.path.dirname(time.__package__)' > more errors > > I am obviously doing something wrong. The method to find the location of a module that I gave works only for modules and only for modules implemented in Python. You can find both functions and modules implemented in Python with inspect.getsourcefile(): >>> from inspect import getsourcefile >>> import os >>> getsourcefile(os) # a module '/usr/lib/python2.6/os.py' >>> getsourcefile(os.path) # another module with an interesting filename '/usr/lib/python2.6/posixpath.py' >>> getsourcefile(os.walk) # a function implemented in Python '/usr/lib/python2.6/os.py' >>> getsourcefile(os.mkdir) # a function implemented in C Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/inspect.py", line 441, in getsourcefile filename = getfile(object) File "/usr/lib/python2.6/inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object From __peter__ at web.de Sun Aug 14 08:51:31 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Aug 2011 08:51:31 +0200 Subject: [Tutor] tkinter.TclError References: <4E4758FE.7060705@gmx.com> Message-ID: brandon w wrote: > radio1 = Radiobutton(master=myapp, text="had breakfast", value="had > breakfast", variable=relStatus, commmand=iClicked).pack() > *Traceback (most recent call last): > File "tkwindow.py", line 54, in > radio1 = Radiobutton(master=myapp, text="had breakfast", value="had > breakfast", variable=relStatus, commmand=iClicked).pack() > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 2732, in __init__ > Widget.__init__(self, master, 'radiobutton', cnf, kw) > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1935, in __init__ > (widgetName, self._w) + extra + self._options(cnf)) > _tkinter.TclError: unknown option "-commmand"* Read the error message carefully. Hint: count the m-s. By the way: the pack() method returns None; you cannot abbreviate #correct widget = Widget(...) widget.pack(...) with #wrong widget = Widget(...).pack(...) From robert.sjoblom at gmail.com Sun Aug 14 09:10:22 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 14 Aug 2011 09:10:22 +0200 Subject: [Tutor] Tkinter: no module named messagebox (brandon w) Message-ID: > I have tried to follow the tutorial I found here: > > Python 2.7 Tutorial > http://www.youtube.com/watch?v=uh6AdDX7K7U > > This is what I have done so far: > > #!/usr/bin/python > > from Tkinter import * > import Tkinter.MessageBox I figured I might as well, given how I recently had to learn about this, give you a heads up on imports. The format "from module import * " is not a very good idea: it makes your code harder to read (as the reader has to inspect each and every barename to check whether it's actually assigned locally OR comes from the deuced *). To quote the Zen of Python; "namespaces are a honking great idea -- let's do more of those!". You can import modules with several different syntaxes: import importable import importable1, importable2, ..., importableN import importable as preferred_name Here importable is usually a module such as collections, but could be a package or module in a package, in which case each part is separated with a dot, for example os.path. The first two syntaxes are the simplest and also the safest because they avoid the possibility of having name conflicts, since they force us to always use fully qualified names. The third syntax allows us to give a name of our choice to the package or module we are importing. Theoretically, this could lead to name clashes, but in practice the "import importable as" syntax is used to avoid them. There are some other import syntaxes: from importable import object as preferred_name from importable import object1, object2, ..., objectN from importable import (object1, object2, ..., objectN) from importable import * In the last syntax, the * means "import everything that is not private", which in practical terms means either that every object in the module is imported except for those whose names begin with a leading underscore, or, if the module has a global __all__ variable that holds a list of names, that all the objects in the __all__ variable are imported. The from importable import * syntax imports all the objects from the module (or all the modules from the package) -- this could be hundreds of names. In the case of from os.path import *, almost 40 names are imported, including "dirname", "exists", and "split", any of which might be names we would prefer to use for our own variables or functions. For example, if we write from os.path import dirname we can conveniently call dirname() without qualification. But if further on in our code we write dirname = "." the object reference dirname will now be bound to the string "." instead of to the dirname() function, so if we try calling dirname() we will get a TypeError exception because dirname now refers to a string, and we can't call strings. However, given that Tkinter is such a huge package to begin with, I'd say that you should continue to use from Tkinter import *, but be aware of what you're doing when you type that, and that there is a certain risk of conflicts. best regards, Robert S. From waynejwerner at gmail.com Sun Aug 14 15:07:30 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 14 Aug 2011 08:07:30 -0500 Subject: [Tutor] Tkinter: no module named messagebox (brandon w) In-Reply-To: References: Message-ID: On Aug 14, 2011 2:12 AM, "Robert Sjoblom" wrote: > > However, given that Tkinter is such a huge package to begin with, I'd > say that you should continue to use from Tkinter import *, but be > aware of what you're doing when you type that, and that there is a > certain risk of conflicts. Also, most (all?) Tkinter names are uppercase, such as Button, Label, etc. Of course I personally I usually do import Tkinter as tk Which means I only have to type 3 extra characters, but it removes any ambiguity - tk.Something had to come from Tkinter, and never something that I defined. I suppose it's really all about trade-offs, and what you find works best, or whatever the prevailing convention is when you're working with others. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From je.rees at virgin.net Sun Aug 14 15:04:39 2011 From: je.rees at virgin.net (je.rees e-mail) Date: Sun, 14 Aug 2011 14:04:39 +0100 Subject: [Tutor] python Message-ID: I have made a small program but I would like to know how to write or. There is multiple choice answer. Good=raw_input("Good to hear") ok=raw_input("Good good") Bad=raw_input("Oh dear") I would only like the person using the program to be able to pick one. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 14 17:14:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Aug 2011 16:14:24 +0100 Subject: [Tutor] Tkinter: no module named messagebox (brandon w) In-Reply-To: References: Message-ID: <4E47E650.6010207@btinternet.com> On 14/08/11 14:07, Wayne Werner wrote: > Of course I personally I usually do > > import Tkinter as tk > > Which means I only have to type 3 extra characters, but it removes any > ambiguity - tk.Something had to come from Tkinter Thats exactly what I tend to do nowadays. I used to use the import * method for tkinter but eventually I got bit by a name clash and it took too long to realize the problem so I now use the "import as tk" shortcut except for very short scripts - usually just for tests or experiments.. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From je.rees at virgin.net Sun Aug 14 17:42:21 2011 From: je.rees at virgin.net (je.rees e-mail) Date: Sun, 14 Aug 2011 16:42:21 +0100 Subject: [Tutor] (no subject) Message-ID: I would like this script to only have a choice of one these. I'm not sure how to do it. My example would be when someone types Good next to print how I want it to reply Thats nice. Anyone know how and if I am making more mistakes point them out please. How=("How are you today: ") print How Good=('Thats nice') good=raw_input(Good) Good=raw_input(Good) Ok=('Good good') Ok=raw_input(Ok) ok=raw_input(Ok) Bad=('Oh dear') Bad=raw_input(Bad) bad=raw_input(Bad) Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Aug 14 19:20:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Aug 2011 03:20:06 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4E4803C6.8050505@pearwood.info> je.rees e-mail wrote: > I would like this script to only have a choice of one these. I'm not sure > how to do it. My example would be when someone types Good next to print how > I want it to reply Thats nice. Anyone know how and if I am making more > mistakes point them out please. Consider this example: def test(): prompt = "Please type 'Thats nice'" answer = raw_input(prompt) if answer == "Thats nice": print "You have typed it accurately" else: print "I'm sorry, you have made a mistake" Paste that into the interactive interpreter, then run: test() and follow the instructions. Does that help? -- Steven From thisisonlyatest at gmx.com Sun Aug 14 19:40:39 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sun, 14 Aug 2011 13:40:39 -0400 Subject: [Tutor] python In-Reply-To: References: Message-ID: <4E480897.1010002@gmx.com> On 08/14/2011 09:04 AM, je.rees e-mail wrote: > I have made a small program but I would like to know how to write or. > There is multiple choice answer. > Good=raw_input("Good to hear") > ok=raw_input("Good good") > Bad=raw_input("Oh dear") > I would only like the person using the program to be able to pick one. > > Thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Why not writing the program and running it to see what happens? try something like this: good = raw_input("Did you have a nice day? ") if good == "yes": print "I'm glad you had a nice day." else: print "Sorry to hear that." -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacktradespublic at gmail.com Sun Aug 14 22:44:46 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sun, 14 Aug 2011 15:44:46 -0500 Subject: [Tutor] python In-Reply-To: References: Message-ID: On Sun, Aug 14, 2011 at 8:04 AM, je.rees e-mail wrote: > I have made a small program but I would like to know how to write or. There > is multiple choice answer. > Good=raw_input("Good to hear") > ok=raw_input("Good good") > Bad=raw_input("Oh dear") > I would only like the person using the program to be able to pick one. > > Thanks > You might want to try something like this... def ask(): ans = raw_input("Please enter (g)ood, (o)k or (b)ad: ") if ans == "g" or ans == "good": print "Good to hear" elif ans == "o" or ans == "ok": print "Good good" elif ans == "b" or ans == "bad": print "Oh dear" else: print "Incorrect choice" ask() And here's how it works... >>> ask() Please enter (g)ood, (o)k or (b)ad: b Oh dear >>> ask() Please enter (g)ood, (o)k or (b)ad: o Good good >>> ask() Please enter (g)ood, (o)k or (b)ad: ok Good good Or you could also use something a bit more general like this... def ask(question, list_of_responses): ans = raw_input(question) return list_of_responses[int(ans)] >>> ask("(0)Good (1)OK (2)Bad: ", ["Good to hear", "Good good", "Oh dear"]) (0)Good (1)OK (2)Bad: 0 'Good to hear' -- Jack Trades Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfrage8765 at gmail.com Mon Aug 15 04:09:27 2011 From: wolfrage8765 at gmail.com (Jordan) Date: Sun, 14 Aug 2011 19:09:27 -0700 Subject: [Tutor] Moveable and Animated Sprites Message-ID: <4E487FD7.8020107@gmail.com> Is there a more Pythonic way to create the class "MoveableAnimatedSheetSprite" I am using multiple inheritance but I see that I am really loading the image twice when I call __init__ for "AnimatedSheetSprite" and "MoveableSprite". Should I just make a moveable class and have moveable items inherit it with out inheriting from "Sprite"? By the way the code does work as intended right now. Thank you in advance, if you need more code or what ever just let me know. import pygame from vec2d import * class Sprite(pygame.sprite.Sprite): """This defines a sprite that is a single image in a file that only contains it as an image.""" def __init__(self, imageName, startx=0, starty=0): pygame.sprite.Sprite.__init__(self) self.image=pygame.image.load(imageName) self.rect=self.image.get_rect() self.image.convert() self.x=startx self.y=starty self.position=vec2d(self.x,self.y) self.selected=False def update(self): pygame.sprite.Sprite.update(self) class AnimatedSheetSprite(Sprite): """This defines a sprite that is multiple images but is in a image file that has only it's images.""" def __init__(self, imageName, startx=0, starty=0, height=0, width=0): Sprite.__init__(self, imageName, startx, starty) self.images=[] masterWidth, masterHeight=self.image.get_size() for i in xrange(int(masterWidth/width)): self.images.append(self.image.subsurface((i*width,0,width,height))) self.image=self.images[0] self.maxFrame=len(self.images)-1 self.frame=0 def animate(self): if self.frame < self.maxFrame: self.frame=self.frame+1 else: self.frame=0 self.image=self.images[self.frame] def update(self): Sprite.update(self) self.animate() class MoveableSprite(Sprite): """This defines a sprite that is a single image in a file that only contains it as an image. But this sprite can move.""" def __init__(self, imageName, startx=0, starty=0, targetx=0, targety=0, speed=2): Sprite.__init__(self, imageName, startx, starty) self.target=vec2d(targetx,targety) self.speed=speed def move(self): self.direction=self.target-self.position if self.direction.length > self.speed: self.position= self.position+self.speed def update(self): Sprite.update(self) self.move() class MoveableAnimatedSheetSprite(MoveableSprite, AnimatedSheetSprite): """This defines a sprite that is multiple images but is in a image file that has only it's images. But this sprite can move.""" def __init__(self, imageName, startx=0, starty=0,targetx=0, targety=0, speed=2, height=0, width=0): MoveableSprite.__init__(self, imageName, startx, starty, targetx, targety, speed) AnimatedSheetSprite.__init__(self, imageName, startx, starty, height, width) def update(self): MoveableSprite.update(self) AnimatedSheetSprite.update(self) -- Jordan Farrell From alan.gauld at btinternet.com Mon Aug 15 09:00:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Aug 2011 08:00:41 +0100 Subject: [Tutor] Moveable and Animated Sprites In-Reply-To: <4E487FD7.8020107@gmail.com> References: <4E487FD7.8020107@gmail.com> Message-ID: On 15/08/11 03:09, Jordan wrote: > Is there a more Pythonic way to create the class > "MoveableAnimatedSheetSprite" I am using multiple inheritance but I see > that I am really loading the image twice when I call __init__ for > "AnimatedSheetSprite" and "MoveableSprite". Should I just make a > moveable class and have moveable items inherit it with out inheriting > from "Sprite"? This is really more a pyGame question than a Python one so you will probably get a better response posting on the PyGame forum. However there are a few pyGamers here so you might get lucky... > class Sprite(pygame.sprite.Sprite): > def __init__(self, imageName, startx=0, starty=0): > pygame.sprite.Sprite.__init__(self) > self.image=pygame.image.load(imageName) > self.rect=self.image.get_rect() > self.image.convert() > self.x=startx > self.y=starty > self.position=vec2d(self.x,self.y) > self.selected=False > > def update(self): > pygame.sprite.Sprite.update(self) > If you are just calling the superclass you don't need this method. But I assume you will be adding extra content later? If not, your subclasses can still call Sprite.update() without this definition being here. Beyond that I can't add much... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Mon Aug 15 10:44:52 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Aug 2011 10:44:52 +0200 Subject: [Tutor] Moveable and Animated Sprites References: <4E487FD7.8020107@gmail.com> Message-ID: Jordan wrote: > Is there a more Pythonic way to create the class > "MoveableAnimatedSheetSprite" I am using multiple inheritance but I see > that I am really loading the image twice when I call __init__ for > "AnimatedSheetSprite" and "MoveableSprite". Should I just make a > moveable class and have moveable items inherit it with out inheriting > from "Sprite"? > By the way the code does work as intended right now. > Thank you in advance, if you need more code or what ever just let me know. You can use super() to avoid duplicate method calls in a diamond-shaped inheritance tree. The vanilla example: >>> class A(object): ... def __init__(self): ... print "A" ... super(A, self).__init__() ... >>> class B(A): ... def __init__(self): ... print "B" ... super(B, self).__init__() ... >>> class C(A): ... def __init__(self): ... print "C" ... super(C, self).__init__() ... >>> class D(B, C): ... def __init__(self): ... print "D" ... super(D, self).__init__() ... >>> D() D B C A <__main__.D object at 0x7f5345de9d50> In your code it's a bit harder because you need compatible method signatures. One way to achieve that is to rely on keyword arguments and then stick in **kw. To illustrate: class Sprite(pygame.sprite.Sprite): def __init__(self, imageName, startx=0, starty=0, **kw): super(Sprite, self).__init__(self) ... class MoveableSprite(Sprite): def __init__(self, imageName, **kw): super(MoveableSprite, self).__init__(imageName, **kw) speed = kw["speed"] ... m = MoveableSprite("rumpelstiltskin", speed=10, category="fairy tale") I usually don't get it right the first time, but here's what I think your update() method would become: class Sprite(pygame.sprite.Sprite): pass # no need to implement update() here class AnimatedSheetSprite(Sprite): def update(self): super(AnimatedSheetSprite, self).update() self.animate() class MoveableSprite(Sprite): def update(self): super(MoveableSprite, self).update() self.move() class MoveableAnimatedSheetSprite(MoveableSprite, AnimatedSheetSprite): pass # no need to implement update() here From john at netcore.com.au Mon Aug 15 21:27:42 2011 From: john at netcore.com.au (John Collins) Date: Tue, 16 Aug 2011 05:27:42 +1000 Subject: [Tutor] print to file probelm Message-ID: <4E49732E.3050105@netcore.com.au> Hi, I'm a baffled beginner. The script below is one of a suite of scripts written by Simon Tatham a decade ago; http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/ http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/polyhedra.tar.gz OS: WinXP Py Ver: 2.7 Script: canvas.py It reads from a file name in the command line and should print to a file name also specified in the command line. It inputs and runs fine but outputs to the command prompt *screen* while creating and *empty* output file of the name specified? I cannot figure out why? [the dashed lines below are not in the script(s)] ------------------------------------------------------------------- #!/usr/bin/env python # Read in a polyhedron description, and output a JavaScript list # suitable for use in the "data" field of a canvas used by # canvaspoly.js. import sys import os import string import random from math import pi, asin, atan2, cos, sin, sqrt from crosspoint import crosspoint args = sys.argv[1:] if len(args) > 0: infile = open(args[0], "r") args = args[1:] else: infile = sys.stdin if len(args) > 0: outfile = open(args[0], "w") args = args[1:] else: outfile = sys.stdout vertices = {} faces = {} normals = {} lineno = 0 while 1: s = infile.readline() if s == "": break sl = string.split(s) lineno = lineno + 1 if sl[0] == "point" and len(sl) == 5: vertices[sl[1]] = \ (string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4])) elif sl[0] == "face" and len(sl) == 3: if not vertices.has_key(sl[2]): sys.stderr.write("line %d: vertex %s not defined\n" % \ (lineno, sl[2])) else: if not faces.has_key(sl[1]): faces[sl[1]] = [] faces[sl[1]].append(sl[2]) elif sl[0] == "normal" and len(sl) == 5: if not faces.has_key(sl[1]): sys.stderr.write("line %d: face %s not defined\n" % \ (lineno, sl[1])) else: normals[sl[1]] = \ (string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4])) else: sys.stderr.write("line %d: unrecognised line format\n" % lineno) continue infile.close() # Normalise the radius of our polyhedron so that it just fits # inside the unit sphere. maxlen = 0 for v in vertices.values(): vlen = sqrt(v[0]**2 + v[1]**2 + v[2]**2) if maxlen < vlen: maxlen = vlen for v in vertices.keys(): vv = vertices[v] vertices[v] = (vv[0]/maxlen, vv[1]/maxlen, vv[2]/maxlen) # Assign integer indices to vertices and faces. vindex = {} findex = {} vlist = [] flist = [] for v in vertices.keys(): vindex[v] = len(vlist) vlist.append(v) for f in faces.keys(): findex[f] = len(flist) flist.append(f) s = "[%d" % len(vertices) for i in range(len(vertices)): v = vertices[vlist[i]] s = s + ",%.17g,%.17g,%.17g" % (v[0], v[1], v[2]) s = s + ",%d" % len(faces) for i in range(len(faces)): f = faces[flist[i]] n = normals[flist[i]] s = s + ",%d" % len(f) for v in f: s = s + ",%d" % vindex[v] s = s + ",%.17g,%.17g,%.17g" % (n[0], n[1], n[2]) s = s + "]" print s ------------------------------------------------------------------ The other scripts run and output just fine. They do have some extra script of varying parameters that seem to be about reassigning the print command, possible with formatting of output in mind? Here are a those sections from two of the other scripts: From mkpoints.py -------------------------------------------- def realprint(a): for i in range(len(a)): outfile.write(str(a[i])) if i < len(a)-1: outfile.write(" ") else: outfile.write("\n") def pprint(*a): realprint(a) ---------------------------------------------- the final output lines are ---------------------------------------------- # Output the points. for x, y, z in points: pprint(x, y, z) ---------------------------------------------- From drawpoly.py ---------------------------------------------- def realprint(a): for i in range(len(a)): outfile.write(str(a[i])) if i < len(a)-1: outfile.write(" ") else: outfile.write("\n") def psprint(*a): realprint(a) ---------------------------------------------- the last two output lines are ---------------------------------------------- psprint("showpage grestore") psprint("%%EOF") ---------------------------------------------- For the problem script, canvas.py, the output is a long single line beginning with a "[", containing a mixture of integers and signed real numbers separated only by a commas, and ending in a "]". Any help to begin my understanding of print (re)assignments, and, fixing this script would be MOST welcome, thanks to you all! Best Regards, John. [Total newbie, time since first Python DL, <24hrs! Still use GWBasic!!! ... Really need to learn Python!] From __peter__ at web.de Mon Aug 15 22:02:36 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Aug 2011 22:02:36 +0200 Subject: [Tutor] print to file probelm References: <4E49732E.3050105@netcore.com.au> Message-ID: John Collins wrote: > Hi, > I'm a baffled beginner. The script below is one of a suite of scripts > written by Simon Tatham a decade ago; > http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/ > http://www.chiark.greenend.org.uk/~sgtatham/polyhedra/polyhedra.tar.gz > > OS: WinXP > Py Ver: 2.7 > Script: canvas.py > > It reads from a file name in the command line and should print to a file > name also specified in the command line. It inputs and runs fine but > outputs to the command prompt *screen* while creating and *empty* output > file of the name specified? I cannot figure out why? > args = sys.argv[1:] > > if len(args) > 0: > infile = open(args[0], "r") > args = args[1:] > else: > infile = sys.stdin > > if len(args) > 0: > outfile = open(args[0], "w") > args = args[1:] > else: > outfile = sys.stdout If you pass two args this will open two files, infile for reading, and outfile for writing. While infile is actually used... > while 1: > s = infile.readline() > if s == "": break ... > infile.close() ... outfile is not. The print statement > print s will always write to stdout. You can modify the print statement to print >> outfile, s or use outfile.write(s + "\n") instead. It is good style to close the file explicitly when you're done with outfile.close() From ramit.prasad at jpmorgan.com Mon Aug 15 22:09:34 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 15 Aug 2011 16:09:34 -0400 Subject: [Tutor] print to file probelm In-Reply-To: <4E49732E.3050105@netcore.com.au> References: <4E49732E.3050105@netcore.com.au> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7A5DEAB@EMARC112VS01.exchad.jpmchase.net> Hi John, Just as a note, I am looking at the included scripts (and not the linked scripts). I believe the problem you are having is with the lines below. for i in range(len(faces)): f = faces[flist[i]] n = normals[flist[i]] s = s + ",%d" % len(f) for v in f: s = s + ",%d" % vindex[v] s = s + ",%.17g,%.17g,%.17g" % (n[0], n[1], n[2]) s = s + "]" print s The problem is probably caused by the very last line above. This prints 's' to std out (the console) instead of a file. This should probably be something like (not tested - just a guide) outfile.write(s) outfline.close() I would also like to add that string concatenation is not recommended in Python. The better way to concatenate is to do something like: S = [] s.append( 'test' ) s.append( ",{0}".format( vindex[v] ) ) s.append( ",%.17g,%.17g,%.17g" % (v[0], v[1], v[2]) ) # Join at the very end " ".join(s) Furthermore, the following can be easily written without the backslash (which can be prone to errors if something appends anything after it (like non-CRLR whitespace --or whatever Windows uses). Instead you can wrap things is parenthesis normals[sl[1]] = \ (string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4])) Try this instead: normals[sl[1]] = (string.atof(sl[2]), string.atof(sl[3]), string.atof(sl[4])) OR if you have a single long string. Var = ( self.really_long_variable_name + some_other_really_long_variable + what_another_really_long_variable ) # returns a single element Be careful not to put a comma at the end of the parenthesis, because if you do the statement will return a tuple instead. Var = ( self.really_long_variable_name + some_other_really_long_variable + what_another_really_long_variable, ) # returns a tuple with one element Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From kingconnor333 at gmail.com Tue Aug 16 01:43:38 2011 From: kingconnor333 at gmail.com (Connor Merritt) Date: Mon, 15 Aug 2011 19:43:38 -0400 Subject: [Tutor] which version do i have and how do i change it Message-ID: So i installed python 2.7.1 on my linux and i bought a book that requires python 3 so installed python 3, and i used terminal and typed in python -V and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i couldn't what should i do?) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Aug 16 01:48:08 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 16 Aug 2011 00:48:08 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: Message-ID: On 16 August 2011 00:43, Connor Merritt wrote: > So i installed python 2.7.1 on my linux and i bought a book that requires > python 3 so installed python 3, and i used terminal and typed in python -V > and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i > couldn't what should i do?) > Try python3 -V The default is probably still Python2 but that does not mean you can't use Python explicitly. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Aug 16 01:48:42 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 16 Aug 2011 00:48:42 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: Message-ID: On 16 August 2011 00:48, Walter Prins wrote: > The default is probably still Python2 but that does not mean you can't use > Python explicitly. > Meant to say, "can't use Python3 explicitly". -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Tue Aug 16 05:47:50 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 16 Aug 2011 13:47:50 +1000 Subject: [Tutor] directory within directory Message-ID: I would like to open up a bunch of files within a folder within a folder and then process them and output them in another location but with the same folder structure. I seem to having trouble with the folder within folder section. I have a separate folder for each year and then within a year I have a separate folder for each month but when I try to make a directory in a new location it does not place the month folders within the year folders, instead they are all places in the outputpath together any help will be greatly appreciated import os inputpath=r'E:/temp_samples2/' outputpath=r'E:/figureoutputs/' for (path, dirs, files) in os.walk(inputpath): for dir in dirs: print path, dir newfolders=outputpath+dir if not os.path.exists(newfolders): os.makedirs(newfolders) print newfolders -------------- next part -------------- An HTML attachment was scrubbed... URL: From nauty.me04 at gmail.com Tue Aug 16 06:31:36 2011 From: nauty.me04 at gmail.com (aditya) Date: Tue, 16 Aug 2011 10:01:36 +0530 Subject: [Tutor] help in TKINTER Message-ID: Hello tutors, I wanted some help in using the Tkinter class for button creation, I am not able to add on click events i.e. when I press the button certain action should be performed for example if I press the button named 5, then it should display 5 in the text field . Help will be appreciated. -- Regards Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Tue Aug 16 08:52:49 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 16 Aug 2011 07:52:49 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: Message-ID: <201108160752.49727.lisi.reisz@gmail.com> On Tuesday 16 August 2011 00:48:08 Walter Prins wrote: > On 16 August 2011 00:43, Connor Merritt wrote: > > So i installed python 2.7.1 on my linux and i bought a book that requires > > python 3 so installed python 3, and i used terminal and typed in python > > -V and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i > > couldn't what should i do?) > > Try > > python3 -V > > The default is probably still Python2 but that does not mean you can't use > Python explicitly. If you prefer to have Python 3 only, you could also uninstall Python 2.7.1. You do not say what version of what distro you are using, nor what method you used to install Python 2, so I can't be more explicit. Lisi From alan.gauld at btinternet.com Tue Aug 16 10:05:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Aug 2011 09:05:44 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: <201108160752.49727.lisi.reisz@gmail.com> References: <201108160752.49727.lisi.reisz@gmail.com> Message-ID: On 16/08/11 07:52, Lisi wrote: > On Tuesday 16 August 2011 00:48:08 Walter Prins wrote: > >> So i installed python 2.7.1 on my linux and i bought a book that > requires > >> python 3 so installed python 3, and i used terminal and typed in python > >> -V and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i > >> couldn't what should i do?) > > > > Try > > > > python3 -V > > > > The default is probably still Python2 but that does not mean you > can't use > > Python explicitly. > > If you prefer to have Python 3 only, you could also uninstall Python > 2.7.1. > You do not say what version of what distro you are using, nor what > method you > used to install Python 2, so I can't be more explicit. You might need to ensure that you have at least 1 version of Python2 around because a lot of Linux tools are still written in v2 and might break if you uninstall all v2 versions... I'd go with the python3 tip, that's what I use with 2 versions of Python... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 16 10:10:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Aug 2011 09:10:13 +0100 Subject: [Tutor] help in TKINTER In-Reply-To: References: Message-ID: On 16/08/11 05:31, aditya wrote: > Hello tutors, > > I wanted some help in using the Tkinter class for button creation, I am > not able to add on click events i.e. when I press the button certain > action should be performed for example if I press the button named 5, > then it should display 5 in the text field . The default behaviour for a button is to do nothing. If you want it to do something you will need to assign a command action, usually a function or method name. But without seeing your code (or at least short sample code) we can't begin to guess what you might be doing wrong... If you look at the GUI programming topic in my tutorial you will see various short programs including some adding a button and an associated action. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Tue Aug 16 10:21:45 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Aug 2011 10:21:45 +0200 Subject: [Tutor] directory within directory References: Message-ID: questions anon wrote: > I would like to open up a bunch of files within a folder within a folder > and then process them and output them in another location but with the > same folder structure. I seem to having trouble with the folder within > folder section. > I have a separate folder for each year and then within a year I have a > separate folder for each month but when I try to make a directory in a new > location it does not place the month folders within the year folders, > instead they are all places in the outputpath together > any help will be greatly appreciated > > import os > > inputpath=r'E:/temp_samples2/' > outputpath=r'E:/figureoutputs/' > > for (path, dirs, files) in os.walk(inputpath): > for dir in dirs: > print path, dir > newfolders=outputpath+dir Using string concatenation to produce file paths is errorprone. Have a look at the path manipulation functions that the os.path module has to offer. > if not os.path.exists(newfolders): > os.makedirs(newfolders) > print newfolders dir is just the directory name. You get the source directory with sourcepath = os.path.join(path, dir) Now you have to remove the start of the path with relativepath = os.path.relpath(sourcepath, inputpath) Finally add the outputpath: newdir = os.path.join(outputpath, relativepath) From lisi.reisz at gmail.com Tue Aug 16 11:14:07 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 16 Aug 2011 10:14:07 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: <201108160752.49727.lisi.reisz@gmail.com> Message-ID: <201108161014.07487.lisi.reisz@gmail.com> On Tuesday 16 August 2011 09:05:44 Alan Gauld wrote: > You might need to ensure that you have at least 1 version of Python2 around > because a lot of Linux tools are still written in v2 and might break if you > uninstall all v2 versions... Thanks for that, Alan. I knew that I had Python 2 by default and did not have to install it, but had not queried why. I clearly should have. I should also, of course, check whether something is a dependancy of something else before suggesting its removal. :-( Luckily, if he used a package manager of any kind, it would have warned him that it is a dependancy of various packages. If it was already on the system , I wonder why the OP needed to install it? Lisi From timomlists at gmail.com Tue Aug 16 15:10:53 2011 From: timomlists at gmail.com (Timo) Date: Tue, 16 Aug 2011 15:10:53 +0200 Subject: [Tutor] Adding index numbers to tuple Message-ID: Hello, Maybe a bit confusing topic title, probably the example will do. I have a tuple: t = ('a', 'b', 'c', 'd') And need the following output, list or tuple, doesn't matter: (0, 'a', 1, 'b', 2, 'c', 3, 'd') I tried with zip(), but get a list of tuples, which isn't the desired output. Anyone with a solution or push in the right direction? Cheers, TImo -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Tue Aug 16 15:17:12 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 16 Aug 2011 15:17:12 +0200 Subject: [Tutor] Adding index numbers to tuple In-Reply-To: References: Message-ID: Hello, : Maybe a bit confusing topic title, probably the example will do. : : I have a tuple: : t = ('a', 'b', 'c', 'd') : And need the following output, list or tuple, doesn't matter: : (0, 'a', 1, 'b', 2, 'c', 3, 'd') : : I tried with zip(), but get a list of tuples, which isn't the desired : output. Anyone with a solution or push in the right direction? Perhaps you did not know about enumerate? t = ('a', 'b', 'c', 'd') l = list() for x in enumerate(t): l.extend(x) -Martin -- Martin A. Brown http://linux-ip.net/ From cwitts at compuscan.co.za Tue Aug 16 15:42:30 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 16 Aug 2011 15:42:30 +0200 Subject: [Tutor] Adding index numbers to tuple In-Reply-To: References: Message-ID: <4E4A73C6.4040508@compuscan.co.za> On 2011/08/16 03:10 PM, Timo wrote: > Hello, > Maybe a bit confusing topic title, probably the example will do. > > I have a tuple: > t = ('a', 'b', 'c', 'd') > And need the following output, list or tuple, doesn't matter: > (0, 'a', 1, 'b', 2, 'c', 3, 'd') > > I tried with zip(), but get a list of tuples, which isn't the desired > output. Anyone with a solution or push in the right direction? > > Cheers, > TImo > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor >>> t = ('a', 'b', 'c', 'd') >>> new_t = zip(xrange(len(t)), t) >>> new_t [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] >>> from itertools import chain >>> list(chain.from_iterable(new_t)) [0, 'a', 1, 'b', 2, 'c', 3, 'd'] That would be for if you were using the zip way, but enumerate should be simpler as Martin pointed out. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 16 18:06:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Aug 2011 17:06:42 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: <201108161014.07487.lisi.reisz@gmail.com> References: <201108160752.49727.lisi.reisz@gmail.com> <201108161014.07487.lisi.reisz@gmail.com> Message-ID: On 16/08/11 10:14, Lisi wrote: > On Tuesday 16 August 2011 09:05:44 Alan Gauld wrote: > > You might need to ensure that you have at least 1 version of Python2 > around > > because a lot of Linux tools are still written in v2 and might break > if you > > uninstall all v2 versions... > > Thanks for that, Alan. I knew that I had Python 2 by default and did > not have > to install it, but had not queried why. It can be hard to tell, sometimes distro designers just think something is useful. For example many Linux users nowadays have no use for gcc but it is usually packaged anyway. > If it was already on the system , I wonder why the OP needed to > install it? I suspect that the default was probably version 2.5 or 2.6 (My Ubuntu 10.04 has 2.6) So if OP installed 2.7 it would be additional. My concern was that if they uninstalled 2.7 the default would revert to 2.6 (or whatever) and they might then be tempted to uninstall that too! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Tue Aug 16 18:10:15 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 16 Aug 2011 18:10:15 +0200 Subject: [Tutor] Adding index numbers to tuple In-Reply-To: <4E4A73C6.4040508@compuscan.co.za> References: <4E4A73C6.4040508@compuscan.co.za> Message-ID: On Tue, Aug 16, 2011 at 3:42 PM, Christian Witts wrote: > On 2011/08/16 03:10 PM, Timo wrote: > > Hello, > Maybe a bit confusing topic title, probably the example will do. > > I have a tuple: > t = ('a', 'b', 'c', 'd') > And need the following output, list or tuple, doesn't matter: > (0, 'a', 1, 'b', 2, 'c', 3, 'd') > > I tried with zip(), but get a list of tuples, which isn't the desired > output. Anyone with a solution or push in the right direction? > > Cheers, > TImo > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > >>>> t = ('a', 'b', 'c', 'd') >>>> new_t = zip(xrange(len(t)), t) >>>> new_t > [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] >>>> from itertools import chain >>>> list(chain.from_iterable(new_t)) > [0, 'a', 1, 'b', 2, 'c', 3, 'd'] > > That would be for if you were using the zip way, but enumerate should be > simpler as Martin pointed out. > You can sort of mix the two together: >>> from itertools import chain >>> t = ('a', 'b', 'c', 'd') >>> list(chain.from_iterable(enumerate(t))) [0, 'a', 1, 'b', 2, 'c', 3, 'd'] >>> From jeffp at swva.net Tue Aug 16 18:44:41 2011 From: jeffp at swva.net (Jeff Peters) Date: Tue, 16 Aug 2011 12:44:41 -0400 Subject: [Tutor] Passing functions(with parameters) as paramiters to (looping)functions. Message-ID: <4E4A9E79.5090207@swva.net> Hi; I am trying to run a function inside a continuing loop, but do not seem to be able to pass any parameters (arguments ) when I do so. I have placed working and non-working code , with output below. ## This works: def loop(fn ): for i in range(5): fn( ) def this_function(a=" i am not a string"): print( a ) loop(this_function) ## with output: >>> i am not a string i am not a string i am not a string i am not a string i am not a string >>> ## But , this does not : def loop(fn ): for i in range(5): fn( ) def this_function(a=" i am not a string"): print( a ) loop(this_function("I am a string") ) ## note the only change is here ## With this as output: >>> I am a string Traceback (most recent call last): File "/home/jeff/MyPythonStuff/call_sub.py", line 9, in loop(this_function("I am a string") ) File "/home/jeff/MyPythonStuff/call_sub.py", line 4, in loop fn( ) TypeError: 'NoneType' object is not callable >>> My OS is Debian 64 bit I get the same output for both python2.7 and Python3.1 I think this should be do-able but I am in need of a clue. Thanks. From gtirloni at sysdroid.com Tue Aug 16 19:15:53 2011 From: gtirloni at sysdroid.com (Giovanni Tirloni) Date: Tue, 16 Aug 2011 14:15:53 -0300 Subject: [Tutor] Passing functions(with parameters) as paramiters to (looping)functions. In-Reply-To: <4E4A9E79.5090207@swva.net> References: <4E4A9E79.5090207@swva.net> Message-ID: On Tue, Aug 16, 2011 at 1:44 PM, Jeff Peters wrote: > Hi; > > I am trying to run a function inside a continuing loop, but do not seem to > be able to pass any parameters (arguments ) when I do so. > I have placed working and non-working code , with output below. > > ## This works: > > def loop(fn ): > for i in range(5): > fn( ) > > def this_function(a=" i am not a string"): > print( a ) > > loop(this_function) > > ## with output: > >>> > i am not a string > i am not a string > i am not a string > i am not a string > i am not a string > >>> > > ## But , this does not : > > def loop(fn ): > for i in range(5): > fn( ) > > def this_function(a=" i am not a string"): > print( a ) > > loop(this_function("I am a string") ) ## note the only change is here > > ## With this as output: > > >>> > I am a string > Traceback (most recent call last): > File "/home/jeff/MyPythonStuff/**call_sub.py", line 9, in > loop(this_function("I am a string") ) > File "/home/jeff/MyPythonStuff/**call_sub.py", line 4, in loop > fn( ) > TypeError: 'NoneType' object is not callable > >>> > Your loop() function expects the parameter 'fn' to be a function that it can then call. In your second example, it doesn't work because you already called the function and is passing as parameter 'fn' whatever this_function() returned. >>> type(this_function) >>> type(this_function("I am a string")) I am a string If you really want this design, one way to "fix" it is to change loop() to accept another argument that is going to be passed to the function. def loop(fn, b): for i in range(5): fn(b) Perhaps if you explain what you are trying to accomplish, someone can suggest a better way to design the code. -- Giovanni Tirloni sysdroid.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 16 19:46:20 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Aug 2011 19:46:20 +0200 Subject: [Tutor] Passing functions(with parameters) as paramiters to (looping)functions. References: <4E4A9E79.5090207@swva.net> Message-ID: Jeff Peters wrote: > Hi; > > I am trying to run a function inside a continuing loop, but do not seem > to be able to pass any parameters (arguments ) when I do so. > I have placed working and non-working code , with output below. > > ## This works: > > def loop(fn ): > for i in range(5): > fn( ) > > def this_function(a=" i am not a string"): > print( a ) > > loop(this_function) > > ## with output: > >>> > i am not a string > i am not a string > i am not a string > i am not a string > i am not a string > >>> > > ## But , this does not : > > def loop(fn ): > for i in range(5): > fn( ) > > def this_function(a=" i am not a string"): > print( a ) > > loop(this_function("I am a string") ) ## note the only change is here You are calling this_function() and then pass the result of the function call to your other function loop(). Instead you need another function that builds a function that calls this_function() with the desired argument: >>> def loop(f): ... for i in range(5): ... f() ... >>> def this_function(a): ... print(a) ... >>> def make_function(f, arg): ... def g(): ... f(arg) ... return g ... >>> loop(make_function(this_function, "foo")) foo foo foo foo foo >>> loop(make_function(this_function, "bar")) bar bar bar bar bar >>> Of course you could also change loop() to pass on arbitrary arguments: >>> def loop(f, *args, **kw): ... for i in range(3): ... f(*args, **kw) ... >>> loop(print, 1, 2) 1 2 1 2 1 2 >>> loop(print, 1, 2, sep="<-->") 1<-->2 1<-->2 1<-->2 Because building a function that just calls another function with some predefined arguments is a common need the standard library has functools.partial(): >>> from functools import partial >>> print42 = partial(print, 42) >>> print42() 42 >>> loop(print42) 42 42 42 Another variant is a lambda function with a default argument: >>> loop(lambda a="whatever": print(a)) whatever whatever whatever From ramit.prasad at jpmorgan.com Tue Aug 16 19:26:56 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 16 Aug 2011 13:26:56 -0400 Subject: [Tutor] Passing functions(with parameters) as paramiters to (looping)functions. In-Reply-To: <4E4A9E79.5090207@swva.net> References: <4E4A9E79.5090207@swva.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7A5EB8F@EMARC112VS01.exchad.jpmchase.net> >def loop(fn ): > for i in range(5): > fn( ) > >def this_function(a=" i am not a string"): > print( a ) > >loop(this_function("I am a string") ) ## note the only change is here > >## With this as output: > > >>> >I am a string >Traceback (most recent call last): > File "/home/jeff/MyPythonStuff/call_sub.py", line 9, in > loop(this_function("I am a string") ) > File "/home/jeff/MyPythonStuff/call_sub.py", line 4, in loop > fn( ) >TypeError: 'NoneType' object is not callable > >>> NOTE: All code is untested. You get a NoneType because this_function returns a None. What is happening is the this_function("xxx") gets called first and then that return value gets passed into loop as 'loop(None)'. I am not sure exactly what you are trying to do, but I would probably do something like passing in a list of arguments. loop(this_function, iterable_of_arguments) def loop(fn, args): for arg in args : fn( arg ) The way I would get an argument gets passed to this_function is really dependent on your goal. You may want to look at itertools / map libraries as well for more options. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From jeremy.clark at ucr.edu Tue Aug 16 19:59:05 2011 From: jeremy.clark at ucr.edu (Jeremy G Clark) Date: Tue, 16 Aug 2011 17:59:05 +0000 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: <201108160752.49727.lisi.reisz@gmail.com> <201108161014.07487.lisi.reisz@gmail.com> Message-ID: <343C0CEA73D3804F91FC1E9FCEC11D4916A6A58C@EXCH-MBOX-1.exch.ucr.edu> @ Connor -- you probably should heed the advice of Alan and leave your existing Python 2.x install alone. For the exercises in your book, you should be able to include this line at the top of every script and it'll work just fine. I can't remember, you may need to chmod +x in order for this to work. Anyone? #! /usr/bin/python3 Or, use python3 to open the script from the command line: connor at linuxbox# python3 script.py This is how I test on my Ubuntu install. -----Original Message----- From: tutor-bounces+jeremy.clark=ucr.edu at python.org [mailto:tutor-bounces+jeremy.clark=ucr.edu at python.org] On Behalf Of Alan Gauld Sent: Tuesday, August 16, 2011 9:07 AM To: tutor at python.org Subject: Re: [Tutor] which version do i have and how do i change it On 16/08/11 10:14, Lisi wrote: > On Tuesday 16 August 2011 09:05:44 Alan Gauld wrote: > > You might need to ensure that you have at least 1 version of Python2 > around > > because a lot of Linux tools are still written in v2 and might break > if you > > uninstall all v2 versions... > > Thanks for that, Alan. I knew that I had Python 2 by default and did > not have to install it, but had not queried why. It can be hard to tell, sometimes distro designers just think something is useful. For example many Linux users nowadays have no use for gcc but it is usually packaged anyway. > If it was already on the system , I wonder why the OP needed to > install it? I suspect that the default was probably version 2.5 or 2.6 (My Ubuntu 10.04 has 2.6) So if OP installed 2.7 it would be additional. My concern was that if they uninstalled 2.7 the default would revert to 2.6 (or whatever) and they might then be tempted to uninstall that too! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From jeffp at swva.net Tue Aug 16 20:09:56 2011 From: jeffp at swva.net (Jeff Peters) Date: Tue, 16 Aug 2011 14:09:56 -0400 Subject: [Tutor] Passing functions(with parameters) as paramiters to (looping)functions. In-Reply-To: References: <4E4A9E79.5090207@swva.net> Message-ID: <4E4AB274.6090800@swva.net> On 08/16/2011 01:46 PM, Peter Otten wrote: > Jeff Peters wrote: > >> Hi; >> >> I am trying to run a function inside a continuing loop, but do not seem >> to be able to pass any parameters (arguments ) when I do so. >> I have placed working and non-working code , with output below. >> >> ## This works: >> >> def loop(fn ): >> for i in range(5): >> fn( ) >> >> def this_function(a=" i am not a string"): >> print( a ) >> >> loop(this_function) >> >> ## with output: >> >>> >> i am not a string >> i am not a string >> i am not a string >> i am not a string >> i am not a string >> >>> >> >> ## But , this does not : >> >> def loop(fn ): >> for i in range(5): >> fn( ) >> >> def this_function(a=" i am not a string"): >> print( a ) >> >> loop(this_function("I am a string") ) ## note the only change is here > You are calling this_function() and then pass the result of the function > call to your other function loop(). > > Instead you need another function that builds a function that calls > this_function() with the desired argument: > >>>> def loop(f): > ... for i in range(5): > ... f() > ... >>>> def this_function(a): > ... print(a) > ... >>>> def make_function(f, arg): > ... def g(): > ... f(arg) > ... return g > ... >>>> loop(make_function(this_function, "foo")) > foo > foo > foo > foo > foo >>>> loop(make_function(this_function, "bar")) > bar > bar > bar > bar > bar > Of course you could also change loop() to pass on arbitrary arguments: > >>>> def loop(f, *args, **kw): > ... for i in range(3): > ... f(*args, **kw) > ... >>>> loop(print, 1, 2) > 1 2 > 1 2 > 1 2 >>>> loop(print, 1, 2, sep="<-->") > 1<-->2 > 1<-->2 > 1<-->2 > > Because building a function that just calls another function with some > predefined arguments is a common need the standard library has > functools.partial(): > >>>> from functools import partial >>>> print42 = partial(print, 42) >>>> print42() > 42 >>>> loop(print42) > 42 > 42 > 42 > > Another variant is a lambda function with a default argument: > >>>> loop(lambda a="whatever": print(a)) > whatever > whatever > whatever > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks, that is what I needed. not splitting the function name and argument list was my problem. and the function creator idea really appeals thanks again - jeff From ramit.prasad at jpmorgan.com Tue Aug 16 20:23:38 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 16 Aug 2011 14:23:38 -0400 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: <343C0CEA73D3804F91FC1E9FCEC11D4916A6A58C@EXCH-MBOX-1.exch.ucr.edu> References: <201108160752.49727.lisi.reisz@gmail.com> <201108161014.07487.lisi.reisz@gmail.com> <343C0CEA73D3804F91FC1E9FCEC11D4916A6A58C@EXCH-MBOX-1.exch.ucr.edu> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7AF62CF@EMARC112VS01.exchad.jpmchase.net> > I can't remember, you may need to chmod +x in order for this to work. Anyone? You need to chmod if you want to call the script via shebang (./script.py). If you are calling it by doing 'python3 script.py' then you do not need it as python3 should already be executable. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Jeremy G Clark Sent: Tuesday, August 16, 2011 12:59 PM To: tutor at python.org Subject: Re: [Tutor] which version do i have and how do i change it @ Connor -- you probably should heed the advice of Alan and leave your existing Python 2.x install alone. For the exercises in your book, you should be able to include this line at the top of every script and it'll work just fine. I can't remember, you may need to chmod +x in order for this to work. Anyone? #! /usr/bin/python3 Or, use python3 to open the script from the command line: connor at linuxbox# python3 script.py This is how I test on my Ubuntu install. -----Original Message----- From: tutor-bounces+jeremy.clark=ucr.edu at python.org [mailto:tutor-bounces+jeremy.clark=ucr.edu at python.org] On Behalf Of Alan Gauld Sent: Tuesday, August 16, 2011 9:07 AM To: tutor at python.org Subject: Re: [Tutor] which version do i have and how do i change it On 16/08/11 10:14, Lisi wrote: > On Tuesday 16 August 2011 09:05:44 Alan Gauld wrote: > > You might need to ensure that you have at least 1 version of Python2 > around > > because a lot of Linux tools are still written in v2 and might break > if you > > uninstall all v2 versions... > > Thanks for that, Alan. I knew that I had Python 2 by default and did > not have to install it, but had not queried why. It can be hard to tell, sometimes distro designers just think something is useful. For example many Linux users nowadays have no use for gcc but it is usually packaged anyway. > If it was already on the system , I wonder why the OP needed to > install it? I suspect that the default was probably version 2.5 or 2.6 (My Ubuntu 10.04 has 2.6) So if OP installed 2.7 it would be additional. My concern was that if they uninstalled 2.7 the default would revert to 2.6 (or whatever) and they might then be tempted to uninstall that too! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From jeremy.clark at ucr.edu Tue Aug 16 20:27:32 2011 From: jeremy.clark at ucr.edu (Jeremy G Clark) Date: Tue, 16 Aug 2011 18:27:32 +0000 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7AF62CF@EMARC112VS01.exchad.jpmchase.net> References: <201108160752.49727.lisi.reisz@gmail.com> <201108161014.07487.lisi.reisz@gmail.com> <343C0CEA73D3804F91FC1E9FCEC11D4916A6A58C@EXCH-MBOX-1.exch.ucr.edu> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7AF62CF@EMARC112VS01.exchad.jpmchase.net> Message-ID: <343C0CEA73D3804F91FC1E9FCEC11D4916A6A610@EXCH-MBOX-1.exch.ucr.edu> Yes, that's what I was trying to say. Thanks for translating! :) -----Original Message----- From: Prasad, Ramit [mailto:ramit.prasad at jpmorgan.com] Sent: Tuesday, August 16, 2011 11:24 AM To: Jeremy G Clark; tutor at python.org Subject: RE: [Tutor] which version do i have and how do i change it > I can't remember, you may need to chmod +x in order for this to work. Anyone? You need to chmod if you want to call the script via shebang (./script.py). If you are calling it by doing 'python3 script.py' then you do not need it as python3 should already be executable. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Jeremy G Clark Sent: Tuesday, August 16, 2011 12:59 PM To: tutor at python.org Subject: Re: [Tutor] which version do i have and how do i change it @ Connor -- you probably should heed the advice of Alan and leave your existing Python 2.x install alone. For the exercises in your book, you should be able to include this line at the top of every script and it'll work just fine. I can't remember, you may need to chmod +x in order for this to work. Anyone? #! /usr/bin/python3 Or, use python3 to open the script from the command line: connor at linuxbox# python3 script.py This is how I test on my Ubuntu install. -----Original Message----- From: tutor-bounces+jeremy.clark=ucr.edu at python.org [mailto:tutor-bounces+jeremy.clark=ucr.edu at python.org] On Behalf Of Alan Gauld Sent: Tuesday, August 16, 2011 9:07 AM To: tutor at python.org Subject: Re: [Tutor] which version do i have and how do i change it On 16/08/11 10:14, Lisi wrote: > On Tuesday 16 August 2011 09:05:44 Alan Gauld wrote: > > You might need to ensure that you have at least 1 version of Python2 > around > > because a lot of Linux tools are still written in v2 and might break > if you > > uninstall all v2 versions... > > Thanks for that, Alan. I knew that I had Python 2 by default and did > not have to install it, but had not queried why. It can be hard to tell, sometimes distro designers just think something is useful. For example many Linux users nowadays have no use for gcc but it is usually packaged anyway. > If it was already on the system , I wonder why the OP needed to > install it? I suspect that the default was probably version 2.5 or 2.6 (My Ubuntu 10.04 has 2.6) So if OP installed 2.7 it would be additional. My concern was that if they uninstalled 2.7 the default would revert to 2.6 (or whatever) and they might then be tempted to uninstall that too! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From susana.delgado_s at utzmg.edu.mx Tue Aug 16 20:46:39 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 16 Aug 2011 13:46:39 -0500 Subject: [Tutor] Message: pygobject_register_sinkfunc is deprecated (GtkWindow) Message-ID: Hello List! I just started to use PyGTK and Glade to create graphical interfaces, my python interpreter version is 2.6.6; I also install the GTK2 Runtime enviroment and Glade 3.6.6. I also installed in my computer pycairo-1.8.10.win32-py2.6.exe, pygobject-2.26.0-1.win32-py2.6.exe and pygtk-2.16.0+glade.win32-py2.6.exe so my graphic application will look and work fine. I tried to do an example in order to get familiar with this new tool, but when I run the script I got the next message: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import glade1 ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow) ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible) ** Message: pygobject_register_sinkfunc is deprecated (GtkObject) >>> My code is: import pygtk pygtk.require("2.0") import gtk import gtk.glade class MainWin: def __init__(self): self.widgets = gtk.glade.XML("ejemplo_glade.glade") signals = { "on_entry1_activate" : self.on_button1_clicked, "on_button1_clicked" : self.on_button1_clicked, "gtk_main_quit" : gtk.main_quit } self.widgets.signal_autoconnect(signals) self.label1 = self.widgets.get_widget("label1") self.entry1 = self.widgets.get_widget("entry1") def on_button1_clicked(self, widget): texto = self.entry1.get_text() self.label1.set_text("Hola %s" % texto) if __name__ == "__main__": MainWin() gtk.main() Does my python libraries are the correct ones for my interpreter? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Tue Aug 16 22:35:55 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 16 Aug 2011 21:35:55 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: <201108161014.07487.lisi.reisz@gmail.com> Message-ID: <201108162135.55428.lisi.reisz@gmail.com> On Tuesday 16 August 2011 17:06:42 Alan Gauld wrote: > It can be hard to tell, sometimes distro designers just think something > is useful. lisi at Tux:~$ aptitude why python i reportbug Depends python (>= 2.5) lisi at Tux:~$ !! Lisi From lisi.reisz at gmail.com Tue Aug 16 22:37:39 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 16 Aug 2011 21:37:39 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: <201108161014.07487.lisi.reisz@gmail.com> Message-ID: <201108162137.39936.lisi.reisz@gmail.com> On Tuesday 16 August 2011 17:06:42 Alan Gauld wrote: > My concern was that if they uninstalled 2.7 the default would revert to > 2.6 (or > whatever) and they might then be tempted to uninstall that too! Yes - mea culpa for not realising that. Mind you, if I had investigated my own system I would hardly have come to the conclusion that Python was essential. Lisi From malaclypse2 at gmail.com Tue Aug 16 22:53:46 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 16 Aug 2011 16:53:46 -0400 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: <201108162135.55428.lisi.reisz@gmail.com> References: <201108161014.07487.lisi.reisz@gmail.com> <201108162135.55428.lisi.reisz@gmail.com> Message-ID: On Tue, Aug 16, 2011 at 4:35 PM, Lisi wrote: > lisi at Tux:~$ aptitude why python > i ? reportbug Depends python (>= 2.5) > lisi at Tux:~$ Keep in mind that that command only shows you a single dependency chain. Try again with "aptitude -v why python" to see all of the dependencies. On my ubuntu 11.04 machine, that command produces over 9000 lines of output, and over 800 distinct packages that depend on python in one way or another. -- Jerry From lisi.reisz at gmail.com Tue Aug 16 23:23:03 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 16 Aug 2011 22:23:03 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: <201108162135.55428.lisi.reisz@gmail.com> Message-ID: <201108162223.03149.lisi.reisz@gmail.com> On Tuesday 16 August 2011 21:53:46 Jerry Hill wrote: > On Tue, Aug 16, 2011 at 4:35 PM, Lisi wrote: > > lisi at Tux:~$ aptitude why python > > i ? reportbug Depends python (>= 2.5) > > lisi at Tux:~$ > > Keep in mind that that command only shows you a single dependency > chain. ?Try again with "aptitude -v why python" to see all of the > dependencies. ?On my ubuntu 11.04 machine, that command produces over > 9000 lines of output, and over 800 distinct packages that depend on > python in one way or another. Thanks for that. Very illuminating and interesting. I hadn't come across that command before. (I tend to look things up in man aptitude rather than read it through.) But in my case it only served to illustrate that nothing of any real importance in my system depends on Python. In fact, not only were there no direct dependency chains leading to Python, since all of them had at least 2 "suggests" in the chain, the few things that did depend on Python, at the end of the chain, after the suggests, were mostly not installed, so would not have missed Python. Lisi From questions.anon at gmail.com Wed Aug 17 00:46:44 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 17 Aug 2011 08:46:44 +1000 Subject: [Tutor] directory within directory In-Reply-To: References: Message-ID: Thank you, that does create the directories in the new place but when I process the data it does not put the outputs in the correct directory they all end up in the last directory created. Below is the code of what I am trying to do. Any feedback will be greatly appreciated. from netCDF4 import Dataset import numpy as N import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os inputpath=r'E:/temp_samples2/' outputpath=r'E:/figureoutputs/' for (path, dirs, files) in os.walk(inputpath): for dir in dirs: print dir sourcepath=os.path.join(path,dir) relativepath=os.path.relpath(sourcepath,inputpath) newdir=os.path.join(outputpath,relativepath) if not os.path.exists(newdir): os.makedirs(newdir) for ncfile in files: if ncfile[-3:]=='.nc': ncfile=os.path.join(sourcepath,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TSFC=ncfile.variables['T_SFC'][:,:,:] LAT=ncfile.variables['latitude'][:] LON=ncfile.variables['longitude'][:] TIME=ncfile.variables['time'][:] fillvalue=ncfile.variables['T_SFC']._FillValue TSFC=MA.masked_values(TSFC, fillvalue) ncfile.close() for TSFC, TIME in zip((TSFC[4::24]),(TIME[4::24])): print TSFC, TIME #convert time from numbers to date and prepare it to have no symbols for saving to filename cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') print date_string #Set up basemap using mercator projection map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') # compute map projection coordinates for lat/lon grid. x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.drawstates() plt.title('Surface temperature at %s UTC'%ncfiletime) ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) #save map as *.png and plot netcdf file plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) On Tue, Aug 16, 2011 at 6:21 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > I would like to open up a bunch of files within a folder within a folder > > and then process them and output them in another location but with the > > same folder structure. I seem to having trouble with the folder within > > folder section. > > I have a separate folder for each year and then within a year I have a > > separate folder for each month but when I try to make a directory in a > new > > location it does not place the month folders within the year folders, > > instead they are all places in the outputpath together > > any help will be greatly appreciated > > > > import os > > > > inputpath=r'E:/temp_samples2/' > > outputpath=r'E:/figureoutputs/' > > > > for (path, dirs, files) in os.walk(inputpath): > > for dir in dirs: > > print path, dir > > newfolders=outputpath+dir > > Using string concatenation to produce file paths is errorprone. > Have a look at the path manipulation functions that the os.path module has > to offer. > > > if not os.path.exists(newfolders): > > os.makedirs(newfolders) > > print newfolders > > dir is just the directory name. You get the source directory with > > sourcepath = os.path.join(path, dir) > > Now you have to remove the start of the path with > > relativepath = os.path.relpath(sourcepath, inputpath) > > Finally add the outputpath: > > newdir = os.path.join(outputpath, relativepath) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Aug 17 00:57:17 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 17 Aug 2011 08:57:17 +1000 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: Message-ID: <4E4AF5CD.8020104@pearwood.info> Connor Merritt wrote: > So i installed python 2.7.1 on my linux and i bought a book that requires > python 3 so installed python 3, and i used terminal and typed in python -V > and it said 2.7.1 how do i get it to be 3 (i tried deleting it but i > couldn't what should i do?) At the terminal, type python3 instead of python. -- Steven From questions.anon at gmail.com Wed Aug 17 01:04:05 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 17 Aug 2011 09:04:05 +1000 Subject: [Tutor] numpy.mean across multiple netcdf files In-Reply-To: <82B2C27D-5A95-435B-B488-C7D34A32C6E9@gmail.com> References: <82B2C27D-5A95-435B-B488-C7D34A32C6E9@gmail.com> Message-ID: Thanks Andre I had a go at following your advice but it didn't seem to work (it kept focusing on the last loop and not combining them all together) so I have posted a note on scipy user group instead (code below). Also thanks for the advice regarding averaging! from netCDF4 import Dataset import matplotlib.pyplot as plt import numpy as N from mpl_toolkits.basemap import Basemap import os MainFolder=r"E:/temp_samples/" for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir for ncfile in files: if ncfile[-3:]=='.nc': ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TSFC=ncfile.variables['T_SFC'][4::24] LAT=ncfile.variables['latitude'][:] LON=ncfile.variables['longitude'][:] TIME=ncfile.variables['time'][:] fillvalue=ncfile.variables['T_SFC']._FillValue ncfile.close() #calculate summary stats big_array=[] for i in TSFC: big_array.append(i) big_array=N.array(big_array) Mean=N.mean(big_array, axis=0) #plot output summary stats map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') map.drawcoastlines() map.drawstates() x,y=map(*N.meshgrid(LON,LAT)) plt.title('Total Mean at 3pm') ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] CS = map.contourf(x,y,Mean,ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h]) plt.colorbar(CS,cax=cax, drawedges=True) plt.show() On Thu, Aug 11, 2011 at 4:48 PM, Andre' Walker-Loud wrote: > Hello Anonymous Questioner, > > First - you will probably be told this isn't the correct email list for > this question - this is a general python tutorial list, while your question > is numpy specific, so if this doesn't help, you should probably look to > another email list. > > There are a couple general comments to make regarding your question. > Basically, you want to load all the data into one big numpy array. > Currently, it seems your data array has 3 indices, from this line > > > TSFC=ncfile.variables['T_SFC'][4::24,:,:] > > you can make a larger array with one more index, where the new index runs > over files. So instead of looping over the files as you do, you can use the > loop to build the larger array. > > I am sure there is a more elegant way to do this, but here is something > that is along the lines of what you want > > > big_array = [] > > for ncfile in files: > > big_array.append(ncfile.variables['T_SFC'][4::24,:,:]) > > if all of your data you are taking from each file is the same size for all > the files, then you can declare the whole thing an array > > > big_array = N.array(big_array) > > and then you can take averages very easily by specifying which index, or > indices you want to average over. If life is not so kind, and your files > are of different sizes, then you have to be more careful. But to give a > precise answer to your problem would require knowledge of what your data > files actually look like. > > > Also, a bit of caution with averaging (in case you are unfamiliar). Say > you have 5 data sets, and each one has a different amount of data in it. If > you first take the average of each set, you can not simply take the average > of those sets to produce the global average. You have to weight each set by > the amount of data you averaged. Say the length of the sets are > [N0,N1,N2,N3,N4] with average values [a0,a1,a2,a3,a4], then to produce the > global average, you need to take > > avg = (1 / (N0+N1+N2+N3+N4) ) * (N0*a0 + N1*a1 + N2*a2 + N3*a3 + N4*a4) > > a few lines of algebra can demonstrate this produces the average you would > get by combining all the data in all the sets and taking one big average. > > > Regards, > > Andre > > > > On Aug 10, 2011, at 6:57 PM, questions anon wrote: > > > I have many ncfiles each containing one month of hourly temperature data. > > I have worked out how to loop through a number of ncfiles and calculate > the mean for each file at a particular time and even plot this and output as > a *.png. > > What I am unsure of is how to calculate the mean at a particular time for > all files. > > Do I somehow output the mean for each folder and then calculate the mean > of all the means? Or is there some way to loop through and calculate it > directly? > > Below is the code I have working that calculates the mean for each file. > Any help will be greatly appreciated!! > > > > from netCDF4 import Dataset > > import numpy as N > > > > MainFolder=r"D:/temp_samples/" > > print MainFolder > > for (path, dirs, files) in os.walk(MainFolder): > > for dir in dirs: > > print dir > > path=path+'/' > > > > for ncfile in files: > > if ncfile[-3:]=='.nc': > > print "dealing with ncfiles:", ncfile > > ncfile=os.path.join(path,ncfile) > > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > > TSFC=ncfile.variables['T_SFC'][4::24,:,:] #this chooses a > particular time for each day for the whole month > > LAT=ncfile.variables['latitude'][:] > > LON=ncfile.variables['longitude'][:] > > TIME=ncfile.variables['time'][:] > > fillvalue=ncfile.variables['T_SFC']._FillValue > > ncfile.close() > > > > #calculate summary stats > > TSFCmean=N.mean(TSFC, axis=0) > > print "The TSFCmean array is:", TSFCmean > > > > # there is a lot more code that follows this to plot the mean for each > ncfile but I have cut that out as I think it is irrelevant to my question > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 17 01:42:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Aug 2011 00:42:42 +0100 Subject: [Tutor] which version do i have and how do i change it In-Reply-To: References: <201108161014.07487.lisi.reisz@gmail.com> <201108162135.55428.lisi.reisz@gmail.com> Message-ID: On 16/08/11 21:53, Jerry Hill wrote: > ... Try again with "aptitude -v why python" to see all of the > dependencies. On my ubuntu 11.04 machine, that command produces over > 9000 lines of output, And on my 10.04 LTS PC it gives too many lines to scroll back to the top (actually 1645 , I just checked :-) And interestingly dependencies include gimp, gedit and scribus, all things I use regularly. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From thisisonlyatest at gmx.com Wed Aug 17 04:15:13 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Tue, 16 Aug 2011 22:15:13 -0400 Subject: [Tutor] Tkinter: no module named messagebox In-Reply-To: References: <4E46D9C8.1060501@gmx.com> <4E4743A4.2030804@gmx.com> Message-ID: <4E4B2431.6080504@gmx.com> On 08/14/2011 02:29 AM, Peter Otten wrote: > brandon w wrote: > > >> On 08/13/2011 04:49 PM, Peter Otten wrote: >> > >>>> How do I find the modules in Tkinter? >>>> >>>> >>> The simplest approach is probably to explore your file system: >>> >>> Step 1: where's Tkinter? >>> >>> $ python -c 'import Tkinter, os; print os.path.dirname(Tkinter.__file__)' >>> /usr/lib/python2.6/lib-tk >>> > >> I have tried # 1. with another command but all I get is an error messages. >> >> $ python -c 'import time, os; print os.path.dirname(time.__doc__)' # >> This one gave no output. >> > You typed time.__doc__ instead of time.__file__. With the latter you'd get > an AttributeError because the time module is implemented in C. > > >> $ python -c 'import time, strftime, os; print >> os.path.dirname(strftime.__doc__)' >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: No module named strftime >> > Well you cannot import a module that doesn't exist... > > >> $ python -c 'import os; from time import strftime; print >> os.path.dirname(strftime.__file__)' >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'builtin_function_or_method' object has no attribute >> '__file__' >> >> $ python -c 'import time, os; print os.path.dirname(time.__file__)' >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python2.6/posixpath.py", line 119, in dirname >> i = p.rfind('/') + 1 >> AttributeError: 'NoneType' object has no attribute 'rfind' >> >> $ python -c 'import time, os; print os.path.dirname(time.__package__)' >> more errors >> >> I am obviously doing something wrong. >> > The method to find the location of a module that I gave works only for > modules and only for modules implemented in Python. You can find both > functions and modules implemented in Python with inspect.getsourcefile(): > > >>>> from inspect import getsourcefile >>>> import os >>>> getsourcefile(os) # a module >>>> > '/usr/lib/python2.6/os.py' > >>>> getsourcefile(os.path) # another module with an interesting filename >>>> > '/usr/lib/python2.6/posixpath.py' > >>>> getsourcefile(os.walk) # a function implemented in Python >>>> > '/usr/lib/python2.6/os.py' > >>>> getsourcefile(os.mkdir) # a function implemented in C >>>> > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/inspect.py", line 441, in getsourcefile > filename = getfile(object) > File "/usr/lib/python2.6/inspect.py", line 418, in getfile > raise TypeError('arg is not a module, class, method, ' > TypeError: arg is not a module, class, method, function, traceback, frame, > or code object > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thank a lot for your help. I will study what you have shown me. From thisisonlyatest at gmx.com Wed Aug 17 04:19:26 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Tue, 16 Aug 2011 22:19:26 -0400 Subject: [Tutor] Tkinter: no module named messagebox (brandon w) In-Reply-To: References: Message-ID: <4E4B252E.20306@gmx.com> On 08/14/2011 03:10 AM, Robert Sjoblom wrote: >> I have tried to follow the tutorial I found here: >> >> Python 2.7 Tutorial >> http://www.youtube.com/watch?v=uh6AdDX7K7U >> >> This is what I have done so far: >> >> #!/usr/bin/python >> >> from Tkinter import * >> import Tkinter.MessageBox >> > I figured I might as well, given how I recently had to learn about > this, give you a heads up on imports. The format "from module import * > " is not a very good idea: it makes your code harder to read (as the > reader has to inspect each and every barename to check whether it's > actually assigned locally OR comes from the deuced *). To quote the > Zen of Python; "namespaces are a honking great idea -- let's do more > of those!". > > You can import modules with several different syntaxes: > import importable > import importable1, importable2, ..., importableN > import importable as preferred_name > > Here importable is usually a module such as collections, but could be > a package or module in a package, in which case each part is separated > with a dot, for example os.path. The first two syntaxes are the > simplest and also the safest because they avoid the possibility of > having name conflicts, since they force us to always use fully > qualified names. > > The third syntax allows us to give a name of our choice to the package > or module we are importing. Theoretically, this could lead to name > clashes, but in practice the "import importable as" syntax is used to > avoid them. > > There are some other import syntaxes: > from importable import object as preferred_name > from importable import object1, object2, ..., objectN > from importable import (object1, object2, ..., objectN) > from importable import * > > In the last syntax, the * means "import everything that is not > private", which in practical terms means either that every object in > the module is imported except for those whose names begin with a > leading underscore, or, if the module has a global __all__ variable > that holds a list of names, that all the objects in the __all__ > variable are imported. > > The from importable import * syntax imports all the objects from the > module (or all the modules from the package) -- this could be hundreds > of names. In the case of from os.path import *, almost 40 names are > imported, including "dirname", "exists", and "split", any of which > might be names we would prefer to use for our own variables or > functions. > > For example, if we write > from os.path import dirname > we can conveniently call dirname() without qualification. But if > further on in our code we write > dirname = "." > the object reference dirname will now be bound to the string "." > instead of to the dirname() function, so if we try calling dirname() > we will get a TypeError exception because dirname now refers to a > string, and we can't call strings. > > However, given that Tkinter is such a huge package to begin with, I'd > say that you should continue to use from Tkinter import *, but be > aware of what you're doing when you type that, and that there is a > certain risk of conflicts. > > best regards, > Robert S. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > That is some really good information. Thank you for taking time to explain it all to me. From thisisonlyatest at gmx.com Wed Aug 17 04:26:04 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Tue, 16 Aug 2011 22:26:04 -0400 Subject: [Tutor] Tkinter: no module named messagebox (brandon w) In-Reply-To: <4E47E650.6010207@btinternet.com> References: <4E47E650.6010207@btinternet.com> Message-ID: <4E4B26BC.4040809@gmx.com> On 08/14/2011 11:14 AM, Alan Gauld wrote: > On 14/08/11 14:07, Wayne Werner wrote: >> Of course I personally I usually do >> >> import Tkinter as tk >> >> Which means I only have to type 3 extra characters, but it removes any >> ambiguity - tk.Something had to come from Tkinter > > Thats exactly what I tend to do nowadays. > > I used to use the import * method for tkinter but eventually > I got bit by a name clash and it took too long to realize the > problem so I now use the "import as tk" shortcut except for > very short scripts - usually just for tests or experiments.. > Thanks. I just downloaded the pdf from your website. From thisisonlyatest at gmx.com Wed Aug 17 05:05:38 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Tue, 16 Aug 2011 23:05:38 -0400 Subject: [Tutor] Printing in the same place Message-ID: <4E4B3002.90706@gmx.com> I am trying to print in the same place to make a clock in a tkinter window. I will loop the following code to update the time. This seems to work but it is not printing in the same place: #!/usr/bin/python #Python 2.6.6 import time for t in range(5): digits = time.strftime('%H:%M:%S') print "\r", digits time.sleep(0.1) From __peter__ at web.de Wed Aug 17 09:43:50 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Aug 2011 09:43:50 +0200 Subject: [Tutor] directory within directory References: Message-ID: questions anon wrote: > Thank you, that does create the directories in the new place but when I > process the data it does not put the outputs in the correct directory they > all end up in the last directory created. > Below is the code of what I am trying to do. > Any feedback will be greatly appreciated. I think > for (path, dirs, files) in os.walk(inputpath): > for dir in dirs: > print dir > sourcepath=os.path.join(path,dir) > relativepath=os.path.relpath(sourcepath,inputpath) > newdir=os.path.join(outputpath,relativepath) the following two lines > if not os.path.exists(newdir): > os.makedirs(newdir) belong in the for-dirs-loop. plt.savefig() belongs into the for-ncfile loop and needs a path based on the path variable: > > for ncfile in files: > if ncfile[-3:]=='.nc': ... relativepath = os.path.relpath(path, inputpath) newdir = os.path.join(outputpath, relativepath) plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) All untested guesswork. I don't see how you ensure that you get a new figure for each *.nc file and am too lazy to consult the matplotlib documentation... From __peter__ at web.de Wed Aug 17 09:46:44 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Aug 2011 09:46:44 +0200 Subject: [Tutor] Printing in the same place References: <4E4B3002.90706@gmx.com> Message-ID: brandon w wrote: > I am trying to print in the same place to make a clock in a tkinter > window. I will loop the following code to update the time. > > This seems to work but it is not printing in the same place: > > #!/usr/bin/python > #Python 2.6.6 > > import time > > for t in range(5): > digits = time.strftime('%H:%M:%S') > print "\r", digits > time.sleep(0.1) The print statement automatically adds a newline. Try sys.stdout.write("\r" + digits) sys.stdout.flush() instead of print. From alan.gauld at btinternet.com Wed Aug 17 10:02:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Aug 2011 09:02:04 +0100 Subject: [Tutor] Printing in the same place In-Reply-To: <4E4B3002.90706@gmx.com> References: <4E4B3002.90706@gmx.com> Message-ID: On 17/08/11 04:05, brandon w wrote: > I am trying to print in the same place to make a clock in a tkinter > window. I will loop the following code to update the time. This is not a tkinter program so its completely irrelevant to your stated aim. In tkinter how print works is of no importance. You will not be using print in a tkinter program you will simply be changing the text in a widget. > This seems to work but it is not printing in the same place: > > #!/usr/bin/python > #Python 2.6.6 > > import time > > for t in range(5): > digits = time.strftime('%H:%M:%S') > print "\r", digits > time.sleep(0.1) That's because you are using \r which is platform dependant (and even terminal dependant on *nix) . You don't say which platform you are using. Using \b (backspace) may be more successful. >>> print ("test","\b\b\b\b\b\b","Foo") Foo But, as I say, that won't be very useful in tkinter since you won't be using print(). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From timomlists at gmail.com Wed Aug 17 11:01:35 2011 From: timomlists at gmail.com (Timo) Date: Wed, 17 Aug 2011 11:01:35 +0200 Subject: [Tutor] Message: pygobject_register_sinkfunc is deprecated (GtkWindow) In-Reply-To: References: Message-ID: <4E4B836F.6030309@gmail.com> On 16-08-11 20:46, Susana Iraiis Delgado Rodriguez wrote: > Hello List! > > I just started to use PyGTK and Glade to create graphical interfaces, > my python interpreter version is 2.6.6; I also install the GTK2 > Runtime enviroment and Glade 3.6.6. I also installed in my computer > pycairo-1.8.10.win32-py2.6.exe, pygobject-2.26.0-1.win32-py2.6.exe and > pygtk-2.16.0+glade.win32-py2.6.exe so my graphic application will look > and work fine. > > I tried to do an example in order to get familiar with this new tool, > but when I run the script I got the next message: > Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import glade1 > ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow) > ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible) > ** Message: pygobject_register_sinkfunc is deprecated (GtkObject) > >>> > My code is: > import pygtk > pygtk.require("2.0") > import gtk > import gtk.glade gtk.glade is deprecated, you should use the builtin gtk.builder instead (Google for examples). You should also get the latest GTK/PyGTK versions from the PyGTK website. There is a really nice all-in-one installer! Cheers, Timo > > class MainWin: > def __init__(self): > self.widgets = gtk.glade.XML("ejemplo_glade.glade") > signals = { "on_entry1_activate" : self.on_button1_clicked, > "on_button1_clicked" : self.on_button1_clicked, > "gtk_main_quit" : gtk.main_quit } > self.widgets.signal_autoconnect(signals) > self.label1 = self.widgets.get_widget("label1") > self.entry1 = self.widgets.get_widget("entry1") > def on_button1_clicked(self, widget): > texto = self.entry1.get_text() > self.label1.set_text("Hola %s" % texto) > > > if __name__ == "__main__": > MainWin() > gtk.main() > > Does my python libraries are the correct ones for my interpreter? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Aug 17 15:14:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Aug 2011 14:14:36 +0100 Subject: [Tutor] Printing in the same place In-Reply-To: References: <4E4B3002.90706@gmx.com> Message-ID: On 17/08/11 09:02, Alan Gauld wrote: > On 17/08/11 04:05, brandon w wrote: > > I am trying to print in the same place to make a clock in a tkinter > > window. I will loop the following code to update the time. > This is not a tkinter program so its completely irrelevant to your > stated aim. In tkinter how print works is of no importance. You will > not be using print in a tkinter program you will simply be changing > the text in a widget. > > > This seems to work but it is not printing in the same place: > > > > #!/usr/bin/python > > #Python 2.6.6 > > > > import time > > > > for t in range(5): > > digits = time.strftime('%H:%M:%S') > > print "\r", digits > > time.sleep(0.1) > > That's because you are using \r which is platform dependant > (and even terminal dependant on *nix) . You don't say which > platform you are using. Using \b (backspace) may be more > successful. > > >>> print ("test","\b\b\b\b\b\b","Foo") > Foo > > But, as I say, that won't be very useful in tkinter since you > won't be using print(). > Oops, you also need to suppress the newline as Peter Otten mentioned! You can do that in Python v2 by adding a training comma or in v3 you can specify no newline as a parameter. But again, all irrelevent for tkinter. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From deshpande.jaidev at gmail.com Wed Aug 17 15:28:18 2011 From: deshpande.jaidev at gmail.com (Jaidev Deshpande) Date: Wed, 17 Aug 2011 18:58:18 +0530 Subject: [Tutor] Using Python to send signals to the USB port Message-ID: Hi Is there some way I can use Python to send data through a USB port and control the data in real-time? (For instance, I can make a sinusoidal wave of a given specification, and visualize it using NumPy / Matplotlib. How can I send the digitized form of this array through a USB port, and then convert it back into analog so I can view it on an oscilloscope?) Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Aug 17 16:01:12 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 17 Aug 2011 16:01:12 +0200 Subject: [Tutor] Using Python to send signals to the USB port In-Reply-To: References: Message-ID: <4E4BC9A8.30104@compuscan.co.za> On 2011/08/17 03:28 PM, Jaidev Deshpande wrote: > Hi > > Is there some way I can use Python to send data through a USB port and > control the data in real-time? > > (For instance, I can make a sinusoidal wave of a given specification, > and visualize it using NumPy / Matplotlib. How can I send the > digitized form of this array through a USB port, and then convert it > back into analog so I can view it on an oscilloscope?) > > Thanks. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Possibly look at the PyUSB module [1] and a tutorial on it [2]. Hopefully that helps and is enough for you. [1] http://sourceforge.net/apps/trac/pyusb/ [2] http://pyusb.sourceforge.net/docs/1.0/tutorial.html -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Wed Aug 17 16:05:05 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 17 Aug 2011 09:05:05 -0500 Subject: [Tutor] Message: pygobject_register_sinkfunc is deprecated (GtkWindow) In-Reply-To: <4E4B836F.6030309@gmail.com> References: <4E4B836F.6030309@gmail.com> Message-ID: Hello Timo!! Thank you so much for your help! I'll do it 2011/8/17 Timo > On 16-08-11 20:46, Susana Iraiis Delgado Rodriguez wrote: > >> Hello List! >> >> I just started to use PyGTK and Glade to create graphical interfaces, my >> python interpreter version is 2.6.6; I also install the GTK2 Runtime >> enviroment and Glade 3.6.6. I also installed in my computer >> pycairo-1.8.10.win32-py2.6.**exe, pygobject-2.26.0-1.win32-py2.**6.exe >> and pygtk-2.16.0+glade.win32-py2.**6.exe so my graphic application will >> look and work fine. >> >> I tried to do an example in order to get familiar with this new tool, but >> when I run the script I got the next message: >> Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit >> (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import glade1 >> ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow) >> ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible) >> ** Message: pygobject_register_sinkfunc is deprecated (GtkObject) >> >>> >> My code is: >> import pygtk >> pygtk.require("2.0") >> import gtk >> import gtk.glade >> > gtk.glade is deprecated, you should use the builtin gtk.builder instead > (Google for examples). You should also get the latest GTK/PyGTK versions > from the PyGTK website. There is a really nice all-in-one installer! > > Cheers, > Timo > > >> class MainWin: >> def __init__(self): >> self.widgets = gtk.glade.XML("ejemplo_glade.**glade") >> signals = { "on_entry1_activate" : self.on_button1_clicked, >> "on_button1_clicked" : self.on_button1_clicked, >> "gtk_main_quit" : gtk.main_quit } >> self.widgets.signal_**autoconnect(signals) >> self.label1 = self.widgets.get_widget("**label1") >> self.entry1 = self.widgets.get_widget("**entry1") >> def on_button1_clicked(self, widget): >> texto = self.entry1.get_text() >> self.label1.set_text("Hola %s" % texto) >> >> >> if __name__ == "__main__": >> MainWin() >> gtk.main() >> >> Does my python libraries are the correct ones for my interpreter? >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 17 19:11:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Aug 2011 18:11:44 +0100 Subject: [Tutor] Using Python to send signals to the USB port In-Reply-To: References: Message-ID: On 17/08/11 14:28, Jaidev Deshpande wrote: Hi > Is there some way I can use Python to send data through a USB port and > control the data in real-time? Yes, but its not what I'd call easy! > .... How can I send the digitized form of this array through a USB port, > and then convert it back intoanalog so I can view it on an oscilloscope? The sending to USB is fairly straightforward but to convert that back to analog once its left the PC you will need some kind of DAC (digital to analog convertor), you cannot do that from inside the PC! DACs are relatively easy to find but not that cheap. But if the frequency is not too high you an probably do it inside the PC and send the analog out using the loudspeaker or line-out jack. Then connect that directly to the 'scope. That should work for frequencies up to 20kHz or so, even 40Khz if you have a good sound card!... hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Aug 17 22:19:46 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 17 Aug 2011 21:19:46 +0100 (BST) Subject: [Tutor] Using Python to send signals to the USB port In-Reply-To: References: Message-ID: <1313612386.30639.YahooMailRC@web86702.mail.ird.yahoo.com> > Well, my application requires roughly 20 MHz ( :O ... I know )... > However, the DACs are not a problem, I can afford them. OK, Well to digitize a 20M signal you need to sample it at 40M rate. Then just send the digital levels out through the usb port one bit at a time which will require around 8x40M = 320Mbps (plus protocol overheads). That's about the limit of USB2 (maybe even over the limit?). Looks like you will need to use USB3 or resort to compression. And i'm assuming you only want 256 quantization levels, if you want to go to 16bit encoding then you need to double the bitrate. Definitely too high for USB2... If you use compression you need to find a DAC that can unscramble a compressed signal. There are a number of encoding schemes that you could use. You can also save bandwidth by using a bitstream encoding provided the signal slew rate is not too high. Lots of choices but it all depends heavily on the nature of the signal. Its not a simple task, and although the mechanics of sending the data through the usb port are not too hard the algorithms and protocols to generate the data are all documented and not too hard to code up, the plethora of choice is what makes it hard. I'm also assuming that you can process this data in batch mode rather than in real-time and then transmit the digital signal in one go. If it all needs to be real time you might be pushed to use standard Python and need to look at things like Cython or writing a C module. I suspect you need to do a bit of digging on Wikipedia to get a feel for which algorithms/mechanisms are best suited to your needs. Then find a DAC that matches that and use the spec for the DAC to guide your coding. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thisisonlyatest at gmx.com Thu Aug 18 00:20:27 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Wed, 17 Aug 2011 18:20:27 -0400 Subject: [Tutor] Printing in the same place In-Reply-To: References: <4E4B3002.90706@gmx.com> Message-ID: <4E4C3EAB.4060401@gmx.com> On 08/17/2011 04:02 AM, Alan Gauld wrote: > On 17/08/11 04:05, brandon w wrote: >> I am trying to print in the same place to make a clock in a tkinter >> window. I will loop the following code to update the time. > This is not a tkinter program so its completely irrelevant to your > stated aim. In tkinter how print works is of no importance. You will > not be using print in a tkinter program you will simply be changing > the text in a widget. > >> This seems to work but it is not printing in the same place: >> >> #!/usr/bin/python >> #Python 2.6.6 >> >> import time >> >> for t in range(5): >> digits = time.strftime('%H:%M:%S') >> print "\r", digits >> time.sleep(0.1) > > That's because you are using \r which is platform dependant > (and even terminal dependant on *nix) . You don't say which > platform you are using. Using \b (backspace) may be more > successful. > > >>> print ("test","\b\b\b\b\b\b","Foo") > Foo > > But, as I say, that won't be very useful in tkinter since you > won't be using print(). > I am using Linux with Python 2.6.6. "\b" seems like a good simple solution to the problem. I guess I will have to find another way to create a digital clock in a tkinter window. I found someone who made a Python clock but I want to create my own version without just coping his. I will learn more if I try to do it myself. Thanks for your help. From alan.gauld at btinternet.com Thu Aug 18 01:43:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Aug 2011 00:43:50 +0100 Subject: [Tutor] Printing in the same place In-Reply-To: <4E4C3EAB.4060401@gmx.com> References: <4E4B3002.90706@gmx.com> <4E4C3EAB.4060401@gmx.com> Message-ID: On 17/08/11 23:20, brandon w wrote: > I guess I will have to find another way to create a digital clock in a > tkinter window. The point about a GUI is that you display widgets that have text on them. It could be a Label, or a Button or a Text box or even a Canvas. Then to change the text you simply replace the text en-masse with a new string, you don't attempt to backspace or return or anything like you would with print(). (Actually with a Text box widget you could do that by controlling the cursor, but for your purpose that is just making it harder than it needs to be!) You just assign a new string to the widgets text attribute. You can see how to do that with one of the examples on my GUI tutor. It replaces the text on a label with the contents of an entry box: # create the event handler to clear the text def evClear(): lHistory['text'] = eHello.get() eHello.delete(0,END) the label(lHistory) simply displays whatever is assigned to its text attribute, and in this case its whatever is in the Entry widget (eHello) before we clear it. It could just as well be a string displaying the current time... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From quasipedia at gmail.com Thu Aug 18 14:33:21 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 18 Aug 2011 14:33:21 +0200 Subject: [Tutor] Standard way to create debian packages for python programs? Message-ID: <20110818143321.342baff3@jabbar> Although it's years I program with python, I never distributed my software with packages (I never created *any* packages in my life, indeed). Out there there is ton of information on how to do this, but after a day of scouring the Internet I still did not wrap my mind around it. The problem for me is that "there is more than a way to skin a cat", and all the tutorials/manuals that cover a bit of the process seem to make certain assumptions which are different from other tutorials, sot that is not self-evident how I should merge the info from two sources together. For example: when I find a manual on how to create a binary package, it is assumed there are makefile for C code, when I find a page on how to use distutils, it is assumed I want to "package" a module and not a stand-alone program, etc... So I am turning to the community to ask for advice/guidance. So far I seem to have understood the following (please correct me if I am wrong): a) I need to create a "binary" .deb package. Such package will be platform independend (32 vs 64 bit) as all python programs are such. b) To create a "binary" package I need first to create a source package. c) To create the source package I can use either CDBS or debhelper. Debhelper is the recommended way for beginners. d) The core of creating a source package is populating the DEBIAN directory in the source directory with a number of files clarifying where files need to be copied, what copyright and licensing scheme they are subject to, what dependencies they have, etc... e) Step d) can be largely automated the 'dh_make' command IF the python source also comes with a distutils' setup.py script. Now my questions: 1. Is my understanding of the process correct? Is there anything I am missing, or anything that I got wrong? 2. Step e) is really the more confusing to me: specifically the two points that remains most obscure to me are: I. How do I write a script that install a stand-alone programe? II. What are the specificities for DEB packages? The official documentation only seems to deal with RPM and Windows stuff... 3. Is there any "reasonable sized" source of information that you would recommend me to read [by "reasonable sized" I mean something specific to python and concise, rather that the complete debian policy on packaging]. 4. Any word of wisdom / additional info you would like to share? BTW: This is are the best source of information that I could find myself so far: - Ubuntu's python packaging guide (clearly explains steps a-b-c): https://wiki.ubuntu.com/PackagingGuide/Python#The_debhelper_way - Creating a .deb package from a python setup.py (it _shows_ the steps but doesn't _explain_ them enough for me to follow along): http://ghantoos.org/2008/10/19/creating-a-deb-package-from-a-python-setuppy/ - ShowMeDo video on "creating a .deb package out of a python program" (it doesn't seem up-to-date and - if I got it right - will produce packages for personal use, without dependencies and without key data for distribution with ubuntu/debian): http://showmedo.com/videotutorials/series?name=linuxJensMakingDebSeries Thanks in advance for your help and support! /mac From steve at pearwood.info Thu Aug 18 14:43:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 18 Aug 2011 22:43:09 +1000 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <20110818143321.342baff3@jabbar> References: <20110818143321.342baff3@jabbar> Message-ID: <4E4D08DD.7030909@pearwood.info> Mac Ryan wrote: > Although it's years I program with python, I never distributed my > software with packages (I never created *any* packages in my life, > indeed). This is a mailing list for learning the programming Python, not on how to built Debian packages. You will probably get better answers if you ask this question on a Debian packaging forum. -- Steven From quasipedia at gmail.com Thu Aug 18 17:39:05 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 18 Aug 2011 17:39:05 +0200 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <4E4D08DD.7030909@pearwood.info> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> Message-ID: <20110818173905.56894f35@jabbar> On Thu, 18 Aug 2011 22:43:09 +1000 Steven D'Aprano wrote: > Mac Ryan wrote: > > Although it's years I program with python, I never distributed my > > software with packages (I never created *any* packages in my life, > > indeed). > > This is a mailing list for learning the programming Python, not on > how to built Debian packages. > > You will probably get better answers if you ask this question on a > Debian packaging forum. Steven, I appreciate the feedback, yet it feels like you did not read my question through: apart a general feedback about the packaging process [which I felt important to explain in case I got it totally wrong and was asking something that did not make sense at all] the other to points are specific to python. In particular, `distutils` is part of the standard python distribution and it is in no way specific to Debian, so I don't feel this is the wrong place to ask, although it's totally ok if tutors feel they aren't competent enough on the subject to give proper feedback. :) I will surely cross-post on some debian-specific ML or forum, but I don't think I will have better luck in getting feedback on distutils there than on a python-specific ML like this one. I will let you know if I will be proved wrong, though! :) Best, /mac From ramit.prasad at jpmorgan.com Thu Aug 18 18:48:19 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 18 Aug 2011 12:48:19 -0400 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <20110818173905.56894f35@jabbar> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BD55@EMARC112VS01.exchad.jpmchase.net> To be honest, even after reading your original post twice (now knowing you are actually asking a Python question) I am unsure what Python question you are asking. >Now my questions: > >1. Is my understanding of the process correct? Is there anything I am > missing, or anything that I got wrong? No clue, I use Debian and Python but never in attempt to build a package. >2. Step e) is really the more confusing to me: specifically the two > points that remains most obscure to me are: > I. How do I write a script that install a stand-alone programe? I assume you can use Python and os.system or better yet subprocess (worst case scenario Python calls the other utils). This is not really a python specific question and you did not mention distutils here. Either way I have no clue, sorry. > II. What are the specificities for DEB packages? The official > documentation only seems to deal with RPM and Windows stuff... Not a Python question and no clue. >3. Is there any "reasonable sized" source of information that you would > recommend me to read [by "reasonable sized" I mean something > specific to python and concise, rather that the complete debian > policy on packaging]. Not a Python question and no clue. >4. Any word of wisdom / additional info you would like to share? Again, not really a Python question. The Debian forum is probably far more likely to know. You will also have much better luck on the main Python list because there is a much larger userbase. Also, because Ubuntu is based off Debian (i.e. share package management systems) and is highly popular, you may want to see if there is any web information on Python + Ubuntu for packaging. Something like: http://showmedo.com/videotutorials/video?name=linuxJensMakingDeb OR http://ghantoos.org/2008/10/19/creating-a-deb-package-from-a-python-setuppy/ OR http://ask.debian.net/questions/how-to-build-a-pure-python-debian-package Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From swiftone at swiftone.org Thu Aug 18 19:01:08 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 18 Aug 2011 13:01:08 -0400 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <20110818173905.56894f35@jabbar> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> Message-ID: On Thu, Aug 18, 2011 at 11:39 AM, Mac Ryan wrote: > ? ? ? ?In particular, `distutils` is part of the standard python > distribution and it is in no way specific to Debian, so I don't feel > this is the wrong place to ask, although it's totally ok if tutors feel > they aren't competent enough on the subject to give proper feedback. :) Are you looking for distutils advice, or .deb advice? They are pretty different. How are you expecting your users to install your package? Via easy_install? Apt-get? Something else? -- Brett Ritter / SwiftOne swiftone at swiftone.org From quasipedia at gmail.com Thu Aug 18 19:33:27 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 18 Aug 2011 19:33:27 +0200 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> Message-ID: <20110818193327.706a5aa8@jabbar> On Thu, 18 Aug 2011 13:01:08 -0400 Brett Ritter wrote: > On Thu, Aug 18, 2011 at 11:39 AM, Mac Ryan > wrote: > > ? ? ? ?In particular, `distutils` is part of the standard python > > distribution and it is in no way specific to Debian, so I don't feel > > this is the wrong place to ask, although it's totally ok if tutors > > feel they aren't competent enough on the subject to give proper > > feedback. :) > > Are you looking for distutils advice, or .deb advice? They are pretty > different. > How are you expecting your users to install your package? Via > easy_install? Apt-get? Something else? Hi Brett, thanks for coming back to me. My goal is to have a .deb package installable with apt-get. What I am asking advice on is primarily the distutils script. The procedure on how to get to a .deb package is there just to give a context to my question and - hopefully - to have somebody tell me if I am 100% wrong and indeed a setup.py script is NOT part of the process. I'm going to reply to Ramit in a second and hopefully I will be able to further clarify there what I am asking. Thank you, /mac From quasipedia at gmail.com Thu Aug 18 19:48:35 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 18 Aug 2011 19:48:35 +0200 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BD55@EMARC112VS01.exchad.jpmchase.net> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BD55@EMARC112VS01.exchad.jpmchase.net> Message-ID: <20110818194835.526e9782@jabbar> On Thu, 18 Aug 2011 12:48:19 -0400 "Prasad, Ramit" wrote: > To be honest, even after reading your original post twice (now > knowing you are actually asking a Python question) I am unsure what > Python question you are asking. Apologies, English is not my mother tongue, maybe I wasn't able to express myself clearly enough? > >2. Step e) is really the more confusing to me: specifically the two > > points that remains most obscure to me are: > > I. How do I write a script that install a stand-alone programe? > > I assume you can use Python and os.system or better yet subprocess > (worst case scenario Python calls the other utils). This is not > really a python specific question and you did not mention distutils > here. Either way I have no clue, sorry. You lost me, but I assume this is because you didn't get my question in the first place. My point "e" mentions the setup.py script that one must write for using distutils. This is what the question is about: how do I write a script that handle a full program with several modules, data files, etc? The official documentation seems not to provide an example for this. Since my posting this question here, I received a useful link for this from another source, that I'm still working through: http://wiki.python.org/moin/Distutils/Tutorial > > II. What are the specificities for DEB packages? The official > > documentation only seems to deal with RPM and Windows stuff... > > Not a Python question and no clue. It *IS* a python question as it refers to the distutils module. If you read the documentation (http://docs.python.org/distutils/builtdist.html) you will see that there are sections about windows exe installer and RPM packages, but none for DEB... how is so? Maybe distutils can't handle build distribution for this platform? Or maybe it is simply undocumented? > >3. Is there any "reasonable sized" source of information... > Not a Python question and no clue. > > >4. Any word of wisdom / additional info you would like to share? > Again, not really a Python question. In some 3 years I am member of this list I have seen thousands of messages containing pointers to external documentation and advice from this list users' personal experience... so they might not be technically about python code, but I'm positive they are not off-topic requests. > Something like: > http://showmedo.com/videotutorials/video?name=linuxJensMakingDeb OR > http://ghantoos.org/2008/10/19/creating-a-deb-package-from-a-python-setuppy/ > OR > http://ask.debian.net/questions/how-to-build-a-pure-python-debian-package Of the three links you provided, two were in my original question... The third link's answer only contains a link to another source from my original question... :( /mac From ramit.prasad at jpmorgan.com Thu Aug 18 20:26:49 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 18 Aug 2011 14:26:49 -0400 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <20110818194835.526e9782@jabbar> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BD55@EMARC112VS01.exchad.jpmchase.net> <20110818194835.526e9782@jabbar> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BFDF@EMARC112VS01.exchad.jpmchase.net> >> To be honest, even after reading your original post twice (now >> knowing you are actually asking a Python question) I am unsure what >> Python question you are asking. > >Apologies, English is not my mother tongue, maybe I wasn't able to >express myself clearly enough? No apologies are necessary. I was just trying to explain that I (and possibly others) did not understand. Your clarification has helped greatly. >> > II. What are the specificities for DEB packages? The official >> > documentation only seems to deal with RPM and Windows stuff... >> >> Not a Python question and no clue. > >It *IS* a python question as it refers to the distutils module. If you >read the documentation > (http://docs.python.org/distutils/builtdist.html) you will see that >there are sections about windows exe installer and RPM packages, but >none for DEB... how is so? Maybe distutils can't handle build >distribution for this platform? Or maybe it is simply undocumented? I know this does not directly answer your question, but are you able to build an RPM? You can use the utility 'alien' to convert an RPM to a .deb >Of the three links you provided, two were in my original question... >The third link's answer only contains a link to another source from my >original question... :( Whoops, sorry about that. Sadly, this as much help as I can provide. Again, I suggest you take this to the main python list. You are more likely to receive the help you desire there. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Thu Aug 18 20:55:19 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 18 Aug 2011 14:55:19 -0400 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BFDF@EMARC112VS01.exchad.jpmchase.net> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BD55@EMARC112VS01.exchad.jpmchase.net> <20110818194835.526e9782@jabbar> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BFDF@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3C09F@EMARC112VS01.exchad.jpmchase.net> Have you taken a look at: http://pypi.python.org/pypi/stdeb/0.5.1 This actually looks like it might be what you want: http://ubuntuforums.org/showthread.php?t=1002909 Hope that helps, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri Aug 19 01:08:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Aug 2011 00:08:30 +0100 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <20110818173905.56894f35@jabbar> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> Message-ID: On 18/08/11 16:39, Mac Ryan wrote: > On Thu, 18 Aug 2011 22:43:09 +1000 > Steven D'Aprano wrote: >> >> This is a mailing list for learning the programming Python, not on >> how to built Debian packages. >> >> You will probably get better answers if you ask this question on a >> Debian packaging forum. > > In particular, `distutils` is part of the standard python > distribution and it is in no way specific to Debian, so I don't feel > this is the wrong place to ask, Technically it's a valid question because it is about a module in the standard library. But it's not really about the language and building Linux packages is well beyond what most newbies get up to - and in fact I don't know of too many experienced Python users who do it either! So I think Steven's advice is probably valid and you will get better advice asking on the Debian/[UKX]buntu/Mint forums or on the main Python list. I notice there is also a distutils SIG with a mailing list which looks like they might help. A quick look at some mails suggests they cover this kind of issue. FWIW I used the gmane web site to take a quick look... -- Alan G tutor list moderator From quasipedia at gmail.com Fri Aug 19 02:30:30 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 19 Aug 2011 02:30:30 +0200 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> Message-ID: <20110819023030.16a816ec@jabbar> On Fri, 19 Aug 2011 00:08:30 +0100 Alan Gauld wrote: > I notice there is also a distutils SIG with a mailing list which > looks like they might help. A quick look at some mails suggests they > cover this kind of issue. > > FWIW I used the gmane web site to take a quick look... Thanks for both the suggestions. I just subscribed to the SIG group, although since my original call for help I already received a few inputs that helped me a lot. Best, /mac From quasipedia at gmail.com Fri Aug 19 02:37:14 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 19 Aug 2011 02:37:14 +0200 Subject: [Tutor] Standard way to create debian packages for python programs? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3C09F@EMARC112VS01.exchad.jpmchase.net> References: <20110818143321.342baff3@jabbar> <4E4D08DD.7030909@pearwood.info> <20110818173905.56894f35@jabbar> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BD55@EMARC112VS01.exchad.jpmchase.net> <20110818194835.526e9782@jabbar> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3BFDF@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7C3C09F@EMARC112VS01.exchad.jpmchase.net> Message-ID: <20110819023714.61ec5dbb@jabbar> On Thu, 18 Aug 2011 14:55:19 -0400 "Prasad, Ramit" wrote: > Have you taken a look at: http://pypi.python.org/pypi/stdeb/0.5.1 Thank you for this. Actually I got the same advice also on my SO question here: http://stackoverflow.com/q/7110604/146792 at about the same time you answered me. Good source. [Also the link to the forum thread was good!] For the records: the other good piece of advice I received elsewhere was to look into `Distribute`, a collection of enhancements to `distutils` that indeed make the creation of setup.py easier for what I want to achieve. Here's a link to the docs for those interested: http://packages.python.org/distribute/setuptools.html Thank you for the support, /mac From david.crisp at gmail.com Fri Aug 19 05:14:50 2011 From: david.crisp at gmail.com (David Crisp) Date: Fri, 19 Aug 2011 13:14:50 +1000 Subject: [Tutor] Best way to store and access a fixed coordinate list Message-ID: Hello, I have a large grid of numbers 100 * 100 I then randomly select an X and Y to act as a "centre" point. I have a list of numbers which are coordinate offsets which are then applied to the centre point as per: X = (-2,2),(-4,2),(4,2),(2,2) (The list is about 200 coordinate pairs long) The idea is that I iterate through the list of coordinates in X and do the following: if (Centrepoint plus x and y offset) = something then something else. So, what is the best way of storeing this within a script. What is the best way of accessing it then later so I can break out the first and second number in the coordinate pair and actually use them in a calculation. suggestions are welcome. I have been focused on this for a few hours now and I think i cant see the trees for the forest (of the problem) Regards, David From steve at pearwood.info Fri Aug 19 06:34:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 19 Aug 2011 14:34:51 +1000 Subject: [Tutor] Best way to store and access a fixed coordinate list In-Reply-To: References: Message-ID: <4E4DE7EB.9090301@pearwood.info> David Crisp wrote: > Hello, > > I have a large grid of numbers 100 * 100 > > I then randomly select an X and Y to act as a "centre" point. > > I have a list of numbers which are coordinate offsets which are then > applied to the centre point as per: > > X = (-2,2),(-4,2),(4,2),(2,2) (The list is about 200 coordinate pairs long) Two-tuples (x, y) are probably the most light-weight way of doing this. You then add them like this: >>> a = (1, 2) >>> b = (100, 200) >>> (a[0] + b[0], a[1] + b[1]) (101, 202) A helper function for adding them together will make life easier: def add(p1, p2): """Return points p1 + p2.""" return (p1[0] + p2[0], p1[1] + p2[1]) And in action: >>> a = (1, 2) >>> b = (100, 200) >>> add(a, b) (101, 202) Slightly less light-weight would be a namedtuple, available from Python 2.6 on up. This lets you define a light-weight Point class with named attributes: >>> from collections import namedtuple >>> Point = namedtuple("Point", "x y") >>> a = Point(23, 42) >>> a.x 23 >>> a.y 42 Named tuples still behave like tuples, so you can use them like ordinary tuples: >>> a[0] 23 >>> a == (23, 42) True and the add() helper function will continue to work. A more heavy-weight solution would be a full-blown Point class, that defines all the arithmetic operations. Here's one way to do it: class Point(namedtuple("Point", "x y")): def __add__(self, other): return (self[0] + other[0], self[1] + other[1]) __radd__ = __add__ # and similar for subtraction __sub__ and __rsub__ And in action: >>> a = Point(1, 2) >>> b = Point(100, 200) >>> a + b (101, 202) The advantage here is that you don't need the helper function, you can just add Points with the + operator. -- Steven From questions.anon at gmail.com Fri Aug 19 08:16:58 2011 From: questions.anon at gmail.com (questions anon) Date: Fri, 19 Aug 2011 16:16:58 +1000 Subject: [Tutor] directory within directory In-Reply-To: References: Message-ID: Excellent, thank you!! On Wed, Aug 17, 2011 at 5:43 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > Thank you, that does create the directories in the new place but when I > > process the data it does not put the outputs in the correct directory > they > > all end up in the last directory created. > > Below is the code of what I am trying to do. > > Any feedback will be greatly appreciated. > > I think > > > for (path, dirs, files) in os.walk(inputpath): > > for dir in dirs: > > print dir > > sourcepath=os.path.join(path,dir) > > relativepath=os.path.relpath(sourcepath,inputpath) > > newdir=os.path.join(outputpath,relativepath) > > the following two lines > > > if not os.path.exists(newdir): > > os.makedirs(newdir) > > belong in the for-dirs-loop. plt.savefig() belongs into the for-ncfile loop > and needs a path based on the path variable: > > > > for ncfile in files: > > if ncfile[-3:]=='.nc': > ... > relativepath = os.path.relpath(path, inputpath) > newdir = os.path.join(outputpath, relativepath) > > plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) > > All untested guesswork. I don't see how you ensure that you get a new > figure > for each *.nc file and am too lazy to consult the matplotlib > documentation... > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.crisp at gmail.com Fri Aug 19 12:53:12 2011 From: david.crisp at gmail.com (David Crisp) Date: Fri, 19 Aug 2011 20:53:12 +1000 Subject: [Tutor] Best way to store and access a fixed coordinate list In-Reply-To: References: Message-ID: Dont worry! I solved this. I had a brain fade earlier today when I was working on the problem and it wasnt untill this evening when I got home and relaxed that what I was after came to mind. The following code example does the basics of what I was trying to do. Its pretty damn simple. so i was deep in the forest and couldnt see the tree! x = {(1,2),(4,4),(4,6),(3,5)} for eachitem in x: print eachitem,eachitem[0], eachitem[1] Regards, On Fri, Aug 19, 2011 at 1:14 PM, David Crisp wrote: > Hello, > > I have a large grid of numbers ?100 * 100 > > I then randomly select an X and Y to act as a "centre" point. > > I have a list of numbers which are coordinate offsets which are then > applied to the centre point as per: > > X = (-2,2),(-4,2),(4,2),(2,2) ?(The list is about 200 coordinate pairs long) > > The idea is that I iterate through the list of coordinates in X and do > the following: > > if (Centrepoint plus x and y offset) = something then something else. > > So, what is the best way of storeing this within a script. > > What is the best way of accessing it then later so I can break out the > first and second number in the coordinate pair and actually use them > in a calculation. > > suggestions are welcome. ?I have been focused on this for a few hours > now and I think i cant see the trees for the forest (of the problem) > > Regards, > David > From artie.ziff at gmail.com Fri Aug 19 21:55:55 2011 From: artie.ziff at gmail.com (Artie Ziff) Date: Fri, 19 Aug 2011 12:55:55 -0700 Subject: [Tutor] file fetcher class object through http Message-ID: <4E4EBFCB.1020601@gmail.com> Hello.. I like reading different people's implementations of python as it helps me decide what is necessary vs what is not. Essentially, I want to write a class that finds, and downloads a file from a web server. Of course I may add some file matching features through regex... and other things that I need. mostly, I am looking for a smart class implementation that has well-considered API and method choices. I tried to read through packages such as distutils and setuptools however I believe I may need to read some code that is less "industrial strength". lol! maybe you know of one in an author's particular open source package? pls point me to one you know about... thank you. az From steve at pearwood.info Sat Aug 20 03:59:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Aug 2011 11:59:19 +1000 Subject: [Tutor] file fetcher class object through http In-Reply-To: <4E4EBFCB.1020601@gmail.com> References: <4E4EBFCB.1020601@gmail.com> Message-ID: <4E4F14F7.8040709@pearwood.info> Artie Ziff wrote: > Hello.. > > I like reading different people's implementations of python as it helps > me decide what is necessary vs what is not. > > Essentially, I want to write a class that finds, and downloads a file > from a web server. Such tools already exist, although they may not be written in Python. In particular, google on "wget" or "curl" for two very well-known industrial-strength tools for downloading files from the web (and other places). If you just want something that works, I recommend you learn how to use those tools rather than re-inventing the wheel. (A lot of my scripts that download from the web do text processing in Python then call wget for the actual download.) If you add "python" to your search terms, you may find the sort of code you are looking for, or at least examples that will point you in the right direction. E.g.: http://duckduckgo.com/?q=python+wget http://duckduckgo.com/?q=python+curl -- Steven From steve at pearwood.info Sat Aug 20 04:05:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Aug 2011 12:05:25 +1000 Subject: [Tutor] file fetcher class object through http In-Reply-To: <4E4EBFCB.1020601@gmail.com> References: <4E4EBFCB.1020601@gmail.com> Message-ID: <4E4F1665.1060307@pearwood.info> Oh, I forgot to mention... Artie Ziff wrote: > Essentially, I want to write a class that finds, and downloads a file > from a web server. [...] > mostly, I am looking for a smart class implementation that has > well-considered API and method choices. Have you looked at the code in the Python standard library itself? E.g.: http://docs.python.org/library/httplib.html http://www.voidspace.org.uk/python/articles/urllib2.shtml -- Steven From james at jamesthornton.com Sat Aug 20 06:07:15 2011 From: james at jamesthornton.com (James Thornton) Date: Fri, 19 Aug 2011 23:07:15 -0500 Subject: [Tutor] file fetcher class object through http In-Reply-To: <4E4EBFCB.1020601@gmail.com> References: <4E4EBFCB.1020601@gmail.com> Message-ID: > Essentially, I want to write a class that finds, and downloads a file from a > web server. mostly, I am looking for a smart class implementation that has > well-considered API and method choices. httplib2 (http://code.google.com/p/httplib2) by Joe Gregorio of Google is what I use. It has an intuitive interface that's easy to use. $ pip install httplib2 >>> import httplib2 >>> http = httplib2.Http() >>> resp, content = http.request("http://example.org/", "GET") Here are more examples: http://code.google.com/p/httplib2/wiki/Examples - James -- Bulbflow: A Python framework for graph databases (http://bulbflow.com) From dave6502 at gmail.com Sat Aug 20 11:58:38 2011 From: dave6502 at gmail.com (dave selby) Date: Sat, 20 Aug 2011 10:58:38 +0100 Subject: [Tutor] I am trying to read and decode an emails PDF attachment via python, Message-ID: I am trying to read and decode an emails PDF attachment via python, its a dedicated mailbox, anything emailed there is to be read by the script, deleted from the mailbox and processed. http://pastebin.com/VA1gwWH3 def get_next_mail() works AOK, I get a nice long string containing the next email and PDF data block but when I execute msg.is_multipart() I get False ??? And when I execute msg.get_payload() I get nothing Any ideas anyone, at a guess its because my string is not formatted correctly, can anyone advise ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From lisi.reisz at gmail.com Sat Aug 20 16:25:15 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sat, 20 Aug 2011 15:25:15 +0100 Subject: [Tutor] Modules and Python tutorial by S. Thurlow - opinions please Message-ID: <201108201525.15200.lisi.reisz@gmail.com> I have got myself well and truly bogged down. I need to change the angle from which I am looking. I only have a short while left for now in which to make some sort of progress with Python. What do people think of: http://www.sthurlow.com/python/ Is it reasonably accurate and therefore useful? If not, or even in addition, what can people recommend for me to dig myself out of the quagmire? I am having difficulty with the "wrong" things. If statements, while or for loops etc. don't phase me. But I am stuck on something so trivial that it is ridiculous. I think that I understand how to write a basic function, but I can't work out how to save and call it. To show you what I mean: How to save and run a bash script: Write your script save it in the normal manner chmod to x for everyone you want to be able to execute it. (E.g. where owner is root: perhaps 744) Either move the file into a directory on your path, or add the directory that the file is in to your path. It will now run. Can anyone point me to a similar set of basic instructions for Python modules?? Thanks, Lisi From steve at pearwood.info Sat Aug 20 17:51:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Aug 2011 01:51:07 +1000 Subject: [Tutor] Modules and Python tutorial by S. Thurlow - opinions please In-Reply-To: <201108201525.15200.lisi.reisz@gmail.com> References: <201108201525.15200.lisi.reisz@gmail.com> Message-ID: <4E4FD7EB.9070203@pearwood.info> Lisi wrote: > I have got myself well and truly bogged down. I need to change the angle from > which I am looking. I only have a short while left for now in which to make > some sort of progress with Python. What do people think of: > > http://www.sthurlow.com/python/ > > Is it reasonably accurate and therefore useful? As far as I can tell after a lightning fast read of it (about three minutes to skim a few of the lessons), it seems perfectly fine to me. [...] > To show you what I mean: > How to save and run a bash script: > Write your script > save it in the normal manner > chmod to x for everyone you want to be able to execute it. (E.g. where owner > is root: perhaps 744) > Either move the file into a directory on your path, or add the directory that > the file is in to your path. > It will now run. > > Can anyone point me to a similar set of basic instructions for Python > modules?? More or less exactly the same, except you need a hash-bang line at the top of the script so that the shell knows that it is Python and not a shell script. So you can add a line like: #!/usr/bin/python at the VERY TOP of your script (it MUST be in the first line for the shell to recognise it). (This is exactly the same practice for all scripting languages, including Perl, Bash, Ruby, and many more... if the hash-bang line is missing, the shell will try to execute the file with "sh".) As an alternative, you can call the script from the shell prompt like this: $ python path/to/my/script.py (naturally you don't type the $ that is just the shell prompt) Finally, you can put your script somewhere in the PYTHONPATH and then call it like this: $ python -m script Note that this way you leave the .py off the end -- you're not telling Python to *run* a file, but to *import* a file, which happens to run it as a side-effect. I don't recommend you use this technique until you're more comfortable with Python. I mention it only for completeness. -- Steven From lisi.reisz at gmail.com Sat Aug 20 18:02:52 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sat, 20 Aug 2011 17:02:52 +0100 Subject: [Tutor] Modules and Python tutorial by S. Thurlow - opinions please In-Reply-To: <4E4FD7EB.9070203@pearwood.info> References: <201108201525.15200.lisi.reisz@gmail.com> <4E4FD7EB.9070203@pearwood.info> Message-ID: <201108201702.52700.lisi.reisz@gmail.com> Thanks, Steven. :-) I'll get back to this this evening. Lisi On Saturday 20 August 2011 16:51:07 Steven D'Aprano wrote: > Lisi wrote: > > I have got myself well and truly bogged down. I need to change the angle > > from which I am looking. I only have a short while left for now in which > > to make some sort of progress with Python. What do people think of: > > > > http://www.sthurlow.com/python/ > > > > Is it reasonably accurate and therefore useful? > > As far as I can tell after a lightning fast read of it (about three > minutes to skim a few of the lessons), it seems perfectly fine to me. > > [...] > > > To show you what I mean: > > How to save and run a bash script: > > Write your script > > save it in the normal manner > > chmod to x for everyone you want to be able to execute it. (E.g. where > > owner is root: perhaps 744) > > Either move the file into a directory on your path, or add the directory > > that the file is in to your path. > > It will now run. > > > > Can anyone point me to a similar set of basic instructions for Python > > modules?? > > More or less exactly the same, except you need a hash-bang line at the > top of the script so that the shell knows that it is Python and not a > shell script. So you can add a line like: > > #!/usr/bin/python > > at the VERY TOP of your script (it MUST be in the first line for the > shell to recognise it). > > (This is exactly the same practice for all scripting languages, > including Perl, Bash, Ruby, and many more... if the hash-bang line is > missing, the shell will try to execute the file with "sh".) > > > As an alternative, you can call the script from the shell prompt like this: > > > $ python path/to/my/script.py > > (naturally you don't type the $ that is just the shell prompt) > > > Finally, you can put your script somewhere in the PYTHONPATH and then > call it like this: > > > $ python -m script > > > Note that this way you leave the .py off the end -- you're not telling > Python to *run* a file, but to *import* a file, which happens to run it > as a side-effect. I don't recommend you use this technique until you're > more comfortable with Python. I mention it only for completeness. From thisisonlyatest at gmx.com Sat Aug 20 21:12:53 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sat, 20 Aug 2011 15:12:53 -0400 Subject: [Tutor] Tkinter: Deleting text when clicking in field. Message-ID: <4E500735.30605@gmx.com> I worked on this for a long time. I did many searches to fix the many error messages I was getting and I finally got this to work. I would now just like to have the text disappear when a person clicks in the box to type something. How can I do that? (This is just a sample of the whole program.) from Tkinter import * class MyGrid(Frame): def __init__(self, win=None): Frame.__init__(self, win) self.grid() self.mkWidgets() [...snip...] self.mytext = StringVar() self.mytext.set("Enter text here") # This text needs to be deleted upon clicking in the field. self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, width=50) self.e.grid(row=0, column=0) [...snip...] app = MyGrid() app.mainloop() #==============================================================END I have created a method to clear the field. This is not working: def clearBox(self): self.mytext.delete(0, END) return self.mytext = StringVar(None) self.mytext.set("Enter text here") self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, width=50, command=self.clearBox) self.e.grid(row=0, column=0) This does not work either: def clearBox(self): self.mytext.get() self.mytext.delete(0, END) return self.mytext = StringVar(None) self.mytext.set("Enter text here") self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, width=50, command=self.clearBox) self.e.grid(row=0, column=0) This either: def clearBox(self): #self.mytext.get() self.e.delete(0, END) return From alan.gauld at btinternet.com Sun Aug 21 00:53:53 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Aug 2011 23:53:53 +0100 Subject: [Tutor] Modules and Python tutorial by S. Thurlow - opinions please In-Reply-To: <201108201525.15200.lisi.reisz@gmail.com> References: <201108201525.15200.lisi.reisz@gmail.com> Message-ID: On 20/08/11 15:25, Lisi wrote: > ridiculous. I think that I understand how to write a basic function, but I > can't work out how to save and call it. If you literally mean how to write,save and use a Python function (from within another script) then I'll have a go: > How to save and run a bash script: > Write your script Same with Python, create a text file with your favourite editor and save it with a .py extension. This is now a Python module that you can import into any other script. Lets assume you called it mymodule.py. > save it in the normal manner Yes, gotta do that with Python too. > chmod to x for everyone you want to be able to execute it. (E.g. where owner > is root: perhaps 744) You don't need that for a Python module, it only needs to be readable. (But if you do make it executable you can add a shebang line at the top and then run it directly from the command prompt. But since you only want to access the functions within we won't need to do that.) > Either move the file into a directory on your path, or add the directory that > the file is in to your path. Either save the file in a directory in your PYTHONPATH or add the directory you saved it in to your PYTHONPATH > It will now run. It can now be imported. So to use your function, let's call it spam(), in your mymodule.py file: Create a new python script, lets assume its called myfile.py. add the line import mymodule call the function with myVariable = mymodule.spam() Save your new Python script file Execute your new file from Pyhon with $ python /full/path/to/myfile.py There is a full worked example in the Functions and Modules topic in my tutorial... HTH Alan G. Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Aug 21 01:11:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Aug 2011 00:11:46 +0100 Subject: [Tutor] Tkinter: Deleting text when clicking in field. In-Reply-To: <4E500735.30605@gmx.com> References: <4E500735.30605@gmx.com> Message-ID: On 20/08/11 20:12, brandon w wrote: > I worked on this for a long time. I did many searches to fix the many > error messages I was getting and I finally got this to work. I would now > just like to have the text disappear when a person clicks in the box to > type something. How can I do that? > You need to buind the mouse click event to the event handler method. It will not be called unless you tell Tkinter to call it. > from Tkinter import * > > class MyGrid(Frame): > def __init__(self, win=None): > Frame.__init__(self, win) > self.grid() > self.mkWidgets() > > [...snip...] > > self.mytext = StringVar() > self.mytext.set("Enter text here") # This text needs to be deleted upon > clicking in the field. > self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, > width=50) > self.e.grid(row=0, column=0) You need to add a Bind statement to bind a mouse click to a method that clears the text. Remember that everything in a GUI is event driven, so you have to link your code to the events. > > I have created a method to clear the field. > This is not working: > > def clearBox(self): > self.mytext.delete(0, END) > return You need to delete the text in the Entry widget not the StringVar Alternatively you need to set the StringVar to an empty string and wait for the widget to redraw itself. (Or force it to redraw!) Then you need to add a bind statement to tie that method to a mouse click in the Entry. > self.mytext = StringVar(None) > self.mytext.set("Enter text here") > self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, > width=50, command=self.clearBox) That binds the event to the command parameter of the Entry. BUT the Entry widget does not have a command option - I'm surprised you dont get an error complaining about that? So you need to use the bind() function. The bind function specifies the event type and the method to be called. It expects the method to take an additional event argument: It should look something like: # define an event handler def handleEvent(self, event): print "I'm habdling an event" # bind the button-1 click of the Entry to the handler self.e.bind('Button-1', handleEvent) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From thisisonlyatest at gmx.com Sun Aug 21 07:14:02 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sun, 21 Aug 2011 01:14:02 -0400 Subject: [Tutor] Tkinter: Deleting text when clicking in field. In-Reply-To: References: <4E500735.30605@gmx.com> Message-ID: <4E50941A.40806@gmx.com> On 08/20/2011 07:11 PM, Alan Gauld wrote: > On 20/08/11 20:12, brandon w wrote: >> I worked on this for a long time. I did many searches to fix the many >> error messages I was getting and I finally got this to work. I would now >> just like to have the text disappear when a person clicks in the box to >> type something. How can I do that? >> > > You need to buind the mouse click event to the event handler method. > It will not be called unless you tell Tkinter to call it. > >> from Tkinter import * >> >> class MyGrid(Frame): >> def __init__(self, win=None): >> Frame.__init__(self, win) >> self.grid() >> self.mkWidgets() >> >> [...snip...] >> >> self.mytext = StringVar() >> self.mytext.set("Enter text here") # This text needs to be deleted upon >> clicking in the field. >> self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, >> width=50) >> self.e.grid(row=0, column=0) > > You need to add a Bind statement to bind a mouse click to a method > that clears the text. Remember that everything in a GUI is event > driven, so you have to link your code to the events. > >> >> I have created a method to clear the field. >> This is not working: >> >> def clearBox(self): >> self.mytext.delete(0, END) >> return > > You need to delete the text in the Entry widget not the StringVar > Alternatively you need to set the StringVar to an empty string and > wait for the widget to redraw itself. (Or force it to redraw!) > > Then you need to add a bind statement to tie that method to a mouse > click in the Entry. > >> self.mytext = StringVar(None) >> self.mytext.set("Enter text here") >> self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN, >> width=50, command=self.clearBox) > > That binds the event to the command parameter of the Entry. > BUT the Entry widget does not have a command option - I'm surprised > you dont get an error complaining about that? > > So you need to use the bind() function. > The bind function specifies the event type and the method to be > called. It expects the method to take an additional event argument: > It should look something like: > > # define an event handler > def handleEvent(self, event): > print "I'm habdling an event" > > # bind the button-1 click of the Entry to the handler > self.e.bind('Button-1', handleEvent) > > HTH > Thanks again for your help. I'll work on this tomorrow. From dave6502 at gmail.com Sun Aug 21 08:24:06 2011 From: dave6502 at gmail.com (dave selby) Date: Sun, 21 Aug 2011 07:24:06 +0100 Subject: [Tutor] I am trying to read and decode an emails PDF attachment via python, In-Reply-To: References: Message-ID: Did a lot more digging and finally sorted it, sorry for bothering you guys, Cheers Dave On 20 August 2011 10:58, dave selby wrote: > I am trying to read and decode an emails PDF attachment via python, > its a dedicated mailbox, anything emailed there is to be read by the > script, deleted from the mailbox and processed. > > http://pastebin.com/VA1gwWH3 > > def get_next_mail() works AOK, I get a nice long string containing the > next email and PDF data block but when I execute > > msg.is_multipart() > I get False ??? > > And when I execute > msg.get_payload() > I get nothing > > Any ideas anyone, at a guess its because my string is not formatted > correctly, can anyone advise ? > > Cheers > > Dave > > -- > > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From lisi.reisz at gmail.com Sun Aug 21 12:06:25 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 21 Aug 2011 11:06:25 +0100 Subject: [Tutor] Modules and Python tutorial by S. Thurlow - opinions please In-Reply-To: References: <201108201525.15200.lisi.reisz@gmail.com> Message-ID: <201108211106.25345.lisi.reisz@gmail.com> On Saturday 20 August 2011 23:53:53 Alan Gauld wrote: > On 20/08/11 15:25, Lisi wrote: > > ridiculous. I think that I understand how to write a basic function, but > > I can't work out how to save and call it. [snip] > There is a full worked example in the Functions and Modules > topic in my tutorial... Bless you, Alan. Not only is your description great, but it caused me to start to read your tutorial. Bingo. I think I now understand the conceptual problem I had at the core of this. You actually make it clear in your answer in this thread, but I was so bogged down that I didn't take it in. A function is a sub-routine and not a program. That's it. So simple and I have been stuck on this for weeks! Now to start again! When, of course, I may get stuck again. But I think next time I am stuck on something apparently trivial, I'll ask sooner. And the descriptions that you and Steven have given me of how to do it make a lot more sense than the ones I was struggling with. Heartfelt thanks to Alan and Steven. Lisi From lisi.reisz at gmail.com Sun Aug 21 13:57:50 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 21 Aug 2011 12:57:50 +0100 Subject: [Tutor] Where is sys.py? Message-ID: <201108211257.50231.lisi.reisz@gmail.com> If sys.py is a file, it must be somewhere; but I can't find it. Where is it? I would like to look at it. The modules within it must surely be somewhere too. But since I can't find sys, I obviously can't find the modules. Again, I'd like to look at them. In case it is relevant, I am using Python 2.5.2 on Debian 5. Lisi From bermanrl at cfl.rr.com Sun Aug 21 15:39:27 2011 From: bermanrl at cfl.rr.com (R. Berman) Date: Sun, 21 Aug 2011 09:39:27 -0400 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108211257.50231.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> Message-ID: <025f01cc6007$bf568de0$3e03a9a0$@rr.com> > -----Original Message----- > From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Lisi > Sent: Sunday, August 21, 2011 7:58 AM > To: tutor at python.org > Subject: [Tutor] Where is sys.py? > > If sys.py is a file, it must be somewhere; but I can't find it. > Where is it? > I would like to look at it. > > The modules within it must surely be somewhere too. But since I > can't find > sys, I obviously can't find the modules. Again, I'd like to look at > them. > > In case it is relevant, I am using Python 2.5.2 on Debian 5. > > Lisi > Try whereis python.sys Robert -- I am using the free version of SPAMfighter. We are a community of 7 million users fighting spam. SPAMfighter has removed 342 of my spam emails to date. Get the free SPAMfighter here: http://www.spamfighter.com/len The Professional version does not have this message From __peter__ at web.de Sun Aug 21 16:10:06 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 21 Aug 2011 16:10:06 +0200 Subject: [Tutor] Where is sys.py? References: <201108211257.50231.lisi.reisz@gmail.com> Message-ID: Lisi wrote: > If sys.py is a file, it must be somewhere; but I can't find it. Where is > it? I would like to look at it. You are out of luck, there is no sys.py. The sys module is so tightly integrated that Python cannot run without it; it has to be part of the interpreter and is written in C. In general, to see the parts of Python that are written in C you have to download the source distribution, but for an occasional glimpse at a specific module you can also use an URL like http://hg.python.org/cpython/file/2.5/Python/sysmodule.c From thudfoo at gmail.com Sun Aug 21 16:12:43 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sun, 21 Aug 2011 07:12:43 -0700 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108211257.50231.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> Message-ID: <201108210712.43128.thudfoo@gmail.com> On Sunday 2011 August 21 04:57, Lisi wrote: > If sys.py is a file, it must be somewhere; but I can't find it. Where is > it? I would like to look at it. > > The modules within it must surely be somewhere too. But since I can't find > sys, I obviously can't find the modules. Again, I'd like to look at them. > > In case it is relevant, I am using Python 2.5.2 on Debian 5. The source is in C, try locate */Python/sysmodule.c if you have the source for your Python. -- I have seen the future and I am not in it. From lisi.reisz at gmail.com Sun Aug 21 16:43:32 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 21 Aug 2011 15:43:32 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108211257.50231.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> Message-ID: <201108211543.32961.lisi.reisz@gmail.com> On Sunday 21 August 2011 12:57:50 Lisi wrote: > If sys.py is a file, it must be somewhere; but I can't find it. Where is > it? I would like to look at it. > > The modules within it must surely be somewhere too. But since I can't find > sys, I obviously can't find the modules. Again, I'd like to look at them. > > In case it is relevant, I am using Python 2.5.2 on Debian 5. Thanks, all three. At least I now know why I can't find it! Robert - I had already tried various combimations of whereis, python and sys, all to no avail. But I tried your command and looked at every directory and file under the results (and tehre were a lot)! Still to no avail - so I switched from my personal inbox to the Python one - and there we have the explanation. Thanks Peter and "xDog". Lisi From emile at fenx.com Sun Aug 21 17:31:20 2011 From: emile at fenx.com (Emile van Sebille) Date: Sun, 21 Aug 2011 08:31:20 -0700 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108211257.50231.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> Message-ID: On 8/21/2011 4:57 AM Lisi said... > If sys.py is a file, it must be somewhere; but I can't find it. Where is it? > I would like to look at it. > > The modules within it must surely be somewhere too. But since I can't find > sys, I obviously can't find the modules. Again, I'd like to look at them. > > In case it is relevant, I am using Python 2.5.2 on Debian 5. > Modules have a __file__ attribute, but not sys as you've heard. Python 2.6.6 (r266:84292, May 25 2011, 09:51:06) [GCC 3.4.6 20060404 (Red Hat 3.4.6-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.__file__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__file__' >>> import os >>> os.__file__ '/usr/local/lib/python2.6/os.pyc' >>> From joel.preston.626 at gmail.com Sun Aug 21 18:14:37 2011 From: joel.preston.626 at gmail.com (Joel Preston) Date: Sun, 21 Aug 2011 12:14:37 -0400 Subject: [Tutor] Coin Flipping Program Message-ID: Hello Programmers, I am trying to learn Python on my own through a book called "Python Programming for the Absolute Beginner". I am stuck on a challenge at the end of a chapter and I am hoping for a little help. The challenge is to write a program that flips a coin 100 times and tells you the number of heads and tails that come up. So far I can write a program that will flip a coin 100 times but it will only come up tails or heads all 100 times. I have been stuck on this for about 3 days now. I have attached the program and am hoping for some advice. Oh by the way this is Python 3.2 and I am running Window Vista. Thanks in advance, Joel Preston -- Joel Preston Home Again Restorations, L.L.C. 988 Birdwood Drive Orange Park, FL 32073 904-505-3306 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Coin Flip 6.py Type: application/octet-stream Size: 425 bytes Desc: not available URL: From thudfoo at gmail.com Sun Aug 21 18:38:45 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sun, 21 Aug 2011 09:38:45 -0700 Subject: [Tutor] Coin Flipping Program In-Reply-To: References: Message-ID: <201108210938.45627.thudfoo@gmail.com> On Sunday 2011 August 21 09:14, Joel Preston wrote: > Hello Programmers, > > I am trying to learn Python on my own through a book called "Python > Programming for the Absolute Beginner". I am stuck on a challenge at the > end of a chapter and I am hoping for a little help. > > The challenge is to write a program that flips a coin 100 times and tells > you the number of heads and tails that come up. So far I can write a > program that will flip a coin 100 times but it will only come up tails or > heads all 100 times. I have been stuck on this for about 3 days now. I > have attached the program and am hoping for some advice. > Move coin = random.randint(1, 2) inside the "flipping loop". -- I have seen the future and I am not in it. From lisi.reisz at gmail.com Sun Aug 21 19:08:55 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 21 Aug 2011 18:08:55 +0100 Subject: [Tutor] How have I transgressed?? Message-ID: <201108211808.55730.lisi.reisz@gmail.com> I have just received the following.* In what way have I transgressed? I apologise to you all - but as I mentioned, I had been stuck for weeks and am running out of time. And I certainly tried to help myself - I just didn't succeed! Anyhow, if someone will tell me in what way I have transgressed, I'll try harder in future. Thanks, Lisi *Your message for tutor at python.org, the Python programming tutor list, has been received and is being delivered. This automated response is sent to those of you new to the Tutor list, to point out a few resources that can help with answering your own questions, or improve the chances of getting a useful answer from the other subscribers. If your question is something akin to: "I've just heard about Python, and it sounds great! Where can I find out more on how to program with Python?" or: "What's Python?" please read section 1 below. On the other hand, if your question is: "I've heard that Python is good for hacking -- I want to know more!" or "Can you teach me how to break into a computer with Python?" please read section 2 at the bottom of this email. Section 1: ---------- The most comprehensive overview of python.org help resources is at http://www.python.org/Help.html The Python FAQ is available at http://www.python.org/doc/FAQ.html and it has answers to many questions that people ask, possibly including your question. Another wealth of information and experience can be found via the python.org searches, at http://www.python.org/search/ There you'll find comprehensive, easy-to-use searches over the python.org web site and the Python newsgroup, comp.lang.python. Python has an online tutorial, available freely from http://www.python.org/doc/current/tutorial/index.html Finally, when you do send email to the Tutor list, be as clear as you can about the problem, including, when relevant, details like: - Precise error messages, including complete tracebacks - The hardware platform (available in the Python sys module as sys.platform) - The python version (sys.version) - The python search path (sys.path) In general, be specific about what was going on connected with the problem or what specific concept you're having difficulties with. The better the info you provide, the more likely the helpers will be able to glean the answer... There's a HOWTO that shows how to ask "smart" questions to technical folks: http://catb.org/~esr/faqs/smart-questions.html Although it is provocative, it does have some good points, and is an interesting read. Note that no one is paid to read the tutor list or provide answers, and most readers often have other work that demands their attention. Well-posed requests for help are usually answered fairly promptly, but occasionally a request slips by, so if you do not get a response with one or two working days (it's usually quicker than that), please feel free to send a followup, asking whether anyone is working on your question. Anyway, your message is being delivered to the Tutor list as this one is being sent. However, if your question was about as detailed as "Teach me how to program in Python", do not count on an answer -- this email contains all the information you need to start. Come back with a more precise question, and we'll be glad to help. Thanks! From coolankur2006 at gmail.com Sun Aug 21 19:15:12 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Sun, 21 Aug 2011 22:45:12 +0530 Subject: [Tutor] Store the output of os.system Message-ID: Hey I am executing a grep command in my python program using os.system. I want to store the output somewhere but because of GUI's involved (generated using tkinter and pyzenity) I am unable to store my output or the result of the executed grep command in some form. Can you guys tell me how to store the output of a terminal or show the output in a GUI in python?? Thanks in advance. Ankur Aggarwal From emile at fenx.com Sun Aug 21 19:25:44 2011 From: emile at fenx.com (Emile van Sebille) Date: Sun, 21 Aug 2011 10:25:44 -0700 Subject: [Tutor] How have I transgressed?? In-Reply-To: <201108211808.55730.lisi.reisz@gmail.com> References: <201108211808.55730.lisi.reisz@gmail.com> Message-ID: On 8/21/2011 10:08 AM Lisi said... > I have just received the following.* In what way have I transgressed? I > apologise to you all - but as I mentioned, I had been stuck for weeks and am > running out of time. And I certainly tried to help myself - I just didn't > succeed! Anyhow, if someone will tell me in what way I have transgressed, > I'll try harder in future. > > Thanks, > Lisi > > *Your message for tutor at python.org, the Python programming tutor list, > has been received and is being delivered. This automated response is > sent to those of you new to the Tutor list, The sender's email address is verified and those 'new to the list' get this message -- do you have multiple email accounts or possibly typoed in your email address on the message that evoked the 'new' response? Emile From emile at fenx.com Sun Aug 21 19:28:12 2011 From: emile at fenx.com (Emile van Sebille) Date: Sun, 21 Aug 2011 10:28:12 -0700 Subject: [Tutor] Store the output of os.system In-Reply-To: References: Message-ID: On 8/21/2011 10:15 AM ANKUR AGGARWAL said... > Hey > I am executing a grep command in my python program using os.system. I > want to store the output somewhere but because of GUI's involved > (generated using tkinter and pyzenity) I am unable to store my output > or the result of the executed grep command in some form. Can you guys > tell me how to store the output of a terminal or show the output in a > GUI in python?? Instead of os.system, try the commands or subprocess module as appropriate for your version of python. HTH, Emile From alan.gauld at btinternet.com Sun Aug 21 19:34:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Aug 2011 18:34:34 +0100 Subject: [Tutor] Coin Flipping Program In-Reply-To: References: Message-ID: On 21/08/11 17:14, Joel Preston wrote: > tells you the number of heads and tails that come up. So far I can > write a program that will flip a coin 100 times but it will only come up > tails or heads all 100 times. Look again at your code, you only assign a value to coin once, before you enter the loop. > import random > > print('Flip the coin 100 times and see how many times tails come up.') > input('Flip...') > > # Set initial values > > coin = random.randint(1, 2) This is the only assignment. > tries = 0 > > # flipping loop > while tries != 100: In general if you are looping for a fixed number of times its easier to use a for loop: for tries in range(100): > if coin == 1: > print("heads") > else: > print("tails") > > input("Flip again...") You ask the user to flip but you never assign a new value So you need to add an assignment line inside the lop. The easiest way is just to move the existing line above down to the start of the loop code. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lisi.reisz at gmail.com Sun Aug 21 20:06:47 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 21 Aug 2011 19:06:47 +0100 Subject: [Tutor] How have I transgressed?? In-Reply-To: References: <201108211808.55730.lisi.reisz@gmail.com> Message-ID: <201108211906.48009.lisi.reisz@gmail.com> Thanks for the reply, Emile. :-) On Sunday 21 August 2011 18:25:44 Emile van Sebille wrote: > The sender's email address is verified and those 'new to the list' get > this message -- do you have multiple email accounts Yes - but I consistently use the same one for this list, and have checked my recent emails, and all came from the same (correct) address. > or possibly typoed > in your email address on the message that evoked the 'new' response? No - I have checked. So long as it wasn't triggered by a misdemeanour - that was what I was worried about! I have my email client set twice over to be correct for this list. a) it knows that this is a list and what email address I want used for this list and b) I use the default address for this list. Oh - and c) I don't type the address - I just chose which one. I think that it must just remain one of life's little mysteries. :-/ Lisi From delegbede at dudupay.com Sun Aug 21 19:50:47 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sun, 21 Aug 2011 17:50:47 +0000 Subject: [Tutor] Coin Flipping Program In-Reply-To: References: Message-ID: <1156387548-1313949049-cardhu_decombobulator_blackberry.rim.net-796229421-@b5.c12.bise7.blackberry> Hi Joel, Someone has asked this question before and I think it was dealt with. That said, in my opinion, starting out with python 3 reduces the number of assist you can get on the fly. I for one have dealt with this issue before but can't help with the python 3 areas. Have you checked Alan Gauld's website? He dealt with python 3. Sorry Mate. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Joel Preston Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sun, 21 Aug 2011 12:14:37 To: Subject: [Tutor] Coin Flipping Program _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From andreengels at gmail.com Sun Aug 21 21:37:34 2011 From: andreengels at gmail.com (Andre Engels) Date: Sun, 21 Aug 2011 21:37:34 +0200 Subject: [Tutor] How have I transgressed?? In-Reply-To: References: <201108211808.55730.lisi.reisz@gmail.com> Message-ID: On Sun, Aug 21, 2011 at 7:25 PM, Emile van Sebille wrote: > On 8/21/2011 10:08 AM Lisi said... > > I have just received the following.* In what way have I transgressed? I >> apologise to you all - but as I mentioned, I had been stuck for weeks and >> am >> running out of time. And I certainly tried to help myself - I just didn't >> succeed! Anyhow, if someone will tell me in what way I have transgressed, >> I'll try harder in future. >> >> Thanks, >> Lisi >> >> *Your message for tutor at python.org, the Python programming tutor list, >> has been received and is being delivered. This automated response is >> sent to those of you new to the Tutor list, >> > > The sender's email address is verified and those 'new to the list' get this > message -- do you have multiple email accounts or possibly typoed in your > email address on the message that evoked the 'new' response? > I have gotten it several times on this address; It seems the reaction is also given if you send a message after having been absent for a while. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Aug 21 22:03:25 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 21 Aug 2011 15:03:25 -0500 Subject: [Tutor] How have I transgressed?? In-Reply-To: References: <201108211808.55730.lisi.reisz@gmail.com> Message-ID: Same here as Andre said. I've gotten that email probably a dozen times by now. It's based on an amount of absence I believe. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Aug 21, 2011, at 2:37 PM, Andre Engels wrote: > On Sun, Aug 21, 2011 at 7:25 PM, Emile van Sebille wrote: > On 8/21/2011 10:08 AM Lisi said... > > I have just received the following.* In what way have I transgressed? I > apologise to you all - but as I mentioned, I had been stuck for weeks and am > running out of time. And I certainly tried to help myself - I just didn't > succeed! Anyhow, if someone will tell me in what way I have transgressed, > I'll try harder in future. > > Thanks, > Lisi > > *Your message for tutor at python.org, the Python programming tutor list, > has been received and is being delivered. This automated response is > sent to those of you new to the Tutor list, > > The sender's email address is verified and those 'new to the list' get this message -- do you have multiple email accounts or possibly typoed in your email address on the message that evoked the 'new' response? > > I have gotten it several times on this address; It seems the reaction is also given if you send a message after having been absent for a while. > > -- > Andr? Engels, andreengels at gmail.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 21 22:26:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Aug 2011 21:26:21 +0100 Subject: [Tutor] Store the output of os.system In-Reply-To: References: Message-ID: On 21/08/11 18:15, ANKUR AGGARWAL wrote: > Hey > I am executing a grep command in my python program using os.system. I guess the first question is why? Python's re module can do pretty much anything that grep can do and do it inside your program with no extra processes being started. Why not just use the re module? > or the result of the executed grep command in some form. Can you guys > tell me how to store the output of a terminal or show the output in a > GUI in python?? If you really must start an external program then the best solution these days is to use the subprocess module. The system() call is very rarely the best solution for anything other than a very basic fire 'n forget command. The subprocess documentation gives lots of example usage, one of them should be right for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From guandalino at gmail.com Sun Aug 21 23:35:48 2011 From: guandalino at gmail.com (D. Guandalino) Date: Sun, 21 Aug 2011 23:35:48 +0200 Subject: [Tutor] Please explain TypeError Message-ID: Python documentation says: > exception TypeError > > Raised when an operation or function is applied to an object of > inappropriate type. The associated value is a string giving details > about the type mismatch. For example: >>> 'foo' + (1, 2) Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'tuple' objects So far so good. But why the following code gives a TypeError too? >>> class C(object): ... def __init__(self): ... pass ... >>> C(1) Traceback (most recent call last): File "", line 1, in TypeError: __init__() takes exactly 1 argument (2 given) I'm having hard times understanding why a TypeError is raised here. Could you explain? Thanks. From guandalino at gmail.com Mon Aug 22 00:15:02 2011 From: guandalino at gmail.com (D. Guandalino) Date: Mon, 22 Aug 2011 00:15:02 +0200 Subject: [Tutor] Please help understanding unittest fixtures Message-ID: Suppose I have this TestCase class. class C(TestCase): def setUp(): # very time consuming and resources intensive stuffs. pass def test_A(self): pass def test_B(self): pass def test_C(self): pass The unittest docs says: > Each instance of the TestCase will only be used to run a single test > method, so a new fixture is created for each test. Does this mean that the setUp() method, which is called to prepare the test fixture, get called for test_A, test_B and test_C? In this case is there a way to force just one setUp() call? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Aug 22 00:17:29 2011 From: d at davea.name (Dave Angel) Date: Sun, 21 Aug 2011 18:17:29 -0400 Subject: [Tutor] Please explain TypeError In-Reply-To: References: Message-ID: <4E5183F9.6050004@davea.name> On 08/21/2011 05:35 PM, D. Guandalino wrote: > Python documentation says: > >> exception TypeError >> >> Raised when an operation or function is applied to an object of >> inappropriate type. The associated value is a string giving details >> about the type mismatch. > For example: > >>>> 'foo' + (1, 2) > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot concatenate 'str' and 'tuple' objects > > So far so good. But why the following code gives a TypeError too? > >>>> class C(object): > ... def __init__(self): > ... pass > ... >>>> C(1) > Traceback (most recent call last): > File "", line 1, in > TypeError: __init__() takes exactly 1 argument (2 given) > > I'm having hard times understanding why a TypeError is raised here. > Could you explain? > You didn't supply a parameter in the __init__() to receive the value of 1. The self argument is automatically supplied by Python for all ordinary method calls including initial object construction. So when you say C(1) you're actually going to get 2 arguments in the __init__() call. Add another parm to the definition: def __init__(self, startvalue): pass -- DaveA From guandalino at gmail.com Mon Aug 22 00:27:59 2011 From: guandalino at gmail.com (D. Guandalino) Date: Mon, 22 Aug 2011 00:27:59 +0200 Subject: [Tutor] Please explain TypeError In-Reply-To: <4E5183F9.6050004@davea.name> References: <4E5183F9.6050004@davea.name> Message-ID: On 22 August 2011 00:17, Dave Angel wrote: > On 08/21/2011 05:35 PM, D. Guandalino wrote: > >> Python documentation says: >> >> exception TypeError >>> >>> Raised when an operation or function is applied to an object of >>> inappropriate type. The associated value is a string giving details >>> about the type mismatch. >>> >> >> > You didn't supply a parameter in the __init__() to receive the value of 1. > The self argument is automatically supplied by Python for all ordinary > method calls including initial object construction. So when you say C(1) > you're actually going to get 2 arguments in the __init__() call. > > Add another parm to the definition: > > def __init__(self, startvalue): > pass > Thanks and apologies for not being clear. I missed to say that I'm more interested in understanding which error I did with types (given that a TypeError is raised) than in fixing the code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Aug 22 00:31:38 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 21 Aug 2011 23:31:38 +0100 Subject: [Tutor] Please explain TypeError In-Reply-To: References: Message-ID: On 21 August 2011 22:35, D. Guandalino wrote: > >>> class C(object): > ... def __init__(self): > ... pass > ... > >>> C(1) > Traceback (most recent call last): > File "", line 1, in > TypeError: __init__() takes exactly 1 argument (2 given) > > I'm having hard times understanding why a TypeError is raised here. > Could you explain? > The more obvious answer was given by David, but I'd like to also add that the reason why Python complains in this instance with *TypeError* (as opposed to say something like "ArgumentError" or "ValueError" imagining for the moment such things existed) is becuase, looking function objects, fn(a) is type-incompatible with fn(a,b). Differently put, the argument list is part of the type of a function, and the different argument lists makes the expected function and the actual provided incompatible, hence Python raises TypeError. (Note this is somewhat speculative on my part so take it for what it's worth.) Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 22 01:03:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Aug 2011 09:03:48 +1000 Subject: [Tutor] How have I transgressed?? In-Reply-To: <201108211808.55730.lisi.reisz@gmail.com> References: <201108211808.55730.lisi.reisz@gmail.com> Message-ID: <4E518ED4.3020501@pearwood.info> Lisi wrote: > I have just received the following.* In what way have I transgressed? I > apologise to you all - but as I mentioned, I had been stuck for weeks and am > running out of time. And I certainly tried to help myself - I just didn't > succeed! Anyhow, if someone will tell me in what way I have transgressed, > I'll try harder in future. > > Thanks, > Lisi > > *Your message for tutor at python.org, the Python programming tutor list, > has been received and is being delivered. This automated response is [...] I get these occasionally. As far as I can tell, the mailing list software gets confused sometimes and thinks you are posting for the first time, when you're not. It's annoying but meaningless. -- Steven From steve at pearwood.info Mon Aug 22 01:13:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Aug 2011 09:13:37 +1000 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108211257.50231.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> Message-ID: <4E519121.8080604@pearwood.info> Lisi wrote: > If sys.py is a file, it must be somewhere; but I can't find it. Where is it? > I would like to look at it. Others have already answered this, but consider how you might explore the answer at the interactive interpreter: >>> import os >>> os.__file__ '/usr/lib/python2.5/os.pyc' >>> import sys >>> sys.__file__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__file__' So the sys module has no __file__ attribute, and therefore there is no sys.py. Looking deeper: >>> import inspect >>> inspect.getfile(sys) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/inspect.py", line 347, in getfile raise TypeError('arg is a built-in module') TypeError: arg is a built-in module Hmmm, not the most user-friendly of messages ("arg" is a built-in module? how about *naming* it, all modules have a name!) but the answer is clear: sys is part of the Python virtual machine itself, and does not live in a file. (Except, of course, that Python itself is compiled from files, and the code creating sys will be in those.) Furthermore: >>> import math >>> math.__file__ '/usr/lib/python2.5/lib-dynload/mathmodule.so' So here we have a module that does live in a file, but it is a C library, not a .py python file. (On Windows, it may be a .dll.) > The modules within it must surely be somewhere too. But since I can't find > sys, I obviously can't find the modules. Again, I'd like to look at them. I don't understand what you mean by "modules within it". Do you mean sys.modules? That's easy: >>> sys.modules['inspect'] -- Steven From steve at pearwood.info Mon Aug 22 01:19:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Aug 2011 09:19:19 +1000 Subject: [Tutor] Please help understanding unittest fixtures In-Reply-To: References: Message-ID: <4E519277.1090707@pearwood.info> D. Guandalino wrote: > Suppose I have this TestCase class. > > class C(TestCase): > def setUp(): > # very time consuming and resources intensive stuffs. > pass > > def test_A(self): > pass > def test_B(self): > pass > def test_C(self): > pass > > The unittest docs says: > >> Each instance of the TestCase will only be used to run a single test >> method, so a new fixture is created for each test. > > > Does this mean that the setUp() method, which is called to prepare the test > fixture, get called for test_A, test_B and test_C? That's easy enough to find out: def setUp(self): print("calling setUp") ... See how many times "calling setUp" is printed. > In this case is there a > way to force just one setUp() call? I don't know if this is the best way, but the first way that comes to mind is this: class C(TestCase): initialised = False def setUp(self): if self.initialised: return # Make sure you save the flag on the class, not the instance! self.__class__.initialised = True ... -- Steven From steve at pearwood.info Mon Aug 22 01:35:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Aug 2011 09:35:07 +1000 Subject: [Tutor] Please explain TypeError In-Reply-To: References: Message-ID: <4E51962B.1070902@pearwood.info> D. Guandalino wrote: >>>> class C(object): > ... def __init__(self): > ... pass > ... >>>> C(1) > Traceback (most recent call last): > File "", line 1, in > TypeError: __init__() takes exactly 1 argument (2 given) > > I'm having hard times understanding why a TypeError is raised here. > Could you explain? Because it is an error involving a type (class). Type C doesn't take any arguments. You gave it an argument. Therefore, it's an error regarding a type, hence, a TypeError. If you feel that this is a fairly dubious line of reasoning, I agree with you! I think that such failures would be best given their own dedicated exception for "wrong number of arguments". But they don't: >>> import math >>> math.sin(1.1, 2.2) Traceback (most recent call last): File "", line 1, in TypeError: sin() takes exactly 1 argument (2 given) No types involved here, math.sin is just a function. Oh well. -- Steven From __peter__ at web.de Mon Aug 22 10:35:10 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Aug 2011 10:35:10 +0200 Subject: [Tutor] Please help understanding unittest fixtures References: <4E519277.1090707@pearwood.info> Message-ID: Steven D'Aprano wrote: > D. Guandalino wrote: >> In this case is there a >> way to force just one setUp() call? > > > I don't know if this is the best way, but the first way that comes to > mind is this: > > > class C(TestCase): > initialised = False > def setUp(self): > if self.initialised: > return > # Make sure you save the flag on the class, not the instance! > self.__class__.initialised = True > ... Python 2.7 and 3.2 support setUpClass()/tearDownClass() classmethods, see http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass From lisi.reisz at gmail.com Mon Aug 22 15:45:29 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 22 Aug 2011 14:45:29 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: <4E519121.8080604@pearwood.info> References: <201108211257.50231.lisi.reisz@gmail.com> <4E519121.8080604@pearwood.info> Message-ID: <201108221445.29592.lisi.reisz@gmail.com> On Monday 22 August 2011 00:13:37 Steven D'Aprano wrote: > > The modules within it must surely be somewhere too. ?But since I can't > > find sys, I obviously can't find the modules. ?Again, I'd like to look at > > them. > > I don't understand what you mean by "modules within it". The problem may be that I have again failed to understand. As I understand it, I can, should I wish to do so, write and save a subroutine that I wish to reuse rather than write the same subroutine out multiple times. The book also says that one can import sys and then run the various commands within it. It also appears to say that sys is a file, and I thought that it said sys.py existed. Clearly, it didn't since it doesn't. Anyhow, I therefore thought - erroneously - that if there could be commands in sys, then it must be possible to store subroutines in some sort of "envelope" so that I could import the "envelope" and call the subroutines as I wanted them. Otherwise, storing short subroutines would appear to me to be a waste of time and effort. By the time one has imported the subroutine and then run it, and done this for every one of a number of short subroutines, it would be quicker and easier just to run them when needed. So I wanted to look at how Python itself does it, so that I could copy it. a) I am clearly barking up a non-existent tree and b) the sooner I forget completely about the text that I was working from (I am still turning over in my mind the exercise I got hung up on) and focus only on Alan's, the sooner I am going to make some kind of progress!! Lisi From emile at fenx.com Mon Aug 22 16:09:45 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 22 Aug 2011 07:09:45 -0700 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108221445.29592.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> <4E519121.8080604@pearwood.info> <201108221445.29592.lisi.reisz@gmail.com> Message-ID: On 8/22/2011 6:45 AM Lisi said... > On Monday 22 August 2011 00:13:37 Steven D'Aprano wrote: >>> The modules within it must surely be somewhere too. But since I can't >>> find sys, I obviously can't find the modules. Again, I'd like to look at >>> them. >> >> I don't understand what you mean by "modules within it". > > The problem may be that I have again failed to understand. Actually, sys retains a reference to all imported modules in sys.modules and that gives a pretty good idea of where stuff comes from(tm). :) >>> from pprint import pprint as pp >>> pp(sys.modules) {'UserDict': , '__builtin__': , '__main__': , '_abcoll': , '_codecs': , '_functools': , '_locale': , '_sre': , '_warnings': , 'abc': , 'cStringIO': , 'codecs': , 'copy_reg': , 'encodings': , 'encodings.__builtin__': None, 'encodings.aliases': , 'encodings.codecs': None, 'encodings.cp1252': , 'encodings.cp437': , 'encodings.encodings': None, 'errno': , 'exceptions': , 'functools': , 'genericpath': , 'linecache': , 'locale': , 'nt': , 'ntpath': , 'operator': , 'os': , 'os.path': , 'pprint': , 're': , 'signal': , 'site': , 'sre_compile': , 'sre_constants': , 'sre_parse': , 'stat': , 'sys': , 'types': , 'warnings': , 'zipimport': } From lisi.reisz at gmail.com Mon Aug 22 16:18:53 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 22 Aug 2011 15:18:53 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> Message-ID: <201108221518.53590.lisi.reisz@gmail.com> On Monday 22 August 2011 15:09:45 Emile van Sebille wrote: > Actually, sys retains a reference to all imported modules in sys.modules > and that gives a pretty good idea of where stuff comes from(tm). ?:) [snip interesting file] Thanks, Emile. :-) Lisi From susana.delgado_s at utzmg.edu.mx Mon Aug 22 17:21:10 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 22 Aug 2011 10:21:10 -0500 Subject: [Tutor] Making a Python Window Message-ID: Hello List!! I want to start desingning and developing python interfaces, but I don't know what library or tool can help me to accomplish my goal. I have installed the 2.6.6 python interpreter version, my operative system is Windows XP. The interfaces I want to create will be very simple, just to select a directory, entry some text, etc. What will be the best option? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Mon Aug 22 17:27:52 2011 From: norman at khine.net (Norman Khine) Date: Mon, 22 Aug 2011 17:27:52 +0200 Subject: [Tutor] return all the days between two dates using the calendar module Message-ID: Hello, I have this code http://pastie.org/2411735 which basically reads a CSV file, takes the date field and then for each day executes an SQL query to pull the amount of orders that have been generated. My issue I have is that on the back-office of the e-commerce package the total orders for the same range of time returns different amount, even though the SQL is correct. One possible error may occur from the fact that I am using the CSV file for the date range, rather than the calendar module, and I am unsure how to return the list of dates for a given range. So in line 72, rather then using the dates in the CSV file I would like to build this list from the calendar module. I got this, http://pastie.org/2411864 but this just adds a day and is not 100% precise. Any advice much appreciated. Norman -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From alan.gauld at btinternet.com Mon Aug 22 18:31:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Aug 2011 17:31:41 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108221445.29592.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> <4E519121.8080604@pearwood.info> <201108221445.29592.lisi.reisz@gmail.com> Message-ID: On 22/08/11 14:45, Lisi wrote: >> I don't understand what you mean by "modules within it". > > The problem may be that I have again failed to understand. > > As I understand it, I can, should I wish to do so, write and save a subroutine > that I wish to reuse rather than write the same subroutine out multiple > times. That's correct > The book also says that one can import sys and then run the various commands > within it. It also appears to say that sys is a file, and I thought that it > said sys.py existed. Clearly, it didn't since it doesn't. I hope that's not my tutorial you are reading? :-) If so, you missed the bit in parentheses: --------------- It is almost like making a copy the contents of sys.py into our program, like a cut n' paste operation. (it's not really like that but the concept is similar. In fact sys is a special kind of module that doesn't actually have a sys.py file, but we will ignore that for now!) ---------------- > Anyhow, I therefore thought - erroneously - that if there could be commands in > sys, then it must be possible to store subroutines in some sort of "envelope" > so that I could import the "envelope" and call the subroutines as I wanted > them. Otherwise, storing short subroutines would appear to me to be a waste > of time and effort. By the time one has imported the subroutine and then run > it, and done this for every one of a number of short subroutines, it would be > quicker and easier just to run them when needed. Now I'm confused. There can be functions inside a module but not commands, they are technically something different and only exist within the Python interpreter itself. And you can access those functions from the module after you have imported it. I'm not sure what you mean by an envelope though? The module is the envelope... And I don't understand the bit about the time taken for short routines? Do you mean the time taken to access them in terms of typing time? Or in terms of execution time? It is faster to import than the time it takes to retype a function unless the function is only a simple expression. def foo(x): return x+1 is 22 characters. If saved in a module called foo.py it can be used with import foo Which is 10 characters. and used with foo.foo(5) which is only 4 extra characters, that's a lot less than retyping the definition. And if you expect to type foo. a lot then use: from foo import foo which is still only 19 characters, less than the definition. So even for this trivially simple case its still faster to put foo into a module... > So I wanted to look at how Python itself does it, so that I could copy it. > > a) I am clearly barking up a non-existent tree and b) the sooner I forget > completely about the text that I was working from (I am still turning over in > my mind the exercise I got hung up on) and focus only on Alan's, the sooner I > am going to make some kind of progress!! There seems to be some strange terminology creeping in but whether that's down to your text (looks like its not mine! :-) or just your own preconceptions I'm not sure. One advantage of using mine is that you know where to find me if you don't understand something! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Aug 22 18:37:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Aug 2011 17:37:24 +0100 Subject: [Tutor] Making a Python Window In-Reply-To: References: Message-ID: On 22/08/11 16:21, Susana Iraiis Delgado Rodriguez wrote: > I want to start desingning and developing python interfaces, but I don't > know what library or tool can help me to accomplish my goal. Three are pros and cons to all the different options available. My personal recommendation is to use Tkinter, purely because it comes with Python and is one of the easiest to learn. wxPython and PyQt and pyGTK are all valid alternatives but you need to download and install them. Tkinter comes in the standard library. > Windows XP. The interfaces I want to create will be very simple, just to > select a directory, entry some text, etc. You might find easyGUI is sufficient for your needs but its not a full GUI tool, it just makes using Python in a GUI environment slightly more user friendly. Personally I'd stick with Tkinter. You can find a short introduction to GUI programming in my tutorial, and it covers Tkinter and a short comparative example using wxPython. The latter is definitely a better bet if you want to move on to more sophisticated UIs, especially if you want to include features like printing (surprisingly difficult on Windows!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mnshtb at gmail.com Mon Aug 22 18:42:35 2011 From: mnshtb at gmail.com (Michael Scharf) Date: Mon, 22 Aug 2011 12:42:35 -0400 Subject: [Tutor] Where to direct non-language questions? In-Reply-To: <4E462EA0.9050206@pearwood.info> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7951A86@EMARC112VS01.exchad.jpmchase.net> <4E462EA0.9050206@pearwood.info> Message-ID: On Sat, Aug 13, 2011 at 3:58 AM, Steven D'Aprano wrote: > Michael Scharf wrote: >> >> Sent: Friday, August 12, 2011 3:54 PM >> >> Hi List, >> >> I'm am not quite at the point of needing this, but where would I go to >> ask a question like "Why is the OpenCalais Python API not returning >> all fields when I do x or y" ?or "Has anyone built their own Python >> API for OpenCalais"? ?Stack Overflow? Or is there something >> Python-specific? > > Something as specific as the first question is best asked on whatever forum > the OpenCalais Python library makes available: a mailing list, a bug > tracker, the author's personal email, an IRC channel. The second question > should be asked on whatever forums specialise in OpenCalais. > > Failing that, you could try comp.lang.python, which tends to have a lot more > people that here. If you don't have access to Usenet, it is also available > on python-list at python.org. > > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thank you, Steven, and Alan. From susana.delgado_s at utzmg.edu.mx Mon Aug 22 18:51:08 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 22 Aug 2011 11:51:08 -0500 Subject: [Tutor] Making a Python Window In-Reply-To: References: Message-ID: Hello Alan!! Thank you for tha advice! I'll look at your tutorial, and test the options you're giving to me. Thank you 2011/8/22 Alan Gauld > On 22/08/11 16:21, Susana Iraiis Delgado Rodriguez wrote: > > I want to start desingning and developing python interfaces, but I don't >> know what library or tool can help me to accomplish my goal. >> > > Three are pros and cons to all the different options available. > > My personal recommendation is to use Tkinter, purely because it comes with > Python and is one of the easiest to learn. > > wxPython and PyQt and pyGTK are all valid alternatives but you need to > download and install them. Tkinter comes in the standard library. > > > Windows XP. The interfaces I want to create will be very simple, just to >> select a directory, entry some text, etc. >> > > You might find easyGUI is sufficient for your needs but its not a full GUI > tool, it just makes using Python in a GUI environment slightly more user > friendly. > > Personally I'd stick with Tkinter. > > You can find a short introduction to GUI programming in my tutorial, and it > covers Tkinter and a short comparative example using wxPython. > The latter is definitely a better bet if you want to move on to more > sophisticated UIs, especially if you want to include features like printing > (surprisingly difficult on Windows!) > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Mon Aug 22 19:38:11 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 22 Aug 2011 18:38:11 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> Message-ID: <201108221838.11693.lisi.reisz@gmail.com> On Monday 22 August 2011 17:31:41 Alan Gauld wrote: > Now I'm confused. Yes, I'm afraid that _I_ was very confused. I am gradually getting the mess in my head disentangled. > There can be functions inside a module but not commands, they are > technically something different and only exist within the Python > interpreter itself. And you can access those functions from the module > after you have imported it. > > I'm not sure what you mean by an envelope though? > The module is the envelope... By "envelope" I meant container, because I was afraid of misusing the correct technical terms. I am still very confused by the terminology. Having been told that modules, functions and methods are just different names for the same thing, that commands are really also the same thing and having had them called yet a fifth thing in order "not to confuse you" (ouch!!) I am in a right muddle. What I am doing at the moment is trying to sort out the muddle in my own head. You have no idea what a relief it was to be told (by you Alan in your text) that a function is a sub-routine. I know what a sub-routine is! And I shall just go on asking questions until I have got the whole thing disentangled in my head. Sorry, everybody. (Unlearning something is much harder than learning it.) Alan, I did enjoy playing around with address books, which I can see have some point, instead of chasing bears, lollipops and flowers, or whatever it was. :-( So now, can anyone suggest an example of a module to look at? (Preferably with some subroutines inside).It is clearly NOT just another name for function or method. I imagine that there are some on the Internet? > And I don't understand the bit about the time taken for short routines? > Do you mean the time taken to access them in terms of typing time? Or in > terms of execution time? It is faster to import than the time it takes > to retype a function unless the function is only a simple expression. I hadn't actually counted the keystrokes. I stand corrected. But saving 6 keystrokes is still a fairly pointless thing to do. If several subroutines can be stored in a module and imported together, then that is quite another matter. Lisi From norman at khine.net Mon Aug 22 19:46:17 2011 From: norman at khine.net (Norman Khine) Date: Mon, 22 Aug 2011 19:46:17 +0200 Subject: [Tutor] return all the days between two dates using the calendar module In-Reply-To: References: Message-ID: ok ignore, this works def date_range(start_date, end_date): r = (end_date+datetime.timedelta(days=1)-start_date).days return [start_date+datetime.timedelta(days=i) for i in range(r)] On Mon, Aug 22, 2011 at 5:27 PM, Norman Khine wrote: > Hello, > I have this code http://pastie.org/2411735 which basically reads a CSV > file, takes the date field and then for each day executes an SQL query > to pull the amount of orders that have been generated. > > My issue I have is that on the back-office of the e-commerce package > the total orders for the same range of time returns different amount, > even though the SQL is correct. > > One possible error may occur from the fact that I am using the CSV > file for the date range, rather than the calendar module, and I am > unsure how to return the list of dates for a given range. So in line > 72, rather then using the dates in the CSV file I would like to build > this list from the calendar module. > > I got this, http://pastie.org/2411864 but this just adds a day and is > not 100% precise. > > Any advice much appreciated. > > Norman > > -- > ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? > ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? > ?q s,??? ??? > %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or > chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) > -- ??? ?o? ?u???d ??,no? ?ou pu? ???o?? ? ?oo? ? ???? s? '?ln?????p s? ???? ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo? ?q s,??? ??? %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From steve at pearwood.info Mon Aug 22 20:55:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 23 Aug 2011 04:55:02 +1000 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108221838.11693.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> Message-ID: <4E52A606.1010803@pearwood.info> Lisi wrote: > By "envelope" I meant container, because I was afraid of misusing the correct > technical terms. I am still very confused by the terminology. Having been > told that modules, functions and methods are just different names for the > same thing, that commands are really also the same thing and having had them > called yet a fifth thing in order "not to confuse you" (ouch!!) I am in a > right muddle. Ayyeee!!!! You have my sympathy! Okay, let's start with the basics. Here's a small piece of simple Python code, to count down from ten: for i in range(10, 0, -1): print(i) print("Lift off!") If you type that in the interactive interpreter, and hit Enter, Python will execute that code and print 10 9 8 ... 2 1 Lift off! Suppose you want to do a count-down again. In the interpreter, you would have to type out the whole thing again. This is annoying and frustrating -- imagine if you wanted to run it a thousand times. So instead, we can make a re-usable, named, piece of code: a function. def countdown(): for i in range(10, 0, -1): print(i) print("Lift off!") If you type that in, once, it defines a reusable piece of code called "countdown". Now you can run that code as many times as you like, by typing: countdown() and then hitting Enter. Much simpler, with much less chance of error. Note that the parentheses are required. Without the round brackets, the code inside the function won't be run. (Methods are very similar to functions. At the most basic level, we can pretend that a method is just a function that comes stuck to something else. Don't worry about methods for now.) But the problem here is that the countdown function is not permanent. If you exit the interpreter, and start again, it will be lost for good. The solution is to save the function in a .py file -- a module. So in your text editor, type def countdown(): for i in range(10, 0, -1): print(i) print("Lift off!") in the file, save the file as "example.py". This becomes a module. A module can contain any Python code you like: one line or a thousand, one function or a hundred functions, or anything else. Then, later, you can restart the Python interpreter, give the command: from example import countdown and use countdown as if you had just typed it in by hand. Sometimes people will use "function" and "command" interchangeably. I don't like this. Commands (also known as statements) are always built-in to Python and operate as *instructions* to the interpreter. There are only a few: import ... from ... import ... def class del print (Python 2 only, in Python 3 it becomes a function) are the main ones. (There may be a few more I have missed.) Such commands generally don't use parentheses, except for grouping items. Functions always require parentheses. They may be built-in, such as len, or you can write your own, using the def command. Functions also always return a result, so you can do this: x = some_function(a, b, c) Commands don't. You can't say: x = del a, b, c because del doesn't return anything. Since it doesn't return anything, you can't save the result in x. (Aside: you can create functions that mimic commands by returning the special value None. That's used for functions which are intended to not return a value, but since Python requires functions to return something, they return the special value None to mean "ignore this, it's nothing". But they're still functions, and they still return something: the special value None.) So, summary: * Commands are built-in Python instructions; * Sometimes also known as "statements". * They take actions, but don't return a result. * "Command" is not an official Python term, so some people may disagree with me! * Functions may be built-in, or defined by the user. * Functions always return something. * Functions can mimic commands by returning None. I call these "procedures", copying the language Pascal. * Methods are related to functions. * A module is a container that holds functions and any other values you like. * Modules are NOT functions, although they can hold functions. * Modules usually are loaded from .py files on your disk. * When you import the module, Python runs the code inside the file, builds a module, and makes the module appear in the interpreter. * Some special modules are built-in to the Python compiler, and don't exist in a .py file. * Other modules come from DLLs or .so files, and are written in C. > So now, can anyone suggest an example of a module to look at? (Preferably > with some subroutines inside).It is clearly NOT just another name for > function or method. I imagine that there are some on the Internet? The Python standard library consists of 200 or so Python files, all of which can be opened in a text editor and read or printed for study. (Be careful not to make modifications to the files, since you risk breaking them and preventing Python from working correctly.) Are you using Windows or Linux or Mac? On my Linux system, I can look inside: /usr/lib/python2.5/ and see the Python modules. -- Steven From ramit.prasad at jpmorgan.com Mon Aug 22 21:06:40 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 22 Aug 2011 15:06:40 -0400 Subject: [Tutor] file fetcher class object through http In-Reply-To: <4E4F14F7.8040709@pearwood.info> References: <4E4EBFCB.1020601@gmail.com> <4E4F14F7.8040709@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEA865@EMARC112VS01.exchad.jpmchase.net> >Such tools already exist, although they may not be written in Python. In >particular, google on "wget" or "curl" for two very well-known >industrial-strength tools for downloading files from the web (and other >places). If you just want something that works, I recommend you learn >how to use those tools rather than re-inventing the wheel. http://pycurl.sourceforge.net/ <- Python interface for curl. I have never used it, but it would probably do what you want. Normally I use os.system with wget, but it is a quick dirty hack. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Mon Aug 22 22:11:51 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 22 Aug 2011 16:11:51 -0400 Subject: [Tutor] methods vs. functions In-Reply-To: <4E52A606.1010803@pearwood.info> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> <4E52A606.1010803@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> Steven D'Aprano wrote: >(Methods are very similar to functions. At the most basic level, we can >pretend that a method is just a function that comes stuck to something >else. Don't worry about methods for now.) Can someone please explain the difference between methods and functions? Thanks, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From theirda at gmail.com Mon Aug 22 23:05:49 2011 From: theirda at gmail.com (TheIrda) Date: Mon, 22 Aug 2011 23:05:49 +0200 Subject: [Tutor] methods vs. functions In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> <4E52A606.1010803@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> Message-ID: Well, my understanding is that function are used in procedural programmming to make the code reusable, and to divide the bigger problem in a serie of smaller ones. Methods are used in OOP, and mainly are the actions taht objects can perform. Thay have a very similar syntax in python, but the concept is quite different. In the procedural programming you have the code that manipulare date to get the result, while in OOP you have objects that act through methods to get teh result. At least this is my understanding :) 2011/8/22 Prasad, Ramit > Steven D'Aprano wrote: > >(Methods are very similar to functions. At the most basic level, we can > >pretend that a method is just a function that comes stuck to something > >else. Don't worry about methods for now.) > > Can someone please explain the difference between methods and functions? > > Thanks, > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Mon Aug 22 23:23:09 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 22 Aug 2011 22:23:09 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: <4E52A606.1010803@pearwood.info> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> <4E52A606.1010803@pearwood.info> Message-ID: <201108222223.09377.lisi.reisz@gmail.com> Thanks, Steven, for an extremely helpful email. I _think_ that I have now grasped it; tho' teh proof of teh pudding is in the eating. :-/ On Monday 22 August 2011 19:55:02 Steven D'Aprano wrote: > Lisi wrote: [snip] > Are you using Windows or Linux or Mac? Linux Debian 6. > On my Linux system, I can look inside: > > /usr/lib/python2.5/ and on mine. > and see the Python modules. Thanks again, Steven. Lisi From waynejwerner at gmail.com Mon Aug 22 23:49:01 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 22 Aug 2011 16:49:01 -0500 Subject: [Tutor] methods vs. functions In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> <4E52A606.1010803@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Mon, Aug 22, 2011 at 3:11 PM, Prasad, Ramit wrote: > Steven D'Aprano wrote: > >(Methods are very similar to functions. At the most basic level, we can > >pretend that a method is just a function that comes stuck to something > >else. Don't worry about methods for now.) > > Can someone please explain the difference between methods and functions? > > Thanks, > Ramit > You could define a function as a reusable section of related code. Technically speaking, it doesn't have to be related, but that's bad programming. A method is a section of related code that is attached to related data. For instance, say you have a string that you would like to reverse. How would you do it, if Python didn't have batteries included? Here's the functional way: def string_reverse(string): return_string = "" for x in xrange(len(string)-1, -1, -1): # range in Python 3.x return_string += string[x] return return_string mystring = "Norwegian Blue" print(string_reverse(mystring)) However, if you wanted to view strings as objects - "things" if you will, you can create a class: class String: def __init__(self, startvalue=""): self.value = startvalue def reverse(self): self.value = self.value[::-1] # Using slicing mystring = String("A Slug") mystring.reverse() print(mystring.value) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Tue Aug 23 00:51:10 2011 From: modulok at gmail.com (Modulok) Date: Mon, 22 Aug 2011 16:51:10 -0600 Subject: [Tutor] methods vs. functions In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> <4E52A606.1010803@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7DEAA18@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 8/22/11, Prasad, Ramit wrote: > Steven D'Aprano wrote: >>(Methods are very similar to functions. At the most basic level, we can >>pretend that a method is just a function that comes stuck to something >>else. Don't worry about methods for now.) > > Can someone please explain the difference between methods and functions? > > Thanks, > Ramit At the most basic level, they're the same. If you have a named, stand-alone section of code that (optionally) operates on some argument passed to it, it's called a function. If you have the same exact code, but you group it together into a named unit along with the data it (optionally) operates on, it's called a method. Technically in Python, they're both objects, both callables and can be called in similar ways. The distinction is quite minimal. Here's a few examples: # A function that expects the first argument to be some object it operates on. # This is just like a method, except it hasn't been declared within any class. # Therefore, it's called a function: def setx(foo): foo.x = 1 # The same exact thing again, but declared in a 'Bar' class. Now it's # called a method. Normally the first parameter to every instance method is # named 'self', (A convention you should adhere to.) To make this example # clearer, however, I use the name 'foo' instead just like the last example: class Bar(object): def setx(foo): foo.x = 1 The call itself is a little different: # As a function you must pass the arguments: a = Bar() setx(a) #<-- Explicitly pass the object as an argument. # As a method the first argument is implied: a = Bar() a.setx() #<-- First argument is passed automatically for you. That said, you could also call a method as if it were a function living in the Bar namespace: a = Bar() Bar.setx(a) You can even declare a function within a class that *doesn't* operate on any instance of the class. Just like an ordinary function, you must pass all arguments. This is called a static method and is declared with the '@staticmethod' decorator: class Baz(object): @staticmethod def bonzo(x, y): return x+y You can then call it like this: Baz.bonzo(3, 5) This looks remarably similar to calling a function that exists in some namespace. For example: import random random.randrange(3, 5) So the ultimate difference? Pretty much just where you declare it. If it's in a class it's called a method, outside of a class its called a function. Especially in python - the distinction is small. -Kurt- From robert.sjoblom at gmail.com Tue Aug 23 01:10:07 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 23 Aug 2011 01:10:07 +0200 Subject: [Tutor] methods vs. functions Message-ID: > Can someone please explain the difference between methods and functions? I've heard the explanation "A cow is an animal but an animal is not necessarily a cow." used to describe the difference between methods and functions (ie, all methods are functions, but not all functions are methods). Obviously, that's a horrible description. This one's better: A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed. A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences. It is implicitly passed the object for which it was called It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data) Credit where credit is due: http://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function /Robert S. From alan.gauld at btinternet.com Tue Aug 23 01:45:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Aug 2011 00:45:22 +0100 Subject: [Tutor] methods vs. functions In-Reply-To: References: Message-ID: On 23/08/11 00:10, Robert Sjoblom wrote: >> Can someone please explain the difference between methods and functions? I'm sure if you go to Wikipedia you will get the correct computer science distinctions, however in practical terms and limiting the discussion to Python: > A function is a piece of code that is called by name. It can be passed > data to operate on (ie. the parameters) and can optionally return data > (the return value). That's about right, except that both theoretically and in Python there is always a return value. If you don't specify it Python returns a default value of None. (In other languages a "function" that does not return a value is more correctly called a procedure) > All data that is passed to a function is explicitly passed. That depends on how you define "passed to". A function has visibility of the data in its surrounding scope too. So x = 42 def f(): print x f() will print 42 because x is implicitly passed to f() by virtue of being in the enclosing scope. > A method is a piece of code that is called by name that is associated > with an object. In most respects it is identical to a function except > for two key differences. > It is implicitly passed the object for which it was called Correct. A method is a function defined inside a class. It is the function that the class calls on receipt of a message passed to an object. It is therefore the method by which the object fulfils the message request, hence the name "method". > It is able to operate on data that is contained within the class > (remembering that an object is an instance of a class - the class is > the definition, the object is an instance of that data) That's more complicated. It can operate on data within the object by using the object reference passed to it. It can operate on data within the class (ie. class data not instance data) by reference to the class in which it is defined. But in Python, unlike other languages, there is no "magic" visibility of these data attributes, it all happens via very explicit references. Perhaps more important is that methods are part of the class heirarchy lookup mechanism. Thus a method may be executed by an object of another class if the other class inherits from the defining class. class A: def f(self): print 'I'm in A' class B(A): pass a = A() b = B() for obj in (a,b): obj.f() Method f() gets called for both objects even though it is only defined in class A. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 23 02:15:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Aug 2011 01:15:52 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: <201108221838.11693.lisi.reisz@gmail.com> References: <201108211257.50231.lisi.reisz@gmail.com> <201108221445.29592.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> Message-ID: On 22/08/11 18:38, Lisi wrote: > technical terms. I am still very confused by the terminology. Having been > told that modules, functions and methods are just different names for the > same thing, that commands are really also the same thing and having had them > called yet a fifth thing in order "not to confuse you" (ouch!!) I see Steven has sent a very good reply, I'll add a slightly different slant but try not to confuse things further! There is a loty of confusion and double definitions in Computing, mainly through history and the evolution of different languages etc. There is also the difference between a computing concept, like a module, and the implementation of that concept in a given language. In general the concept will be a broader definition than the implementation. So sub-routine comers from the world of assembler programming and was adopted by BASIC because BASIC was invented back in the 1960's when most folks were used to assembler. Function comes from math and is directly related to the math theory behind computing and was therefore introduced into theoretical biased languages like Algol. Modularity is a design concept from the world of engineering. sub routines and functions were early attempts to introduce modularity into the world of computing. Gradually modularity was extended to include concepts like code libraries of sub-routines/functions and eventually the term module started to appwear in programming languages themselves - Modula, (and then Modula 2 and Modula 3) being I think the main source. Commands are slightly different in that they look quite similar to functions but usually have slightly different calling syntax and they are usually built into the core language rather than being user defined( but as always exceptions exist so that Tcl for example allows you to define your own commands) In Python 2 the best known command is print. It has been turned into a function in Python v3, thus in v2 print "Hello" becomes, in V3 print("Hello") Notice the addition of parentheses. So what does all that mean in practice in Python? Modules are files that contain any kind of arbitrary python code that can be imported into other programs and reused. Very often Modules contain one or more function definitions. Modules can also contain class definitions - classes are another mechanism for providing modularity (the concept!) in programs. Class definitions also contain functions (with the special classification "method" - see another thread) within them. > I am in a right muddle. It is entirely understandable. This is one of the most confusing areas of computing. > ... And I shall just go on asking questions until I have got the > whole thing disentangled in my head. Sorry, everybody. Don't apologise, it's the right thing to do. And on a list like this you will almost certainly clarify things in a lot of other folks heads too, who may not have thought through the complexities for themselves yet. > So now, can anyone suggest an example of a module to look at? (Preferably > with some subroutines inside).It is clearly NOT just another name for > function or method. I imagine that there are some on the Internet? Look in the standard library at glob.py It is one of the few that doesn't confuse things with classes, it is just a collection of functions and not too complicated ones at that. But being part of the standard library it has all the features that make a good reusable module too (documentation etc). And its not too big. > I hadn't actually counted the keystrokes. I stand corrected. But saving 6 > keystrokes is still a fairly pointless thing to do. If several subroutines > can be stored in a module and imported together, then that is quite another > matter. Even a single function can be useful, since you only need to maintain it in one place even if its used in many projects. But in general a module contains several (hopefully related) functions. glob.py is a good example. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lisi.reisz at gmail.com Tue Aug 23 08:49:48 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 23 Aug 2011 07:49:48 +0100 Subject: [Tutor] Where is sys.py? In-Reply-To: References: <201108211257.50231.lisi.reisz@gmail.com> <201108221838.11693.lisi.reisz@gmail.com> Message-ID: <201108230749.48990.lisi.reisz@gmail.com> Thanks, Alan. Very helpful; tho' I probably need to gigest Steven's information before I fully digest yours. On Tuesday 23 August 2011 01:15:52 Alan Gauld wrote: > So sub-routine comers from the world of assembler programming and was > adopted by BASIC because BASIC was invented back in the 1960's when most > folks were used to assembler. So _that's_ why I understand it. It is many years since I did any programmimg at all, but way back before the ark I did a bit of programming in both Basic and machine code. (And I mean machine code, not assembler.) Lisi From simulacrx at gmail.com Tue Aug 16 09:32:40 2011 From: simulacrx at gmail.com (simulacrx) Date: Tue, 16 Aug 2011 10:32:40 +0300 Subject: [Tutor] eval func with floating... Message-ID: <4E4A1D18.8000601@gmail.com> hi; ----------------------- check=(1,2,3,4,5,6,7,8,9,"/","*","-","+","(",")","[","]") while True: a=raw_input("type your query : \n") c=set(a).intersection(set(check)) if c: print *eval("float(%s)"%a)* else: print "error! please use -defined operators-!" ----------------------------- this script works.. but if i type 15/8 it returns 1.. no floatin'.. i must fix this? can anyone help me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From tlinnet at gmail.com Tue Aug 23 12:27:27 2011 From: tlinnet at gmail.com (=?ISO-8859-1?Q?Troels_Emtek=E6r_Linnet?=) Date: Tue, 23 Aug 2011 12:27:27 +0200 Subject: [Tutor] eval func with floating... In-Reply-To: <4E4A1D18.8000601@gmail.com> References: <4E4A1D18.8000601@gmail.com> Message-ID: Thats because you do integer division. Do either: float(15)/8 15/float(8) 15.0/8 15/8.0 Just be sure, that either 15 or 8 is a float, and not both an integer. Best Troels 2011/8/16 simulacrx > hi; > ----------------------- > check=(1,2,3,4,5,6,7,8,9,"/","*","-","+","(",")","[","]") > > while True: > a=raw_input("type your query : \n") > c=set(a).intersection(set(check)) > > if c: > print *eval("float(%s)"%a)* > else: > print "error! please use -defined operators-!" > ----------------------------- > > this script works.. but if i type > > 15/8 > > it returns 1.. no floatin'.. i must fix this? can anyone help me? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 23 12:52:10 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Aug 2011 12:52:10 +0200 Subject: [Tutor] eval func with floating... References: <4E4A1D18.8000601@gmail.com> Message-ID: simulacrx wrote: > check=(1,2,3,4,5,6,7,8,9,"/","*","-","+","(",")","[","]") You have to quote the digits: 1 is an integer while "1" is a string of length one: >>> "1" == 1 False Also, you forgot the "0". Note that there's no need to use a tuple as set() will happily accept a string: check = set("0123456789/*-+,()") > while True: > a=raw_input("type your query : \n") > c=set(a).intersection(set(check)) > > if c: > print *eval("float(%s)"%a)* > else: > print "error! please use -defined operators-!" > ----------------------------- > > this script works.. but if i type > > 15/8 > > it returns 1.. no floatin'.. i must fix this? can anyone help me? From joel.goldstick at gmail.com Tue Aug 23 13:53:05 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 23 Aug 2011 07:53:05 -0400 Subject: [Tutor] eval func with floating... In-Reply-To: References: <4E4A1D18.8000601@gmail.com> Message-ID: On Tue, Aug 23, 2011 at 6:52 AM, Peter Otten <__peter__ at web.de> wrote: > simulacrx wrote: > > > check=(1,2,3,4,5,6,7,8,9,"/","*","-","+","(",")","[","]") > > You have to quote the digits: 1 is an integer while "1" is a string of > length one: > > >>> "1" == 1 > False > > Also, you forgot the "0". > Note that there's no need to use a tuple as set() will happily accept a > string: > > check = set("0123456789/*-+,()") > > > while True: > > a=raw_input("type your query : \n") > > c=set(a).intersection(set(check)) > > > > if c: > > print *eval("float(%s)"%a)* > > else: > > print "error! please use -defined operators-!" > > ----------------------------- > > > > this script works.. but if i type > > > > 15/8 > > > > it returns 1.. no floatin'.. i must fix this? can anyone help me? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I'm not sure if the performance difference would matter, but if you make check a set above your loop there is no need to use the set(check) in the loop when check will do -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From chanakya at optirisk-systems.com Tue Aug 23 16:51:43 2011 From: chanakya at optirisk-systems.com (Chanakya Mitra) Date: Tue, 23 Aug 2011 15:51:43 +0100 Subject: [Tutor] eval func with floating... In-Reply-To: References: <4E4A1D18.8000601@gmail.com> Message-ID: c=set(a).intersection(set(check)) shouldn?t this be: c=set(a).issubset(set(check)) ? set(a).intersection(set(check)) will be true as long as only one element appears in both. ie. 15/a8 kill the process and spit out an error instead of asking "error! please use -defined operators-!" Sent: 23 August 2011 12:53 To: tutor at python.org Subject: Re: [Tutor] eval func with floating... On Tue, Aug 23, 2011 at 6:52 AM, Peter Otten <__peter__ at web.de> wrote: simulacrx wrote: > check=(1,2,3,4,5,6,7,8,9,"/","*","-","+","(",")","[","]") You have to quote the digits: 1 is an integer while "1" is a string of length one: >>> "1" == 1 False Also, you forgot the "0". Note that there's no need to use a tuple as set() will happily accept a string: check = set("0123456789/*-+,()") > while True: > a=raw_input("type your query : \n") > c=set(a).intersection(set(check)) > > if c: > print *eval("float(%s)"%a)* > else: > print "error! please use -defined operators-!" > ----------------------------- > > this script works.. but if i type > > 15/8 > > it returns 1.. no floatin'.. i must fix this? can anyone help me? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I'm not sure if the performance difference would matter, but if you make check a set above your loop there is no need to use the set(check) in the loop when check will do -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 23 17:44:30 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Aug 2011 17:44:30 +0200 Subject: [Tutor] eval func with floating... References: <4E4A1D18.8000601@gmail.com> Message-ID: Chanakya Mitra wrote: [simulacrx] > c=set(a).intersection(set(check)) [Chanakya Mitra] > shouldn?t this be: > c=set(a).issubset(set(check)) > ? > set(a).intersection(set(check)) will be true as long as only one element > appears in both. ie. 15/a8 kill the process and spit out an error instead > of asking "error! please use -defined operators-!" You are right. The original poster may still run into errors because input strings that aren't a valid Python expression are possible even with the restricted character set. From eire1130 at gmail.com Tue Aug 23 19:19:39 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Aug 2011 13:19:39 -0400 Subject: [Tutor] Zip - password protect Message-ID: Does anyone know if a way to password protect a zip file? I have no issues creating the zip file, but I would like to password protect as well. I'm aware of a commercial solution, but I would like something open source. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Aug 23 19:42:03 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Aug 2011 10:42:03 -0700 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On 8/23/2011 10:19 AM James Reynolds said... > Does anyone know if a way to password protect a zip file? I have no > issues creating the zip file, but I would like to password protect as > well. I'm aware of a commercial solution, but I would like something > open source. > The standard zipfile library includes a setpassword option. help(zipfile.PyZipFile.setpassword) Help on method setpassword in module zipfile: setpassword(self, pwd) unbound zipfile.PyZipFile method Set default password for encrypted files. Emile From eire1130 at gmail.com Tue Aug 23 20:23:04 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Aug 2011 14:23:04 -0400 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: I tried that already. that's only to set the default password to read the zip, not to set a pasword (wording is misleading I think) On Tue, Aug 23, 2011 at 1:42 PM, Emile van Sebille wrote: > On 8/23/2011 10:19 AM James Reynolds said... > > Does anyone know if a way to password protect a zip file? I have no >> issues creating the zip file, but I would like to password protect as >> well. I'm aware of a commercial solution, but I would like something >> open source. >> >> > > The standard zipfile library includes a setpassword option. > > help(zipfile.PyZipFile.**setpassword) > > Help on method setpassword in module zipfile: > > setpassword(self, pwd) unbound zipfile.PyZipFile method > Set default password for encrypted files. > > > Emile > > > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Aug 23 20:41:05 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Aug 2011 11:41:05 -0700 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On 8/23/2011 11:23 AM James Reynolds said... > I tried that already. > > that's only to set the default password to read the zip, not to set a > pasword (wording is misleading I think) Did you see http://stackoverflow.com/questions/2195747/python-code-to-create-a-password-encrypted-zip-file ? Check the answer that references the external open-source 7-Zip utility. Emile From alan.gauld at btinternet.com Tue Aug 23 20:57:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Aug 2011 19:57:32 +0100 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On 23/08/11 19:23, James Reynolds wrote: > I tried that already. > > that's only to set the default password to read the zip, not to set a > pasword (wording is misleading I think) > I'm confused. Which password are you thinking of? Is it at the OS level to prevent access to the file - in which case the fact that its a zipfile is immaterial. Or is it the zipfile's own password? In which case what is different from the "default password to read the file"? What exactly are you trying to achieve? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.sjoblom at gmail.com Tue Aug 23 21:27:54 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 23 Aug 2011 21:27:54 +0200 Subject: [Tutor] issues with urllib and loading a webpage. Message-ID: So, an issue regarding urllib (python 3) came up earlier. I solved it by using httplib2 instead, but I'm rather curious as to why urllib wouldn't work. Here's the code I'm working with: from http.client import HTTPConnection HTTPConnection.debuglevel = 1 from urllib.request import urlopen url = "http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=1xEURUS" response = urlopen(url) print(response.headers.as_string()) print(type(response)) Output is: send: b'GET /includes/cours/last_transactions.phtml?symbole=1xEURUS HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.boursorama.com\r\nConnection: close\r\nUser-Agent: Python-urllib/3.2\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Server header: Date header: Content-Type header: Connection header: Cache-Control header: Pragma header: Expires header: Set-Cookie header: Set-Cookie header: Vary header: Content-Length header: Content-Language header: X-sid Server: nginx Date: Tue, 23 Aug 2011 19:08:00 GMT Content-Type: text/html; charset=ISO-8859-1 Connection: keep-alive Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Expires: Thu, 19 Nov 1981 08:52:00 GMT Set-Cookie: OBJECT_BOURSORAMA=0; expires=Fri, 20-Aug-2021 19:07:59 GMT; path=/; domain=.www.boursorama.com Set-Cookie: PHPSESSIONID=d6ceed9aab3dba2e61ded126a925a881; path=/; domain=.www.boursorama.com Vary: Accept-Encoding,User-Agent Content-Length: 7787 Content-Language: fr X-sid: 30,E Now, if I were to do a data = response.read() and then print(data), I should get the source code printed (testing this on python.org works, btw). However, what I do get is: b'' What gives? FYI, the httplib2 solution is easy enough: import httplib2 h = httplib2.Http('.cache') # I prefer to use folders when working with httplib2 response, content = h.request(url) Response headers are put in response, the content is accessible as a byte object in content. -- best regards, Robert S. From eire1130 at gmail.com Tue Aug 23 21:31:25 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Aug 2011 15:31:25 -0400 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On Tue, Aug 23, 2011 at 2:57 PM, Alan Gauld wrote: > On 23/08/11 19:23, James Reynolds wrote: > >> I tried that already. >> >> that's only to set the default password to read the zip, not to set a >> pasword (wording is misleading I think) >> >> > I'm confused. > > Which password are you thinking of? > > Is it at the OS level to prevent access to the file > - in which case the fact that its a zipfile is immaterial. > Or is it the zipfile's own password? In which case what > is different from the "default password to read the file"? > > > What exactly are you trying to achieve? > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > (from earlier) I need to password protect a zip file I am creating from within python. I would rather not have a user open the zip and set the password manually. I'm trying the 7-zip solution, but I can't get past this error: WindowsError: [Error 2] The system cannot find the file specified The line it fails at is here: z = subprocess.call(['7z', 'a', '1234', '-y', name + '.zip'] + self.file_locs) (from now) oddly enough, when I open up a python shell, i can run the above just fine and it creates a .zip file. But when I run it from eclipse, the exact thing, I get the error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Aug 23 21:49:24 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Aug 2011 12:49:24 -0700 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On 8/23/2011 12:31 PM James Reynolds said... > I'm trying the 7-zip solution, but I can't get past this > error: WindowsError: [Error 2] The system cannot find the file specified > > The line it fails at is here: z = subprocess.call(['7z', 'a', '1234', > '-y', name + '.zip'] + self.file_locs) > > (from now) > > oddly enough, when I open up a python shell, i can run the above just > fine and it creates a .zip file. > > But when I run it from eclipse, the exact thing, I get the error. I'd try providing the full path to 7z -- maybe that's why it probably can't find the file specified. Emile From sander.sweers at gmail.com Tue Aug 23 21:57:28 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 23 Aug 2011 21:57:28 +0200 Subject: [Tutor] issues with urllib and loading a webpage. In-Reply-To: References: Message-ID: <4E540628.1030205@gmail.com> On 23/08/11 21:27, Robert Sjoblom wrote: > Here's the code I'm working with: > from http.client import HTTPConnection > HTTPConnection.debuglevel = 1 > from urllib.request import urlopen > > url = "http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=1xEURUS" > response = urlopen(url) > print(response.headers.as_string()) > print(type(response)) > Now, if I were to do a data = response.read() and then print(data), I > should get the source code printed (testing this on python.org works, > btw). However, what I do get is: > b'' > > What gives? Don't know, works fine for me.. Greets Sander From eire1130 at gmail.com Tue Aug 23 22:11:26 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Aug 2011 16:11:26 -0400 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On Tue, Aug 23, 2011 at 3:49 PM, Emile van Sebille wrote: > On 8/23/2011 12:31 PM James Reynolds said... > > I'm trying the 7-zip solution, but I can't get past this >> error: WindowsError: [Error 2] The system cannot find the file specified >> >> The line it fails at is here: z = subprocess.call(['7z', 'a', '1234', >> '-y', name + '.zip'] + self.file_locs) >> >> (from now) >> >> oddly enough, when I open up a python shell, i can run the above just >> fine and it creates a .zip file. >> >> But when I run it from eclipse, the exact thing, I get the error. >> > > I'd try providing the full path to 7z -- maybe that's why it probably can't > find the file specified. > > Emile > > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > It was a silly problem. I guess Eclipse saves your PATH variables once the program is started, instead of referencing the os directly. (I just did print "Current path is %s" % os.path.expandvars("$PATH")) and that told me what was going on. Anyway, it's saving the files a .7z which isn't doing me much good. i was under the impression i could save them as .zip, if not I'm just going to have to password protect manually. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Aug 23 22:23:27 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Aug 2011 16:23:27 -0400 Subject: [Tutor] Zip - password protect In-Reply-To: References: Message-ID: On Tue, Aug 23, 2011 at 4:11 PM, James Reynolds wrote: > > > On Tue, Aug 23, 2011 at 3:49 PM, Emile van Sebille wrote: > >> On 8/23/2011 12:31 PM James Reynolds said... >> >> I'm trying the 7-zip solution, but I can't get past this >>> error: WindowsError: [Error 2] The system cannot find the file specified >>> >>> The line it fails at is here: z = subprocess.call(['7z', 'a', '1234', >>> '-y', name + '.zip'] + self.file_locs) >>> >>> (from now) >>> >>> oddly enough, when I open up a python shell, i can run the above just >>> fine and it creates a .zip file. >>> >>> But when I run it from eclipse, the exact thing, I get the error. >>> >> >> I'd try providing the full path to 7z -- maybe that's why it probably >> can't find the file specified. >> >> Emile >> >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > It was a silly problem. > > I guess Eclipse saves your PATH variables once the program is started, > instead of referencing the os directly. (I just did print "Current path is > %s" % os.path.expandvars("$PATH")) and that told me what was going on. > > Anyway, it's saving the files a .7z which isn't doing me much good. i was > under the impression i could save them as .zip, if not I'm just going to > have to password protect manually. > > got it working, had a flag in the wrong spot. Seems to work better than the Zip module in some ways. Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Tue Aug 23 22:59:26 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 23 Aug 2011 22:59:26 +0200 Subject: [Tutor] issues with urllib and loading a webpage. Message-ID: >Don't know, works fine for me.. > >Greets >Sander Are you using Python 3 and urllib, and not using httplib2? Because I honestly can't get urllib.request.urlopen to work with http://www.boursorama.com/ -- I only get b'' from there. best regards, Robert S. From sander.sweers at gmail.com Tue Aug 23 23:09:54 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 23 Aug 2011 23:09:54 +0200 Subject: [Tutor] issues with urllib and loading a webpage. In-Reply-To: References: Message-ID: On 23 August 2011 22:59, Robert Sjoblom wrote: > Are you using Python 3 and urllib, and not using httplib2? Because I > honestly can't get urllib.request.urlopen to work with > http://www.boursorama.com/ -- I only get b'' from there. Yes, Python 3.2 which version one are you using? I tried both with debug and without. Greets Sander From robert.sjoblom at gmail.com Wed Aug 24 00:03:23 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Wed, 24 Aug 2011 00:03:23 +0200 Subject: [Tutor] issues with urllib and loading a webpage Message-ID: >> Are you using Python 3 and urllib, and not using httplib2? Because I >> honestly can't get urllib.request.urlopen to work with >> http://www.boursorama.com/ -- I only get b'' from there. > > Yes, Python 3.2 which version one are you using? I tried both with > debug and without. Python 3.2.1 64 bit on win 32. This is really quite weird. There should be something there, because the headers alone doesn't account for the 7kb that's received. From alan.gauld at btinternet.com Wed Aug 24 01:11:48 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 24 Aug 2011 00:11:48 +0100 (BST) Subject: [Tutor] Fw: Zip - password protect In-Reply-To: References: Message-ID: <1314141108.74246.YahooMailRC@web86702.mail.ird.yahoo.com> Forwarding to group. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ---- From: James Reynolds To: Alan Gauld Sent: Tuesday, 23 August, 2011 20:11:57 Subject: Re: [Tutor] Zip - password protect On Tue, Aug 23, 2011 at 2:57 PM, Alan Gauld wrote: On 23/08/11 19:23, James Reynolds wrote: > >I tried that already. >> >>that's only to set the default password to read the zip, not to set a >>pasword (wording is misleading I think) >> >> I'm confused. > >Which password are you thinking of? > >Is it at the OS level to prevent access to the file > - in which case the fact that its a zipfile is immaterial. >Or is it the zipfile's own password? In which case what >is different from the "default password to read the file"? > > >What exactly are you trying to achieve? > > >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > I need to password protect a zip file I am creating from within python. I would rather not have a user open the zip and set the password manually. I'm trying the 7-zip solution, but I can't get past this error: WindowsError: [Error 2] The system cannot find the file specified The line it fails at is here: z = subprocess.call(['7z', 'a', '1234', '-y', name + '.zip'] + self.file_locs) -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Wed Aug 24 02:26:03 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 23 Aug 2011 20:26:03 -0400 Subject: [Tutor] Python Speech Message-ID: Hello Tutors, I need help with text to speech and or speech to text. I know of two packages, but they require win32, which I can't get to work. The Win32 package was filled with pyd's and no py's..Could some one tell me how to get win32 to work or a package that doesn't use it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Aug 24 02:37:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Aug 2011 10:37:01 +1000 Subject: [Tutor] Python Speech In-Reply-To: References: Message-ID: <4E5447AD.8060506@pearwood.info> Christopher King wrote: > Hello Tutors, > I need help with text to speech and or speech to text. I know of two > packages, but they require win32, which I can't get to work. The Win32 > package was filled with pyd's and no py's..Could some one tell me how to get > win32 to work or a package that doesn't use it. Are you running Windows? If not, you'll need to use a Windows PC. -- Steven From g.nius.ck at gmail.com Wed Aug 24 02:43:11 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 23 Aug 2011 20:43:11 -0400 Subject: [Tutor] eval func with floating... In-Reply-To: <4E4A1D18.8000601@gmail.com> References: <4E4A1D18.8000601@gmail.com> Message-ID: > if c: > print *eval("float(%s)"%a)* > else: > print "error! please use -defined operators-!" > I would use a assert statement for more readability, like so. *try: assert c* *except AssertionError: print "error! please use -defined operators-!"* else: *print *eval("float(%s)"%a) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Aug 24 02:46:33 2011 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 23 Aug 2011 20:46:33 -0400 Subject: [Tutor] Python Speech In-Reply-To: <4E5447AD.8060506@pearwood.info> References: <4E5447AD.8060506@pearwood.info> Message-ID: Depending on what you want, you could try accessible_output. This uses the first available screen reader to speak, or sapi5 speech if no screen reader is loaded. I believe the link is: http://hg.qwitter-client.net/dependencies HTH. On 8/23/11, Steven D'Aprano wrote: > Christopher King wrote: >> Hello Tutors, >> I need help with text to speech and or speech to text. I know of two >> packages, but they require win32, which I can't get to work. The Win32 >> package was filled with pyd's and no py's..Could some one tell me how to >> get >> win32 to work or a package that doesn't use it. > > Are you running Windows? > > If not, you'll need to use a Windows PC. > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Wed Aug 24 02:49:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Aug 2011 10:49:50 +1000 Subject: [Tutor] eval func with floating... In-Reply-To: References: <4E4A1D18.8000601@gmail.com> Message-ID: <4E544AAE.9080701@pearwood.info> Christopher King wrote: >> if c: >> print *eval("float(%s)"%a)* >> else: >> print "error! please use -defined operators-!" >> > I would use a assert statement for more readability, like so. > *try: assert c* > *except AssertionError: print "error! please use -defined operators-!"* > else: *print *eval("float(%s)"%a) Only if you want the user to be able to turn off error checking and break your program. "python -O" switches off all assertions. Do not use asserts except for assertions about internal states of your program. Never, ever use them for testing user input, or for reporting errors to the user. That is not what they are for. If the user ever sees an AssertionError, your code is buggy. -- Steven From g.nius.ck at gmail.com Wed Aug 24 03:10:41 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 23 Aug 2011 21:10:41 -0400 Subject: [Tutor] Python Speech In-Reply-To: <4E544ACD.4050809@pearwood.info> References: <4E5447AD.8060506@pearwood.info> <4E544ACD.4050809@pearwood.info> Message-ID: Sorry, forgot to hit reply all. -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Wed Aug 24 03:15:38 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 23 Aug 2011 21:15:38 -0400 Subject: [Tutor] eval func with floating... In-Reply-To: <4E544AAE.9080701@pearwood.info> References: <4E4A1D18.8000601@gmail.com> <4E544AAE.9080701@pearwood.info> Message-ID: > > If the user ever sees an AssertionError, your code is buggy. > Well you saw that I caught the AssertionError, so the user wouldn't technically see it. For the other stuff, I didn't know the etiquette for assertion -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Aug 24 03:46:34 2011 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 23 Aug 2011 21:46:34 -0400 Subject: [Tutor] Python Speech In-Reply-To: References: <4E5447AD.8060506@pearwood.info> <4E544ACD.4050809@pearwood.info> Message-ID: Sorry, the link is: http://hg.qwitter-client.net then select "accessible output". On 8/23/11, Christopher King wrote: > Sorry, forgot to hit reply all. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Wed Aug 24 03:52:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Aug 2011 11:52:11 +1000 Subject: [Tutor] eval func with floating... In-Reply-To: References: <4E4A1D18.8000601@gmail.com> <4E544AAE.9080701@pearwood.info> Message-ID: <4E54594B.3070606@pearwood.info> Christopher King wrote: >> If the user ever sees an AssertionError, your code is buggy. >> > Well you saw that I caught the AssertionError, so the user > wouldn't technically see it. For the other stuff, I didn't know > the etiquette for assertion It's not etiquette, it is the actual way assert works. If you have code that looks like this: assert x > 0 print x + 1 and the user runs your code using "python -O", the code is converted to: print x + 1 and the assert is just *gone*. It is as simple as that. Any time you use an assert, you should imagine that it will just *disappear* some times. When are assertions useful? If you have ever written code like this: if x > 0: print x + 1 else: # This can never happen! raise RuntimeError('unexpected internal error') that's a good case for using an assert. Because you are sure that the else can never happen, it won't matter if the assert goes away. But because you can't be absolutely 100% sure, it's better to code defensively with a check that your program logic is correct. -- Steven From sander.sweers at gmail.com Wed Aug 24 09:13:00 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 24 Aug 2011 09:13:00 +0200 Subject: [Tutor] issues with urllib and loading a webpage In-Reply-To: References: Message-ID: <1314169980.30840.6.camel@Nokia-N900> On Wed, 24 Aug 2011, 00:03:23 CEST, Robert Sjoblom wrote: > > > Are you using Python 3 and urllib, and not using httplib2? Because I > > > honestly can't get urllib.request.urlopen to work with > > > http://www.boursorama.com/ -- I only get b'' from there. > > > > Yes, Python 3.2 which version one are you using? I tried both with > > debug and without. > > Python 3.2.1 64 bit on win 32. This is really quite weird. You are running 64bit on a 32bit operating system, did you meant to say 32bit python on win64? If you actually do have 64bit python installed remove it and install the 32bit version. > There > should be something there, because the headers alone doesn't account > for the 7kb that's received. How large is the page when dowloading from the browser? Is it comparable in size? Greets Sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From WPJones at ewation.co.za Wed Aug 24 11:26:38 2011 From: WPJones at ewation.co.za (Warren P. Jones) Date: Wed, 24 Aug 2011 09:26:38 +0000 Subject: [Tutor] cPickle and shjelving Message-ID: <11A03473DAAAA0428C260C058D4248799691E2@ExchMBX.ewation.co.za> Hi, I am new to python. I am having slight issue in using the cPickle and shelving function. Here is what i want the program need to do: Open an file with employees in it with relevant information like: employee number, surname and department. I also need to add an employee with the relevant information without rewriting the current data. I have tried the code but not completely sure what i am doing wrong. Here is the code that i tried: # Defines pickles["employee_num"] pickle_file = shelve.open("empl.dat") print "Add new Employee" employee_num = raw_input("\nEmployee number: ") surname = raw_input("Surname: ") name = raw_input("Name: ") department = raw_input("Department: ") ######################## # Storing DATA # ######################## cPickles.dump(employee_num, emp1.dat) print key, "-",pickles[key] pickles.sync () # Makes sure date is written Can you please help me in solving this issue? Kind regards Warren Jones ________________________________ This E-mail and any attachment(s) to it are for the addressee's use only. It is strictly confidential and may contain legally privileged information. No confidentiality or privilege is waived or lost by any mis-transmission. If you are not the intended addressee, then please delete it from your system and notify the sender immediately. You are hereby notified that any use, disclosure, copying or any action taken in reliance on it is strictly prohibited and may be unlawful. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Aug 24 13:32:25 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 24 Aug 2011 13:32:25 +0200 Subject: [Tutor] cPickle and shjelving In-Reply-To: <11A03473DAAAA0428C260C058D4248799691E2@ExchMBX.ewation.co.za> References: <11A03473DAAAA0428C260C058D4248799691E2@ExchMBX.ewation.co.za> Message-ID: On Wed, Aug 24, 2011 at 11:26 AM, Warren P. Jones wrote: > Hi, > > I am new to python. I am having slight issue in using the cPickle and > shelving function. > > Here is what i want the program need to do: > > Open an file with employees in it with relevant information like: employee > number, surname and department. I also need to add an employee with the > relevant information without rewriting the current data. > > I have tried the code but not completely sure what i am doing wrong. > > Here is the code that i tried: > > # Defines > pickles["employee_num"] > > ??? pickle_file = shelve.open("empl.dat") > ?????????? print "Add new Employee" > ?????????? employee_num = raw_input("\nEmployee number: ") > ?????????? surname = raw_input("Surname: ") > ?????????? name = raw_input("Name: ") > ?????????? department = raw_input("Department: ") > > ?????????? ######################## > > ?????????? #??? Storing DATA????? # > > ?????????? ######################## > > ?????????? cPickles.dump(employee_num, emp1.dat) > ?????????? print key, "-",pickles[key] > ?????????? pickles.sync () # Makes sure date is written > > Can you please help me in solving this issue? > > Kind regards > > Warren? Jones > That code makes very little sense. The indentation is wrong, and some variables are never declared. Is that the full code? Also, shelve already uses cPickle internally, so you don't need to use it separately. Once you open a shelf, you can use it as a regular dictionary object afterward: shelf = shelve.open("empl.dat") employee_num = raw_input("\nEmployee number: ") shelf[employee_num] = { "surname": raw_input("Surname: "), "name": raw_input("Name: "), "department": raw_input("Department: ") } shelf.close() From emailkgnow at gmail.com Wed Aug 24 13:34:56 2011 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Wed, 24 Aug 2011 14:34:56 +0300 Subject: [Tutor] Tutorials on csv module?? Message-ID: Hi everyone, can anyone point me to a good tutorial on using the csv module? also, is there a module that can help me check data in a excel file other than the csv module? thanks a lot khaild -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Aug 24 13:58:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Aug 2011 21:58:49 +1000 Subject: [Tutor] Tutorials on csv module?? In-Reply-To: References: Message-ID: <4E54E779.6060600@pearwood.info> Khalid Al-Ghamdi wrote: > Hi everyone, > > can anyone point me to a good tutorial on using the csv module? Search engines are a wonderful thing. http://duckduckgo.com/?q=python+csv+tutorial > also, is there a module that can help me check data in a excel file other > than the csv module? http://duckduckgo.com/?q=python+excel http://duckduckgo.com/?q=python+xls Try the xlwt and xlrd libraries. http://www.python-excel.org/ -- Steven From g.nius.ck at gmail.com Wed Aug 24 19:07:12 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 24 Aug 2011 13:07:12 -0400 Subject: [Tutor] eval func with floating... In-Reply-To: <4E544AAE.9080701@pearwood.info> References: <4E4A1D18.8000601@gmail.com> <4E544AAE.9080701@pearwood.info> Message-ID: > > If the user ever sees an AssertionError, your code is buggy. > Well you saw that I caught the AssertionError, so the user wouldn't technically see it. For the other stuff, I didn't know the etiquette for assertion statements. -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Wed Aug 24 19:09:04 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 24 Aug 2011 13:09:04 -0400 Subject: [Tutor] Python Speech In-Reply-To: References: <4E5447AD.8060506@pearwood.info> <4E544ACD.4050809@pearwood.info> Message-ID: how do you unzip a gz on windows? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 24 19:17:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Aug 2011 18:17:40 +0100 Subject: [Tutor] Python Speech In-Reply-To: References: <4E5447AD.8060506@pearwood.info> <4E544ACD.4050809@pearwood.info> Message-ID: On 24/08/11 18:09, Christopher King wrote: > how do you unzip a gz on windows? Pretty much any zip tool (Qzip, Winzip etc) will handle gz files too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Wed Aug 24 19:45:31 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 24 Aug 2011 13:45:31 -0400 Subject: [Tutor] Python Speech In-Reply-To: References: <4E5447AD.8060506@pearwood.info> Message-ID: On Tue, Aug 23, 2011 at 8:46 PM, Alex Hall wrote: > Depending on what you want, you could try accessible_output. It requires platform_utils. Anything else? -------------- next part -------------- An HTML attachment was scrubbed... URL: From crp at cmc.net Wed Aug 24 19:40:37 2011 From: crp at cmc.net (Ray Parrish) Date: Wed, 24 Aug 2011 10:40:37 -0700 Subject: [Tutor] Syntax error with if statement Message-ID: <4E553795.7050102@cmc.net> Hello, I haven't been programming for a while and today I am working on something and have encountered an error I cannot figure out. Here is my code: thisFile = column[6] if thisFile == "/Images/My%20Face.JPG" CallCount += 1 print CallCount And here is the error message: ray at RaysComputer:~$ python /home/ray/EmailCount/CountEmails.py File "/home/ray/EmailCount/CountEmails.py", line 41 if thisFile == "/Images/My%20Face.JPG" ^ SyntaxError: invalid syntax Any help you can be will be much appreciated. Later, Ray Parrish -- The Unknown Lead Player, Ray Parrish http://www.facebook.com/pages/The-Unknown-Lead-Player/123388551041130?sk=wall Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com From andreengels at gmail.com Wed Aug 24 20:08:25 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 24 Aug 2011 20:08:25 +0200 Subject: [Tutor] Syntax error with if statement In-Reply-To: <4E553795.7050102@cmc.net> References: <4E553795.7050102@cmc.net> Message-ID: On Wed, Aug 24, 2011 at 7:40 PM, Ray Parrish wrote: > Hello, > > I haven't been programming for a while and today I am working on something > and have encountered an error I cannot figure out. > > Here is my code: > > thisFile = column[6] > if thisFile == "/Images/My%20Face.JPG" > CallCount += 1 > print CallCount > > And here is the error message: > > ray at RaysComputer:~$ python /home/ray/EmailCount/**CountEmails.py > File "/home/ray/EmailCount/**CountEmails.py", line 41 > if thisFile == "/Images/My%20Face.JPG" > ^ > SyntaxError: invalid syntax > > Any help you can be will be much appreciated. > There has to be a : at the end of an if statement, or more generally, any statement that is to be followed by an indented block. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at dcsoftware.com Wed Aug 24 19:57:36 2011 From: jeff at dcsoftware.com (Jeff Johnson) Date: Wed, 24 Aug 2011 10:57:36 -0700 Subject: [Tutor] Python Speech In-Reply-To: References: <4E5447AD.8060506@pearwood.info> <4E544ACD.4050809@pearwood.info> Message-ID: <4E553B90.9080508@dcsoftware.com> On 08/24/2011 10:17 AM, Alan Gauld wrote: > On 24/08/11 18:09, Christopher King wrote: >> how do you unzip a gz on windows? > > > Pretty much any zip tool (Qzip, Winzip etc) will > handle gz files too. > 7 zip works great on Windows for most formats. http://www.7-zip.org/ Jeff ------------------- Jeff Johnson jeff at dcsoftware.com From washakie at gmail.com Wed Aug 24 20:34:14 2011 From: washakie at gmail.com (John) Date: Wed, 24 Aug 2011 20:34:14 +0200 Subject: [Tutor] help with a class Message-ID: Hello, I have a class that has an attribute that is a dict which I fill with more dicts. I've created a function to return those dictionaries if a key is provide, otherwise, it returns the 'default' dictionary. I have the following methods (see below), it seems the update_options method is fine, but I'm not sure about the override_options method... and for that matter, I'm not sure this is the best approach overall... any comments, critiques? Thank you, john class Runner(object): """ Initiate with an optional dictionary of settings. Defaults are set in the options dictionary, which can be overridden. """ # Simplest default: default_options = { 'file' : '../data/input.dat', 'wavelength' : '310.0 310.0' } def __init__(self, **kwargs): if 'options' not in kwargs: self.options = copy(self.default_options) self.run_queue = {} def _get_from_queue(self, queue_key): """ internal method to set options """ if queue_key: if queue_key not in self.run_queue: raise ValueError('queue_key: {0} not in queue'.format(queue_key)) else: return self.run_queue[queue_key] else: return self.options def update_options(self, options, queue_key=None): """ update the options dictionary using a dict """ assert isinstance(options, dict), "update options requires a dict" old_options = self._get_from_queue(queue_key) old_options.update(options) def overide_options(self, options, queue_key=None): """ completely overide the options dict """ assert isinstance(options, dict), "override options requires a dict" old_options = self._get_from_queue(queue_key) old_options = options -- From hugo.yoshi at gmail.com Wed Aug 24 21:21:30 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 24 Aug 2011 21:21:30 +0200 Subject: [Tutor] help with a class In-Reply-To: References: Message-ID: On Wed, Aug 24, 2011 at 8:34 PM, John wrote: > Hello, I have a class that has an attribute that is a dict which I > fill with more dicts. I've created a function to return those > dictionaries if a key is provide, otherwise, it returns the 'default' > dictionary. > > I have the following methods (see below), it seems the update_options > method is fine, but I'm not sure about the override_options method... > and for that matter, I'm not sure this is the best approach overall... > any comments, critiques? > You've identified the problem point correctly, override_options will not work as expected. What it does is: 1) retrieve a dict through _get_from_queue() 2) point the name old_options toward that dict 3) point the name old_options toward a different dict (the one that options points to) as you can see, the dict that is inside self.run_queue isn't actually changed just by making old_options point towards the new dict. What you need to do is actually assign the new dict to the place in the queue, like so: self.run_queue[queue_key] = options of course, this will also just create a new entry in the dict if there wasn't one previously, which isn't exactly an 'override.' So if you want that behavior, check for it and raise an error by yourself. One other thing, inside _get_from_queue(). If a key isn't present in a dictionary, you generally raise a KeyError, not a ValueError. A ValueError is for when a function argument is of the correct type, but has an inappropriate value, and the error isn't more accurately described by another exception like an IndexError. For example, math.sqrt(-1) raises a ValueError because negative numbers don't make sense for square roots, even though the argument is of the correct type (yes, the math module doesn't have support for imaginary numbers built in, even though the language does ?_? There is cmath though). From washakie at gmail.com Wed Aug 24 21:52:38 2011 From: washakie at gmail.com (John) Date: Wed, 24 Aug 2011 21:52:38 +0200 Subject: [Tutor] help with a class In-Reply-To: References: Message-ID: Thank you. I've corrected the KeyError, and changed the function to: def overide_options(self, options, run_id=None): """ completely overide the options dict """ assert isinstance(options, dict), "override options requires a dict" if run_id in self.run_queue: self.run_queue[run_id] = options else: self.options = options From ramit.prasad at jpmorgan.com Wed Aug 24 22:03:15 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 24 Aug 2011 16:03:15 -0400 Subject: [Tutor] help with a class In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2EE89@EMARC112VS01.exchad.jpmchase.net> I was under the impression that asserts are more for testing than for production code (especially since they can be removed when running from python from command line). Instead I removed the assert and replaced it to raise an error. def overide_options(self, options, run_id=None): """ completely overide the options dict """ if not isinstance(options, dict): raise TypeError("override options requires a dict") if run_id in self.run_queue: self.run_queue[run_id] = options else: self.options = options Do you really care if it is a dict versus defaultdict or something else that is dict-like? This will fail if I pass in a dict-like class (i.e. if I wrote dict from scratch) that does not inherit from dict. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Wed Aug 24 23:37:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Aug 2011 22:37:13 +0100 Subject: [Tutor] help with a class In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2EE89@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2EE89@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 24/08/11 21:03, Prasad, Ramit wrote: > I was under the impression that asserts are more for testing > than for production code That's true. > def overide_options(self, options, run_id=None): > > if not isinstance(options, dict): > raise TypeError("override options requires a dict") This is good if you want to keep the check in for production. But using an assert here while testing then removing it from production would be a valid use too. The typecheck is not required for the function to work if you are confident of the data being passed in. assert checks the data while you are gaining that confidence. So either approach is valid. It all depends on how variable your input data is going to be. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Thu Aug 25 03:53:42 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 24 Aug 2011 21:53:42 -0400 Subject: [Tutor] Python Speech In-Reply-To: References: Message-ID: I got the speech module to work actually, except for input. Only say works. Here's a traceback on speech.input. Traceback (most recent call last): File "C:\Python26\test.py", line 6, in print speech.input() File "C:\Python26\speech.py", line 162, in input listener = listenforanything(response) File "C:\Python26\speech.py", line 193, in listenforanything return _startlistening(None, callback) File "C:\Python26\speech.py", line 222, in _startlistening context = _recognizer.CreateRecoContext() File "C:\Python26\lib\site-packages\win32com\gen_py\C866CA3A-32F7-11D2-9602-00 C04F8EE628x0x5x0.py", line 2457, in CreateRecoContext ret = self._oleobj_.InvokeTypes(10, LCID, 1, (9, 0), (),) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -214722 1164), None) -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Thu Aug 25 07:51:55 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Thu, 25 Aug 2011 15:51:55 +1000 Subject: [Tutor] Confirmation if command worked Message-ID: <007401cc62eb$19ee5c70$4dcb1550$@com.au> Hi all, I have the following code that uses pexpect to execute a system command. My problem is, I don't know how to identify if the command was successfully executed. The code works as it is to execute the SCP command, but it executes regardless if the SCP session can actually connect to something. Thanks def doScp(files): logger.log("Files to get: " + `files`) fNames = ' '.join(files) cmd = 'scp %s %s@%s:%s%s' % (fNames, SCP_USERNAME, SCP_HOST, SCP_IMG_FILE_DIR, SCP_IMG_FILE_PATH) logger.log("Sending: " + cmd) child = pexpect.spawn(cmd) i = child.expect(['assword:', 'yes/no'], timeout=30) if i == 0: child.sendline(SCP_PASSWD) elif i == 1: child.sendline("yes") child.expect("assword:", timeout=30) child.sendline(SCP_PASSWD) data = child.read() if data != None: success = True else: success = False child.close() logger.log("Files sent to SCP host") return success From cwitts at compuscan.co.za Thu Aug 25 08:25:16 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 25 Aug 2011 08:25:16 +0200 Subject: [Tutor] Confirmation if command worked In-Reply-To: <007401cc62eb$19ee5c70$4dcb1550$@com.au> References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> Message-ID: <4E55EACC.8080409@compuscan.co.za> On 2011/08/25 07:51 AM, Johan Geldenhuys wrote: > Hi all, > > > I have the following code that uses pexpect to execute a system command. My > problem is, I don't know how to identify if the command was successfully > executed. > The code works as it is to execute the SCP command, but it executes > regardless if the SCP session can actually connect to something. > > Thanks > > def doScp(files): > > > logger.log("Files to get: " + `files`) > fNames = ' '.join(files) > > cmd = 'scp %s %s@%s:%s%s' % (fNames, > SCP_USERNAME, > SCP_HOST, > SCP_IMG_FILE_DIR, > SCP_IMG_FILE_PATH) > > logger.log("Sending: " + cmd) > > child = pexpect.spawn(cmd) > > i = child.expect(['assword:', 'yes/no'], timeout=30) > if i == 0: > child.sendline(SCP_PASSWD) > > elif i == 1: > child.sendline("yes") > child.expect("assword:", timeout=30) > child.sendline(SCP_PASSWD) > > data = child.read() > > if data != None: > success = True > else: > success = False > child.close() > > logger.log("Files sent to SCP host") > > return success > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Once you call child.close() the exit and signal status will be stored in .exitstatus and .signalstatus, for a normal exit of the program .exitstatus will store the return code from SCP as per [1] [2] [3] and .signalstatus will be None. If SCP was terminated with a signal then .exitstatus will be None and .signalstatus will contain the signal value. Info found in the docs [4]. So the changes to your code will be: data = child.read() child.close() if child.exitstatus and child.exitstatus == 0: success = True else: success = False I'll leave putting in handling of failed error codes and abnormal termination to you. [1] http://support.attachmate.com/techdocs/2116.html [2] http://support.attachmate.com/techdocs/2487.html [3] http://support.attachmate.com/techdocs/2285.html [4] http://pexpect.sourceforge.net/pexpect.html -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Thu Aug 25 08:50:27 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Thu, 25 Aug 2011 16:50:27 +1000 Subject: [Tutor] Confirmation if command worked In-Reply-To: <4E55EACC.8080409@compuscan.co.za> References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> <4E55EACC.8080409@compuscan.co.za> Message-ID: <009601cc62f3$49a90390$dcfb0ab0$@com.au> Hi Christian, Thanks for that. I'll give it a shot and see if I can catch the error. Lekker dag Johan From: Christian Witts [mailto:cwitts at compuscan.co.za] Sent: Thursday, 25 August 2011 4:25 PM To: Johan Geldenhuys Cc: tutor at python.org Subject: Re: [Tutor] Confirmation if command worked On 2011/08/25 07:51 AM, Johan Geldenhuys wrote: Hi all, I have the following code that uses pexpect to execute a system command. My problem is, I don't know how to identify if the command was successfully executed. The code works as it is to execute the SCP command, but it executes regardless if the SCP session can actually connect to something. Thanks def doScp(files): logger.log("Files to get: " + `files`) fNames = ' '.join(files) cmd = 'scp %s %s@%s:%s%s' % (fNames, SCP_USERNAME, SCP_HOST, SCP_IMG_FILE_DIR, SCP_IMG_FILE_PATH) logger.log("Sending: " + cmd) child = pexpect.spawn(cmd) i = child.expect(['assword:', 'yes/no'], timeout=30) if i == 0: child.sendline(SCP_PASSWD) elif i == 1: child.sendline("yes") child.expect("assword:", timeout=30) child.sendline(SCP_PASSWD) data = child.read() if data != None: success = True else: success = False child.close() logger.log("Files sent to SCP host") return success _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Once you call child.close() the exit and signal status will be stored in .exitstatus and .signalstatus, for a normal exit of the program .exitstatus will store the return code from SCP as per [1] [2] [3] and .signalstatus will be None. If SCP was terminated with a signal then .exitstatus will be None and .signalstatus will contain the signal value. Info found in the docs [4]. So the changes to your code will be: data = child.read() child.close() if child.exitstatus and child.exitstatus == 0: success = True else: success = False I'll leave putting in handling of failed error codes and abnormal termination to you. [1] http://support.attachmate.com/techdocs/2116.html [2] http://support.attachmate.com/techdocs/2487.html [3] http://support.attachmate.com/techdocs/2285.html [4] http://pexpect.sourceforge.net/pexpect.html -- Christian Witts Python Developer -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Thu Aug 25 09:51:29 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 25 Aug 2011 09:51:29 +0200 Subject: [Tutor] Help with if-elif-else structure Message-ID: I've written a function that rolls (standard) dice. There are a few special cases though: Any sixes rolled are removed and 2*number of sixes new dice are rolled in their place. Initial roll is important to keep track of. I've solved it with the following function: from random import randint def roll_dice(count, sides=6): """Rolls specified number of dice, returns a tuple with the format (result, number of 1's rolled, number of 6's rolled).""" initial_mins = None initial_max = None result = 0 while count: dice = [randint(1, sides) for die in range(count)] if initial_mins == None: initial_mins = dice.count(1) if initial_max == None: initial_max = dice.count(sides) result += sum(result for result in dice if result != sides) count = 2 * dice.count(sides) # number to roll the next time through. return (result, initial_mins, initial_max) Now, when I test against a target number (this is from a Swedish RPG system, btw -- I just wanted to see if I could write it), several things can happen: If I roll two sixes (on the initial roll) and below the target number (in total), it's a failure. If I roll two sixes (on the initial roll) and above the target number (in total), it's a critical failure. If I roll two ones (on the initial roll) and above the target number (in total), it's a success. If I roll two ones (on the initial roll) and below the target number (in total), it's a critical success. If I roll below the target number (in total), it's a success. If I roll above the target number (in total), it's a failure. I've written a horrible-looking piece of code to solve this, but I'm sure there are better ways to structure it: #assuming target number 15 roll = (result, initial_mins, initial_max) if roll[0] > 15: if roll[1] >= 2: print("Success") elif roll[2] >= 2: print("Critical failure!") else: print("Failure.") elif roll[0] <= 15: if roll[1] >= 2: print("Critical success!") elif roll[2] >= 2: print("Failure") else: print("Success") This handles all the test cases I've come up with, but it feels very ugly. Is there a better way to do this? -- best regards, Robert S. From alan.gauld at btinternet.com Thu Aug 25 10:19:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2011 09:19:49 +0100 Subject: [Tutor] Confirmation if command worked In-Reply-To: <4E55EACC.8080409@compuscan.co.za> References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> <4E55EACC.8080409@compuscan.co.za> Message-ID: On 25/08/11 07:25, Christian Witts wrote: > Once you call child.close() the exit and signal status will be stored in > .exitstatus and .signalstatus, for a normal exit of the program > .exitstatus will store the return code from SCP as per [1] [2] [3] and > .signalstatus will be None. If SCP was terminated with a signal then > .exitstatus will be None and .signalstatus will contain the signal > value. Info found in the docs [4]. > > data = child.read() > child.close() > > if child.exitstatus and child.exitstatus == 0: > success = True > else: > success = False Won't that if statement always evaluate to false? If exitstatus is 0 the first part of the and will be false and so the entire and expression is false. If exitstatus is not 0 then the second part of the and will be false and again the and result will be false. Did you mean to use exitstatus for both tests? Or am I missing something subtle here? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From washakie at gmail.com Thu Aug 25 10:27:36 2011 From: washakie at gmail.com (John) Date: Thu, 25 Aug 2011 10:27:36 +0200 Subject: [Tutor] understanding **kwargs syntax Message-ID: Just a quick question, is it wrong to use the *args and **kwargs ( the latter in particular) when DEFINING a function? def fest(**kwargs): """ a function test """ keys = sorted(kwargs.keys()) print("You provided {0} keywords::\n".format(len(keys))) for kw in keys: print("{0} => {1}".format(kw, kwargs[kw])) Are there some good examples of when this would be a good idea to implement? --john From washakie at gmail.com Thu Aug 25 10:30:56 2011 From: washakie at gmail.com (John) Date: Thu, 25 Aug 2011 10:30:56 +0200 Subject: [Tutor] help with a class In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2EE89@EMARC112VS01.exchad.jpmchase.net> Message-ID: Thanks for the feedback. I wasn't aware about the assert usage not being intended for production code. On Wed, Aug 24, 2011 at 11:37 PM, Alan Gauld wrote: > On 24/08/11 21:03, Prasad, Ramit wrote: >> >> I was under the impression that asserts are more for testing > >> than for production code > > That's true. > >> def overide_options(self, options, run_id=None): >> >> ? ? ? ? if not isinstance(options, dict): >> ? ? ? ? ? ? ? ? raise TypeError("override options requires a dict") > > This is good if you want to keep the check in for production. > But using an assert here while testing then removing it from production > would be a valid use too. The typecheck is not required for the function to > work if you are confident of the data being passed in. assert checks the > data while you are gaining that confidence. > > So either approach is valid. > It all depends on how variable your input data is going to be. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From cwitts at compuscan.co.za Thu Aug 25 10:37:21 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 25 Aug 2011 10:37:21 +0200 Subject: [Tutor] Confirmation if command worked In-Reply-To: References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> <4E55EACC.8080409@compuscan.co.za> Message-ID: <4E5609C1.2000400@compuscan.co.za> On 2011/08/25 10:19 AM, Alan Gauld wrote: > On 25/08/11 07:25, Christian Witts wrote: > >> Once you call child.close() the exit and signal status will be stored in >> .exitstatus and .signalstatus, for a normal exit of the program >> .exitstatus will store the return code from SCP as per [1] [2] [3] and >> .signalstatus will be None. If SCP was terminated with a signal then >> .exitstatus will be None and .signalstatus will contain the signal >> value. Info found in the docs [4]. >> >> data = child.read() >> child.close() >> >> if child.exitstatus and child.exitstatus == 0: >> success = True >> else: >> success = False > > Won't that if statement always evaluate to false? > > If exitstatus is 0 the first part of the and will be false and so the > entire and expression is false. > > If exitstatus is not 0 then the second part of the and will be false > and again the and result will be false. > > Did you mean to use exitstatus for both tests? > > Or am I missing something subtle here? > Good catch, it should be `if child.exitstatus != None and child.exitstatus == 0:` or removing the first part entirely. The zero-evaluating-as-False has bitten me before and for some reason I still on occasion forget it even though I use it often for data extracts. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Aug 25 10:38:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2011 09:38:11 +0100 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: References: Message-ID: On 25/08/11 08:51, Robert Sjoblom wrote: > If I roll two sixes (on the initial roll) and below the target number > (in total), it's a failure. > If I roll two sixes (on the initial roll) and above the target number > (in total), it's a critical failure. > If I roll two ones (on the initial roll) and above the target number > (in total), it's a success. > If I roll two ones (on the initial roll) and below the target number > (in total), it's a critical success. > If I roll below the target number (in total), it's a success. > If I roll above the target number (in total), it's a failure. > > I've written a horrible-looking piece of code to solve this, but I'm > sure there are better ways to structure it: > > #assuming target number 15 > roll = (result, initial_mins, initial_max) I'd forget the tuple and just use the names, it is more readable that way... > if roll[0]> 15: > if roll[1]>= 2: > print("Success") > elif roll[2]>= 2: > print("Critical failure!") if result > 15: if initial_mins >= 2:... elif initial_max >=2:... But otherwise it seems to reflect the rules as you've written them... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 25 10:44:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2011 09:44:55 +0100 Subject: [Tutor] understanding **kwargs syntax In-Reply-To: References: Message-ID: On 25/08/11 09:27, John wrote: > Just a quick question, > > is it wrong to use the *args and **kwargs ( the latter in particular) > when DEFINING a function? No, in fact it's essential if you don't know in advance what arguments are going to be passed to the function. This is very common if you are wrapping another function that itself takes variable arguments. > def fest(**kwargs): > """ a function test """ > keys = sorted(kwargs.keys()) > > print("You provided {0} keywords::\n".format(len(keys))) > for kw in keys: > print("{0} => {1}".format(kw, kwargs[kw])) > > Are there some good examples of when this would be a good idea to implement? GUI frameworks like Tkinter often take variable numbers of configuration values. If you want to wrap that with a function of your own you can do something like(pseudocode): def myfunc(**kwargs): if some interesting arg exists do something with it return wrappedFunc(kwargs) There are plenty other cases, try grepping the standard library code for lines with def and **kwargs for some examples... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.sjoblom at gmail.com Thu Aug 25 11:05:56 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 25 Aug 2011 11:05:56 +0200 Subject: [Tutor] Help with if-elif-else structure Message-ID: >> #assuming target number 15 >> roll = (result, initial_mins, initial_max) > I'd forget the tuple and just use the names, > it is more readable that way... >if result > 15: > if initial_mins >= 2:... > elif initial_max >=2:... > But otherwise it seems to reflect the rules as you've written them... Oh, that's a good idea, that's definitely more readable. But the issue isn't if it reflects the rules (although it's good that it does!), but whether there's a better way to structure the if-elif-else part, or even if there's a better way to handle it. I'll probably send it through a function, something like (pseudocode): def check_result(diceroll_result, initial_mins, initial_max): check for success/failure and so on return result But even so, is my if-elif-else structure the best way to go about it? -- best regards, Robert S. From steve at alchemy.com Thu Aug 25 10:48:16 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 25 Aug 2011 01:48:16 -0700 Subject: [Tutor] Confirmation if command worked In-Reply-To: <4E5609C1.2000400@compuscan.co.za> References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> <4E55EACC.8080409@compuscan.co.za> <4E5609C1.2000400@compuscan.co.za> Message-ID: <4E560C50.90603@alchemy.com> On 25-Aug-11 01:37, Christian Witts wrote: > Good catch, it should be `if child.exitstatus != None and > child.exitstatus == 0:` It's better form to say if child.exitstatus is not None instead of comparing for equality to None with the != operator. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From lisi.reisz at gmail.com Thu Aug 25 11:46:33 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 25 Aug 2011 10:46:33 +0100 Subject: [Tutor] Raw input query (?) Message-ID: <201108251046.33881.lisi.reisz@gmail.com> I copied and ran the following script: multiplier = 12 for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) That ran perfectly and gave me the 12 times table. I then decided that it would be fun to branch out and make teh script "universal", so I wrote and ran: print "Which times table do you want?" multiplier = raw_input () for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) The j in range section of code is identical, but I now get: lisi at Tux:~/Python$ python multiplier.py Which times table do you want? 4 Traceback (most recent call last): File "multiplier.py", line 8, in print "%d x %d = %d" %(j, multiplier, j*multiplier) TypeError: int argument required lisi at Tux:~/Python$ What extra should I have done because the variable value came from the keyboard, and why is it different from the first example? Lisi From d at davea.name Thu Aug 25 12:17:49 2011 From: d at davea.name (Dave Angel) Date: Thu, 25 Aug 2011 06:17:49 -0400 Subject: [Tutor] Raw input query (?) In-Reply-To: <201108251046.33881.lisi.reisz@gmail.com> References: <201108251046.33881.lisi.reisz@gmail.com> Message-ID: <4E56214D.1080800@davea.name> On 08/25/2011 05:46 AM, Lisi wrote: > I copied and ran the following script: > > multiplier = 12 > > for j in range(1,13): > print "%d x %d = %d" %(j, multiplier, j*multiplier) > > That ran perfectly and gave me the 12 times table. > > I then decided that it would be fun to branch out and make teh > script "universal", so I wrote and ran: > > print "Which times table do you want?" > > multiplier = raw_input () > > for j in range(1,13): > print "%d x %d = %d" %(j, multiplier, j*multiplier) > > The j in range section of code is identical, but I now get: > > lisi at Tux:~/Python$ python multiplier.py > Which times table do you want? > 4 > Traceback (most recent call last): > File "multiplier.py", line 8, in > print "%d x %d = %d" %(j, multiplier, j*multiplier) > TypeError: int argument required > lisi at Tux:~/Python$ > > What extra should I have done because the variable value came from the > keyboard, and why is it different from the first example? > > Lisi > If you get an error with that specific a wording, use the system to tell you what's wrong. Add a print statement immediately before the offending line, and print thorough information about each of the variables used. In this case, the obvious candidate is multiplier. So print repr(multiplier) and type(multiplier) and see if that shows you anything different from what the error message asked for, or different from the repr() and type() of your first script. Now that you know what the type of variable multiplier is, can you guess how to convert it to the one you need? DaveA -- DaveA From steve at pearwood.info Thu Aug 25 14:18:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Aug 2011 22:18:41 +1000 Subject: [Tutor] Confirmation if command worked In-Reply-To: <4E55EACC.8080409@compuscan.co.za> References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> <4E55EACC.8080409@compuscan.co.za> Message-ID: <4E563DA1.6060703@pearwood.info> Christian Witts wrote: > if child.exitstatus and child.exitstatus == 0: > success = True > else: > success = False There is never any need to write Python code that looks like that. (Or in any other language I'm familiar with either.) Anything of the form: if some_condition: flag = True else: flag = False is better written as: flag = some_condition In the above example, you should write: success = child.exitstatus and child.exitstatus == 0 except that I think you have the condition wrong... if exitstatus is zero, you get False and True => False, but if exitstatus is non-zero, you get True and False => False. So you will always get success = False. -- Steven From steve at pearwood.info Thu Aug 25 14:55:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Aug 2011 22:55:56 +1000 Subject: [Tutor] help with a class In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2EE89@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E56465C.9020307@pearwood.info> John wrote: > Thanks for the feedback. I wasn't aware about the assert usage not > being intended for production code. That's not quite true. There is nothing wrong with using asserts in production code. The important thing is to use them *properly*. Asserts are for checking your internal program logic, and should never be used for validating data. The reason is that asserts can be turned off. If the user calls Python with the optimize -O switch, all assertions are silently dropped from the code when it is compiled. Obviously this is disastrous if you are using assert to check input arguments and user data, since now those checks won't happen. But assertions can still be useful in production code. When and why? For testing *your* logic about the program. The sad truth is that programmers are merely human, and we make mistakes. Sometimes we reason that our code does one thing, when in fact we've forgotten a case or misunderstood it, and the code does something different from what we expected. Or we fear that some function we rely on has a bug. As they say, beware of any situation which you are sure can't possibly happen, because it surely will. To program defensively, you might write something like this: n = some_function(arg) if n > 0: do_something(n) else: # This can never happen! But just in case it does... raise RuntimeError("unexpected internal error") What does this tell us? It tells us that some_function promises to always return a positive number (this is sometimes called a contract), but we don't *quite* believe it. If we trusted it completely, we would just write this: n = some_function(arg) do_something(n) and that's perfectly fine. 99.999% of your code should look like that: you trust the function to do what you expect. But perhaps you have a little nagging doubt: "some_function is really complicated, I'm pretty sure it works correctly, but maybe I made a subtle mistake". Hey, you're only human. So you leave the test in *just in case*. Assertions are for those "just in case" tests. If you're sure that the "else" clause will never happen, why do the test every time? Because you're cautious. But maybe you don't need to be cautious all the time. Perhaps you'd like an option to run your code faster by skipping all those tests that you're sure will never fail. So you might start with a global variable: __debug__ = True and write code like this: n = some_function(arg) if __debug__: # Just in case... if n <= 0: # note we swap the test around. # This can never happen! But just in case it does... raise RuntimeError("unexpected internal error") do_something(n) That gives you the best of both worlds: if __debug__ is True (the default), you have the extra safety of the debugging test. And if it's False, you skip the test, and so your code is a little bit faster. That's what Python *automatically* does for you. Just write your code like this instead n = some_function(arg) assert n <= 0, "unexpected internal error" do_something(n) and the Python compiler will automatically handle everything for you, according to whether or not you are running in standard "debug mode" or with the -O optimize switch. -- Steven From steve at pearwood.info Thu Aug 25 15:02:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Aug 2011 23:02:27 +1000 Subject: [Tutor] Raw input query (?) In-Reply-To: <201108251046.33881.lisi.reisz@gmail.com> References: <201108251046.33881.lisi.reisz@gmail.com> Message-ID: <4E5647E3.7080903@pearwood.info> Lisi wrote: > I copied and ran the following script: [...] > What extra should I have done because the variable value came from the > keyboard, and why is it different from the first example? You can investigate this yourself: >>> a = 12 >>> a = raw_input("please type 12") please type 12 12 >>> a = 12 >>> b = raw_input("please type 12: ") please type 12: 12 >>> a 12 >>> b '12' See the difference? Here's more of a clue: >>> type(a) >>> type(b) -- Steven From steve at pearwood.info Thu Aug 25 15:27:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Aug 2011 23:27:42 +1000 Subject: [Tutor] Confirmation if command worked In-Reply-To: <4E563DA1.6060703@pearwood.info> References: <007401cc62eb$19ee5c70$4dcb1550$@com.au> <4E55EACC.8080409@compuscan.co.za> <4E563DA1.6060703@pearwood.info> Message-ID: <4E564DCE.6080805@pearwood.info> Steven D'Aprano wrote: > if some_condition: > flag = True > else: > flag = False > > is better written as: > > flag = some_condition Actually, that's a slight over-simplification. some_condition may not actually be a bool. If you don't mind flag also being a non-bool, that's fine, but if you want to ensure that it is one of True/False, then you can call: flag = bool(some_condition) to force flag to be one of True or False. But that's generally not necessary unless you care about what flag looks like when printed. -- Steven From alan.gauld at btinternet.com Thu Aug 25 16:17:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2011 15:17:04 +0100 Subject: [Tutor] Raw input query (?) In-Reply-To: <201108251046.33881.lisi.reisz@gmail.com> References: <201108251046.33881.lisi.reisz@gmail.com> Message-ID: On 25/08/11 10:46, Lisi wrote: > I copied and ran the following script: > > multiplier = 12 > > for j in range(1,13): > print "%d x %d = %d" %(j, multiplier, j*multiplier) > > That ran perfectly and gave me the 12 times table. > > I then decided that it would be fun to branch out and make teh > script "universal", so I wrote and ran: > > print "Which times table do you want?" > > multiplier = raw_input () I seem to recognise that code :-) You will find if you fast-forward to the "talking to the user" topic that we revisit the multiplication table doing exactly this. You will find out what is missing there. :-) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Thu Aug 25 16:36:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 25 Aug 2011 10:36:27 -0400 Subject: [Tutor] String encoding Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> I have a string question for Python2. Basically I have two strings with non-ASCII characters and I would like to have a better understanding of what the escapes are from and how to possibly remove/convert/encode the string to something else. If the description of my intended action is vague it is because my intent at this point is vague until I understand the situation better. ' M\xc9XICO' and ' M\311XICO' Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From g.nius.ck at gmail.com Thu Aug 25 17:23:40 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 25 Aug 2011 11:23:40 -0400 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: References: Message-ID: Looks good, although I would add one or two things. > #assuming target number 15 > Put that in a variable for the target number > roll = (result, initial_mins, initial_max) > if roll[0] > 15: > if roll[1] >= 2: You could even put all the constants in variables > print("Success") > elif roll[2] >= 2: > print("Critical failure!") > else: > print("Failure.") > elif roll[0] <= 15: > if roll[1] >= 2: > print("Critical success!") > elif roll[2] >= 2: > print("Failure") > else: > print("Success") > Also need a couple comments, plus everything from the other emails. -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Aug 25 17:24:48 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 25 Aug 2011 11:24:48 -0400 Subject: [Tutor] Python Speech In-Reply-To: References: Message-ID: It wasn't on the repo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Thu Aug 25 18:49:08 2011 From: suryak at live.com (surya k) Date: Thu, 25 Aug 2011 22:19:08 +0530 Subject: [Tutor] largest palindrome number Message-ID: Hi, I'm doing a puzzle where it asked me to find the largest palindrome number formed by the product of two three-digit numbers. They mentioned an example saying that 9009 is the largest palindrome number formed by two two-digit numbers (99 * 91). I've written my code this way.. and I tested it with the given example and I got it right! *Logic I used :* largest two digit number is 99 and three digit number is 999.. so largest product of two two-digit numbers is < 100*100 and for three-digit numbers is < 1000*1000. So, I used a for loop and it assigns a palindromic value to *PNum* till it is < 100*100 (for 2 digit number) and < 1000*1000 (for three-digit number).. Thus it stops at the max possible palindromic value, which is what we want. def palindrome (n) : TempN = n rev = 0 while n != 0 : k = n % 10 rev = (rev * 10) + k n = n / 10 if TempN == rev : return TempN # Palindrome else : return 0 # not Palindrome for i in range (1,100) : for j in range (i,100) : Temp = palindrome(i*j) if Temp < 10000 and Temp != 0 : PNum = Temp print PNum So, for getting the largest palindrome number formed by two three-digit numbers, I changed 100 to 1000 and 1,00,00 to 1,000,000 in the highlighted area. Thus I got the answer to be 888888. When I submitted the answer, its saying wrong! Where I'm going wrong ? help me, please ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Aug 25 18:54:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Aug 2011 17:54:01 +0100 Subject: [Tutor] String encoding In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 25/08/11 15:36, Prasad, Ramit wrote: > I have a string question for Python2. Basically I have two strings with > non-ASCII characters and I would like to have a better understanding > of what the escapes are from > ' M\xc9XICO' and ' M\311XICO' I don't know what they are from but they are both the same value, one in hex and one in octal. 0xC9 == 0311 As for the encoding mechanisms I'm afraid I can't help there! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Thu Aug 25 19:18:36 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 25 Aug 2011 19:18:36 +0200 Subject: [Tutor] largest palindrome number In-Reply-To: References: Message-ID: On Thu, Aug 25, 2011 at 6:49 PM, surya k wrote: > Hi, > I'm doing a puzzle where it asked me to find the largest palindrome number > formed by the product of two three-digit numbers.?They mentioned an example > saying that 9009 is the largest palindrome number formed by two two-digit > numbers (99 * 91). > I've written my code this way.. and I tested it with the given example and I > got it right! > Logic I used : > largest two digit number is 99 and three digit number is 999.. so largest > product of two two-digit numbers is < 100*100 and for three-digit numbers is > < 1000*1000. > So, I used a for loop and it assigns a palindromic value to PNum till it is > ?< 100*100 (for 2 digit number) and < 1000*1000 (for three-digit number).. > Thus it stops at the max possible palindromic value, which is what we want. > > def palindrome (n) : > > ?? ?TempN = n > ?? ?rev ?= 0 > ?? ?while n != 0 : > ?? ? ? ?k = n % 10 > ?? ? rev = (rev * 10) + k > ?? ? n = n / 10 > ?? ?if ?TempN == rev : > ?? ? ? ?return TempN # Palindrome > ?? ?else : > ?? ? return 0 # not Palindrome > > for i in range (1,100) : > ?? ?for j in range (i,100) : > ?? ? ? ?Temp = palindrome(i*j) > ?? ? ? ?if Temp < 10000 and Temp != 0 : > ?? ? ? ? ? PNum = Temp > print PNum > > > So, for getting the largest palindrome number formed by two three-digit > numbers, I changed 100 to 1000 and 1,00,00 to 1,000,000 in the highlighted > area. Thus I got the answer to be 888888. When I submitted the answer, its > saying wrong! > Where I'm going wrong ? > help me, please ! > When you get a new palindrome, you should make sure it's bigger than the one you already have before you replace the old one. 888888 is the last palindrome you find, but it is not the the biggest. You cannot assume the biggest one will be found last. From lisi.reisz at gmail.com Thu Aug 25 19:38:49 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 25 Aug 2011 18:38:49 +0100 Subject: [Tutor] Raw input query (?) In-Reply-To: References: <201108251046.33881.lisi.reisz@gmail.com> Message-ID: <201108251838.49670.lisi.reisz@gmail.com> On Thursday 25 August 2011 15:17:04 Alan Gauld wrote: > On 25/08/11 10:46, Lisi wrote: > > I copied and ran the following script: > > > > multiplier = 12 > > > > for j in range(1,13): > > print "%d x %d = %d" %(j, multiplier, j*multiplier) > > > > That ran perfectly and gave me the 12 times table. > > > > I then decided that it would be fun to branch out and make teh > > script "universal", so I wrote and ran: > > > > print "Which times table do you want?" > > > > multiplier = raw_input () > > I seem to recognise that code :-) > > You will find if you fast-forward to the "talking to the user" topic > that we revisit the multiplication table doing exactly this. You will > find out what is missing there. :-) Thanks to all three of you for your input. I do now understand what is wrong, but can't work out how to put it right. I did as you suggested, Dave. But by the time I was able to get to my computer and read it, the others' replies had come in. So I ran it mainly to learn how to do it. And I am not entirely sure that I would have understood the result if I hadn't already known what it was meant to be saying!! I started to say that I would just have to wait, but on second thoughts I'll fast forward as suggested, and then go back to do the missing sections. Lisi From washakie at gmail.com Thu Aug 25 19:51:15 2011 From: washakie at gmail.com (John) Date: Thu, 25 Aug 2011 19:51:15 +0200 Subject: [Tutor] help with 'organization' Message-ID: Hello, I am writing a module that will have two classes ('runners') I am calling them, as they will ultimately use subprocess to run a command line program, so they are basically option parsers, etc... As I wrote the second 'runner', I realized many of the methods are going to be the same as the first, so I would actually like to create a third class that has the methods which are mutual between the two. The problem are the 'self' calls.... I know a code example might help, so I try to show it here (my code I'm afraid is too complex and ugly at the moment). You can see the it fails because MyTools doesn't have 'this' attribute... class MyTools: def f(self, this): print(this) def foo(self): this = self.this print(this) class MyProcess: def __init__(self): self.tools = MyTools() self.this = 'My Process, this' self.tools.f(self.this) self.tools.foo() if __name__ == "__main__": mp = MyProcess() From justin.wendl at gmail.com Thu Aug 25 20:56:02 2011 From: justin.wendl at gmail.com (Justin Wendl) Date: Thu, 25 Aug 2011 14:56:02 -0400 Subject: [Tutor] Finding the differences between two lists Message-ID: Hello, Bare with me, as I am new to Python and a beginner programmer. I am trying to compare two lists (not of the same length), and create a new list of items that are -not- found in both lists. Scenario: I have a list of MAC addresses that are known and good, and am comparing it to a list of MACs found in a scan. I want to weed out the those which are unknown. I am using IDLE (Python 2.7) on Windows, and all files are in the same directory. Code: scanResults = open('scanResults.txt', 'r') verifiedList = open('verifiedList.txt', 'r') badMacs = [] for mac in scanResults: if mac not in verifiedList: print mac badMacs.append(mac) else: break When I print 'badMacs', the results come up empty: [] Any help would be greatly appreciated! Regards, Justin -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Thu Aug 25 20:59:53 2011 From: washakie at gmail.com (John) Date: Thu, 25 Aug 2011 20:59:53 +0200 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: Not entirely sure, but I think it is as simple as: scanResults = open('scanResults.txt', 'r').readlines() verifiedList = open('verifiedList.txt', 'r').readlines() Now both are lists. I assume each mac address is on it's own line? -john On Thu, Aug 25, 2011 at 8:56 PM, Justin Wendl wrote: > Hello, > > Bare with me, as I am new to Python and a beginner programmer. > I am trying to compare two lists (not of the same length), and create a new > list of items that are -not- found in both lists. > > Scenario: I have a list of MAC addresses that are known and good, and am > comparing it to a list of MACs found in a scan.? I want to weed out the > those which are unknown.? I am using IDLE (Python 2.7) on Windows, and all > files are in the same directory. > > Code: > > scanResults = open('scanResults.txt', 'r') > verifiedList = open('verifiedList.txt', 'r') > badMacs = [] > > for mac in scanResults: > ? if mac not in verifiedList: > ??? print mac > ??? badMacs.append(mac) > ? else: > ??? break > > > When I print 'badMacs', the results come up empty: > [] > > > Any help would be greatly appreciated! > > Regards, > Justin > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From justin.wendl at gmail.com Thu Aug 25 21:08:43 2011 From: justin.wendl at gmail.com (Justin Wendl) Date: Thu, 25 Aug 2011 15:08:43 -0400 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: Hi John, Thanks for the quick response. Unfortunately it is returning the same result.. - Justin On Thu, Aug 25, 2011 at 2:59 PM, John wrote: > Not entirely sure, but I think it is as simple as: > > scanResults = open('scanResults.txt', 'r').readlines() > verifiedList = open('verifiedList.txt', 'r').readlines() > > Now both are lists. I assume each mac address is on it's own line? > > -john > > > On Thu, Aug 25, 2011 at 8:56 PM, Justin Wendl > wrote: > > Hello, > > > > Bare with me, as I am new to Python and a beginner programmer. > > I am trying to compare two lists (not of the same length), and create a > new > > list of items that are -not- found in both lists. > > > > Scenario: I have a list of MAC addresses that are known and good, and am > > comparing it to a list of MACs found in a scan. I want to weed out the > > those which are unknown. I am using IDLE (Python 2.7) on Windows, and > all > > files are in the same directory. > > > > Code: > > > > scanResults = open('scanResults.txt', 'r') > > verifiedList = open('verifiedList.txt', 'r') > > badMacs = [] > > > > for mac in scanResults: > > if mac not in verifiedList: > > print mac > > badMacs.append(mac) > > else: > > break > > > > > > When I print 'badMacs', the results come up empty: > > [] > > > > > > Any help would be greatly appreciated! > > > > Regards, > > Justin > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Python 2.6 > PIL 1.1.6 > Mailman 2.1.9 > Postfix 2.4.5 > Procmail v3.22 2001/09/10 > Basemap: 1.0 > Matplotlib: 1.0.0 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Thu Aug 25 21:10:24 2011 From: washakie at gmail.com (John) Date: Thu, 25 Aug 2011 21:10:24 +0200 Subject: [Tutor] help with 'organization' In-Reply-To: References: Message-ID: Ha! Inheritance! On Thu, Aug 25, 2011 at 7:51 PM, John wrote: > Hello, I am writing a module that will have two classes ('runners') I > am calling them, as they will ultimately use subprocess to run a > command line program, so they are basically option parsers, etc... > > As I wrote the second 'runner', I realized many of the methods are > going to be the same as the first, so I would actually like to create > a third class that has the methods which are mutual between the two. > The problem are the 'self' calls.... > > I know a code example might help, so I try to show it here (my code > I'm afraid is too complex and ugly at the moment). You can see the it > fails because MyTools doesn't have 'this' attribute... > > class MyTools: > ? ?def f(self, this): > ? ? ? ?print(this) > > ? ?def foo(self): > ? ? ? ?this = self.this > ? ? ? ?print(this) > > class MyProcess: > ? ?def __init__(self): > ? ? ? ?self.tools = MyTools() > > ? ? ? ?self.this = 'My Process, this' > > ? ? ? ?self.tools.f(self.this) > > ? ? ? ?self.tools.foo() > > if __name__ == "__main__": > ? ?mp = MyProcess() > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From eire1130 at gmail.com Thu Aug 25 21:12:00 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 25 Aug 2011 15:12:00 -0400 Subject: [Tutor] help with 'organization' In-Reply-To: References: Message-ID: On Thu, Aug 25, 2011 at 1:51 PM, John wrote: > Hello, I am writing a module that will have two classes ('runners') I > am calling them, as they will ultimately use subprocess to run a > command line program, so they are basically option parsers, etc... > > As I wrote the second 'runner', I realized many of the methods are > going to be the same as the first, so I would actually like to create > a third class that has the methods which are mutual between the two. > The problem are the 'self' calls.... > > I know a code example might help, so I try to show it here (my code > I'm afraid is too complex and ugly at the moment). You can see the it > fails because MyTools doesn't have 'this' attribute... > > class MyTools: > def f(self, this): > print(this) > > def foo(self): > this = self.this > print(this) > > class MyProcess: > def __init__(self): > self.tools = MyTools() > > self.this = 'My Process, this' > > self.tools.f(self.this) > > self.tools.foo() > > if __name__ == "__main__": > mp = MyProcess() > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I am having a very difficult time following what you are trying to do, but then, i'm not that bright, so it's probably me. But, I will say this: class MyTools: def f(self, this): print(this) def foo(self): this = self.this print(this) In the second method (foo) you have it creating a local variable called this, which is equal to the class variable self.this. Why not just use the class variable throughout that method? So, print(self.this). My second thing, and this is just a personal pet peeve, why not create descriptive names for your variables? Creating things called this or that (and in this case, literally this or that) is hyper confusing. My third thing. I think you are going to end up with an attribute error because I don't see where the class has ever created a class variable called this. Maybe you meant to do something like this instead: class MyTools: def __init__(self, this): self.this = this def f(self): print(self.this) def foo(self): print(self.this) so in your other object, it would then look something like this: class MyProcess: def __init__(self): self.this = 'My Process, this' self.tools = MyTools(self.this) self.tools.f() self.tools.foo() But, every time you instantiate MyProcess (not call it) you are going to call the two methods of Tools class. If you want to seperate this, so you can do something like tools.foo() and then later on go tools.f() you can do that in a few ways: One, you can just get rid of self.tools.f() self.tools.foo() and once you create a MyProcess object you are free to call tools methods at your leisure. For example m = MyProcess() m.tools.foo() m.tools.f() Unless you really do want those methods once you create the instance because it's relevent to the creation of the object, then leave them where they are. Lastly, I don't understand what you mean by "self" calls. This seems rather academic to me, do you have a real example? I also don't understand what a Runner is. Maybe its some compsci term or something. -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Thu Aug 25 21:26:58 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Fri, 26 Aug 2011 00:56:58 +0530 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: You may try using set instead of list. >>> verifiedList = {[1,2,3} >>> scanResults = {1,2,3,4,5} >>> badMacs = scanResults - verifiedList >>> badMacs set([4, 5]) >>> verifiedList = {1,2,3,7,8,9} >>> badMacs = scanResults - verifiedList >>> badMacs set([4, 5]) -- shantanoo On 26-Aug-2011, at 12:26 AM, Justin Wendl wrote: > Hello, > > Bare with me, as I am new to Python and a beginner programmer. > I am trying to compare two lists (not of the same length), and create a new list of items that are -not- found in both lists. > > Scenario: I have a list of MAC addresses that are known and good, and am comparing it to a list of MACs found in a scan. I want to weed out the those which are unknown. I am using IDLE (Python 2.7) on Windows, and all files are in the same directory. > > Code: > > scanResults = open('scanResults.txt', 'r') > verifiedList = open('verifiedList.txt', 'r') > badMacs = [] > > for mac in scanResults: > if mac not in verifiedList: > print mac > badMacs.append(mac) > else: > break > > > When I print 'badMacs', the results come up empty: > [] > > > Any help would be greatly appreciated! > > Regards, > Justin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From gtirloni at sysdroid.com Thu Aug 25 21:29:31 2011 From: gtirloni at sysdroid.com (Giovanni Tirloni) Date: Thu, 25 Aug 2011 16:29:31 -0300 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: On Thu, Aug 25, 2011 at 4:08 PM, Justin Wendl wrote: > Hi John, > > Thanks for the quick response.? Unfortunately it is returning the same > result.. Please send a small example of the contents in each file. -- Giovanni Tirloni sysdroid.com From justin.wendl at gmail.com Thu Aug 25 21:33:33 2011 From: justin.wendl at gmail.com (Justin Wendl) Date: Thu, 25 Aug 2011 15:33:33 -0400 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: Giovanni, scanResults.txt: 00:16:3E:D0:26:25 00:16:3E:43:7D:24 00:16:3E:2D:6D:F8 00:16:3E:EB:04:D9 00:16:3E:FD:85:0B 00:1C:14:AF:04:39 00:1C:14:E3:D6:CA 00:1C:14:15:B2:C8 00:1C:14:47:5A:A0 00:1C:14:BA:D9:E9 verifiedList: 00:1C:14:BA:D9:E9 00:16:3E:D0:26:25 00:1C:14:AF:04:39 00:16:3E:EB:04:D9 - Justin On Thu, Aug 25, 2011 at 3:29 PM, Giovanni Tirloni wrote: > On Thu, Aug 25, 2011 at 4:08 PM, Justin Wendl > wrote: > > Hi John, > > > > Thanks for the quick response. Unfortunately it is returning the same > > result.. > > Please send a small example of the contents in each file. > > -- > Giovanni Tirloni > sysdroid.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Thu Aug 25 21:48:40 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 25 Aug 2011 21:48:40 +0200 Subject: [Tutor] Finding the differences between two lists Message-ID: > Scenario: I have a list of MAC addresses that are known and good, and am > comparing it to a list of MACs found in a scan. ?I want to weed out the > those which are unknown. ?I am using IDLE (Python 2.7) on Windows, and all > files are in the same directory. > > Code: > > scanResults = open('scanResults.txt', 'r') > verifiedList = open('verifiedList.txt', 'r') You don't close the files after you open them, which is bad practice. "with" is a great keyword, because it closes the file once it's run its block of code. We'll use that: with open("scanResults.txt", "r") as f: #open scanResults.txt and put the file object in variable f scanResults = f.readlines() #once this finishes scanResults.txt is closed with open("verifiedList.txt", "r") as f: verifiedList = f.readlines() > badMacs = [] > for mac in scanResults: > ?if mac not in verifiedList: > ? ?print mac > ? ?badMacs.append(mac) > ?else: > ? ?break I can't say for sure, since I don't know how your logs look, but this loop will break at the first match (I think!). You could try changing the break statement to a continue statement (or just ignoring it altogether -- if it's in verifiedList you don't need to do anything). Anyway, list comprehensions are something I've been experimenting with lately, because I need the practice, so I'm going to suggest that instead: badMacs = [item for item in scanResults if item not in verifiedList] Other than that, there's not much to say; the standard is 4 spaces indentation, personally I feel that 1 space is too little, since it's hard to see where one block ends and another begins. best regards, Robert S. From andreengels at gmail.com Thu Aug 25 21:49:28 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 25 Aug 2011 21:49:28 +0200 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: On Thu, Aug 25, 2011 at 9:08 PM, Justin Wendl wrote: > Hi John, > > Thanks for the quick response. Unfortunately it is returning the same > result.. > > This is caused by the else: break part of the the code. Break breaks out of the loop, thus you skip all following elements if you go through the 'else' part once. What you probably meant was: else: continue This skips only the remainder of the current traversion of the loop, and goes on with the next one. In this case it's even simpler: There is no remainder of the current run of the loop to skip, so you should be allright if you remove the else part altogether. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From justin.wendl at gmail.com Thu Aug 25 22:22:27 2011 From: justin.wendl at gmail.com (Justin Wendl) Date: Thu, 25 Aug 2011 16:22:27 -0400 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: shantanoo, Andre, and Robert: All of your solutions seem to work (and thank you for the tips!), however, with each solution there seems to be 2 MACs that should not be in the results. 00:1C:14:BA:D9:E9 and 00:16:3E:EB:04:D9 should not be be turning up in the results because they are in the 'verified' list. These lists are not sorted - do you think that could be the issue? - Justin On Thu, Aug 25, 2011 at 3:48 PM, Robert Sjoblom wrote: > > Scenario: I have a list of MAC addresses that are known and good, and am > > comparing it to a list of MACs found in a scan. I want to weed out the > > those which are unknown. I am using IDLE (Python 2.7) on Windows, and > all > > files are in the same directory. > > > > Code: > > > > scanResults = open('scanResults.txt', 'r') > > verifiedList = open('verifiedList.txt', 'r') > > You don't close the files after you open them, which is bad practice. > "with" is a great keyword, because it closes the file once it's run > its block of code. We'll use that: > > with open("scanResults.txt", "r") as f: #open scanResults.txt and > put the file object in variable f > scanResults = f.readlines() #once this finishes > scanResults.txt is closed > with open("verifiedList.txt", "r") as f: > verifiedList = f.readlines() > > > badMacs = [] > > for mac in scanResults: > > if mac not in verifiedList: > > print mac > > badMacs.append(mac) > > else: > > break > > I can't say for sure, since I don't know how your logs look, but this > loop will break at the first match (I think!). You could try changing > the break statement to a continue statement (or just ignoring it > altogether -- if it's in verifiedList you don't need to do anything). > Anyway, list comprehensions are something I've been experimenting with > lately, because I need the practice, so I'm going to suggest that > instead: > badMacs = [item for item in scanResults if item not in verifiedList] > > Other than that, there's not much to say; the standard is 4 spaces > indentation, personally I feel that 1 space is too little, since it's > hard to see where one block ends and another begins. > > best regards, > Robert S. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Thu Aug 25 23:21:12 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 25 Aug 2011 23:21:12 +0200 Subject: [Tutor] Finding the differences between two lists Message-ID: > shantanoo, Andre, and Robert: > > All of your solutions seem to work (and thank you for the tips!), however, > with each solution there seems to be 2 MACs that should not be in the > results. > > 00:1C:14:BA:D9:E9 and > 00:16:3E:EB:04:D9 > > should not be be turning up in the results because they are in the > 'verified' list. ?These lists are not sorted - do you think that could be > the issue? Definitely not, it doesn't matter if they're sorted no matter what way you solve it. What matters is how the logfile looks to Python. Take this fake list I've made consisting of your two MAC addresses: scanResults = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9\n'] verifiedList = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9'] >>> scanResults == verifiedList False The difference, obviously, is that 00:16:3E:EB:04:D9 contains a newline \n in one of the files but not the other. As such, they're not identical. We can solve this (probably) by adding some more list comprehension when we open the files initially: with open("scanResults.txt", "r") as f: scanResults = [line.strip() for line in f.readlines()] with open("verifiedList.txt", "r") as f: verifiedList = [line.strip() for line in f.readlines()] badMacs = [item for item in scanResults if item not in verifiedList] I suspect that it's the newlines that are messing with you, but if it's something else I can't tell without the actual files. -- best regards, Robert S. From justin.wendl at gmail.com Fri Aug 26 00:40:58 2011 From: justin.wendl at gmail.com (Justin Wendl) Date: Thu, 25 Aug 2011 18:40:58 -0400 Subject: [Tutor] Finding the differences between two lists In-Reply-To: References: Message-ID: Robert, The lists were created using MS Notepad, and I forgot about the newlines - so you were absolutely right! So, is it possible to use strip() immediately when reading a file into a list to avoid confusion down the road, and is this common? Thank you everyone who contributed to this thread :-) - Justin On Thu, Aug 25, 2011 at 5:21 PM, Robert Sjoblom wrote: > > shantanoo, Andre, and Robert: > > > > All of your solutions seem to work (and thank you for the tips!), > however, > > with each solution there seems to be 2 MACs that should not be in the > > results. > > > > 00:1C:14:BA:D9:E9 and > > 00:16:3E:EB:04:D9 > > > > should not be be turning up in the results because they are in the > > 'verified' list. These lists are not sorted - do you think that could be > > the issue? > > Definitely not, it doesn't matter if they're sorted no matter what way > you solve it. What matters is how the logfile looks to Python. Take > this fake list I've made consisting of your two MAC addresses: > > scanResults = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9\n'] > verifiedList = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9'] > >>> scanResults == verifiedList > False > > The difference, obviously, is that 00:16:3E:EB:04:D9 contains a > newline \n in one of the files but not the other. As such, they're not > identical. We can solve this (probably) by adding some more list > comprehension when we open the files initially: > with open("scanResults.txt", "r") as f: > scanResults = [line.strip() for line in f.readlines()] > with open("verifiedList.txt", "r") as f: > verifiedList = [line.strip() for line in f.readlines()] > > badMacs = [item for item in scanResults if item not in verifiedList] > > I suspect that it's the newlines that are messing with you, but if > it's something else I can't tell without the actual files. > -- > best regards, > Robert S. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bspymaster at gmail.com Fri Aug 26 00:54:23 2011 From: bspymaster at gmail.com (Bspymaster) Date: Thu, 25 Aug 2011 17:54:23 -0500 Subject: [Tutor] finalizing code Message-ID: Hello! I recently started programming in python (I use IDLE with python 2.7 on ubuntu 11.04, by the way) and recently made a program (no interface) that launches other programs. The problem I'm having is that when I gave my friend the code, he had to get an editor to use the code. How do I make it so that when you open the program, it starts the code (so anyone can use it, not just those who have idle and know ow to program python)? Sorry if this is unclear. I basically want to make a stand- alone command line application (or one that boots in terminal). It's very basic and runs like so (except longer and slightly more complex): loop = 1 > while loop == 1: > choice = raw_input(">") > if choice == "prog1": > print "Launching Prog1" > os.system("prog1") > loop = 0 > else: > print "invalid program. Try again." God Bless, Ben Schwabe -------------- next part -------------- An HTML attachment was scrubbed... URL: From bspymaster at gmail.com Fri Aug 26 00:56:06 2011 From: bspymaster at gmail.com (Bspymaster) Date: Thu, 25 Aug 2011 17:56:06 -0500 Subject: [Tutor] finalizing code In-Reply-To: References: Message-ID: Hello! I recently started programming in python (I use IDLE with python 2.7 on ubuntu 11.04, by the way) and recently made a program (no interface) that launches other programs. The problem I'm having is that when I gave my friend the code, he had to get an editor to use the code. How do I make it so that when you open the program, it starts the code (so anyone can use it, not just those who have idle and know ow to program python)? Sorry if this is unclear. I basically want to make a stand- alone command line application (or one that boots in terminal). It's very basic and runs like so (except longer and slightly more complex): loop = 1 > while loop == 1: > choice = raw_input(">") > if choice == "prog1": > print "Launching Prog1" > os.system("prog1") > loop = 0 > else: > print "invalid program. Try again." God Bless, Ben Schwabe -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Aug 26 01:03:19 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 25 Aug 2011 19:03:19 -0400 Subject: [Tutor] finalizing code In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8DA@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Bspymaster Sent: Thursday, August 25, 2011 5:54 PM To: tutor at python.org Subject: [Tutor] finalizing code Hello! I recently started programming in python (I use IDLE with python 2.7 on ubuntu 11.04, by the way) and recently made a program (no interface) that launches other programs. The problem I'm having is that when I gave my friend the code, he had to get an editor to use the code. How do I make it so that when you open the program, it starts the code (so anyone can use it, not just those who have idle and know ow to program python)? Sorry if this is unclear. I basically want to make a stand- alone command line application (or one that boots in terminal). It's very basic and runs like so (except longer and slightly more complex): loop = 1 while loop == 1: choice = raw_input(">") if choice == "prog1": print "Launching Prog1" os.system("prog1") loop = 0 else: print "invalid program. Try again." God Bless, Ben Schwabe ================================================================= If it is just in the module directly, you can probably just say 'python file.py' It is usually recommended to stick everything into different functions then at the end say If __name__=="__main__": function() Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Aug 26 01:07:30 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 25 Aug 2011 19:07:30 -0400 Subject: [Tutor] String encoding In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> >I don't know what they are from but they are both the same value, one in >hex and one in octal. > >0xC9 == 0311 > >As for the encoding mechanisms I'm afraid I can't help there! Nice catch! Yeah, I am stuck on the encoding mechanism as well. I know how to encode/decode...but not what encoding to use. Is there a reference that I can look up to find what encoding that would correspond to? I know what the character looks like if that helps. I know that Python does display the correct character sometimes, but not sure when or why. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From wprins at gmail.com Fri Aug 26 01:39:50 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 26 Aug 2011 00:39:50 +0100 Subject: [Tutor] finalizing code In-Reply-To: References: Message-ID: On 25 August 2011 23:54, Bspymaster wrote: > How do I make it so that when you open the program, it starts the code (so > anyone can use it, not just those who have idle and know ow to program > python)? > To add to what Ramit's said: On Linux/Ubuntu it's customary to add as the top line of a script file a "shebang" or "hashbang" header ( http://en.wikipedia.org/wiki/Shebang_%28Unix%29), which typically looks like this for Python scripts: #!/usr/bin/env python This then allows the operating system to know which interpreter to use to run the script (Python in this case), when you directly try to execute the script. In order to be able to run the script like any other command on the operating system, you also need to actually mark the file as executable. This may be done via the GUI by right clicking and clicing on "Permssions" or more easily by executing the command: chmod +x file.py This tells the system to make the file executable by anyone on the system. If the current working folder is the location of the script, you dan then run it by entering: ./file.py Additionally it's useful to know that under Ubuntu (and likely some other Linux variants), if you create a folder called "bin" inside the your home folder and the the script in there, then you can run the script directly from any location since your home/bin folder will be automatically searched when you issue commands without specifying their path/location explicitly. Hope all that makes sense and helps you. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Aug 26 03:34:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 26 Aug 2011 11:34:16 +1000 Subject: [Tutor] String encoding In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E56F818.1040108@pearwood.info> Prasad, Ramit wrote: >> I don't know what they are from but they are both the same value, >> one in hex and one in octal. >> >> 0xC9 == 0311 >> >> As for the encoding mechanisms I'm afraid I can't help there! > > Nice catch! Yeah, I am stuck on the encoding mechanism as well. I > know how to encode/decode...but not what encoding to use. Is there a > reference that I can look up to find what encoding that would > correspond to? I know what the character looks like if that helps. I > know that Python does display the correct character sometimes, but > not sure when or why. In general, no. The same byte value (0xC9) could correspond to many different encodings. In general, you *must* know what the encoding is in order to tell how to decode the bytes. Think about it this way... if I gave you a block of data as hex bytes: 240F91BC03...FF90120078CD45 and then asked you whether that was a bitmap image or a sound file or something else, how could you tell? It's just *bytes*, it could be anything. All is not quite lost though. You could try decoding the bytes and see what you get, and see if it makes sense. Start with ASCII, Latin-1, UTF-8, UTF-16 and any other encodings in common use. (This would be like pretending the bytes were a bitmap, and looking at it, and trying to decide whether it looked like an actual picture or like a bunch of random pixels. Hopefully it wasn't meant to look like a bunch of random pixels.) Web browsers such as Internet Explorer and Mozilla will try to guess the encoding by doing frequency analysis of the bytes. Mozilla's encoding guesser has been ported to Python: http://chardet.feedparser.org/ But any sort of guessing algorithm is just a nasty hack. You are always better off ensuring that you accurately know the encoding. -- Steven From steve at pearwood.info Fri Aug 26 03:48:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 26 Aug 2011 11:48:34 +1000 Subject: [Tutor] help with 'organization' In-Reply-To: References: Message-ID: <4E56FB72.4010206@pearwood.info> John wrote: > I know a code example might help, so I try to show it here (my code > I'm afraid is too complex and ugly at the moment). You can see the it > fails because MyTools doesn't have 'this' attribute... Then give it one. > class MyTools: Add an initialisation method: def __init__(self, this): self.this = this > def f(self, this): > print(this) > > def foo(self): > this = self.this > print(this) > > class MyProcess: > def __init__(self): > self.tools = MyTools() > self.this = 'My Process, this' > self.tools.f(self.this) > self.tools.foo() And change this to: def __init__(self): self.this = 'My Process, this' self.tools = MyTools(self.this) self.tools.f(self.this) self.tools.foo() There are probably better, or at least other, ways to organise the code which will do the job. An abstract base class with just the shared methods might work. (I'm not sure if that's best described as a mixin or not...) class SharedMethods(object): # shared methods go here class FirstRunner(SharedMethods): # methods unique to FirstRunner class SecondRunner(SharedMethods): # methods unique to SecondRunner -- Steven From theirda at gmail.com Fri Aug 26 15:55:14 2011 From: theirda at gmail.com (TheIrda) Date: Fri, 26 Aug 2011 15:55:14 +0200 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: References: Message-ID: Hello, I'm quite new on python, so don't hit too hard if I'm wrong ;) A question on the logic... Does this means if roll[0] > 15: if roll[1] >= 2: print("Success") elif roll[2] >= 2: print("Critical failure!") that rolling multiple 1's get the priority on rolling multiple 6's? I mean result > 15 and 2 1's is always a critical success even if multiple 6 are rolled? also if roll[0] > 15: ......... elif roll[0] <=15: <--- this is redundant. already checked for > 15 so if here is always <= 15 if roll[1] >= 2: you can change with: elif roll[1] >= 2: And... which is the RPG name ? :p Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Aug 26 17:21:52 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 26 Aug 2011 11:21:52 -0400 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEC7@EMARC112VS01.exchad.jpmchase.net> >if roll[0] > 15: >?? ......... >elif roll[0] <=15:? <--- this is redundant. already checked for > 15 so if here is always <= 15 >??? if roll[1] >= 2: > >you can change with: > >elif roll[1] >= 2: That is not true. The first one looks at index [0], while the second one is index[1]. >>if roll[0] > 15: >> if roll[1] >= 2: >> print("Success") >> elif roll[2] >= 2: >> print("Critical failure!") This will print "Success" if the first roll is greater than 15 AND second roll is 2 or greater. It will print "Critical failure!" if the first roll is greater than 15 AND the second roll is less than 2 AND the third roll is 2 or greater. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of TheIrda Sent: Friday, August 26, 2011 8:55 AM To: Christopher King Cc: python mail list Subject: Re: [Tutor] Help with if-elif-else structure Hello, I'm quite new on python, so don't hit too hard if I'm wrong ;) A question on the logic... Does this means if roll[0] > 15: ? ?if roll[1] >= 2: ? ? ? ?print("Success") ? ?elif roll[2] >= 2: ? ? ? ?print("Critical failure!") that rolling multiple 1's get the priority on rolling multiple 6's? I mean result > 15 and 2 1's is always a critical success even if multiple 6 are rolled? also if roll[0] > 15: ?? ......... elif roll[0] <=15:? <--- this is redundant. already checked for > 15 so if here is always <= 15 ??? if roll[1] >= 2: you can change with: elif roll[1] >= 2: And... which is the RPG name ? :p Cheers This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From malaclypse2 at gmail.com Fri Aug 26 17:23:14 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 26 Aug 2011 11:23:14 -0400 Subject: [Tutor] String encoding In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Aug 25, 2011 at 7:07 PM, Prasad, Ramit wrote: > Nice catch! Yeah, I am stuck on the encoding mechanism as well. I know how to encode/decode...but not what encoding to use. Is there a reference that I can look up to find what encoding that would correspond to? I know what the character looks like if that helps. I know that Python does display the correct character sometimes, but not sure when or why. In this case, the encoding is almost certainly "latin-1". I know that from playing around at the interactive interpreter, like this: >>> s = 'M\xc9XICO' >>> print s.decode('latin-1') M?XICO If you want to see charts of various encodings, wikipedia has a bunch. For instance, the Latin-1 encoding is here: http://en.wikipedia.org/wiki/ISO/IEC_8859-1 and UTF-8 is here: http://en.wikipedia.org/wiki/Utf-8 As the other respondents have said, it's really hard to figure this out just in code. The chardet module mentioned by Steven D'Aprano is probably the best bet if you really *have* to guess the encoding of an arbitrary sequence of bytes, but it much, much better to actually know the encoding of your inputs. Good luck! -- Jerry From ramit.prasad at jpmorgan.com Fri Aug 26 17:16:58 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 26 Aug 2011 11:16:58 -0400 Subject: [Tutor] String encoding In-Reply-To: <4E56F818.1040108@pearwood.info> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> <4E56F818.1040108@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEA7@EMARC112VS01.exchad.jpmchase.net> >Think about it this way... if I gave you a block of data as hex bytes: > >240F91BC03...FF90120078CD45 > >and then asked you whether that was a bitmap image or a sound file or >something else, how could you tell? It's just *bytes*, it could be anything. Yes, but if you give me data and then tell me it is a sound file then I might be able to reverse engineer or reconstruct it. I know what the character does/should look like. I just need the equivalent to the ASCII table for the various encodings; once I have the table I can compare different characters at \311 and see if they are the correct character. I have not been able to find an encoding table (other than ASCII). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Aug 26 17:49:22 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 26 Aug 2011 11:49:22 -0400 Subject: [Tutor] String encoding In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BF5D@EMARC112VS01.exchad.jpmchase.net> >In this case, the encoding is almost certainly "latin-1". I know that >from playing around at the interactive interpreter, like this: > > >>> s = 'M\xc9XICO' > >>> print s.decode('latin-1') > M?XICO > >If you want to see charts of various encodings, wikipedia has a bunch. > For instance, the Latin-1 encoding is here: >http://en.wikipedia.org/wiki/ISO/IEC_8859-1 and UTF-8 is here: >http://en.wikipedia.org/wiki/Utf-8 Yep, it is. Thanks those charts are exactly what I wanted! Now I have another question. What is the difference between what print shows and what the interpreter shows? >>> print s.decode('latin-1') M?XICO >>> s.decode('latin-1') u'M\xc9XICO' >>> print repr(s) 'M\xc9XICO' >>> repr(s) "'M\\xc9XICO'" Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Fri Aug 26 19:04:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 27 Aug 2011 03:04:58 +1000 Subject: [Tutor] String encoding In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEA7@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> <4E56F818.1040108@pearwood.info> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEA7@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E57D23A.70006@pearwood.info> Prasad, Ramit wrote: >> Think about it this way... if I gave you a block of data as hex >> bytes: >> >> 240F91BC03...FF90120078CD45 >> >> and then asked you whether that was a bitmap image or a sound file >> or something else, how could you tell? It's just *bytes*, it could >> be anything. > > Yes, but if you give me data and then tell me it is a sound file then > I might be able to reverse engineer or reconstruct it. I know what > the character does/should look like. I just need the equivalent to > the ASCII table for the various encodings; once I have the table I > can compare different characters at \311 and see if they are the > correct character. I have not been able to find an encoding table > (other than ASCII). In practice, you can often guess the encoding by trying the most common ones (such as Latin-1 and UTF-8) and seeing if the strings you get make sense. But note that more than one encoding may give sensible results for a specific string: >>> b = 'M\311XICO' # byte-string >>> print b.decode('latin-1') M?XICO >>> print b.decode('iso 8859-9') # Turkish M?XICO So was M\311XICO encoded using the Latin-1 or Turkish encoding, or something else? There is no way to tell. Many encodings overlap. If you have arbitrary byte-strings, and no context to tell what makes sense, then all bets are off. Just because something *can* be decoded doesn't make it meaningful: >>> b = '...\xf7...' >>> print b.decode('macroman') ...?... >>> print b.decode('latin-1') ...?... Which is the right encoding to use and which string is intended? So guessing can sometimes work, but guesses can be wrong because encodings overlap. In general, you must know the encoding to be sure. But if you have to guess, try to guess using the largest byte-string that you can. Python 2.7 comes with 108 encodings: http://docs.python.org/library/codecs.html#standard-encodings Since anyone can define their own encoding, there is no upper limit to the number of encodings, and no promise that Python will include them all. There are even two joke encodings, invented for April's Fool Day, that use nine-bit nonets instead of eight-bit octets (bytes): UTF-9 and UTF-18. -- Steven From d at davea.name Fri Aug 26 19:40:28 2011 From: d at davea.name (Dave Angel) Date: Fri, 26 Aug 2011 13:40:28 -0400 Subject: [Tutor] String encoding In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BF5D@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7F2F656@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA7FEC8E8@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BF5D@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E57DA8C.7050208@davea.name> On 08/26/2011 11:49 AM, Prasad, Ramit wrote: > > Yep, it is. Thanks those charts are exactly what I wanted! Now I have another question. What is the difference between what print shows and what the interpreter shows? > >>>> print s.decode('latin-1') > M?XICO The decoded characters are a Unicode string. Python prints that string by encoding it according to whatever sys.stdout is defaulted to. If that matches your actual terminal, then you see it properly. >>>> s.decode('latin-1') > u'M\xc9XICO' Here, because you don't assign it to anything, the interpreter is printing a repr() of the object. >>>> print repr(s) > 'M\xc9XICO' Here your code is doing the same thing, but explicitly this time. >>>> repr(s) > "'M\\xc9XICO'" > > Here, the repr() is created (which is a string containing single quotes), but then you don't print it, you just leave it. So the interpreter shows you the repr() of that object, enclosing it in double quotes for simplicity. -- DaveA From g.nius.ck at gmail.com Fri Aug 26 21:36:29 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 26 Aug 2011 15:36:29 -0400 Subject: [Tutor] [Python-ideas] Summer of Code Project Idea: Python Apps in the Browser In-Reply-To: <98154FC8-AFB3-4CCF-AD06-09CCB4267924@gmail.com> References: <98154FC8-AFB3-4CCF-AD06-09CCB4267924@gmail.com> Message-ID: > > The http://gumbyapp.com/ project succeeded in > getting Python to run in the browser but it can't import pure python modules > (because there is no filesystem in the browser). > I no this is a lot to ask, but do you think you could make this have real time calibration? You know, like google docs. Maybe you could even team up with Google Docs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bspymaster at gmail.com Sat Aug 27 01:37:36 2011 From: bspymaster at gmail.com (Bspymaster) Date: Fri, 26 Aug 2011 18:37:36 -0500 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: References: Message-ID: Well, I'm not sure what your asking for the first question, but for the second one, you would have an unhandled exception in your code if roll[0] was less than or equal to 0. Hope that helps a bit! On Fri, Aug 26, 2011 at 8:55 AM, TheIrda wrote: > Hello, > > I'm quite new on python, so don't hit too hard if I'm wrong ;) > > > A question on the logic... Does this means > > if roll[0] > 15: > if roll[1] >= 2: > print("Success") > elif roll[2] >= 2: > print("Critical failure!") > > > that rolling multiple 1's get the priority on rolling multiple 6's? I mean > result > 15 and 2 1's is always a critical success even if multiple 6 are > rolled? > > also > > if roll[0] > 15: > ......... > elif roll[0] <=15: <--- this is redundant. already checked for > 15 so if > here is always <= 15 > if roll[1] >= 2: > > you can change with: > > elif roll[1] >= 2: > > > > And... which is the RPG name ? :p > Cheers > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Aug 27 08:25:38 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 27 Aug 2011 08:25:38 +0200 Subject: [Tutor] Help with if-elif-else structure References: Message-ID: Robert Sjoblom wrote: > #assuming target number 15 > roll = (result, initial_mins, initial_max) > if roll[0] > 15: > if roll[1] >= 2: > print("Success") > elif roll[2] >= 2: > print("Critical failure!") > else: > print("Failure.") > elif roll[0] <= 15: > if roll[1] >= 2: > print("Critical success!") > elif roll[2] >= 2: > print("Failure") > else: > print("Success") > > This handles all the test cases I've come up with, but it feels very > ugly. Is there a better way to do this? Sometimes a table-driven approach is preferable. Your code would become something like def show_result(result, initial_mins, initial_max): messages = [ ["Critical success!", "Failure", "Success"], ["Success", "Critical failure!", "Failure."]] messages = messages[result > 15] if initial_mins >= 2: message = messages[0] elif initial_max >= 2: message = messages[1] else: message = messages[2] print(message) or, taken to the extreme, def first(pairs): for predicate, value in pairs: if predicate: return value raise ValueError def show_result(result, initial_mins, initial_max): messages = [ ["Critical success!", "Failure", "Success"], ["Success", "Critical failure!", "Failure."]] def checks(): yield initial_mins >= 2 yield initial_max >= 2 yield True print(first(zip(checks(), messages[result > 15]))) I don't think these alternatives have an advantage over the nested ifs in this case. From theirda at gmail.com Sat Aug 27 13:59:21 2011 From: theirda at gmail.com (TheIrda) Date: Sat, 27 Aug 2011 13:59:21 +0200 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEC7@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEC7@EMARC112VS01.exchad.jpmchase.net> Message-ID: let me rephrase. They code say: If roll[0] >15 : ...... elif roll[0] <= 15: .... If the code arrive to the elif, it is for sure <= 15. Cheers. Inviato da iPhone Il giorno 26/ago/2011, alle ore 17:21, "Prasad, Ramit" ha scritto: >> if roll[0] > 15: >> ......... >> elif roll[0] <=15: <--- this is redundant. already checked for > 15 so if here is always <= 15 >> if roll[1] >= 2: >> >> you can change with: >> >> elif roll[1] >= 2: > > That is not true. The first one looks at index [0], while the second one is index[1]. > >>> if roll[0] > 15: >>> if roll[1] >= 2: >>> print("Success") >>> elif roll[2] >= 2: >>> print("Critical failure!") > > This will print "Success" if the first roll is greater than 15 AND second roll is 2 or greater. > > It will print "Critical failure!" if the first roll is greater than 15 AND the second roll is less than 2 AND the third roll is 2 or greater. > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of TheIrda > Sent: Friday, August 26, 2011 8:55 AM > To: Christopher King > Cc: python mail list > Subject: Re: [Tutor] Help with if-elif-else structure > > Hello, > > I'm quite new on python, so don't hit too hard if I'm wrong ;) > > > A question on the logic... Does this means > > if roll[0] > 15: > if roll[1] >= 2: > print("Success") > elif roll[2] >= 2: > print("Critical failure!") > > > that rolling multiple 1's get the priority on rolling multiple 6's? I mean result > 15 and 2 1's is always a critical success even if multiple 6 are rolled? > > also > > if roll[0] > 15: > ......... > elif roll[0] <=15: <--- this is redundant. already checked for > 15 so if here is always <= 15 > if roll[1] >= 2: > > you can change with: > > elif roll[1] >= 2: > > > > And... which is the RPG name ? :p > Cheers > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. From suryak at live.com Sat Aug 27 17:21:56 2011 From: suryak at live.com (surya k) Date: Sat, 27 Aug 2011 20:51:56 +0530 Subject: [Tutor] largest palindrome number In-Reply-To: References: Message-ID: If you take a close look at my code. for i in range (1,100) : for j in range (i,100) : Temp = palindrome(i*j) here, as the loop goes on, i*j can never become smaller in any case. which is why I think it, as long as "PNum" gets a new number, its bigger palindrome than the previous.. so, at the end of the loop. we'll get largest palindrome number.. On 8/25/11, Hugo Arts wrote: > On Thu, Aug 25, 2011 at 6:49 PM, surya k wrote: >> Hi, >> I'm doing a puzzle where it asked me to find the largest palindrome number >> formed by the product of two three-digit numbers.?They mentioned an >> example >> saying that 9009 is the largest palindrome number formed by two two-digit >> numbers (99 * 91). >> I've written my code this way.. and I tested it with the given example and >> I >> got it right! >> Logic I used : >> largest two digit number is 99 and three digit number is 999.. so largest >> product of two two-digit numbers is < 100*100 and for three-digit numbers >> is >> < 1000*1000. >> So, I used a for loop and it assigns a palindromic value to PNum till it >> is >> ?< 100*100 (for 2 digit number) and < 1000*1000 (for three-digit number).. >> Thus it stops at the max possible palindromic value, which is what we >> want. >> >> def palindrome (n) : >> >> ?? ?TempN = n >> ?? ?rev ?= 0 >> ?? ?while n != 0 : >> ?? ? ? ?k = n % 10 >> ?? ? rev = (rev * 10) + k >> ?? ? n = n / 10 >> ?? ?if ?TempN == rev : >> ?? ? ? ?return TempN # Palindrome >> ?? ?else : >> ?? ? return 0 # not Palindrome >> >> for i in range (1,100) : >> ?? ?for j in range (i,100) : >> ?? ? ? ?Temp = palindrome(i*j) >> ?? ? ? ?if Temp < 10000 and Temp != 0 : >> ?? ? ? ? ? PNum = Temp >> print PNum >> >> >> So, for getting the largest palindrome number formed by two three-digit >> numbers, I changed 100 to 1000 and 1,00,00 to 1,000,000 in the highlighted >> area. Thus I got the answer to be 888888. When I submitted the answer, its >> saying wrong! >> Where I'm going wrong ? >> help me, please ! >> > > When you get a new palindrome, you should make sure it's bigger than > the one you already have before you replace the old one. 888888 is the > last palindrome you find, but it is not the the biggest. You cannot > assume the biggest one will be found last. > From emile at fenx.com Sat Aug 27 17:28:36 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 27 Aug 2011 08:28:36 -0700 Subject: [Tutor] largest palindrome number In-Reply-To: References: Message-ID: On 8/27/2011 8:21 AM surya k said... > If you take a close look at my code. > > for i in range (1,100) : > for j in range (i,100) : > Temp = palindrome(i*j) > > here, as the loop goes on, i*j can never become smaller Of course it can... i=3 * j=90 is less than i=4 * j=4... Emile From emile at fenx.com Sat Aug 27 17:46:06 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 27 Aug 2011 08:46:06 -0700 Subject: [Tutor] Help with if-elif-else structure In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEC7@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA808BEC7@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 8/26/2011 8:21 AM Prasad, Ramit said... >> if roll[0]> 15: >> ......... >> elif roll[0]<=15:<--- this is redundant. already checked for> 15 so if here is always<= 15 >> if roll[1]>= 2: >> >> you can change with: >> >> elif roll[1]>= 2: > > That is not true. The first one looks at index [0], while the second one is index[1]. No, it is true. The resulting code would be: if roll[0] > 15: doeggs() elif roll[1] >= 2 dospam() where the second test only occurs when roll[0] <= 15. Emile > >>> if roll[0]> 15: >>> if roll[1]>= 2: >>> print("Success") >>> elif roll[2]>= 2: >>> print("Critical failure!") > > This will print "Success" if the first roll is greater than 15 AND second roll is 2 or greater. > > It will print "Critical failure!" if the first roll is greater than 15 AND the second roll is less than 2 AND the third roll is 2 or greater. > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of TheIrda > Sent: Friday, August 26, 2011 8:55 AM > To: Christopher King > Cc: python mail list > Subject: Re: [Tutor] Help with if-elif-else structure > > Hello, > > I'm quite new on python, so don't hit too hard if I'm wrong ;) > > > A question on the logic... Does this means > > if roll[0]> 15: > if roll[1]>= 2: > print("Success") > elif roll[2]>= 2: > print("Critical failure!") > > > that rolling multiple 1's get the priority on rolling multiple 6's? I mean result> 15 and 2 1's is always a critical success even if multiple 6 are rolled? > > also > > if roll[0]> 15: > ......... > elif roll[0]<=15:<--- this is redundant. already checked for> 15 so if here is always<= 15 > if roll[1]>= 2: > > you can change with: > > elif roll[1]>= 2: > > > > And... which is the RPG name ? :p > Cheers > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Sat Aug 27 17:48:16 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 27 Aug 2011 17:48:16 +0200 Subject: [Tutor] largest palindrome number References: Message-ID: surya k wrote: > If you take a close look at my code. > > for i in range (1,100) : > for j in range (i,100) : > Temp = palindrome(i*j) > > here, as the loop goes on, i*j can never become smaller in any case. > which is why I think it, as long as "PNum" gets a new number, its > bigger palindrome than the previous.. so, at the end of the loop. > we'll get largest palindrome number.. Add a print statement to your loop for i in range(1, 1000): for j in range(i, 1000): temp = palindrome(i*j) if temp != 0: print temp, i, j pnum = temp print pnum and you'll see the problem: ... 828828 897 924 819918 902 909 824428 902 914 906609 913 993 <-- 886688 916 968 861168 924 932 888888 924 962 888888 You get the palindrome with the largest factor i which is not necessarily the one with the largest product i*j. From david at graniteweb.com Sat Aug 27 18:32:58 2011 From: david at graniteweb.com (David Rock) Date: Sat, 27 Aug 2011 11:32:58 -0500 Subject: [Tutor] largest palindrome number In-Reply-To: References: Message-ID: <20110827163258.GB5721@wdfs> * surya k [2011-08-27 20:51]: > > here, as the loop goes on, i*j can never become smaller in any case. > which is why I think it, as long as "PNum" gets a new number, its > bigger palindrome than the previous.. so, at the end of the loop. > we'll get largest palindrome number.. > > On 8/25/11, Hugo Arts wrote: > > > > When you get a new palindrome, you should make sure it's bigger than > > the one you already have before you replace the old one. 888888 is the > > last palindrome you find, but it is not the the biggest. You cannot > > assume the biggest one will be found last. > > As implied by Hugo, What you need to to do is store your largest current palindrome and as you find a new one, replace the largest current only if the one you just found is actually larger. Once you go through the entire block, the value in your largest current value will actually be the largest palindrome. -- David Rock david at graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From lisi.reisz at gmail.com Sun Aug 28 13:34:15 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 28 Aug 2011 12:34:15 +0100 Subject: [Tutor] Can't find error :-( Message-ID: <201108281234.15969.lisi.reisz@gmail.com> Here is the error message: /usr/local/bin/AddressBook: line 6: syntax error near unexpected token `(' /usr/local/bin/AddressBook: line 6: `name = raw_input("Type the Name - leave blank to finish")' (sorry KMail wrapped it.) Here is what I typed: name = raw_input("Type the Name - leave blank to finish") Here is what I was copying: name = raw_input("Type the Name - leave blank to finish") Help!! All three are copied and pasted from their relevant places to eliminate mis-copying at this stage. What have I miscopied?? The original and my copy look to me *exactly* the same. Lisi From james at jamesthornton.com Sun Aug 28 13:50:51 2011 From: james at jamesthornton.com (James Thornton) Date: Sun, 28 Aug 2011 06:50:51 -0500 Subject: [Tutor] Can't find error :-( In-Reply-To: <201108281234.15969.lisi.reisz@gmail.com> References: <201108281234.15969.lisi.reisz@gmail.com> Message-ID: If you copied and pasted the line, it's possible the quote marks are of the wrong encoding -- try deleting the quote marks and adding them back. On Sun, Aug 28, 2011 at 6:34 AM, Lisi wrote: > Here is the error message: > /usr/local/bin/AddressBook: line 6: syntax error near unexpected token `(' > /usr/local/bin/AddressBook: line 6: `name = raw_input("Type the Name - leave > blank to finish")' > > (sorry KMail wrapped it.) > > Here is what I typed: > name = raw_input("Type the Name - leave blank to finish") > > Here is what I was copying: > name = raw_input("Type the Name - leave blank to finish") > > Help!! ? All three are copied and pasted from their relevant places to > eliminate mis-copying at this stage. ?What have I miscopied?? ?The original > and my copy look to me *exactly* the same. > > Lisi > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bulbflow: A Python framework for graph databases (http://bulbflow.com) From __peter__ at web.de Sun Aug 28 14:01:38 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 28 Aug 2011 14:01:38 +0200 Subject: [Tutor] Can't find error :-( References: <201108281234.15969.lisi.reisz@gmail.com> Message-ID: Lisi wrote: > Here is the error message: > /usr/local/bin/AddressBook: line 6: syntax error near unexpected token `(' > /usr/local/bin/AddressBook: line 6: `name = raw_input("Type the Name - > leave blank to finish")' > > (sorry KMail wrapped it.) > > Here is what I typed: > name = raw_input("Type the Name - leave blank to finish") > > Here is what I was copying: > name = raw_input("Type the Name - leave blank to finish") > > Help!! All three are copied and pasted from their relevant places to > eliminate mis-copying at this stage. What have I miscopied?? The > original and my copy look to me *exactly* the same. That's an error message by your shell. You made your script executable, but forgot to add something like #!/usr/bin/env python as its first line. NB. it's quite common that an error originates before the place where the interpreter complains; it would have been a good idea to post the five lines before the explicitly erroneous one, too. From amonroe at columbus.rr.com Sun Aug 28 14:27:03 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 28 Aug 2011 08:27:03 -0400 Subject: [Tutor] Can't find error :-( In-Reply-To: <201108281234.15969.lisi.reisz@gmail.com> References: <201108281234.15969.lisi.reisz@gmail.com> Message-ID: <0550877860.20110828082703@columbus.rr.com> > /usr/local/bin/AddressBook: line 6: syntax error near unexpected token `(' > /usr/local/bin/AddressBook: line 6: `name = raw_input("Type the Name - leave > blank to finish")' Were you accidentally trying a python 3 tutorial when your machine only has python 2 installed (or vice versa)? Alan From lisi.reisz at gmail.com Sun Aug 28 14:34:05 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 28 Aug 2011 13:34:05 +0100 Subject: [Tutor] Can't find error :-( In-Reply-To: References: <201108281234.15969.lisi.reisz@gmail.com> Message-ID: <201108281334.05961.lisi.reisz@gmail.com> On Sunday 28 August 2011 13:01:38 Peter Otten wrote: > Lisi wrote: > > Here is the error message: > > /usr/local/bin/AddressBook: line 6: syntax error near unexpected token > > `(' /usr/local/bin/AddressBook: line 6: `name = raw_input("Type the Name > > - leave blank to finish")' > > > > (sorry KMail wrapped it.) > > > > Here is what I typed: > > name = raw_input("Type the Name - leave blank to finish") > > > > Here is what I was copying: > > name = raw_input("Type the Name - leave blank to finish") > > > > Help!! All three are copied and pasted from their relevant places to > > eliminate mis-copying at this stage. What have I miscopied?? The > > original and my copy look to me *exactly* the same. > > That's an error message by your shell. You made your script executable, but > forgot to add something like > > #!/usr/bin/env python > > as its first line. > > NB. it's quite common that an error originates before the place where the > interpreter complains; it would have been a good idea to post the five > lines before the explicitly erroneous one, too. Thanks to both. I opened up the file to try retyping the ", although I had in fact typed it - the copying and pasting was into the email to ensure that I did not introduce any errors at that stage. But looking at the file, I realised that I had forgotten my shebang line - and had put it right before I read this answer. I am very grateful to you both. I had realised that the error might be somewhere other than where it is indicated because Alan had already told me so - but had not understood that it could be, not only in a different place, but quite a way away. Not even when I put this right. So thanks for that, Peter, and thank you again, both of you. For future reference, how would I set about changing the encoding for just one character or file? I don't really want to change the encoding I use system wide. Lisi From lisi.reisz at gmail.com Sun Aug 28 15:53:25 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 28 Aug 2011 14:53:25 +0100 Subject: [Tutor] Still stuck - but a bit further on. Message-ID: <201108281453.25451.lisi.reisz@gmail.com> Sorry, everybody. I am still having problems with this script - tho' it now runs correctly nearly to the end! Here is the whole script: #! /usr/bin/python # create an empty address book dictionary AddressBook = {} # read entries till an empty string print name = raw_input("Type the Name - leave blank to finish") while name != "": entry = raw_input("Type the Street, Town, Phone. Leave blank to finish") AddressBook[name] = entry name = raw_input("Type the Name - leave blank to finish") # now ask for one to display name = raw_input("Which name to display?(blank to finish)") while name !="": print name, AddressBook[name] name = raw_input("Which name to display?(blank to finish)") I started with: lisi at Tux:/usr/local/bin$ AddressBook Type the Name - leave blank to finishLisi Type the Street, Town, Phone. Leave blank to finishth, rc, 123457 Type the Name - leave blank to finish Which name to display?(blank to finish) Lisi Lisi Traceback (most recent call last): File "/usr/local/bin/AddressBook", line 17, in print name, AddressBook[name] KeyError: ' Lisi' I have tried various other words besides Lisi, each one less probable than its predecessor. I am getting nowhere. The error may well be somewhere else again, but I can't see where. :-( Lisi From steve at pearwood.info Sun Aug 28 16:15:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Aug 2011 00:15:13 +1000 Subject: [Tutor] Can't find error :-( In-Reply-To: <201108281334.05961.lisi.reisz@gmail.com> References: <201108281234.15969.lisi.reisz@gmail.com> <201108281334.05961.lisi.reisz@gmail.com> Message-ID: <4E5A4D71.8040000@pearwood.info> Lisi wrote: > For future reference, how would I set about changing the encoding for just one > character or file? I don't really want to change the encoding I use system > wide. You can set the encoding for the entire source file with an encoding line like: # -*- coding: utf-8 -*- This MUST be in the first one or two lines of the file to take effect: Optional shebang line. Encoding line. The exact form of the encoding line is very flexible. See here for more information: http://docs.python.org/reference/lexical_analysis.html#encoding-declarations The encoding line is only necessary if you want to include non-ASCII characters in your source code, either as variable names or in literal strings, e.g.: ? = 2.5 name = u"Michael Gro?" (Warning: just because you insert an encoding line in the source file, doesn't mean your editor will obey it. Emacs and vim probably will, but for most other editors, you may need to manually set the encoding. E.g. in the kwrite editor, go to menu Tools > Encoding and choose whichever one you prefer.) Without an encoding line, you would have to use: name = u"Michael Gro\xdf" or name = u"Michael Gro\N{LATIN SMALL LETTER SHARP S}" You might be able to get away without an encoding line if the non-ASCII characters are only in comments. -- Steven From steve at pearwood.info Sun Aug 28 16:18:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Aug 2011 00:18:38 +1000 Subject: [Tutor] Still stuck - but a bit further on. In-Reply-To: <201108281453.25451.lisi.reisz@gmail.com> References: <201108281453.25451.lisi.reisz@gmail.com> Message-ID: <4E5A4E3E.6070507@pearwood.info> Lisi wrote: [...] > Type the Name - leave blank to finishLisi You have no space in the name. It is "Lisi". > Type the Street, Town, Phone. Leave blank to finishth, rc, 123457 > Type the Name - leave blank to finish > Which name to display?(blank to finish) Lisi Here you have a space at the start of the name: " Lisi". > Lisi > Traceback (most recent call last): > File "/usr/local/bin/AddressBook", line 17, in > print name, AddressBook[name] > KeyError: ' Lisi' Sure enough, no Lisi-with-a-space. > I have tried various other words besides Lisi, each one less probable than its > predecessor. I am getting nowhere. The error may well be somewhere else > again, but I can't see where. :-( For further debugging, print AddressBook and see what is in it. -- Steven From alan.gauld at btinternet.com Sun Aug 28 17:15:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Aug 2011 16:15:10 +0100 Subject: [Tutor] Can't find error :-( In-Reply-To: <201108281334.05961.lisi.reisz@gmail.com> References: <201108281234.15969.lisi.reisz@gmail.com> <201108281334.05961.lisi.reisz@gmail.com> Message-ID: On 28/08/11 13:34, Lisi wrote: > On Sunday 28 August 2011 13:01:38 Peter Otten wrote: >> Lisi wrote: >>> Here is the error message: >>> /usr/local/bin/AddressBook: line 6: syntax error near unexpected token >> That's an error message by your shell. You made your script executable, but >> forgot to add something like >> >> #!/usr/bin/env python > I am very grateful to you both. I had realised that the error might be > somewhere other than where it is indicated because Alan had already told me > so - but had not understood that it could be, not only in a different place, > but quite a way away. The really important point here is that the error was a shell error not a Python error. (You need to check the format of the message to see the differences and get used to them) If it had been a Python error it would typically be within a line or two of the reported place (occasionally more but not usually) but shell errors can often be a long way off depending on how much the file content looks like shell script... > For future reference, how would I set about changing the encoding for just one > character or file? I don't really want to change the encoding I use system > wide. Mostly you shouldn't need to for the stuff in my tutorial, I certainly didn't use any funny characters so the default decoding should just work. One of these days I'll add a topic on encodings but I need to really get my own brain wrapped around it before thenm, and I'm still a bit fuzzy in places myself! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Aug 28 17:20:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Aug 2011 16:20:45 +0100 Subject: [Tutor] Still stuck - but a bit further on. In-Reply-To: <201108281453.25451.lisi.reisz@gmail.com> References: <201108281453.25451.lisi.reisz@gmail.com> Message-ID: On 28/08/11 14:53, Lisi wrote: > Type the Name - leave blank to finishLisi Notice no space before Lisi > Type the Street, Town, Phone. Leave blank to finishth, rc, 123457 > Type the Name - leave blank to finish > Which name to display?(blank to finish) Lisi Notice the space before Lisi? > Traceback (most recent call last): > File "/usr/local/bin/AddressBook", line 17, in > print name, AddressBook[name] > KeyError: ' Lisi' Notice the space at the start of the string? The stored entry is keyed on "Lisi" the search was for " Lisi" which doesn't exist. You could as an exercise make the program more robust to that kind of error by eliminating whitespace at each end of the key string both before storing the data and when searching... You might also consider eliminating case errors by forcing both the key string and search string to lowercase, but if you do that you will want to store the name with case in the value part and not rely on the key being part of the data... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lisi.reisz at gmail.com Sun Aug 28 17:51:05 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sun, 28 Aug 2011 16:51:05 +0100 Subject: [Tutor] Still stuck - but a bit further on. In-Reply-To: References: <201108281453.25451.lisi.reisz@gmail.com> Message-ID: <201108281651.05902.lisi.reisz@gmail.com> On Sunday 28 August 2011 16:20:45 Alan Gauld wrote: > > Notice the space at the start of the string? > The stored entry is keyed on "Lisi" the search was for " Lisi" > which doesn't exist. I thought that I had tried that, but I obviously hadn't. I clearly needed that break! Thanks, Alan and Steven. Lisi From contactdayo at gmail.com Sun Aug 28 18:43:07 2011 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Sun, 28 Aug 2011 17:43:07 +0100 Subject: [Tutor] Sorting list of tuples in two passes Message-ID: <4E5A701B.40601@gmail.com> Hi I have a list of tuples that each have four elements: [(firstName,lastName,userName,gidNumber),(.....)....] I'm trying to sort this list in two passes. First by gidNumber and then the subgroups by lastName. So far i've only been able to sort by gidNumber. But I can't seem to wrap my mind around lambda, which is what my browsing around seems to indicate is needed to achieve this? Thanks Dayo import ldap,re from operator import itemgetter,attrgetter l = ldap.initialize("ldap://172.20.0.1") l.simple_bind_s("","") base_dn = 'ou=People,dc=aust,o=ami-net' filter = '(objectclass=pilotPerson)' attrs = ['uid', 'gidNumber', 'sn', 'cn'] users = l.search_s(base_dn, ldap.SCOPE_ONELEVEL, filter, attrs) def onelist(users): studentspubline = tuple() students2xPubLines = [] for aUser in users: # Get the user details from LDAP userName = aUser[1]['uid'][0] gidNumber = aUser[1]['gidNumber'][0] lastName = aUser[1]['sn'][0] fullName = aUser[1]['cn'][0] # Get first names of users splitFullName = fullName.split() firstName = splitFullName[1] if gidNumber[:1] == '9': studentspubline = userName,lastName,fullName,gidNumber students2xPubLines.append(studentspubline) sortedStudents2x = sorted(students2xPubLines, key=itemgetter(3,2)) for userName,lastName,fullName,gidNumber in sortedStudents2x: print "lastName: %s, gidNumber: %s" %(lastName, gidNumber) onelist(users) From payal at scriptkitchen.com Sun Aug 28 18:20:49 2011 From: payal at scriptkitchen.com (Payal) Date: Sun, 28 Aug 2011 09:20:49 -0700 Subject: [Tutor] need help to learn threading Message-ID: <20110828162049.GA9474@scriptkitchen.com> Hi all, Can someone suggest a resource for me to learn threading in python? I don't know threading in any other language. I tried a few online tutorials but got lost soon. How do I start? With warm regards, -Payal -- From nitinpawar432 at gmail.com Sun Aug 28 19:17:50 2011 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Sun, 28 Aug 2011 22:47:50 +0530 Subject: [Tutor] need help to learn threading In-Reply-To: <20110828162049.GA9474@scriptkitchen.com> References: <20110828162049.GA9474@scriptkitchen.com> Message-ID: this one at tutorial point explains multi threading with examples .. http://www.tutorialspoint.com/python/python_multithreading.htm On Sun, Aug 28, 2011 at 9:50 PM, Payal wrote: > Hi all, > Can someone suggest a resource for me to learn threading in python? I > don't know threading in any other language. > I tried a few online tutorials but got lost soon. How do I start? > > With warm regards, > -Payal > -- > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Aug 28 19:23:09 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 28 Aug 2011 19:23:09 +0200 Subject: [Tutor] Sorting list of tuples in two passes In-Reply-To: <4E5A701B.40601@gmail.com> References: <4E5A701B.40601@gmail.com> Message-ID: On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmi wrote: > Hi > > I have a list of tuples that each have four elements: > > [(firstName,lastName,userName,gidNumber),(.....)....] > > I'm trying to sort this list in two passes. First by gidNumber and then the > subgroups by lastName. So far i've only been able to sort by gidNumber. But > I can't seem to wrap my mind around lambda, which is what my browsing around > seems to indicate is needed to achieve this? > > Thanks > > Dayo > Python's builtin sort is stable, which means that ordering of items with the same key is preserved. This property means that you can do multiple pass sorting very easily and efficiently just by sorting twice: >>> # we'll simplify the problem a bit and have tuples with just last name and id. >>> l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] >>> l.sort(key=itemgetter(0)) >>> l [('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)] >>> l.sort(key=itemgetter(1)) >>> l [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] >>> We sort by last name first, then sort again by id. As you can see, the sorting of groups with the same id is preserved, and our list is now in the correct order. Hugo From contactdayo at gmail.com Mon Aug 29 02:19:32 2011 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Mon, 29 Aug 2011 01:19:32 +0100 Subject: [Tutor] Sorting list of tuples in two passes In-Reply-To: References: <4E5A701B.40601@gmail.com> Message-ID: <4E5ADB14.9060006@gmail.com> On 08/28/2011 06:23 PM, Hugo Arts wrote: > On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmi wrote: >> Hi >> >> I have a list of tuples that each have four elements: >> >> [(firstName,lastName,userName,gidNumber),(.....)....] >> >> I'm trying to sort this list in two passes. First by gidNumber and then the >> subgroups by lastName. So far i've only been able to sort by gidNumber. But >> I can't seem to wrap my mind around lambda, which is what my browsing around >> seems to indicate is needed to achieve this? >> >> Thanks >> >> Dayo >> > Python's builtin sort is stable, which means that ordering of items > with the same key is preserved. This property means that you can do > multiple pass sorting very easily and efficiently just by sorting > twice: > >>>> # we'll simplify the problem a bit and have tuples with just last name and id. >>>> l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] >>>> l.sort(key=itemgetter(0)) >>>> l > [('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)] >>>> l.sort(key=itemgetter(1)) >>>> l > [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] > We sort by last name first, then sort again by id. As you can see, the > sorting of groups with the same id is preserved, and our list is now > in the correct order. > > Hugo > It works when I use your example, but I don't understand why it won't work when I use 4-element tuples instead of 2: >>>l = [('wascas','aaa','fdvdfv', 1), ('rtgdsf','bbb','trfg', 1), ('addwe','ccc','esd', 1), ('xasd','aaa','wascaq', 2), ('nhy','bbb','asw', 2), ('zzzz','ccc','dgdeg', 2)] >>> l [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), ('zzzz', 'ccc', 'dgdeg', 2)] >>> l.sort(key=itemgetter(3)) >>> l [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), ('zzzz', 'ccc', 'dgdeg', 2)] >>> l.sort(key=itemgetter(1)) >>> l [('wascas', 'aaa', 'fdvdfv', 1), ('xasd', 'aaa', 'wasca q', 2), ('rtgdsf', 'bbb', 'trfg', 1), ('nhy', 'bbb', ' asw', 2), ('addwe', 'ccc', 'esd', 1), ('zzzz', 'ccc', 'dgdeg', 2)] >>> Also I notice your original list and your end result list are in the same order. Thanks Dayo From steve at pearwood.info Mon Aug 29 02:34:39 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Aug 2011 10:34:39 +1000 Subject: [Tutor] Sorting list of tuples in two passes In-Reply-To: <4E5ADB14.9060006@gmail.com> References: <4E5A701B.40601@gmail.com> <4E5ADB14.9060006@gmail.com> Message-ID: <4E5ADE9F.2040608@pearwood.info> Dayo Adewunmi wrote: > It works when I use your example, but I don't understand why it won't > work when I use 4-element tuples instead of 2: What makes you say it doesn't work? It looks like it works to me: > >>>l = [('wascas','aaa','fdvdfv', 1), ('rtgdsf','bbb','trfg', 1), > ('addwe','ccc','esd', 1), ('xasd','aaa','wascaq', 2), > ('nhy','bbb','asw', 2), ('zzzz','ccc','dgdeg', 2)] > >>> l > [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', > 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', > 2), ('zzzz', 'ccc', 'dgdeg', 2)] > >>> l.sort(key=itemgetter(3)) > >>> l > [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', > 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', > 2), ('zzzz', 'ccc', 'dgdeg', 2)] List "l" is now sorted by the element in position 3 (counting from zero, not one): 1 1 1 2 2 2 > >>> l.sort(key=itemgetter(1)) > >>> l > [('wascas', 'aaa', 'fdvdfv', 1), ('xasd', 'aaa', 'wasca q', 2), > ('rtgdsf', 'bbb', 'trfg', 1), ('nhy', 'bbb', ' > asw', 2), ('addwe', 'ccc', 'esd', 1), ('zzzz', 'ccc', 'dgdeg', 2)] And now elements are sorted in order of position 1: aaa aaa bbb bbb ccc ccc In the event of ties (and there are three pairs of ties) the elements keep the relative order they were in after the first sort. The sorting worked just as expected. -- Steven From hugo.yoshi at gmail.com Mon Aug 29 02:59:43 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 29 Aug 2011 02:59:43 +0200 Subject: [Tutor] Sorting list of tuples in two passes In-Reply-To: <4E5ADB14.9060006@gmail.com> References: <4E5A701B.40601@gmail.com> <4E5ADB14.9060006@gmail.com> Message-ID: On Mon, Aug 29, 2011 at 2:19 AM, Dayo Adewunmi wrote: > On 08/28/2011 06:23 PM, Hugo Arts wrote: >> >> On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmi >> ?wrote: >>> >>> Hi >>> >>> I have a list of tuples that each have four elements: >>> >>> [(firstName,lastName,userName,gidNumber),(.....)....] >>> >>> I'm trying to sort this list in two passes. First by gidNumber and then >>> the >>> subgroups by lastName. So far i've only been able to sort by gidNumber. >>> But >>> I can't seem to wrap my mind around lambda, which is what my browsing >>> around >>> seems to indicate is needed to achieve this? >>> >>> Thanks >>> >>> Dayo >>> >> Python's builtin sort is stable, which means that ordering of items >> with the same key is preserved. This property means that you can do >> multiple pass sorting very easily and efficiently just by sorting >> twice: >> >>>>> # we'll simplify the problem a bit and have tuples with just last name >>>>> and id. >>>>> l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), >>>>> ('ccc', 2)] >>>>> l.sort(key=itemgetter(0)) >>>>> l >> >> [('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)] >>>>> >>>>> l.sort(key=itemgetter(1)) >>>>> l >> >> [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] >> We sort by last name first, then sort again by id. As you can see, the >> sorting of groups with the same id is preserved, and our list is now >> in the correct order. >> >> Hugo >> > > It works when I use your example, but I don't understand why it won't work > when I use 4-element tuples instead of 2: > >>>>l = [('wascas','aaa','fdvdfv', 1), ('rtgdsf','bbb','trfg', 1), >>>> ('addwe','ccc','esd', 1), ('xasd','aaa','wascaq', 2), ('nhy','bbb','asw', >>>> 2), ('zzzz','ccc','dgdeg', 2)] >>>> l > [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', > 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), > ('zzzz', 'ccc', 'dgdeg', 2)] >>>> l.sort(key=itemgetter(3)) >>>> l > [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', > 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), > ('zzzz', 'ccc', 'dgdeg', 2)] >>>> l.sort(key=itemgetter(1)) >>>> l > [('wascas', 'aaa', 'fdvdfv', 1), ('xasd', 'aaa', 'wasca ? ?q', 2), > ('rtgdsf', 'bbb', 'trfg', 1), ('nhy', 'bbb', ' > asw', 2), ('addwe', 'ccc', 'esd', 1), ('zzzz', 'ccc', 'dgdeg', 2)] >>>> > > > Also I notice your original list and your end result list are in the same > order. > > Thanks > > Dayo > In my original example, you can shuffle the list before you sort it and it will still work. Try it, with a quick "from random import shuffle; shuffle(l)". Also, notice that you want to sort by your primary order *last*. I sorted by last name first, then sorted by id second, which means the final list's primary order is by id, and secondary order by last name. So the sorting goes in reverse. In your example, you sort by id first, then last name. So your final list's primary order is by last name. Hugo From memilanuk at gmail.com Mon Aug 29 03:19:05 2011 From: memilanuk at gmail.com (memilanuk) Date: Sun, 28 Aug 2011 18:19:05 -0700 Subject: [Tutor] Better way to compare values? Message-ID: Hello, Recently picked back up the Python bug, and have started chipping away at the warm-up exercises over @ codingbat.com. I'm getting thru the basic stuff okay, but I'm getting a feeling that maybe I'm not doing things the 'right' way, even though the results are correct. Specifically, checking if value 'a' OR value 'b' equal a certain number... The example that I'm on at the moment (like I said, starting over at the basics)... http://codingbat.com/prob/p124984 My solution: ''' Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. makes10(9, 10) = True makes10(9, 9) = False makes10(1, 9) = True ''' def makes10(a, b): if (a == 10) or (b == 10): #print('Yep!') return(True) elif a + b == 10: #print('Si!') return(True) else: #print('Nein!') return(False) makes10(10,9) #makes10(9,9) #makes10(1,9) In particular, the 'if (a == 10) or (b == 10): line... is there a shorter/more compact/more correct (i.e. pythonic) way of testing to see if a OR b is equal to 10? Thanks, Monte From bgailer at gmail.com Mon Aug 29 03:58:36 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 28 Aug 2011 21:58:36 -0400 Subject: [Tutor] Better way to compare values? In-Reply-To: References: Message-ID: <4E5AF24C.4000303@gmail.com> On 8/28/2011 9:19 PM, memilanuk wrote: > Hello, > > Recently picked back up the Python bug, and have started chipping away > at the warm-up exercises over @ codingbat.com. > > I'm getting thru the basic stuff okay, but I'm getting a feeling that > maybe I'm not doing things the 'right' way, even though the results > are correct. > > Specifically, checking if value 'a' OR value 'b' equal a certain > number... > > The example that I'm on at the moment (like I said, starting over at > the basics)... > > http://codingbat.com/prob/p124984 > > My solution: > > ''' > Given 2 ints, a and b, return True if one if them is 10 or if their > sum is 10. > > makes10(9, 10) = True > makes10(9, 9) = False > makes10(1, 9) = True > ''' > > def makes10(a, b): > if (a == 10) or (b == 10): > #print('Yep!') > return(True) > > elif a + b == 10: > #print('Si!') > return(True) > > else: > #print('Nein!') > return(False) > > makes10(10,9) > #makes10(9,9) > #makes10(1,9) > > > > In particular, the 'if (a == 10) or (b == 10): line... is there a > shorter/more compact/more correct (i.e. pythonic) way of testing to > see if a OR b is equal to 10? stinfo/tutor > if 10 in (a,b) would do it. -- Bob Gailer 919-636-4239 Chapel Hill NC From hugo.yoshi at gmail.com Mon Aug 29 04:07:31 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 29 Aug 2011 04:07:31 +0200 Subject: [Tutor] Better way to compare values? In-Reply-To: References: Message-ID: On Mon, Aug 29, 2011 at 3:19 AM, memilanuk wrote: > Hello, > > Recently picked back up the Python bug, and have started chipping away at > the warm-up exercises over @ codingbat.com. > > I'm getting thru the basic stuff okay, but I'm getting a feeling that maybe > I'm not doing things the 'right' way, even though the results are correct. > > Specifically, checking if value 'a' OR value 'b' equal a certain number... > > The example that I'm on at the moment (like I said, starting over at the > basics)... > > http://codingbat.com/prob/p124984 > > My solution: > > ''' > Given 2 ints, a and b, return True if one if them is 10 or if their sum is > 10. > > makes10(9, 10) = True > makes10(9, 9) = False > makes10(1, 9) = True > ''' > > def makes10(a, b): > ? ?if (a == 10) or (b == 10): > ? ? ? ?#print('Yep!') > ? ? ? ?return(True) > > ? ?elif a + b == 10: > ? ? ? ?#print('Si!') > ? ? ? ?return(True) > > ? ?else: > ? ? ? ?#print('Nein!') > ? ? ? ?return(False) > > makes10(10,9) > #makes10(9,9) > #makes10(1,9) > > > > In particular, the 'if (a == 10) or (b == 10): line... is there a > shorter/more compact/more correct (i.e. pythonic) way of testing to see if a > OR b is equal to 10? > There's a few things that can make this a lot shorter. To address your primary question first, the python idiom for this is like so: if 10 in (a, b): it constructs a tuple containing the variables a and b, then checks if the number ten is inside that tuple. simple and straightforward. Now, or's aren't limited to just two operands. you can chain multiple or's together to make this function even shorter, like so: if a == 10 or b == 10 or a + b == 10: That's pretty nice. And now, for the grand trick, we can apply out little idiom we just learned up there to this three part if statement: if 10 in (a, b, a + b): See what we did there? But we can do you one better. this construction I see a lot from beginning programmers: def function(x): if x: return True else: return False But it is actually quite superfluous. if you check if a certain expression is true, and if so, return True, we may just as well return the expression itself to begin with! We only need to make sure the function returns only True or False, and we can do that nicely by converting our initial expression to a boolean: def function(x): return bool(x) So, all said and done, the solution to your problem in idiomatic python looks like this: def makes10(a, b): return 10 in (a, b, a + b) Note: I didn't have to use the bool() function in our last example, because I know that the 'in' operator always returns either True or False. HTH, Hugo From memilanuk at gmail.com Mon Aug 29 05:33:29 2011 From: memilanuk at gmail.com (memilanuk) Date: Sun, 28 Aug 2011 20:33:29 -0700 Subject: [Tutor] Better way to compare values? In-Reply-To: References: Message-ID: > > There's a few things that can make this a lot shorter. To address your > primary question first, the python idiom for this is like so: > > if 10 in (a, b): > > it constructs a tuple containing the variables a and b, then checks if > the number ten is inside that tuple. simple and straightforward. Now, > or's aren't limited to just two operands. you can chain multiple or's > together to make this function even shorter, like so: > > if a == 10 or b == 10 or a + b == 10: That's pretty much what the 'book' solution was (found the 'Show Solution' button staring me in the face shortly after posting my question here. def makes10(a,b) return(a == 10 or b == 10 or a + b == 10) > > So, all said and done, the solution to your problem in idiomatic > python looks like this: > > def makes10(a, b): > return 10 in (a, b, a + b) > Something else I learned from this... for some reason I had the idea in my head that 'return' was a function like print() i.e. 'return()'. Obviously not, from your example and from others that I dug up in the Python docs. Thanks for the detailed explanation - it was very clear and easy to follow! What I had originally been thinking was something like 'a && b' or 'a || b'... but that was probably some cross-pollenation from earlier dabbling in PHP or something ;) Thanks, Monte From rdmoores at gmail.com Mon Aug 29 08:13:54 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 28 Aug 2011 23:13:54 -0700 Subject: [Tutor] program code for Python Programming for the Absolute Beginner, 3rd ed.? Message-ID: The book says the program code is in py3e_source.zip, at www.courseptr.com/downloads , but that leads to the book at with a "View Available Downloads" link that yields no downloads. Does anyone know where py3e_source.zip is? Or if you have it, could you email it to me? Thanks, Dick Moores From guanghua.han at huawei.com Mon Aug 29 08:17:51 2011 From: guanghua.han at huawei.com (Han Guanghua) Date: Mon, 29 Aug 2011 14:17:51 +0800 Subject: [Tutor] One basic question about the Python's PID of Process object. Message-ID: <001101cc6613$618d1730$24a74590$%han@huawei.com> Hello, 1. When I tried to run the following code (belonging to one Python program), for the dynamically created object of CUSTOMER as Process type, the printed PID as the following is always the same. Why? 2. Second question: When I changed the os.getpid() to os.getppid() or self. _pid, the Python?s interpreter generates some error message like ?Customer object has no attribute ?_pid??. Thanks for your help! Partly code for the CUSTOMER object? class Customer(Process): def buyBaguette(self,cusType,bakery): tIn=now() print "PID is %d"%(os.getpid()) yield get,self,bakery.stock,r.choice(buy[cusType]) waits[cusType].append(now()-tIn) def __del__(self): print "distroy the customer" -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Aug 29 09:49:44 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 29 Aug 2011 00:49:44 -0700 Subject: [Tutor] program code for Python Programming for the Absolute Beginner, 3rd ed.? In-Reply-To: References: Message-ID: On Mon, Aug 29, 2011 at 00:19, TheIrda wrote: > on the left check the Programming, networking and security and look for your > book. > Click download and you can see the link to the source code and book related > software > > http://www.delmarlearning.com/companions/content/1435455002/downloads/index.asp?isbn=1435455002 Got it. Thanks very much! Dick From lisi.reisz at gmail.com Mon Aug 29 11:12:15 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 29 Aug 2011 10:12:15 +0100 Subject: [Tutor] One basic question about the Python's PID of Process object. In-Reply-To: <001101cc6613$618d1730$24a74590$%han@huawei.com> References: <001101cc6613$618d1730$24a74590$%han@huawei.com> Message-ID: <201108291012.15359.lisi.reisz@gmail.com> On Monday 29 August 2011 07:17:51 Han Guanghua wrote: > 2. Second question: ?When I changed the os.getpid() to os.getppid() or > self. _pid, ?the Python?s interpreter generates some error message like > ?Customer object has no attribute ?_pid??. > > ? I'm very much a beginner myself, but I am sure that someone will correct me if I am wrong. Should it not be self.pid rather than self._pid? Lisi From benshafat at gmail.com Mon Aug 29 11:46:29 2011 From: benshafat at gmail.com (Elisha Rosensweig) Date: Mon, 29 Aug 2011 12:46:29 +0300 Subject: [Tutor] Auto-detecting of Python version - wrong! Message-ID: Hi All, I'm trying to use easy_install on my Mac to get the Python networx package. On my machine I have installed version 2.5 AND 2.6 of Python. However, wehn I try to install this package, I get: easy_install networkx Searching for networkx Reading http://pypi.python.org/simple/networkx/ Reading http://networkx.lanl.gov/ Reading http://networkx.lanl.gov/download/networkx Reading http://sourceforge.net/project/showfiles.php?group_id=122233 Reading http://networkx.lanl.gov/download Reading http://networkx.lanl.gov Reading https://networkx.lanl.gov Best match: networkx 1.5 Downloading http://networkx.lanl.gov/download/networkx/networkx-1.5.zip Processing networkx-1.5.zip Running networkx-1.5/setup.py -q bdist_egg --dist-dir /var/folders/RF/RFpRZ44UEoO77eeJ7t1eOE+++TM/-Tmp-/easy_install-mTZw0S/networkx-1.5/egg-dist-tmp-TGWeRV *NetworkX requires Python version 2.6 or later (2.5 detected).* error: Setup script exited with -1 this, despite the fact that my default python is version 2.6: python Python *2.6.2* (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Any ideas how to solve this? Thanks in advance, Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From contactdayo at gmail.com Mon Aug 29 12:12:18 2011 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Mon, 29 Aug 2011 11:12:18 +0100 Subject: [Tutor] Sorting list of tuples in two passes In-Reply-To: References: <4E5A701B.40601@gmail.com> <4E5ADB14.9060006@gmail.com> Message-ID: <4E5B6602.6000507@gmail.com> On 08/29/2011 01:59 AM, Hugo Arts wrote: > On Mon, Aug 29, 2011 at 2:19 AM, Dayo Adewunmi wrote: >> On 08/28/2011 06:23 PM, Hugo Arts wrote: >>> On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmi >>> wrote: >>>> Hi >>>> >>>> I have a list of tuples that each have four elements: >>>> >>>> [(firstName,lastName,userName,gidNumber),(.....)....] >>>> >>>> I'm trying to sort this list in two passes. First by gidNumber and then >>>> the >>>> subgroups by lastName. So far i've only been able to sort by gidNumber. >>>> But >>>> I can't seem to wrap my mind around lambda, which is what my browsing >>>> around >>>> seems to indicate is needed to achieve this? >>>> >>>> Thanks >>>> >>>> Dayo >>>> >>> Python's builtin sort is stable, which means that ordering of items >>> with the same key is preserved. This property means that you can do >>> multiple pass sorting very easily and efficiently just by sorting >>> twice: >>> >>>>>> # we'll simplify the problem a bit and have tuples with just last name >>>>>> and id. >>>>>> l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), >>>>>> ('ccc', 2)] >>>>>> l.sort(key=itemgetter(0)) >>>>>> l >>> [('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)] >>>>>> l.sort(key=itemgetter(1)) >>>>>> l >>> [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] >>> We sort by last name first, then sort again by id. As you can see, the >>> sorting of groups with the same id is preserved, and our list is now >>> in the correct order. >>> >>> Hugo >>> >> It works when I use your example, but I don't understand why it won't work >> when I use 4-element tuples instead of 2: >> >>>>> l = [('wascas','aaa','fdvdfv', 1), ('rtgdsf','bbb','trfg', 1), >>>>> ('addwe','ccc','esd', 1), ('xasd','aaa','wascaq', 2), ('nhy','bbb','asw', >>>>> 2), ('zzzz','ccc','dgdeg', 2)] >>>>> l >> [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', >> 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), >> ('zzzz', 'ccc', 'dgdeg', 2)] >>>>> l.sort(key=itemgetter(3)) >>>>> l >> [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', >> 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), >> ('zzzz', 'ccc', 'dgdeg', 2)] >>>>> l.sort(key=itemgetter(1)) >>>>> l >> [('wascas', 'aaa', 'fdvdfv', 1), ('xasd', 'aaa', 'wasca q', 2), >> ('rtgdsf', 'bbb', 'trfg', 1), ('nhy', 'bbb', ' >> asw', 2), ('addwe', 'ccc', 'esd', 1), ('zzzz', 'ccc', 'dgdeg', 2)] >> >> Also I notice your original list and your end result list are in the same >> order. >> >> Thanks >> >> Dayo >> > In my original example, you can shuffle the list before you sort it > and it will still work. Try it, with a quick "from random import > shuffle; shuffle(l)". > > Also, notice that you want to sort by your primary order *last*. I > sorted by last name first, then sorted by id second, which means the > final list's primary order is by id, and secondary order by last name. > So the sorting goes in reverse. In your example, you sort by id first, > then last name. So your final list's primary order is by last name. > > Hugo > I tried it this way and it worked nicely: sortedList = sorted(l, key = itemgetter(3,1)) Thank you :-) Dayo From elisha at cs.umass.edu Mon Aug 29 12:50:44 2011 From: elisha at cs.umass.edu (Elisha Rosensweig) Date: Mon, 29 Aug 2011 13:50:44 +0300 Subject: [Tutor] Package installation on Mac does not detect newer version of python Message-ID: Hi All, I'm trying to use easy_install on my Mac to get the Python networx package. On my machine I have installed version 2.5 AND 2.6 of Python. However, wehn I try to install this package, I get: easy_install networkx Searching for networkx Reading http://pypi.python.org/simple/networkx/ Reading http://networkx.lanl.gov/ Reading http://networkx.lanl.gov/download/networkx Reading http://sourceforge.net/project/showfiles.php?group_id=122233 Reading http://networkx.lanl.gov/download Reading http://networkx.lanl.gov Reading https://networkx.lanl.gov Best match: networkx 1.5 Downloading http://networkx.lanl.gov/download/networkx/networkx-1.5.zip Processing networkx-1.5.zip Running networkx-1.5/setup.py -q bdist_egg --dist-dir /var/folders/RF/RFpRZ44UEoO77eeJ7t1eOE+++TM/-Tmp-/easy_install-mTZw0S/networkx-1.5/egg-dist-tmp-TGWeRV *NetworkX requires Python version 2.6 or later (2.5 detected).* error: Setup script exited with -1 this, despite the fact that my default python is version 2.6: python Python *2.6.2* (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Any ideas how to solve this? Thanks in advance, Elisha -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 29 14:54:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Aug 2011 22:54:05 +1000 Subject: [Tutor] Auto-detecting of Python version - wrong! In-Reply-To: References: Message-ID: <4E5B8BED.50307@pearwood.info> Elisha Rosensweig wrote: > I'm trying to use easy_install on my Mac to get the Python networx package. > On my machine I have installed version 2.5 AND 2.6 of Python. However, wehn > I try to install this package, I get: Hi Elisha, This list is for beginners trying to learning Python the language, not trying to solve arbitrary Python-related problems. You are more likely to get an answer by asking on one of the larger/busier lists, like python-list at python.org (also available on Usenet under comp.lang.python). You are more likely to find somebody who uses easy_install and a Mac there. But in the meantime, my *wild guess* is that this is a file association problem. If you call the python app directly with "python", the most recently added version (version 2.6) gets called, but if you try to run the easy_install directly script, the Mac automatically associates it with Python 2.5 and installation fails. Can you show us exactly how you are calling the easy install script? Another possibility is that it is an issue with the PATH. If you are calling "python" from the command line as a regular user, it might be picking up one version of Python, but if you call it as root (superuser), you might get a different PATH and therefore a different version of Python. Again, this depends on how you are calling the easy install script. (I emphasis that these are guesses... I haven't used Apple Macs regularly since System 7, back when Steve Jobs was still persona non grata at Apple. How times have changed.) -- Steven From cranky.frankie at gmail.com Mon Aug 29 17:26:55 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 29 Aug 2011 11:26:55 -0400 Subject: [Tutor] Intro Message-ID: Hi Python tutor listers, as an intro I'll repost what I sent to my Linux groups, since one of their members turned me on to you: Before Borders imploded I'd joined their club so they'd send me 50% coupons now and then. One afternoon last year I was in the store browsing the computer books and this Python book caught my eye. I knew very little about Python but I knew it had a good rep and I love Monty Python so I bought the book then put in on the shelf. Only recently did I get around to reading it and I only wish I'd done so sooner, it's that good. The book is "Python Programming for the Absolute Beginner, Third Edition" by Michael Dawson, Course Technology, ISBN-13 978-1-4354-5500-9, published in 2010. He presumes you know nothing about programming and then uses simple computer games to demonstrate the power of Python. He starts with those text based games many of us used to play, finishing off with GUI based games with music and animation, and all the code is downloadable from the publisher's web site. That's pretty good for a beginner book, I'd say. Python itself is a beautiful language. Because it uses indenting for constructing programming blocks, not semi-colons or braces, the code is inherently clean and crisp. More about Python: - it's easy to learn yet very powerful - very concise and tight syntax - comes with it's own IDE - no compiling yet can create stand alone apps - can be used for scripting or full blown applications - runs on all the major OSs - no variably type declarations, it can infer them - lots of modules (pre-coded specific code routines) available - can get productive quickly - can code in a procedural or object-oriented style Here's the typical introductory "Hello World" program: print("Hello World") Doesn't get much simpler than that! He even gets into GUI programming, event driven design, sprites, etc. For a book for a supposed absolute beginner I think that's amazing, because I can see someone getting this even if they really have no coding background. That's how clearly it's written and how clean and clear the example code is. One more side benefit of this book: it contains the gentlest, easiest to digest introduction to object-oriented programming I've ever seen, and I read a lot of computer stuff. If you're an old-timer like me who only studied procedural languages, this is about as easy an introduction to the power and flexibility of O-O programming that you will ever find. What I've been wanting to do for a long time is write an app that, when my computer starts, displays a window with a quote of the day. With this book I now have several ways to take my huge collected quotes file, import it into arrays in a Python program, apply a random function, and display a random quote each time I log on. That kind of app is a natural for Python, but don't kid yourself - he actually writes a space invaders type game using some game modules - and this in a beginner book! Amazing. This is a great book about a great language. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer " . . . and the extended forecast, until you come back to me, baby, is high tonight, low tomorrow, and precipitation is expected." - Tom Waits, "Emotional Weather Report" From lisi.reisz at gmail.com Mon Aug 29 17:45:17 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 29 Aug 2011 16:45:17 +0100 Subject: [Tutor] Intro In-Reply-To: References: Message-ID: <201108291645.18115.lisi.reisz@gmail.com> Is it just me, or is this a blatant plug for a specific book, and is it therefore Spam? For what it is worth, I hate all those games. Alan seems to use address books (anyhow initially). Now I can see the point in that. Lisi On Monday 29 August 2011 16:26:55 Cranky Frankie wrote: > Hi Python tutor listers, as an intro I'll repost what I sent to my > Linux groups, since one of their members turned me on to you: > > > > Before Borders imploded I'd joined their club so they'd send me 50% > coupons now and then. One afternoon last year I was in the store > browsing the computer books and this Python book caught my eye. I knew > very little about Python but I knew it had a good rep and I love Monty > Python so I bought the book then put in on the shelf. Only recently > did I get around to reading it and I only wish I'd done so sooner, > it's that good. > > The book is "Python Programming for the Absolute Beginner, Third > Edition" by Michael Dawson, Course Technology, ISBN-13 > 978-1-4354-5500-9, published in 2010. He presumes you know nothing > about programming and then uses simple computer games to demonstrate > the power of Python. He starts with those text based games many of us > used to play, finishing off with GUI based games with music and > animation, and all the code is downloadable from the publisher's web > site. That's pretty good for a beginner book, I'd say. > > Python itself is a beautiful language. Because it uses indenting for > constructing programming blocks, not semi-colons or braces, the code > is inherently clean and crisp. More about Python: > > - it's easy to learn yet very powerful > - very concise and tight syntax > - comes with it's own IDE > - no compiling yet can create stand alone apps > - can be used for scripting or full blown applications > - runs on all the major OSs > - no variably type declarations, it can infer them > - lots of modules (pre-coded specific code routines) available > - can get productive quickly > - can code in a procedural or object-oriented style > > Here's the typical introductory "Hello World" program: > > print("Hello World") > > Doesn't get much simpler than that! > > He even gets into GUI programming, event driven design, sprites, etc. > For a book for a supposed absolute beginner I think that's amazing, > because I can see someone getting this even if they really have no > coding background. That's how clearly it's written and how clean and > clear the example code is. > > One more side benefit of this book: it contains the gentlest, easiest > to digest introduction to object-oriented programming I've ever seen, > and I read a lot of computer stuff. If you're an old-timer like me who > only studied procedural languages, this is about as easy an > introduction to the power and flexibility of O-O programming that you > will ever find. > > What I've been wanting to do for a long time is write an app that, > when my computer starts, displays a window with a quote of the day. > With this book I now have several ways to take my huge collected > quotes file, import it into arrays in a Python program, apply a random > function, and display a random quote each time I log on. That kind of > app is a natural for Python, but don't kid yourself - he actually > writes a space invaders type game using some game modules - and this > in a beginner book! Amazing. > > > This is a great book about a great language. From lisi.reisz at gmail.com Mon Aug 29 18:12:33 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 29 Aug 2011 17:12:33 +0100 Subject: [Tutor] Intro In-Reply-To: <201108291645.18115.lisi.reisz@gmail.com> References: <201108291645.18115.lisi.reisz@gmail.com> Message-ID: <201108291712.33307.lisi.reisz@gmail.com> On Monday 29 August 2011 16:45:17 Lisi wrote: > Is it just me, or is this a blatant plug for a specific book, and is it > therefore Spam? Given that remark, I ought not to have included the full text in my reply. I apologise to our spam filters. :-( Lisi From cranky.frankie at gmail.com Mon Aug 29 19:01:44 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 29 Aug 2011 13:01:44 -0400 Subject: [Tutor] Tutor Digest, Vol 90, Issue 97 In-Reply-To: References: Message-ID: Lisi wrote: <> I hope it's just you, because it is not spam. As I said, I read a *lot* of computer books (I'm a database administrator) and this book really stands out. It's so good I'm thinking of seeing if my wife, who knows nothing about programming, would like to read it. I've never felt that way about a computer book before, and since this is so unusual in the computer book field, I thought I'd share it here. <> I'm not a gamer either, but this paradigm allowed the author to show the great flexibility of Python. I think he made a wise choice. Using games as a starting point should also make this book useful to teachers of programming 101, because kids love games. Anything that gets kids coding instead of just wasting time is good IMHO. << Alan seems to use address books (anyhow initially). Now I can see the point in that.>> I'm sorry you were offended by my posts. If others were as well let me know and I'll unsubscribe immediately. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer " . . . and the extended forecast, until you come back to me, baby, is high tonight, low tomorrow, and precipitation is expected." - Tom Waits, "Emotional Weather Report" From swiftone at swiftone.org Mon Aug 29 19:29:27 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 29 Aug 2011 13:29:27 -0400 Subject: [Tutor] Intro In-Reply-To: References: Message-ID: On Mon, Aug 29, 2011 at 11:26 AM, Cranky Frankie wrote: > Hi Python tutor listers, as an intro I'll repost what I sent to my > Linux groups, since one of their members turned me on to you: Glad you're so happy with this book...did you have a question for this list? -- Brett Ritter / SwiftOne swiftone at swiftone.org From python at bdurham.com Mon Aug 29 19:42:16 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 29 Aug 2011 13:42:16 -0400 Subject: [Tutor] Personal: Re: Tutor Digest, Vol 90, Issue 97 In-Reply-To: References: Message-ID: <1314639736.8546.140258134985041@webmail.messagingengine.com> Hi Frank, Please don't unsubscribe. Book reviews are always welcome. Malcolm From alan.gauld at btinternet.com Mon Aug 29 20:02:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Aug 2011 19:02:29 +0100 Subject: [Tutor] Intro In-Reply-To: <201108291645.18115.lisi.reisz@gmail.com> References: <201108291645.18115.lisi.reisz@gmail.com> Message-ID: On 29/08/11 16:45, Lisi wrote: > Is it just me, or is this a blatant plug for a specific book, and is it > therefore Spam? I think its intended to be a plug for Python rather than (or as well as) the book :-) > For what it is worth, I hate all those games. Alan seems to use address books > (anyhow initially). Now I can see the point in that. To be fair, in the paper edition of my tutor I do use a Games framework as a second case-study. I then use the framework to build a number guessing game and a Hangman (and a Mastermind on the CD)... Games are popular with many beginners especially hobbyists rather than corporate types :-). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Aug 29 20:06:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Aug 2011 19:06:49 +0100 Subject: [Tutor] Auto-detecting of Python version - wrong! In-Reply-To: <4E5B8BED.50307@pearwood.info> References: <4E5B8BED.50307@pearwood.info> Message-ID: On 29/08/11 13:54, Steven D'Aprano wrote: > (I emphasis that these are guesses... I haven't used Apple Macs > regularly since System 7, back when Steve Jobs was still persona non > grata at Apple. How times have changed.) Yeah, although I hear that he is leaving Apple(again) although on friendly terms this time... Due to health problems I believe. Another of the computer heroes leaves the field :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cranky.frankie at gmail.com Mon Aug 29 20:29:19 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 29 Aug 2011 14:29:19 -0400 Subject: [Tutor] Intro In-Reply-To: References: Message-ID: I'm trying to decide what would be better: - reading the huge quote file (hundreds of entries, two strings, author and quotation) in each time the program starts - loading the quotes into an array in the program I'd like to be able to add new quotes easily, so that is a factor as well. I'm satisfied to use a dialog box, I don't need a GUI at this point so no tkinter (yet). On Mon, Aug 29, 2011 at 1:29 PM, Brett Ritter wrote: ou: > > Glad you're so happy with this book...did you have a question for this list? > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org > -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer " . . . and the extended forecast, until you come back to me, baby, is high tonight, low tomorrow, and precipitation is expected." - Tom Waits, "Emotional Weather Report" From joel.goldstick at gmail.com Mon Aug 29 20:56:39 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 29 Aug 2011 14:56:39 -0400 Subject: [Tutor] Intro In-Reply-To: References: Message-ID: On Mon, Aug 29, 2011 at 2:29 PM, Cranky Frankie wrote: > I'm trying to decide what would be better: > > - reading the huge quote file (hundreds of entries, two strings, > author and quotation) in each time the program starts > > - loading the quotes into an array in the program > > I'd like to be able to add new quotes easily, so that is a factor as well. > > I'm satisfied to use a dialog box, I don't need a GUI at this point so > no tkinter (yet). > > On Mon, Aug 29, 2011 at 1:29 PM, Brett Ritter > wrote: > ou: > > > > Glad you're so happy with this book...did you have a question for this > list? > > > > -- > > Brett Ritter / SwiftOne > > swiftone at swiftone.org > > > I'm not sure I understand the either or part of your question. > A file of several hundred quotes doesn't really seem huge to me. At any rate, if you write a program to let you enter the quote and author, you will still need to store them somewhere. A file would be a simpler choice than a database for someone new to programming. What have you got so far? Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Mon Aug 29 21:23:14 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 29 Aug 2011 20:23:14 +0100 Subject: [Tutor] Tutor Digest, Vol 90, Issue 97 In-Reply-To: References: Message-ID: <201108292023.14267.lisi.reisz@gmail.com> On Monday 29 August 2011 18:01:44 Cranky Frankie wrote: > I'm sorry you were offended by my posts. If others were as well let me > know and I'll unsubscribe immediately. Post in the singular. I could not, and can not, I'm afraid, see the point in writing such a long panegyric about Python to a list of Python users. And you do seem to have gone wayyyy OT over that particular book, which I bought and found unusable. But it didn't _offend_ me, it just struck me as spam. Lisi From lisi.reisz at gmail.com Mon Aug 29 21:33:19 2011 From: lisi.reisz at gmail.com (Lisi) Date: Mon, 29 Aug 2011 20:33:19 +0100 Subject: [Tutor] Intro In-Reply-To: References: <201108291645.18115.lisi.reisz@gmail.com> Message-ID: <201108292033.19173.lisi.reisz@gmail.com> On Monday 29 August 2011 19:02:29 Alan Gauld wrote: > To be fair, in the paper edition of my tutor I do use a Games framework > as a second case-study. I then use the framework to build a number > guessing game and a Hangman (and a Mastermind on the CD)... Now, I knew there was a reason I decided to use the on-line version. ;-) I just didn't realise how wise my decision was. Anyhow, those games strike me as being reasonably innocuous - and fairly untypical of what computer games seem normally to be about. > Games are popular with many beginners especially hobbyists rather > than corporate types :-). Yes, I agree. I also agree that many (male) youngsters would like it. But statistically women don't like computer games (and yes, I know some do, but among women they are statistically in a minority). So using games for _all_ programming books strikes me as being almost sexist. It is after all, a good way to keep women out! ;-) And what have you got against corporate types??? ;-) Lisi From ramit.prasad at jpmorgan.com Mon Aug 29 22:26:43 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 29 Aug 2011 16:26:43 -0400 Subject: [Tutor] Intro In-Reply-To: <201108292033.19173.lisi.reisz@gmail.com> References: <201108291645.18115.lisi.reisz@gmail.com> <201108292033.19173.lisi.reisz@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F15DB2404@EMARC112VS01.exchad.jpmchase.net> I think I will take a page from rantingrick and state facts without providing any sources to back them up :) >>But statistically women don't like computer games (and yes, I know some do, but among women they are statistically in a minority). This has been historically true but women gamers are on the rise. In my opinion, the difference traditionally occurs because men and women frequently like to play different types games. As the gaming industry continues to expand (both in terms of target audience and developers), this ratio is starting to change. I can probably attribute some of that to things like Facebook games (e.g. Zynga) for a lot more women playing games (although, they usually do not consider themselves "gamers"). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From cranky.frankie at gmail.com Mon Aug 29 22:08:22 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 29 Aug 2011 16:08:22 -0400 Subject: [Tutor] Tutor Digest, Vol 90, Issue 98 In-Reply-To: References: Message-ID: Joel Goldstick wrote: <> Just planning it out in my head so far, like pseudocode. I hope to get started soon. I'm just looking to have a little dialog box come up, display a random quote of the day, and then hit enter and it's gone. Should be a nice, simple way to get started with Python. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer " . . . and the extended forecast, until you come back to me, baby, is high tonight, low tomorrow, and precipitation is expected." - Tom Waits, "Emotional Weather Report" From emile at fenx.com Mon Aug 29 23:36:02 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Aug 2011 14:36:02 -0700 Subject: [Tutor] Intro In-Reply-To: References: Message-ID: On 8/29/2011 11:29 AM Cranky Frankie said... > I'm trying to decide what would be better: 'better' is subjective. On the one hand, you have a monolithic python program that consolidates data and program into a single source; on the other hand, you have separation of logic and data. Most often, and particularly for larger on-going projects, I'll use the second approach as the infrastructure to support it is already in place. However, I am rather fond of certain monolithic solutions as both maintenance and deployment are much easier. TiddlyWiki and Monmotha's firewall script come to mind. > > - reading the huge quote file (hundreds of entries, two strings, > author and quotation) in each time the program starts > > - loading the quotes into an array in the program I don't imagine you'd see much difference here. The content must be read from disk and organized in a python structure regardless. > > I'd like to be able to add new quotes easily, so that is a factor as well. > > I'm satisfied to use a dialog box, I don't need a GUI at this point so > no tkinter (yet). There's not much difference either in the 'launch a program' or 'load a program' approaches to adding quotes. For learning purposes, I think I'd advise a complete newbie to start with the monolithic approach and build up and out from there. Emile From DAReed at aeraenergy.com Tue Aug 30 00:28:22 2011 From: DAReed at aeraenergy.com (Reed DA (Danny) at Aera) Date: Mon, 29 Aug 2011 15:28:22 -0700 Subject: [Tutor] Loops and matrices' Message-ID: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> Hi all, I have a matrix which contains temperatures. The columns are time, spaced 33 seconds apart, and the rows are depth intervals. What I'm trying to do is create another matrix that contains the rate of change of temperature for each depth. The array is called LS_JULY_11 and the output array should be delta_temp What I have so far is:- import numpy #determine the existing matrix size columnsize = LS_JULY_11.columnSize() matrixsize = LS_JULY_11.size() rowsize = matrixsize/columnsize #define time step TIME_STEP = 33 #create matrix size of the same size delta_temp = numpy.zeros((rowsize,columnsize)) #cycle through all indicies in temperature matrix for i in rowsize: for j in columnsize: delta_temp(i,j) = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP j = j+1 i = i + 1 the error I get is:- File "", line 18 (33) SyntaxError: can't assign to function call Help would be greatly appreciated Thanks Danny -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Aug 30 01:26:03 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Aug 2011 16:26:03 -0700 Subject: [Tutor] Loops and matrices' In-Reply-To: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> References: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> Message-ID: On 8/29/2011 3:28 PM Reed DA (Danny) at Aera said... > Hi all, > > I have a matrix which contains temperatures. The columns are time, > spaced 33 seconds apart, and the rows are depth intervals. What I'm > trying to do is create another matrix that contains the rate of change > of temperature for each depth. The array is called LS_JULY_11 and the > output array should be delta_temp > > What I have so far is:- > > import numpy > > #determine the existing matrix size > > columnsize = LS_JULY_11.columnSize() > > matrixsize = LS_JULY_11.size() > > rowsize = matrixsize/columnsize > > #define time step > > TIME_STEP = 33 > > #create matrix size of the same size > > delta_temp = numpy.zeros((rowsize,columnsize)) > > #cycle through all indicies in temperature matrix > > for i in rowsize: > > for j in columnsize: > > delta_temp(i,j) = (LS_JULY_11(i,j) - > LS_JULY_11(i,j-1))/TIME_STEP > > j = j+1 > > i = i + 1 > > the error I get is:- > > File "", line 18 (33) > > SyntaxError: can't assign to function call delta_temp access and assignment likely wants to be expressed with brackets rather than parens. Emile ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> spam(1,2)=6 File "", line 1 SyntaxError: can't assign to function call >>> > > Help would be greatly appreciated > > Thanks > > Danny > From ramit.prasad at jpmorgan.com Tue Aug 30 00:44:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 29 Aug 2011 18:44:09 -0400 Subject: [Tutor] Loops and matrices' In-Reply-To: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> References: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F15DB2653@EMARC112VS01.exchad.jpmchase.net> Hi Danny, Most likely you want ??????????????????????????????? delta_temp(i,j) = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP to become (changed the character from '()' to '[]': ??????????????????????????????? delta_temp[i,j] = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP Basically it thinks "delta_temp(i,j) " is a function call and function calls cannot be assigned a value. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From questions.anon at gmail.com Tue Aug 30 01:52:42 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 30 Aug 2011 09:52:42 +1000 Subject: [Tutor] select particular directories and files Message-ID: I am trying to select particular files within a particular subdirectory, I have been able to do both but not together! When I try to select my files within the dir loop nothing comes up, but when I leave the files outside the dir loops it selects all the files not just the ones in the dirs I have selected. The code I am using is: import os MainFolder=r"D:/samples/" for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: if dir=='01': print "selected directories are:",dir for ncfile in dir: if ncfile[-3:]=='.nc': print "ncfiles are:", ncfile Any feedback will be greatly appreciated!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Aug 30 02:07:22 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Aug 2011 17:07:22 -0700 Subject: [Tutor] select particular directories and files In-Reply-To: References: Message-ID: On 8/29/2011 4:52 PM questions anon said... > I am trying to select particular files within > a particular subdirectory, You might find glob a better starting point: ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import glob >>> help(glob.glob) Help on function glob in module glob: glob(pathname) Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\*.txt'): print filename ... C:\WSG\GL\2011-08\2011-01-WIP-Details.txt C:\WSG\GL\2011-08\2011-02-WIP-Details.txt C:\WSG\GL\2011-08\2011-03-WIP-Details.txt C:\WSG\GL\2011-08\2011-04-WIP-Details.txt C:\WSG\GL\2011-08\2011-05-WIP-Details.txt C:\WSG\GL\2011-08\2011-06-WIP-Details.txt C:\WSG\GL\2011-08\2011-07 - bankToRec.txt C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt C:\WSG\GL\2011-08\2011-07-WIP-Details.txt C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt C:\WSG\GL\2011-08\BankRecUtils.txt C:\WSG\GL\2011-08\CapitalizationExamples.txt C:\WSG\GL\2011-08\DEALLOCATE-2011-04.txt C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt C:\WSG\GL\2011-08\MAR DEALLOCATION.txt C:\WSG\GL\2011-08\Notes.txt C:\WSG\GL\2011-08\shipping safety net util.txt C:\WSG\GL\2011-08\UNBILLED WIP.txt C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt C:\WSG\GL\2011-08\vacation accrual notes.txt >>> > I have been able to do both but not together! > When I try to select my files within the dir loop nothing comes up, but > when I leave the files outside the dir loops it selects all the files > not just the ones in the dirs I have selected. > The code I am using is: > > import os > > MainFolder=r"D:/samples/" > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > if dir=='01': > print "selected directories are:",dir > > for ncfile in dir: > if ncfile[-3:]=='.nc': > print "ncfiles are:", ncfile > > Any feedback will be greatly appreciated!! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Aug 30 02:30:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Aug 2011 01:30:30 +0100 Subject: [Tutor] Intro In-Reply-To: References: Message-ID: On 29/08/11 19:29, Cranky Frankie wrote: > - reading the huge quote file (hundreds of entries, two strings, > author and quotation) in each time the program starts > > - loading the quotes into an array in the program If you just want a random quote find the size of the file. Generate a random number in that range and go back to find the start of the quote.(Assuming some readily identifiable marker exists) Or, if you write a quote maintenance program to add/delete quotes then even easier is to keep a tally of the number of quotes at the start of the file and then generate the random number based on that. Then simply read forward that many quotes. If it was a really big file(millions of quotes) you could store a table of contents including the quote number and offset, but I suspect you haven't that many quotes yet... > I'm satisfied to use a dialog box, I don't need a GUI at this point so > no tkinter (yet). Consider EasyGUI, its ideal for that. Altthough you could use the standard Tkinter dialogs too (from which easyGUI is built I suspect) The Talking to the User topic of my tutor describes EasyGUI and the GUI topic describes the basic Tkinter message dialogs. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From guanghua.han at huawei.com Tue Aug 30 02:29:29 2011 From: guanghua.han at huawei.com (Han Guanghua) Date: Tue, 30 Aug 2011 08:29:29 +0800 Subject: [Tutor] =?utf-8?b?562U5aSNOiAgT25lIGJhc2ljIHF1ZXN0aW9uIGFib3V0?= =?utf-8?q?_the_Python=27s_PID_of_Process=09object=2E?= In-Reply-To: <201108291012.15359.lisi.reisz@gmail.com> References: <001101cc6613$618d1730$24a74590$%han@huawei.com> <201108291012.15359.lisi.reisz@gmail.com> Message-ID: <007d01cc66ab$e240cc80$a6c26580$%han@huawei.com> Thanks for your help. Now I think I found the reason why os.getpid() returns the same PID value for the Process object, because Process object is NOT the standard Python's process which is adapted by a library called SimPy.(Simulation with Python). BRs, Han / Henrry -----????----- ???: tutor-bounces+guanghua.han=huawei.com at python.org [mailto:tutor-bounces+guanghua.han=huawei.com at python.org] ?? Lisi ????: 2011?8?29? 17:12 ???: tutor at python.org ??: Re: [Tutor] One basic question about the Python's PID of Process object. On Monday 29 August 2011 07:17:51 Han Guanghua wrote: > 2. Second question: When I changed the os.getpid() to os.getppid() or > self. _pid, the Python?s interpreter generates some error message like > ?Customer object has no attribute ?_pid??. > > I'm very much a beginner myself, but I am sure that someone will correct me if I am wrong. Should it not be self.pid rather than self._pid? Lisi _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Aug 30 02:33:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Aug 2011 01:33:34 +0100 Subject: [Tutor] Tutor Digest, Vol 90, Issue 98 In-Reply-To: References: Message-ID: On 29/08/11 21:08, Cranky Frankie wrote: Please use meaningful subject lines. "Re: Tutor Digest, Vol 90, Issue 98" doesn't help anyone identify a topic in the future and it doesn't help filter messages now. However, on the plus side, thank you for *not* including the whole digest in your message, as so often happens! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 30 02:42:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Aug 2011 01:42:07 +0100 Subject: [Tutor] Loops and matrices' In-Reply-To: References: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> Message-ID: On 30/08/11 00:26, Emile van Sebille wrote: >> delta_temp(i,j) = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP > > delta_temp access and assignment likely wants to be expressed with > brackets rather than parens. And for those not speaking the US variant of English that'll be square brackets as opposed to round brackets! ;-) [ One of the sources of amusement to me when having my book reviewed was the fact that *all* the US reviewers picked up on my use of " brackets" to cover [],<>,(), {}. Apparently US usage of brackets is limited to []. Something that greatly surprised me and my English, Indian and South African colleagues! :-) ] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 30 02:45:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Aug 2011 01:45:59 +0100 Subject: [Tutor] Tutor Digest, Vol 90, Issue 97 In-Reply-To: <201108292023.14267.lisi.reisz@gmail.com> References: <201108292023.14267.lisi.reisz@gmail.com> Message-ID: On 29/08/11 20:23, Lisi wrote: > ...I could not, and can not, I'm afraid, see the point in > writing such a long panegyric about Python It's actually quite common on this list. Especially from programmers newly come to Python from other languages and who get quite excited when they discover how powerful and succint Python can be :-) They seem somehow surprised that the folks on a Python list have already figured that out!... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Aug 30 03:19:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 30 Aug 2011 11:19:52 +1000 Subject: [Tutor] Loops and matrices' In-Reply-To: References: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> Message-ID: <4E5C3AB8.4050503@pearwood.info> Alan Gauld wrote: > On 30/08/11 00:26, Emile van Sebille wrote: > >>> delta_temp(i,j) = (LS_JULY_11(i,j) - LS_JULY_11(i,j-1))/TIME_STEP >> >> delta_temp access and assignment likely wants to be expressed with >> brackets rather than parens. > > And for those not speaking the US variant of English that'll be square > brackets as opposed to round brackets! ;-) > > [ One of the sources of amusement to me when having my book reviewed was > the fact that *all* the US reviewers picked up on my use of " > brackets" to cover [],<>,(), {}. Apparently US usage of brackets is > limited to []. Something that greatly surprised me and my English, > Indian and South African colleagues! :-) ] And Australians and New Zealanders too. Any Canadians want to weigh in with an opinion? Brackets are anything that, er, brackets an expression (excluding quotation marks), where the one on the left is different from the one on the right. So: () round brackets [] square brackets {} curly brackets <> angle brackets Easier to spell than parenthesis/parentheses, but longer than brace/braces :) Strictly speaking, the chevrons (angle brackets) should be ?? rather than less than and greater than signs, but they're hard to type at the keyboard and look too similar to round brackets in small font sizes. -- Steven From steve at pearwood.info Tue Aug 30 03:21:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 30 Aug 2011 11:21:15 +1000 Subject: [Tutor] Tutor Digest, Vol 90, Issue 97 In-Reply-To: <201108292023.14267.lisi.reisz@gmail.com> References: <201108292023.14267.lisi.reisz@gmail.com> Message-ID: <4E5C3B0B.4020802@pearwood.info> Lisi wrote: > On Monday 29 August 2011 18:01:44 Cranky Frankie wrote: >> I'm sorry you were offended by my posts. If others were as well let me >> know and I'll unsubscribe immediately. > > Post in the singular. I could not, and can not, I'm afraid, see the point in > writing such a long panegyric about Python to a list of Python users. It's a book review for a book that Cranky Frankie really loved. As book reviews go, I've read much worse. But I'm not sure that this is the right place for it... Frankie, do you have a blog? Perhaps you should consider getting one. Actually, given that this list is aimed at beginners, and the question of "what's a good book to read" keeps coming up, on balance I'm inclined to say that such reviews are legitimate (so long as Frankie has no direct, or indirect, incentive to shill for the book he is reviewing). But please don't over do it. > And you do seem to have gone wayyyy OT over that particular book, which I > bought and found unusable. Heh, well different people find different approaches useful. -- Steven From questions.anon at gmail.com Tue Aug 30 04:23:10 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 30 Aug 2011 12:23:10 +1000 Subject: [Tutor] select particular directories and files In-Reply-To: References: Message-ID: Thanks for responding When I try glob.glob I receive no errors but nothing prints. MainFolder=r"E:/Sample/" for dir in glob.glob(MainFolder + '01'): print "my selected directories are:", dir for ncfile in glob.glob('.nc'): print "my selected netcdf files are:", ncfile any suggestions? thanks On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: > On 8/29/2011 4:52 PM questions anon said... > > I am trying to select particular files within >> a particular subdirectory, >> > > You might find glob a better starting point: > > ActivePython 2.6.6.15 (ActiveState Software Inc.) based on > Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import glob > >>> help(glob.glob) > Help on function glob in module glob: > > glob(pathname) > Return a list of paths matching a pathname pattern. > > The pattern may contain simple shell-style wildcards a la fnmatch. > > >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\***.txt'): > print filename > ... > C:\WSG\GL\2011-08\2011-01-WIP-**Details.txt > C:\WSG\GL\2011-08\2011-02-WIP-**Details.txt > C:\WSG\GL\2011-08\2011-03-WIP-**Details.txt > C:\WSG\GL\2011-08\2011-04-WIP-**Details.txt > C:\WSG\GL\2011-08\2011-05-WIP-**Details.txt > C:\WSG\GL\2011-08\2011-06-WIP-**Details.txt > C:\WSG\GL\2011-08\2011-07 - bankToRec.txt > C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt > C:\WSG\GL\2011-08\2011-07-WIP-**Details.txt > C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt > C:\WSG\GL\2011-08\**BankRecUtils.txt > C:\WSG\GL\2011-08\**CapitalizationExamples.txt > C:\WSG\GL\2011-08\DEALLOCATE-**2011-04.txt > C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt > C:\WSG\GL\2011-08\MAR DEALLOCATION.txt > C:\WSG\GL\2011-08\Notes.txt > C:\WSG\GL\2011-08\shipping safety net util.txt > C:\WSG\GL\2011-08\UNBILLED WIP.txt > C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt > C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt > C:\WSG\GL\2011-08\vacation accrual notes.txt > >>> > > > > > I have been able to do both but not together! >> When I try to select my files within the dir loop nothing comes up, but >> when I leave the files outside the dir loops it selects all the files >> not just the ones in the dirs I have selected. >> The code I am using is: >> >> import os >> >> MainFolder=r"D:/samples/" >> >> for (path, dirs, files) in os.walk(MainFolder): >> for dir in dirs: >> if dir=='01': >> print "selected directories are:",dir >> >> for ncfile in dir: >> if ncfile[-3:]=='.nc': >> print "ncfiles are:", ncfile >> >> Any feedback will be greatly appreciated!! >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Tue Aug 30 05:30:19 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 29 Aug 2011 20:30:19 -0700 Subject: [Tutor] select particular directories and files In-Reply-To: References: Message-ID: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> Dear Anonymous Questioner, I am not sure how the Windows environment works, but in linux, I would replace > for ncfile in glob.glob('.nc'): with > for ncfile in glob.glob('*.nc'): ie, add the "wild card" '*' character to grab all files which end in '.nc' Andre On Aug 29, 2011, at 7:23 PM, questions anon wrote: > Thanks for responding > When I try glob.glob I receive no errors but nothing prints. > > MainFolder=r"E:/Sample/" > for dir in glob.glob(MainFolder + '01'): > print "my selected directories are:", dir > for ncfile in glob.glob('.nc'): > print "my selected netcdf files are:", ncfile > > any suggestions? thanks > > > On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: > On 8/29/2011 4:52 PM questions anon said... > > I am trying to select particular files within > a particular subdirectory, > > You might find glob a better starting point: > > ActivePython 2.6.6.15 (ActiveState Software Inc.) based on > Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import glob > >>> help(glob.glob) > Help on function glob in module glob: > > glob(pathname) > Return a list of paths matching a pathname pattern. > > The pattern may contain simple shell-style wildcards a la fnmatch. > > >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\*.txt'): > print filename > ... > C:\WSG\GL\2011-08\2011-01-WIP-Details.txt > C:\WSG\GL\2011-08\2011-02-WIP-Details.txt > C:\WSG\GL\2011-08\2011-03-WIP-Details.txt > C:\WSG\GL\2011-08\2011-04-WIP-Details.txt > C:\WSG\GL\2011-08\2011-05-WIP-Details.txt > C:\WSG\GL\2011-08\2011-06-WIP-Details.txt > C:\WSG\GL\2011-08\2011-07 - bankToRec.txt > C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt > C:\WSG\GL\2011-08\2011-07-WIP-Details.txt > C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt > C:\WSG\GL\2011-08\BankRecUtils.txt > C:\WSG\GL\2011-08\CapitalizationExamples.txt > C:\WSG\GL\2011-08\DEALLOCATE-2011-04.txt > C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt > C:\WSG\GL\2011-08\MAR DEALLOCATION.txt > C:\WSG\GL\2011-08\Notes.txt > C:\WSG\GL\2011-08\shipping safety net util.txt > C:\WSG\GL\2011-08\UNBILLED WIP.txt > C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt > C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt > C:\WSG\GL\2011-08\vacation accrual notes.txt > >>> > > > > > I have been able to do both but not together! > When I try to select my files within the dir loop nothing comes up, but > when I leave the files outside the dir loops it selects all the files > not just the ones in the dirs I have selected. > The code I am using is: > > import os > > MainFolder=r"D:/samples/" > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: > if dir=='01': > print "selected directories are:",dir > > for ncfile in dir: > if ncfile[-3:]=='.nc': > print "ncfiles are:", ncfile > > Any feedback will be greatly appreciated!! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Tue Aug 30 05:35:25 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 30 Aug 2011 13:35:25 +1000 Subject: [Tutor] select particular directories and files In-Reply-To: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> References: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> Message-ID: thanks, that was an error by me. but that still doesn't help me select the dir and files! Could it be because I am trying to select folders within other folders to then get a file from each of those folders? On Tue, Aug 30, 2011 at 1:30 PM, Andre' Walker-Loud wrote: > Dear Anonymous Questioner, > > I am not sure how the Windows environment works, but in linux, I would > replace > > for ncfile in glob.glob('.nc'): > > > with > > for ncfile in glob.glob('*.nc'): > > > ie, add the "wild card" '*' character to grab all files which end in '.nc' > > > Andre > > > > > On Aug 29, 2011, at 7:23 PM, questions anon wrote: > > Thanks for responding > When I try glob.glob I receive no errors but nothing prints. > > MainFolder=r"E:/Sample/" > for dir in glob.glob(MainFolder + '01'): > print "my selected directories are:", dir > for ncfile in glob.glob('.nc'): > print "my selected netcdf files are:", ncfile > > any suggestions? thanks > > > On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: > >> On 8/29/2011 4:52 PM questions anon said... >> >> I am trying to select particular files within >>> a particular subdirectory, >>> >> >> You might find glob a better starting point: >> >> ActivePython 2.6.6.15 (ActiveState Software Inc.) based on >> Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import glob >> >>> help(glob.glob) >> Help on function glob in module glob: >> >> glob(pathname) >> Return a list of paths matching a pathname pattern. >> >> The pattern may contain simple shell-style wildcards a la fnmatch. >> >> >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\***.txt'): >> print filename >> ... >> C:\WSG\GL\2011-08\2011-01-WIP-**Details.txt >> C:\WSG\GL\2011-08\2011-02-WIP-**Details.txt >> C:\WSG\GL\2011-08\2011-03-WIP-**Details.txt >> C:\WSG\GL\2011-08\2011-04-WIP-**Details.txt >> C:\WSG\GL\2011-08\2011-05-WIP-**Details.txt >> C:\WSG\GL\2011-08\2011-06-WIP-**Details.txt >> C:\WSG\GL\2011-08\2011-07 - bankToRec.txt >> C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt >> C:\WSG\GL\2011-08\2011-07-WIP-**Details.txt >> C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt >> C:\WSG\GL\2011-08\**BankRecUtils.txt >> C:\WSG\GL\2011-08\**CapitalizationExamples.txt >> C:\WSG\GL\2011-08\DEALLOCATE-**2011-04.txt >> C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt >> C:\WSG\GL\2011-08\MAR DEALLOCATION.txt >> C:\WSG\GL\2011-08\Notes.txt >> C:\WSG\GL\2011-08\shipping safety net util.txt >> C:\WSG\GL\2011-08\UNBILLED WIP.txt >> C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt >> C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt >> C:\WSG\GL\2011-08\vacation accrual notes.txt >> >>> >> >> >> >> >> I have been able to do both but not together! >>> When I try to select my files within the dir loop nothing comes up, but >>> when I leave the files outside the dir loops it selects all the files >>> not just the ones in the dirs I have selected. >>> The code I am using is: >>> >>> import os >>> >>> MainFolder=r"D:/samples/" >>> >>> for (path, dirs, files) in os.walk(MainFolder): >>> for dir in dirs: >>> if dir=='01': >>> print "selected directories are:",dir >>> >>> for ncfile in dir: >>> if ncfile[-3:]=='.nc': >>> print "ncfiles are:", ncfile >>> >>> Any feedback will be greatly appreciated!! >>> >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Tue Aug 30 05:40:02 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 29 Aug 2011 20:40:02 -0700 Subject: [Tutor] select particular directories and files In-Reply-To: References: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> Message-ID: <4E78A68F-8DAA-4A70-9675-829300D918F7@gmail.com> hello, yes, I would also try adding a wild card in the dir search >> for dir in glob.glob(MainFolder + '01\*'): to check if this is helps, in an interpreter (rather than script) try dirs = glob.glob(MainFolder + '\01\*'): print dirs if you get "[]" then this was not the answer, but if you get a list of directories, then this should work. Well, it should work with the correction >> for ncfile in glob.glob(dir+'\*.nc'): Cheers, Andre On Aug 29, 2011, at 8:35 PM, questions anon wrote: > thanks, that was an error by me. but that still doesn't help me select the dir and files! > Could it be because I am trying to select folders within other folders to then get a file from each of those folders? > > > On Tue, Aug 30, 2011 at 1:30 PM, Andre' Walker-Loud wrote: > Dear Anonymous Questioner, > > I am not sure how the Windows environment works, but in linux, I would replace > >> for ncfile in glob.glob('.nc'): > > > with > >> for ncfile in glob.glob('*.nc'): > > > ie, add the "wild card" '*' character to grab all files which end in '.nc' > > > Andre > > > > > On Aug 29, 2011, at 7:23 PM, questions anon wrote: > >> Thanks for responding >> When I try glob.glob I receive no errors but nothing prints. >> >> MainFolder=r"E:/Sample/" >> for dir in glob.glob(MainFolder + '01'): >> print "my selected directories are:", dir >> for ncfile in glob.glob('.nc'): >> print "my selected netcdf files are:", ncfile >> >> any suggestions? thanks >> >> >> On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: >> On 8/29/2011 4:52 PM questions anon said... >> >> I am trying to select particular files within >> a particular subdirectory, >> >> You might find glob a better starting point: >> >> ActivePython 2.6.6.15 (ActiveState Software Inc.) based on >> Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import glob >> >>> help(glob.glob) >> Help on function glob in module glob: >> >> glob(pathname) >> Return a list of paths matching a pathname pattern. >> >> The pattern may contain simple shell-style wildcards a la fnmatch. >> >> >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\*.txt'): >> print filename >> ... >> C:\WSG\GL\2011-08\2011-01-WIP-Details.txt >> C:\WSG\GL\2011-08\2011-02-WIP-Details.txt >> C:\WSG\GL\2011-08\2011-03-WIP-Details.txt >> C:\WSG\GL\2011-08\2011-04-WIP-Details.txt >> C:\WSG\GL\2011-08\2011-05-WIP-Details.txt >> C:\WSG\GL\2011-08\2011-06-WIP-Details.txt >> C:\WSG\GL\2011-08\2011-07 - bankToRec.txt >> C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt >> C:\WSG\GL\2011-08\2011-07-WIP-Details.txt >> C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt >> C:\WSG\GL\2011-08\BankRecUtils.txt >> C:\WSG\GL\2011-08\CapitalizationExamples.txt >> C:\WSG\GL\2011-08\DEALLOCATE-2011-04.txt >> C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt >> C:\WSG\GL\2011-08\MAR DEALLOCATION.txt >> C:\WSG\GL\2011-08\Notes.txt >> C:\WSG\GL\2011-08\shipping safety net util.txt >> C:\WSG\GL\2011-08\UNBILLED WIP.txt >> C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt >> C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt >> C:\WSG\GL\2011-08\vacation accrual notes.txt >> >>> >> >> >> >> >> I have been able to do both but not together! >> When I try to select my files within the dir loop nothing comes up, but >> when I leave the files outside the dir loops it selects all the files >> not just the ones in the dirs I have selected. >> The code I am using is: >> >> import os >> >> MainFolder=r"D:/samples/" >> >> for (path, dirs, files) in os.walk(MainFolder): >> for dir in dirs: >> if dir=='01': >> print "selected directories are:",dir >> >> for ncfile in dir: >> if ncfile[-3:]=='.nc': >> print "ncfiles are:", ncfile >> >> Any feedback will be greatly appreciated!! >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Tue Aug 30 06:18:32 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 30 Aug 2011 14:18:32 +1000 Subject: [Tutor] select particular directories and files In-Reply-To: <4E78A68F-8DAA-4A70-9675-829300D918F7@gmail.com> References: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> <4E78A68F-8DAA-4A70-9675-829300D918F7@gmail.com> Message-ID: It worked! thank you. This is the code I ended with: for dir in glob.glob(MainFolder + '*/01/'): print dir for ncfile in glob.glob(dir + '*.nc'): print ncfile can you choose more than one folder with glob? i.e. I tried: for dir in glob.glob(MainFolder + '*/01/', '*/02/', '*/03/'): but I received: TypeError: glob() takes exactly 1 argument (3 given) thanks On Tue, Aug 30, 2011 at 1:40 PM, Andre' Walker-Loud wrote: > hello, > > yes, I would also try adding a wild card in the dir search > > for dir in glob.glob(MainFolder + '01\*'): >> >> > to check if this is helps, in an interpreter (rather than script) try > > dirs = glob.glob(MainFolder + '\01\*'): > print dirs > > > if you get "[]" then this was not the answer, but if you get a list of > directories, then this should work. > > Well, it should work with the correction > > > for ncfile in glob.glob(dir+'\*.nc'): >> >> > > Cheers, > > Andre > > > > > > > On Aug 29, 2011, at 8:35 PM, questions anon wrote: > > thanks, that was an error by me. but that still doesn't help me select the > dir and files! > Could it be because I am trying to select folders within other folders to > then get a file from each of those folders? > > > On Tue, Aug 30, 2011 at 1:30 PM, Andre' Walker-Loud wrote: > >> Dear Anonymous Questioner, >> >> I am not sure how the Windows environment works, but in linux, I would >> replace >> >> for ncfile in glob.glob('.nc'): >> >> >> with >> >> for ncfile in glob.glob('*.nc'): >> >> >> ie, add the "wild card" '*' character to grab all files which end in '.nc' >> >> >> Andre >> >> >> >> >> On Aug 29, 2011, at 7:23 PM, questions anon wrote: >> >> Thanks for responding >> When I try glob.glob I receive no errors but nothing prints. >> >> MainFolder=r"E:/Sample/" >> for dir in glob.glob(MainFolder + '01'): >> print "my selected directories are:", dir >> for ncfile in glob.glob('.nc'): >> print "my selected netcdf files are:", ncfile >> >> any suggestions? thanks >> >> >> On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: >> >>> On 8/29/2011 4:52 PM questions anon said... >>> >>> I am trying to select particular files within >>>> a particular subdirectory, >>>> >>> >>> You might find glob a better starting point: >>> >>> ActivePython 2.6.6.15 (ActiveState Software Inc.) based on >>> Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit >>> (Intel)] on win32 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import glob >>> >>> help(glob.glob) >>> Help on function glob in module glob: >>> >>> glob(pathname) >>> Return a list of paths matching a pathname pattern. >>> >>> The pattern may contain simple shell-style wildcards a la fnmatch. >>> >>> >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\***.txt'): >>> print filename >>> ... >>> C:\WSG\GL\2011-08\2011-01-WIP-**Details.txt >>> C:\WSG\GL\2011-08\2011-02-WIP-**Details.txt >>> C:\WSG\GL\2011-08\2011-03-WIP-**Details.txt >>> C:\WSG\GL\2011-08\2011-04-WIP-**Details.txt >>> C:\WSG\GL\2011-08\2011-05-WIP-**Details.txt >>> C:\WSG\GL\2011-08\2011-06-WIP-**Details.txt >>> C:\WSG\GL\2011-08\2011-07 - bankToRec.txt >>> C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt >>> C:\WSG\GL\2011-08\2011-07-WIP-**Details.txt >>> C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt >>> C:\WSG\GL\2011-08\**BankRecUtils.txt >>> C:\WSG\GL\2011-08\**CapitalizationExamples.txt >>> C:\WSG\GL\2011-08\DEALLOCATE-**2011-04.txt >>> C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt >>> C:\WSG\GL\2011-08\MAR DEALLOCATION.txt >>> C:\WSG\GL\2011-08\Notes.txt >>> C:\WSG\GL\2011-08\shipping safety net util.txt >>> C:\WSG\GL\2011-08\UNBILLED WIP.txt >>> C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt >>> C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt >>> C:\WSG\GL\2011-08\vacation accrual notes.txt >>> >>> >>> >>> >>> >>> >>> I have been able to do both but not together! >>>> When I try to select my files within the dir loop nothing comes up, but >>>> when I leave the files outside the dir loops it selects all the files >>>> not just the ones in the dirs I have selected. >>>> The code I am using is: >>>> >>>> import os >>>> >>>> MainFolder=r"D:/samples/" >>>> >>>> for (path, dirs, files) in os.walk(MainFolder): >>>> for dir in dirs: >>>> if dir=='01': >>>> print "selected directories are:",dir >>>> >>>> for ncfile in dir: >>>> if ncfile[-3:]=='.nc': >>>> print "ncfiles are:", ncfile >>>> >>>> Any feedback will be greatly appreciated!! >>>> >>>> >>>> ______________________________**_________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/**mailman/listinfo/tutor >>>> >>> >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Tue Aug 30 06:37:25 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 29 Aug 2011 21:37:25 -0700 Subject: [Tutor] select particular directories and files In-Reply-To: References: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> <4E78A68F-8DAA-4A70-9675-829300D918F7@gmail.com> Message-ID: <336784D8-6A0E-4F6F-B75C-2AB7A0FB5984@gmail.com> to have multiple dirs is simple, > for dir in glob.glob(MainFolder + '*/01/') + glob.glob(MainFolder + '*/02/') + glob.glob(MainFolder + '*/03/'): there may be a better way, but this should work. By the way, not to discourage you from asking questions on the list, but many of these things can be deduced quickly by trial and error using the python interpreter (the interactive python shell). That is one thing I really like about python, you really can just play around with it. And with all things, if you figure it out on your own, then you will likely feel better about that, and also, you will retain the knowledge better and gain more confidence in trying new things. Cheers, Andre On Aug 29, 2011, at 9:18 PM, questions anon wrote: > It worked! thank you. This is the code I ended with: > > for dir in glob.glob(MainFolder + '*/01/'): > print dir > for ncfile in glob.glob(dir + '*.nc'): > print ncfile > > can you choose more than one folder with glob? > i.e. I tried: > for dir in glob.glob(MainFolder + '*/01/', '*/02/', '*/03/'): > but I received: > TypeError: glob() takes exactly 1 argument (3 given) > > > thanks > > > On Tue, Aug 30, 2011 at 1:40 PM, Andre' Walker-Loud wrote: > hello, > > yes, I would also try adding a wild card in the dir search > >>> for dir in glob.glob(MainFolder + '01\*'): > > > to check if this is helps, in an interpreter (rather than script) try > > dirs = glob.glob(MainFolder + '\01\*'): > print dirs > > > if you get "[]" then this was not the answer, but if you get a list of directories, then this should work. > > Well, it should work with the correction > > >>> for ncfile in glob.glob(dir+'\*.nc'): > > > > Cheers, > > Andre > > > > > > > On Aug 29, 2011, at 8:35 PM, questions anon wrote: > >> thanks, that was an error by me. but that still doesn't help me select the dir and files! >> Could it be because I am trying to select folders within other folders to then get a file from each of those folders? >> >> >> On Tue, Aug 30, 2011 at 1:30 PM, Andre' Walker-Loud wrote: >> Dear Anonymous Questioner, >> >> I am not sure how the Windows environment works, but in linux, I would replace >> >>> for ncfile in glob.glob('.nc'): >> >> >> with >> >>> for ncfile in glob.glob('*.nc'): >> >> >> ie, add the "wild card" '*' character to grab all files which end in '.nc' >> >> >> Andre >> >> >> >> >> On Aug 29, 2011, at 7:23 PM, questions anon wrote: >> >>> Thanks for responding >>> When I try glob.glob I receive no errors but nothing prints. >>> >>> MainFolder=r"E:/Sample/" >>> for dir in glob.glob(MainFolder + '01'): >>> print "my selected directories are:", dir >>> for ncfile in glob.glob('.nc'): >>> print "my selected netcdf files are:", ncfile >>> >>> any suggestions? thanks >>> >>> >>> On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: >>> On 8/29/2011 4:52 PM questions anon said... >>> >>> I am trying to select particular files within >>> a particular subdirectory, >>> >>> You might find glob a better starting point: >>> >>> ActivePython 2.6.6.15 (ActiveState Software Inc.) based on >>> Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> import glob >>> >>> help(glob.glob) >>> Help on function glob in module glob: >>> >>> glob(pathname) >>> Return a list of paths matching a pathname pattern. >>> >>> The pattern may contain simple shell-style wildcards a la fnmatch. >>> >>> >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\*.txt'): >>> print filename >>> ... >>> C:\WSG\GL\2011-08\2011-01-WIP-Details.txt >>> C:\WSG\GL\2011-08\2011-02-WIP-Details.txt >>> C:\WSG\GL\2011-08\2011-03-WIP-Details.txt >>> C:\WSG\GL\2011-08\2011-04-WIP-Details.txt >>> C:\WSG\GL\2011-08\2011-05-WIP-Details.txt >>> C:\WSG\GL\2011-08\2011-06-WIP-Details.txt >>> C:\WSG\GL\2011-08\2011-07 - bankToRec.txt >>> C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt >>> C:\WSG\GL\2011-08\2011-07-WIP-Details.txt >>> C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt >>> C:\WSG\GL\2011-08\BankRecUtils.txt >>> C:\WSG\GL\2011-08\CapitalizationExamples.txt >>> C:\WSG\GL\2011-08\DEALLOCATE-2011-04.txt >>> C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt >>> C:\WSG\GL\2011-08\MAR DEALLOCATION.txt >>> C:\WSG\GL\2011-08\Notes.txt >>> C:\WSG\GL\2011-08\shipping safety net util.txt >>> C:\WSG\GL\2011-08\UNBILLED WIP.txt >>> C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt >>> C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt >>> C:\WSG\GL\2011-08\vacation accrual notes.txt >>> >>> >>> >>> >>> >>> >>> I have been able to do both but not together! >>> When I try to select my files within the dir loop nothing comes up, but >>> when I leave the files outside the dir loops it selects all the files >>> not just the ones in the dirs I have selected. >>> The code I am using is: >>> >>> import os >>> >>> MainFolder=r"D:/samples/" >>> >>> for (path, dirs, files) in os.walk(MainFolder): >>> for dir in dirs: >>> if dir=='01': >>> print "selected directories are:",dir >>> >>> for ncfile in dir: >>> if ncfile[-3:]=='.nc': >>> print "ncfiles are:", ncfile >>> >>> Any feedback will be greatly appreciated!! >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Tue Aug 30 06:40:08 2011 From: questions.anon at gmail.com (questions anon) Date: Tue, 30 Aug 2011 14:40:08 +1000 Subject: [Tutor] select particular directories and files In-Reply-To: <336784D8-6A0E-4F6F-B75C-2AB7A0FB5984@gmail.com> References: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> <4E78A68F-8DAA-4A70-9675-829300D918F7@gmail.com> <336784D8-6A0E-4F6F-B75C-2AB7A0FB5984@gmail.com> Message-ID: ok, thanks for your help Andre On Tue, Aug 30, 2011 at 2:37 PM, Andre' Walker-Loud wrote: > to have multiple dirs is simple, > > for dir in glob.glob(MainFolder + '*/01/') + glob.glob(MainFolder + > '*/02/') + glob.glob(MainFolder + '*/03/'): > > > there may be a better way, but this should work. > > > By the way, not to discourage you from asking questions on the list, but > many of these things can be deduced quickly by trial and error using the > python interpreter (the interactive python shell). That is one thing I > really like about python, you really can just play around with it. And with > all things, if you figure it out on your own, then you will likely feel > better about that, and also, you will retain the knowledge better and gain > more confidence in trying new things. > > > Cheers, > > Andre > > > > > > On Aug 29, 2011, at 9:18 PM, questions anon wrote: > > It worked! thank you. This is the code I ended with: > > for dir in glob.glob(MainFolder + '*/01/'): > print dir > for ncfile in glob.glob(dir + '*.nc'): > print ncfile > > can you choose more than one folder with glob? > i.e. I tried: > for dir in glob.glob(MainFolder + '*/01/', '*/02/', '*/03/'): > but I received: > TypeError: glob() takes exactly 1 argument (3 given) > > > thanks > > > On Tue, Aug 30, 2011 at 1:40 PM, Andre' Walker-Loud wrote: > >> hello, >> >> yes, I would also try adding a wild card in the dir search >> >> for dir in glob.glob(MainFolder + '01\*'): >>> >>> >> to check if this is helps, in an interpreter (rather than script) try >> >> dirs = glob.glob(MainFolder + '\01\*'): >> print dirs >> >> >> if you get "[]" then this was not the answer, but if you get a list of >> directories, then this should work. >> >> Well, it should work with the correction >> >> >> for ncfile in glob.glob(dir+'\*.nc'): >>> >>> >> >> Cheers, >> >> Andre >> >> >> >> >> >> >> On Aug 29, 2011, at 8:35 PM, questions anon wrote: >> >> thanks, that was an error by me. but that still doesn't help me select the >> dir and files! >> Could it be because I am trying to select folders within other folders to >> then get a file from each of those folders? >> >> >> On Tue, Aug 30, 2011 at 1:30 PM, Andre' Walker-Loud wrote: >> >>> Dear Anonymous Questioner, >>> >>> I am not sure how the Windows environment works, but in linux, I would >>> replace >>> >>> for ncfile in glob.glob('.nc'): >>> >>> >>> with >>> >>> for ncfile in glob.glob('*.nc'): >>> >>> >>> ie, add the "wild card" '*' character to grab all files which end in >>> '.nc' >>> >>> >>> Andre >>> >>> >>> >>> >>> On Aug 29, 2011, at 7:23 PM, questions anon wrote: >>> >>> Thanks for responding >>> When I try glob.glob I receive no errors but nothing prints. >>> >>> MainFolder=r"E:/Sample/" >>> for dir in glob.glob(MainFolder + '01'): >>> print "my selected directories are:", dir >>> for ncfile in glob.glob('.nc'): >>> print "my selected netcdf files are:", ncfile >>> >>> any suggestions? thanks >>> >>> >>> On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: >>> >>>> On 8/29/2011 4:52 PM questions anon said... >>>> >>>> I am trying to select particular files within >>>>> a particular subdirectory, >>>>> >>>> >>>> You might find glob a better starting point: >>>> >>>> ActivePython 2.6.6.15 (ActiveState Software Inc.) based on >>>> Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit >>>> (Intel)] on win32 >>>> Type "help", "copyright", "credits" or "license" for more information. >>>> >>> import glob >>>> >>> help(glob.glob) >>>> Help on function glob in module glob: >>>> >>>> glob(pathname) >>>> Return a list of paths matching a pathname pattern. >>>> >>>> The pattern may contain simple shell-style wildcards a la fnmatch. >>>> >>>> >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\***.txt'): >>>> print filename >>>> ... >>>> C:\WSG\GL\2011-08\2011-01-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\2011-02-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\2011-03-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\2011-04-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\2011-05-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\2011-06-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\2011-07 - bankToRec.txt >>>> C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt >>>> C:\WSG\GL\2011-08\2011-07-WIP-**Details.txt >>>> C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt >>>> C:\WSG\GL\2011-08\**BankRecUtils.txt >>>> C:\WSG\GL\2011-08\**CapitalizationExamples.txt >>>> C:\WSG\GL\2011-08\DEALLOCATE-**2011-04.txt >>>> C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt >>>> C:\WSG\GL\2011-08\MAR DEALLOCATION.txt >>>> C:\WSG\GL\2011-08\Notes.txt >>>> C:\WSG\GL\2011-08\shipping safety net util.txt >>>> C:\WSG\GL\2011-08\UNBILLED WIP.txt >>>> C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt >>>> C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt >>>> C:\WSG\GL\2011-08\vacation accrual notes.txt >>>> >>> >>>> >>>> >>>> >>>> >>>> I have been able to do both but not together! >>>>> When I try to select my files within the dir loop nothing comes up, but >>>>> when I leave the files outside the dir loops it selects all the files >>>>> not just the ones in the dirs I have selected. >>>>> The code I am using is: >>>>> >>>>> import os >>>>> >>>>> MainFolder=r"D:/samples/" >>>>> >>>>> for (path, dirs, files) in os.walk(MainFolder): >>>>> for dir in dirs: >>>>> if dir=='01': >>>>> print "selected directories are:",dir >>>>> >>>>> for ncfile in dir: >>>>> if ncfile[-3:]=='.nc': >>>>> print "ncfiles are:", ncfile >>>>> >>>>> Any feedback will be greatly appreciated!! >>>>> >>>>> >>>>> ______________________________**_________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/**mailman/listinfo/tutor >>>>> >>>> >>>> >>>> ______________________________**_________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/**mailman/listinfo/tutor >>>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Tue Aug 30 07:53:51 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 29 Aug 2011 22:53:51 -0700 Subject: [Tutor] select particular directories and files In-Reply-To: References: <38BCEF58-BCDE-4B69-84B5-0D4E18833FE2@gmail.com> <4E78A68F-8DAA-4A70-9675-829300D918F7@gmail.com> <336784D8-6A0E-4F6F-B75C-2AB7A0FB5984@gmail.com> Message-ID: <4ED5949E-9D72-429B-AA3C-705EA79CBF8E@gmail.com> Hello anonymous questioner, > ok, thanks for your help Andre your welcome. hope you continue enjoying python. Andre > On Tue, Aug 30, 2011 at 2:37 PM, Andre' Walker-Loud wrote: > to have multiple dirs is simple, > >> for dir in glob.glob(MainFolder + '*/01/') + glob.glob(MainFolder + '*/02/') + glob.glob(MainFolder + '*/03/'): > > > there may be a better way, but this should work. > > > By the way, not to discourage you from asking questions on the list, but many of these things can be deduced quickly by trial and error using the python interpreter (the interactive python shell). That is one thing I really like about python, you really can just play around with it. And with all things, if you figure it out on your own, then you will likely feel better about that, and also, you will retain the knowledge better and gain more confidence in trying new things. > > > Cheers, > > Andre > > > > > > On Aug 29, 2011, at 9:18 PM, questions anon wrote: > >> It worked! thank you. This is the code I ended with: >> >> for dir in glob.glob(MainFolder + '*/01/'): >> print dir >> for ncfile in glob.glob(dir + '*.nc'): >> print ncfile >> >> can you choose more than one folder with glob? >> i.e. I tried: >> for dir in glob.glob(MainFolder + '*/01/', '*/02/', '*/03/'): >> but I received: >> TypeError: glob() takes exactly 1 argument (3 given) >> >> >> thanks >> >> >> On Tue, Aug 30, 2011 at 1:40 PM, Andre' Walker-Loud wrote: >> hello, >> >> yes, I would also try adding a wild card in the dir search >> >>>> for dir in glob.glob(MainFolder + '01\*'): >> >> >> to check if this is helps, in an interpreter (rather than script) try >> >> dirs = glob.glob(MainFolder + '\01\*'): >> print dirs >> >> >> if you get "[]" then this was not the answer, but if you get a list of directories, then this should work. >> >> Well, it should work with the correction >> >> >>>> for ncfile in glob.glob(dir+'\*.nc'): >> >> >> >> Cheers, >> >> Andre >> >> >> >> >> >> >> On Aug 29, 2011, at 8:35 PM, questions anon wrote: >> >>> thanks, that was an error by me. but that still doesn't help me select the dir and files! >>> Could it be because I am trying to select folders within other folders to then get a file from each of those folders? >>> >>> >>> On Tue, Aug 30, 2011 at 1:30 PM, Andre' Walker-Loud wrote: >>> Dear Anonymous Questioner, >>> >>> I am not sure how the Windows environment works, but in linux, I would replace >>> >>>> for ncfile in glob.glob('.nc'): >>> >>> >>> with >>> >>>> for ncfile in glob.glob('*.nc'): >>> >>> >>> ie, add the "wild card" '*' character to grab all files which end in '.nc' >>> >>> >>> Andre >>> >>> >>> >>> >>> On Aug 29, 2011, at 7:23 PM, questions anon wrote: >>> >>>> Thanks for responding >>>> When I try glob.glob I receive no errors but nothing prints. >>>> >>>> MainFolder=r"E:/Sample/" >>>> for dir in glob.glob(MainFolder + '01'): >>>> print "my selected directories are:", dir >>>> for ncfile in glob.glob('.nc'): >>>> print "my selected netcdf files are:", ncfile >>>> >>>> any suggestions? thanks >>>> >>>> >>>> On Tue, Aug 30, 2011 at 10:07 AM, Emile van Sebille wrote: >>>> On 8/29/2011 4:52 PM questions anon said... >>>> >>>> I am trying to select particular files within >>>> a particular subdirectory, >>>> >>>> You might find glob a better starting point: >>>> >>>> ActivePython 2.6.6.15 (ActiveState Software Inc.) based on >>>> Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 >>>> Type "help", "copyright", "credits" or "license" for more information. >>>> >>> import glob >>>> >>> help(glob.glob) >>>> Help on function glob in module glob: >>>> >>>> glob(pathname) >>>> Return a list of paths matching a pathname pattern. >>>> >>>> The pattern may contain simple shell-style wildcards a la fnmatch. >>>> >>>> >>> for filename in glob.glob(r'C:\WSG\GL\2011-08\*.txt'): >>>> print filename >>>> ... >>>> C:\WSG\GL\2011-08\2011-01-WIP-Details.txt >>>> C:\WSG\GL\2011-08\2011-02-WIP-Details.txt >>>> C:\WSG\GL\2011-08\2011-03-WIP-Details.txt >>>> C:\WSG\GL\2011-08\2011-04-WIP-Details.txt >>>> C:\WSG\GL\2011-08\2011-05-WIP-Details.txt >>>> C:\WSG\GL\2011-08\2011-06-WIP-Details.txt >>>> C:\WSG\GL\2011-08\2011-07 - bankToRec.txt >>>> C:\WSG\GL\2011-08\2011-07 - vsdsToRec.txt >>>> C:\WSG\GL\2011-08\2011-07-WIP-Details.txt >>>> C:\WSG\GL\2011-08\5790-00 RECONCILIATION.txt >>>> C:\WSG\GL\2011-08\BankRecUtils.txt >>>> C:\WSG\GL\2011-08\CapitalizationExamples.txt >>>> C:\WSG\GL\2011-08\DEALLOCATE-2011-04.txt >>>> C:\WSG\GL\2011-08\dump glsmf1 data for 2004-2010.txt >>>> C:\WSG\GL\2011-08\MAR DEALLOCATION.txt >>>> C:\WSG\GL\2011-08\Notes.txt >>>> C:\WSG\GL\2011-08\shipping safety net util.txt >>>> C:\WSG\GL\2011-08\UNBILLED WIP.txt >>>> C:\WSG\GL\2011-08\Vacation Accrual - post-bonus-changes.txt >>>> C:\WSG\GL\2011-08\Vacation Accrual - pre-bonus-changes.txt >>>> C:\WSG\GL\2011-08\vacation accrual notes.txt >>>> >>> >>>> >>>> >>>> >>>> >>>> I have been able to do both but not together! >>>> When I try to select my files within the dir loop nothing comes up, but >>>> when I leave the files outside the dir loops it selects all the files >>>> not just the ones in the dirs I have selected. >>>> The code I am using is: >>>> >>>> import os >>>> >>>> MainFolder=r"D:/samples/" >>>> >>>> for (path, dirs, files) in os.walk(MainFolder): >>>> for dir in dirs: >>>> if dir=='01': >>>> print "selected directories are:",dir >>>> >>>> for ncfile in dir: >>>> if ncfile[-3:]=='.nc': >>>> print "ncfiles are:", ncfile >>>> >>>> Any feedback will be greatly appreciated!! >>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 30 08:27:14 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Aug 2011 08:27:14 +0200 Subject: [Tutor] Loops and matrices' References: <57E81B2D1C861144AEE45241A28694FC0AB7DDAC84@BKMAIL71.aeraenergy.com> Message-ID: Reed DA (Danny) at Aera wrote: > I have a matrix which contains temperatures. The columns are time, spaced > 33 seconds apart, and the rows are depth intervals. What I'm trying to do > is create another matrix that contains the rate of change of temperature > for each depth. The array is called LS_JULY_11 and the output array should > be delta_temp I think you don't need any explicit for-loops: >>> import numpy as np >>> july = np.random.randint(0, 100, (3, 4)) >>> july array([[27, 43, 67, 12], [52, 22, 54, 26], [70, 81, 61, 49]]) >>> dt = 33.0 >>> july[1:] array([[52, 22, 54, 26], [70, 81, 61, 49]]) >>> july[:-1] array([[27, 43, 67, 12], [52, 22, 54, 26]]) >>> (july[1:]-july[:-1]) array([[ 25, -21, -13, 14], [ 18, 59, 7, 23]]) >>> (july[1:]-july[:-1])/dt array([[ 0.75757576, -0.63636364, -0.39393939, 0.42424242], [ 0.54545455, 1.78787879, 0.21212121, 0.6969697 ]]) If rows and columns are swapped in the above, just transpose the matrix before you start and again when you're done: >>> july = july.transpose() >>> july array([[27, 52, 70], [43, 22, 81], [67, 54, 61], [12, 26, 49]]) >>> ((july[1:]-july[:-1])/dt).transpose() array([[ 0.48484848, 0.72727273, -1.66666667], [-0.90909091, 0.96969697, -0.84848485], [ 0.33333333, -0.60606061, -0.36363636]]) From __peter__ at web.de Tue Aug 30 08:45:02 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Aug 2011 08:45:02 +0200 Subject: [Tutor] select particular directories and files References: Message-ID: questions anon wrote: > I am trying to select particular files within a particular subdirectory, I > have been able to do both but not together! > When I try to select my files within the dir loop nothing comes up, but > when I leave the files outside the dir loops it selects all the files > not just the ones in the dirs I have selected. > The code I am using is: > > import os > > MainFolder=r"D:/samples/" > > for (path, dirs, files) in os.walk(MainFolder): > for dir in dirs: dirs contains the names of subdirectories of the directory you are currently processing, but you are interested in the parent directory which you get with with os.path.basename(path) > if dir=='01': > print "selected directories are:",dir > > for ncfile in dir: > if ncfile[-3:]=='.nc': > print "ncfiles are:", ncfile > > Any feedback will be greatly appreciated!! import os mainfolder = "d:/samples" foldername = "01" fileext = ".nc" for path, folders, files in os.walk(mainfolder): if os.path.basename(path) == foldername: for file in files: if file.endswith(fileext): print os.path.join(path, file) From lisi.reisz at gmail.com Tue Aug 30 08:47:29 2011 From: lisi.reisz at gmail.com (Lisi) Date: Tue, 30 Aug 2011 07:47:29 +0100 Subject: [Tutor] Tutor Digest, Vol 90, Issue 97 In-Reply-To: <4E5C3B0B.4020802@pearwood.info> References: <201108292023.14267.lisi.reisz@gmail.com> <4E5C3B0B.4020802@pearwood.info> Message-ID: <201108300747.29554.lisi.reisz@gmail.com> On Tuesday 30 August 2011 02:21:15 Steven D'Aprano wrote: > Heh, well different people find different approaches useful. To coin a clich?, it would be a dull world if we were all the same. :-) Lisi From martin at linux-ip.net Tue Aug 30 11:23:57 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 30 Aug 2011 11:23:57 +0200 Subject: [Tutor] fortune-like utility was [Tutor Digest ...] In-Reply-To: References: Message-ID: Good morning and welcome to the list, : Just planning it out in my head so far, like pseudocode. I hope : to get started soon. I'm just looking to have a little dialog box : come up, display a random quote of the day, and then hit enter : and it's gone. Should be a nice, simple way to get started with : Python. N.B. Most of the questions and answers here are about the python 2.x series, so just note that there are some minor differences with python 3.x. I would suggest starting with the data/format. I think somebody else has already remarked that with a few thousand quotations, you will not have much difficulty loading it all into memory, so here are some tips on how to approach the problem by creating a CLI application first, moving onto the GUI parts after you have worked out the functionality to read a file and produce the quotation. I don't have the book you are recommending, but here are some things that I would be thinking about if I were writing a utility which behaves like the venerable unix game called 'fortune'. 1. Learn how to read line-oriented data from a file [0]. Let's assume that your first pass at this has only one quotation per line. This little functon works much like the 'cat' utility: import sys def main(fname): f = open(fname,'r') for line in f: print line.rstrip() f.close() main(sys.argv[1]) # python this.py Now, put the lines into a list instead of printing them: def main(fname): quotations = list() f = open(fname,'r') for line in f: quotations.append( line.rstrip() ) f.close() return quotations 2. Play with the random module to get your 'pick a quotation at random' behaviour. import random print random.choice(quotations) 3. Experiment with the vagaries of 'print'. It produces a newline. Learn how to suppress the newline when printing (even if you don't want to do that this time). 4. Experiment with string handling. Learn how to break a string into lists. Learn how to make a single string out of the contents of a list. In short, become familiar with using split() http://docs.python.org/library/stdtypes.html#str.split join() http://docs.python.org/library/stdtypes.html#str.join 5. Start thinking about what you would have to change in order to handle multi-line or formatted quotations. This is where you can start thinking about treating your data as records rather than lines, as above. I suspect that you will have all of the above understood in fairly short order. At that point, you could make the foray into the various GUI bits. I will be no help there, as I have never used any of the GUI toolkits--but this list has many others who should be able to help here. I hope the 'Sweet Irene the Disco Queen' flooding in your region was not too bad, Frank. -Martin P.S. Here's a possibly obnoxious tip, assuming the 'fortune' file format [1] suits your tastes for storing your quotations: f = open(fname,'r') quotations = ''.join(f.readlines()).split('%') [0] http://docs.python.org/library/stdtypes.html#file-objects [1] http://www.faqs.org/docs/artu/ch05s02.html -- Martin A. Brown http://linux-ip.net/ From cranky.frankie at gmail.com Tue Aug 30 16:21:36 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 30 Aug 2011 10:21:36 -0400 Subject: [Tutor] fortune-like utility Message-ID: On Tue, Aug 30, 2011 at 5:23 AM, Martin A. Brown wrote: > > Good morning and welcome to the list, > > ?: Just planning it out in my head so far, like pseudocode. I hope > ?: to get started soon. I'm just looking to have a little dialog box > ?: come up, display a random quote of the day, and then hit enter > ?: and it's gone. Should be a nice, simple way to get started with > ?: Python. > > N.B. Most of the questions and answers here are about the python 2.x > series, so just note that there are some minor differences with > python 3.x. > > I would suggest starting with the data/format. snip Thanks Martin for the excellent suggestions. I read in the book that you have to use escape like /n when you want to span lines. I don't want to have to do that to each of my quotes, many of which span several lines, so I will look into your suggestions. Thanks again. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer " . . . and the extended forecast, until you come back to me, baby, is high tonight, low tomorrow, and precipitation is expected." - Tom Waits, "Emotional Weather Report" From rail.shafigulin at gmail.com Tue Aug 30 19:27:15 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Tue, 30 Aug 2011 13:27:15 -0400 Subject: [Tutor] xml parsing without a root element Message-ID: hello everyone. i need to parse a an xml-like file. the problem that i'm facing is that this file doesn't have the root element but in all other terms it is the same as xml, i.e does anybody know if there is a module in python that allows to process an xml file without a root element? i tried ElementTree but it didn't work. any help is appreciated thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Aug 30 20:11:33 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 30 Aug 2011 14:11:33 -0400 Subject: [Tutor] xml parsing without a root element In-Reply-To: References: Message-ID: On Tue, Aug 30, 2011 at 1:27 PM, rail shafigulin wrote: > hello everyone. > > i need to parse a an xml-like file. the problem that i'm facing is that > this file doesn't have the root element but in all other terms it is the > same as xml, i.e > > > > > > > > > > does anybody know if there is a module in python that allows to process an > xml file without a root element? i tried ElementTree but it didn't work. > > any help is appreciated > thanks > > Why not read the file into a buffer, put the xml tag at the top and wrap the buffer with a root element. Then try ElementTree > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 30 20:20:46 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Aug 2011 20:20:46 +0200 Subject: [Tutor] xml parsing without a root element References: Message-ID: rail shafigulin wrote: > hello everyone. > > i need to parse a an xml-like file. the problem that i'm facing is that > this file doesn't have the root element but in all other terms it is the > same as xml, i.e > > > > > > > > > > does anybody know if there is a module in python that allows to process an > xml file without a root element? i tried ElementTree but it didn't work. There may be more sophisticated ways, but I'd start with a simple idea: add a root element to your data and have ElementTree parse the result. $ cat almost.xml foo bar baz $ cat xml_no_root.py from StringIO import StringIO from xml.etree.ElementTree import ElementTree filename = "almost.xml" tree = ElementTree() with open(filename, "rb") as f: data = f.read() pseudo_file = StringIO("%s" % data ) tree.parse(pseudo_file) for link in tree.getiterator("a"): print link.text $ python xml_no_root.py foo bar baz If the file is large you can read the file in smaller chunks. Have a look at the ElementTree.parse() source code to see how to do that. From davidheiserca at gmail.com Tue Aug 30 20:20:26 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Tue, 30 Aug 2011 11:20:26 -0700 Subject: [Tutor] xml parsing without a root element References: Message-ID: <441C316CE0C54FF999CE4C869B325998@dheiser> Can you encapsulate the contents of the file in a root element before processing? ----- Original Message ----- From: rail shafigulin To: tutor at python.org Sent: Tuesday, August 30, 2011 10:27 AM Subject: [Tutor] xml parsing without a root element hello everyone. i need to parse a an xml-like file. the problem that i'm facing is that this file doesn't have the root element but in all other terms it is the same as xml, i.e does anybody know if there is a module in python that allows to process an xml file without a root element? i tried ElementTree but it didn't work. any help is appreciated thanks ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Aug 30 20:44:49 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 30 Aug 2011 14:44:49 -0400 Subject: [Tutor] Fwd: Re: largest palindrome number In-Reply-To: References: Message-ID: <4E5D2FA1.9030000@gmail.com> -------- Original Message -------- Subject: Re: [Tutor] largest palindrome number Date: Tue, 30 Aug 2011 23:24:09 +0530 From: surya k To: bob gailer Mr Gailer, That's an amazing way of writing palindrome function. Actually, I'm still using my old C logic's here. Thanks for sharing. On 8/30/11, bob gailer wrote: > On 8/25/2011 12:49 PM, surya k wrote: >> Hi, >> >> I'm doing a puzzle where it asked me to find the largest palindrome >> number formed by the product of two three-digit numbers. They >> mentioned an example saying that 9009 is the largest palindrome number >> formed by two two-digit numbers (99 * 91). >> >> I've written my code this way.. and I tested it with the given example >> and I got it right! >> >> /Logic I used :/ >> largest two digit number is 99 and three digit number is 999.. so >> largest product of two two-digit numbers is< 100*100 and for >> three-digit numbers is< 1000*1000. >> So, I used a for loop and it assigns a palindromic value to /PNum/ >> till it is< 100*100 (for 2 digit number) and< 1000*1000 (for >> three-digit number).. >> Thus it stops at the max possible palindromic value, which is what we >> want. >> >> >> def palindrome (n) : >> TempN = n >> rev = 0 >> while n != 0 : >> k = n % 10 >> rev = (rev * 10) + k >> n = n / 10 >> if TempN == rev : >> return TempN # Palindrome >> else : >> return 0 # not Palindrome >> > > zTwice as fast on my computer! > > def palindrome (n): > s = '%s' % n > return s == s[::-1] >> >> >> >> for i in range (1,100) : >> for j in range (i,100) : >> Temp = palindrome(i*j) >> if Temp< 10000 and Temp != 0 : >> PNum = Temp >> print PNum >> >> So, for getting the largest palindrome number formed by two >> three-digit numbers, I changed 100 to 1000 and 1,00,00 to 1,000,000 in >> the highlighted area. Thus I got the answer to be 888888. When I >> submitted the answer, its saying wrong! >> >> Where I'm going wrong ? >> help me, please ! >> >> >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rail.shafigulin at gmail.com Tue Aug 30 20:58:37 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Tue, 30 Aug 2011 14:58:37 -0400 Subject: [Tutor] xml parsing without a root element In-Reply-To: References: Message-ID: On Tue, Aug 30, 2011 at 2:20 PM, Peter Otten <__peter__ at web.de> wrote: > rail shafigulin wrote: > > > hello everyone. > > > > i need to parse a an xml-like file. the problem that i'm facing is that > > this file doesn't have the root element but in all other terms it is the > > same as xml, i.e > > > > > > > > > > > > > > > > > > > > does anybody know if there is a module in python that allows to process > an > > xml file without a root element? i tried ElementTree but it didn't work. > > There may be more sophisticated ways, but I'd start with a simple idea: add > a root element to your data and have ElementTree parse the result. > > $ cat almost.xml > foo > bar > baz > $ cat xml_no_root.py > from StringIO import StringIO > from xml.etree.ElementTree import ElementTree > > filename = "almost.xml" > tree = ElementTree() > with open(filename, "rb") as f: > data = f.read() > pseudo_file = StringIO("%s" % data ) > tree.parse(pseudo_file) > > for link in tree.getiterator("a"): > print link.text > $ python xml_no_root.py > foo > bar > baz > > If the file is large you can read the file in smaller chunks. Have a look > at > the ElementTree.parse() source code to see how to do that. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > thanks everyone. i'm going to encapsulate the file with the root tag -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Aug 30 21:37:37 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 30 Aug 2011 14:37:37 -0500 Subject: [Tutor] Fwd: Re: largest palindrome number In-Reply-To: <4E5D2FA1.9030000@gmail.com> References: <4E5D2FA1.9030000@gmail.com> Message-ID: <201108301437.37512.cfuller084@thinkingplanet.net> I played around with this puzzle a bit. I made a palindrome function a bit like Bob's, only i iterated through the string (stopping at the first mismatch) instead of doing the whole thing at once. The rest of the code is even more amenable to speedups. The first thing I saw was the outer "i" loop can start at 100, rather than one. I also saw that using PNum = max(palindrome(i*j), PNum) would replace a half dozen lines in the first try. But I discarded this approach. I figured it would be much faster to work backwards from 999*999, stopping at the first palindrome that was the product of two three digit numbers. This code is quite terse, and uses some advanced features (generator functions, shortcutting), but I'll try to explain it. n = 999*999 while True: if palindrome(n) and \ any( (100<=i<1000 and 100<=n/i<1000 for i in \ (j for j in range(1,1+int(n**.5)) if n%j==0))): break else: n -= 1 print n The inner "j" loop simply finds factors of n (n**.5 is the square root of n); the outer loop checks to see if the factor and its complementary factor are three digit numbers. The generator expressions (like list comprehensions, but bounded by parentheses) only calculate one true/false check on a single factor at a time. The any() built-in function returns as soon as it encounters are true value, so a lot of computation is avoided versus checking all the factors and their three-digit status. A note on the "if palindrome(n) and \" line. Python (and C. and most languages) will stop computing through and and statement if the first expression is false, and likewise for an or statement if the first statement is true. This is the same way any() and all() work, only these functions can operate on iterators of arbitrary length. So by putting the less computationally intensive palindrome check first, a few more cpu cycles are saved. I got around an order of magnitude speedup with this code. Cheers From questions.anon at gmail.com Wed Aug 31 01:21:06 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 31 Aug 2011 09:21:06 +1000 Subject: [Tutor] select particular directories and files In-Reply-To: References: Message-ID: Thanks, that also works really well. One of the hardest things I am finding with programming is that there is always more than one way to do something. This is a good and bad thing. Bad for beginners!! thanks On Tue, Aug 30, 2011 at 4:45 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > I am trying to select particular files within a particular subdirectory, > I > > have been able to do both but not together! > > When I try to select my files within the dir loop nothing comes up, but > > when I leave the files outside the dir loops it selects all the files > > not just the ones in the dirs I have selected. > > The code I am using is: > > > > import os > > > > MainFolder=r"D:/samples/" > > > > for (path, dirs, files) in os.walk(MainFolder): > > for dir in dirs: > > dirs contains the names of subdirectories of the directory you are > currently > processing, but you are interested in the parent directory which you get > with with os.path.basename(path) > > > if dir=='01': > > print "selected directories are:",dir > > > > for ncfile in dir: > > if ncfile[-3:]=='.nc': > > print "ncfiles are:", ncfile > > > > Any feedback will be greatly appreciated!! > > import os > > mainfolder = "d:/samples" > foldername = "01" > fileext = ".nc" > > for path, folders, files in os.walk(mainfolder): > if os.path.basename(path) == foldername: > for file in files: > if file.endswith(fileext): > print os.path.join(path, file) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Aug 31 02:31:27 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 31 Aug 2011 01:31:27 +0100 Subject: [Tutor] Package installation on Mac does not detect newer version of python In-Reply-To: References: Message-ID: On 29 August 2011 11:50, Elisha Rosensweig wrote: > Hi All, > > I'm trying to use easy_install on my Mac to get the Python networx package. > On my machine I have installed version 2.5 AND 2.6 of Python. However, wehn > I try to install this package, I get: > > Best match: networkx 1.5 > Downloading http://networkx.lanl.gov/download/networkx/networkx-1.5.zip > Processing networkx-1.5.zip > Running networkx-1.5/setup.py -q bdist_egg --dist-dir > /var/folders/RF/RFpRZ44UEoO77eeJ7t1eOE+++TM/-Tmp-/easy_install-mTZw0S/networkx-1.5/egg-dist-tmp-TGWeRV > *NetworkX requires Python version 2.6 or later (2.5 detected).* > error: Setup script exited with -1 > > > > this, despite the fact that my default python is version 2.6: > > python > Python *2.6.2* (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > > > > Any ideas how to solve this? > > Offhand, this seems to imply that you have easy_install installed on your Python 2.5 installation, and not on your 2.6 installation, or alternatively if you do have easy_install installed on both versions of python then perhaps somehow easy_install on python 2.5 is the first one found on your path. The solution is to a) ensure you have easy_install installed on Python 2.6 and b) Explicitly run that to ensure you're running the correct version (or, fix the paths if neccesary to ensure the correct version gets run without a path specified.) Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Wed Aug 31 09:46:19 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Wed, 31 Aug 2011 17:46:19 +1000 Subject: [Tutor] urllib2 issue getting realm Message-ID: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> Hi everybody, I am trying to use a very simple piece of code to get the realm from different HTTPS URLs. This realm is essential for successful authentication on the HTTPS session. If have to run this for a few different hosts and capture the realm. For one host, it works perfectly, but when I try the same code to get the next realm, it fails. I suspect that I need to close some type of connections or something, but I can't put my finger on it. This what I try: >>> ips = ['192.168.10.190', '192.168.10.191', '192.168.10.192', '192.168.10.193'] >>> URL = "https://%s/axis-cgi/jpg/image.cgi?resolution=1280x800" >>> import urllib2 >>> try: ... req = urllib2.Request(URL % ips[0]) ... handle = urllib2.urlopen(req) ... except IOError, e: ... print `e` ... HTTPError() >>> >>> e HTTPError() >>> authline = e.headers.get('www-authenticate', '') >>> authline 'Digest realm="AXIS_00408CB71F14", nonce="0002c497Y6450989253d0ea85587e89821031c60ab9768", stale=FALSE, qop="auth", Basic realm="AXIS_00408CB71F14"' >>> >>> handle File "", line 1, in ''' : name 'handle' is not defined ''' >>> req >>> req.host '192.168.10.190' >>> At this point, I am happy. It worked. I expect the try to fail to get the exception. For the next one: >>> try: ... req = urllib2.Request(URL % ips[1]) ... handle = urllib2.urlopen(req) ... except IOError, e: ... print `e` ... >>> See, no "e" printed which means that something worked. The exception didn't happen and I don't know why...Anybody? I tried doing this: >>> del req >>> del handle >>> del e But with the same result: >>> try: ... req = urllib2.Request(URL % ips[1]) ... handle = urllib2.urlopen(req) ... except IOError, e: ... print `e` ... >>> e File "", line 1, in ''' : name 'e' is not defined ''' >>> req >>> handle > Regards ? Johan From sander.sweers at gmail.com Wed Aug 31 14:09:14 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 31 Aug 2011 14:09:14 +0200 Subject: [Tutor] urllib2 issue getting realm In-Reply-To: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> References: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> Message-ID: On 31 August 2011 09:46, Johan Geldenhuys wrote: > I am trying to use a very simple piece of code to get the realm from > different HTTPS URLs. > > This realm is essential for successful authentication on the HTTPS session. I think you got 2 things mixed up, http authentication and encrypted http (https). Just having a https url does not mean you need to authenticate. Take 'https://mail.google.com' as an example. > If have to run this for a few different hosts and capture the realm. > For one host, it works perfectly, but when I try the same code to get the > next realm, it fails. I suspect that I need to close some type of > connections or something, but I can't put my finger on it. > For the next one: > >>>> try: > ... ? ? req = urllib2.Request(URL % ips[1]) > ... ? ? handle = urllib2.urlopen(req) > ... except IOError, e: > ... ? ? print `e` > ... >>>> > > See, no "e" printed which means that something worked. The exception didn't > happen and I don't know why...Anybody? Yes, when you type the url into your browser. I suspect it does not ask you to authenticate via http authentication. Therefor no exception is raised and you never print the headers. Greets Sander From steve at pearwood.info Wed Aug 31 14:10:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 31 Aug 2011 22:10:14 +1000 Subject: [Tutor] urllib2 issue getting realm In-Reply-To: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> References: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> Message-ID: <4E5E24A6.20601@pearwood.info> Johan Geldenhuys wrote: > Hi everybody, > > I am trying to use a very simple piece of code to get the realm from > different HTTPS URLs. > > This realm is essential for successful authentication on the HTTPS session. What happens if you paste https://192.168.10.191/axis-cgi/jpg/image.cgi?resolution=1280x800 into a web browser? -- Steven From johan at accesstel.com.au Wed Aug 31 14:27:33 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Wed, 31 Aug 2011 22:27:33 +1000 Subject: [Tutor] urllib2 issue getting realm In-Reply-To: References: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> Message-ID: Focusing on the code below, do you know why it would raise the exception for the first IP and not for the second? Thank you Johan Sent from my iPhone 4 On 31/08/2011, at 22:09, Sander Sweers wrote: > On 31 August 2011 09:46, Johan Geldenhuys wrote: >> I am trying to use a very simple piece of code to get the realm from >> different HTTPS URLs. >> >> This realm is essential for successful authentication on the HTTPS session. > > I think you got 2 things mixed up, http authentication and encrypted > http (https). Just having a https url does not mean you need to > authenticate. Take 'https://mail.google.com' as an example. > >> If have to run this for a few different hosts and capture the realm. >> For one host, it works perfectly, but when I try the same code to get the >> next realm, it fails. I suspect that I need to close some type of >> connections or something, but I can't put my finger on it. > > >> For the next one: >> >>>>> try: >> ... req = urllib2.Request(URL % ips[1]) >> ... handle = urllib2.urlopen(req) >> ... except IOError, e: >> ... print `e` >> ... >>>>> >> >> See, no "e" printed which means that something worked. The exception didn't >> happen and I don't know why...Anybody? > > Yes, when you type the url into your browser. I suspect it does not > ask you to authenticate via http authentication. Therefor no exception > is raised and you never print the headers. > > Greets > Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sander.sweers at gmail.com Wed Aug 31 15:03:28 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 31 Aug 2011 15:03:28 +0200 Subject: [Tutor] urllib2 issue getting realm In-Reply-To: References: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> Message-ID: On 31 August 2011 14:27, Johan Geldenhuys wrote: > On 31/08/2011, at 22:09, Sander Sweers wrote: >> On 31 August 2011 09:46, Johan Geldenhuys wrote: >>> I am trying to use a very simple piece of code to get the realm from >>> different HTTPS URLs. >>> >>> This realm is essential for successful authentication on the HTTPS session. >> >> I think you got 2 things mixed up, http authentication and encrypted >> http (https). Just having a https url does not mean you need to >> authenticate. Take 'https://mail.google.com' as an example. >> >>> If have to run this for a few different hosts and capture the realm. >>> For one host, it works perfectly, but when I try the same code to get the >>> next realm, it fails. I suspect that I need to close some type of >>> connections or something, but I can't put my finger on it. >> >> >>> For the next one: >>> >>>>>> try: >>> ... ? ? req = urllib2.Request(URL % ips[1]) >>> ... ? ? handle = urllib2.urlopen(req) >>> ... except IOError, e: >>> ... ? ? print `e` >>> ... >>>>>> >>> >>> See, no "e" printed which means that something worked. The exception didn't >>> happen and I don't know why...Anybody? >> >> Yes, when you type the url into your browser. I suspect it does not >> ask you to authenticate via http authentication. Therefor no exception >> is raised and you never print the headers. Top posting is evil ;-). > Focusing on the code below, do you know why it would raise the exception for the first > IP and not for the second? Run this and you should see which error is being raise. Do note we catch urllib2.HTTPError instead of IOError. try: req = urllib2.Request(URL % ips[1]) handle = urllib2.urlopen(req) print 'Success' print handle.getcode() print handle.headers except urllib2.HTTPError as e: print 'Exception caught' print e print e.getcode() print e.hdrs Greets Sander From susana.delgado_s at utzmg.edu.mx Wed Aug 31 19:17:44 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 31 Aug 2011 12:17:44 -0500 Subject: [Tutor] Getting values from different functions (def's) Message-ID: Hello list !! I'm developing a Python GUI application. I alreday developed a very simple window with buttons, each button will do a different task, but the most important button will need to get information gotten in previous python's functions. Let's say I have four functions but at the end I want to collet all the information gotten. from Tkinter import * import tkSimpleDialog import tkMessageBox import tkFileDialog def directorio(): print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname def extension(): print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext def csv(): print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salida: ',inv def boton4(): #In this button I want to make a bigger process, but I need the root selected and the two strings the user types. print csv.inv #Obviously this throws an error root = Tk() top = Toplevel() root.minsize(400,200) toolbar = Frame(root) b = Button(toolbar, text="Selecciona ruta", width=15, command=directorio) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Escriba extension", width=15, command=extension) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Nombre de csv", width=15, command=csv) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Salir", width=6, command=boton4) b.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 31 19:48:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 31 Aug 2011 18:48:45 +0100 Subject: [Tutor] Getting values from different functions (def's) In-Reply-To: References: Message-ID: On 31/08/11 18:17, Susana Iraiis Delgado Rodriguez wrote: > Hello list !! > I'm developing a Python GUI application. I alreday developed a very > simple window with buttons, each button will do a different task, but > the most important button will need to get information gotten in > previous python's functions. Let's say I have four functions but at the > end I want to collet all the information gotten. Instead of (or as well as) printing the data you will need to store it in variables. Then you can use those variables in the other function. > from Tkinter import * > import tkSimpleDialog > import tkMessageBox > import tkFileDialog # define storage variables dir = "" extn = "" csv_name = "" > def directorio(): global dir # need to specify the global one > print 'Seleccione directorio donde empezar' > dirname = > tkFileDialog.askdirectory(parent=root, initialdir="/", title='Selecciona > la ruta a escanear') > if len(dirname ) > 0: > print "You chose %s" % dirname dir = dirname # store the value > def extension(): global extn > print "Escribe la extension que necesitas buscar" > ext=tkSimpleDialog.askstring('Extension a buscar:','') > print 'Buscando archivos: ',ext extn = ext > def csv(): global csv_name > print "Nombre del csv a crear" > inv=tkSimpleDialog.askstring('Nombre de .csv:','') > print 'Archivo de salida: ',inv csv_name = inv > def boton4(): > #In this button I want to make a bigger process, but I need the root > selected and the two strings the user types. > print csv.inv #Obviously this throws an error print dir,csv_name,extn But course in a GUI you would normally not use print but instead populate the text field of a label or Text widget or some such device. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cranky.frankie at gmail.com Wed Aug 31 21:14:17 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 31 Aug 2011 15:14:17 -0400 Subject: [Tutor] Quote of the Day version 1.0 Message-ID: I made some headway on the quote of the day program. I just tried to do it simple using two assumptions: - long quotes are going to print funny until I figure out the string splitting stuff - hard coding the quotes and authors in the program is simple, and I can use a spreadsheet to generate the strings when I put in the rest of the quotes (I have a lot of them). This code works. Now I just have to figure out: - how to get Ubuntu to run it at startup - how to associate .py files in Ubuntu to IDLE Thanks for all who commented, I really appreciate it. Pyhton is fun! # Quote_a_day_V1.py # # This program displays a random quotation # # Frank L. Palmeri August 31, 2011 import random print("\n\tHere is today's quote of the day:\n") author = ( "Kahlil Gibran", "Henrik Ibsen", "Dwight Eisenhower", "Will Rogers", "Will Rogers", "Jean de LaFontaine", "Eleanor Hibbert", "Baruch Spinoza", "Albert Camus", "Thomas a Kempi" ) quotation = ( "A candle loses nothing of its light when lighting another.", "The strongest man in the world is he who stands most alone.", "Leadership consists of nothing but taking responsibility for everything that goes wrong and giving your subordinates credit for everything that goes well.", "Even if you're on the right track, you'll get run over if you just sit there.", "I belong to no organized party. I am a Democrat.", "Patience and time do more than strength or passion.", "Never regret. If it's good, it's wonderful. If it's bad, it's experience.", "I have made a ceaseless effort not to ridicule, not to bewail, not to scorn human actions, but to understand them.", "In the depth of winter I finally learned there was in me an invincible summer.", "Who has a harder fight than he who is striving to overcome himself." ) numAuthors = len(author) printAuthor = random.randrange(numAuthors) print(quotation[printAuthor]) print("by ", author[printAuthor]) input("\nPress the enter key to exit.") -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer " . . . and the extended forecast, until you come back to me, baby, is high tonight, low tomorrow, and precipitation is expected." - Tom Waits, "Emotional Weather Report" From ramit.prasad at jpmorgan.com Wed Aug 31 21:48:29 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 31 Aug 2011 15:48:29 -0400 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F163CD730@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- I made some headway on the quote of the day program. I just tried to do it simple using two assumptions: - long quotes are going to print funny until I figure out the string splitting stuff - hard coding the quotes and authors in the program is simple, and I can use a spreadsheet to generate the strings when I put in the rest of the quotes (I have a lot of them). This code works. Now I just have to figure out: - how to get Ubuntu to run it at startup - how to associate .py files in Ubuntu to IDLE Thanks for all who commented, I really appreciate it. Pyhton is fun! # Quote_a_day_V1.py # # This program displays a random quotation # # Frank L. Palmeri August 31, 2011 import random print("\n\tHere is today's quote of the day:\n") author = ( "Kahlil Gibran", "Henrik Ibsen", "Dwight Eisenhower", "Will Rogers", "Will Rogers", "Jean de LaFontaine", "Eleanor Hibbert", "Baruch Spinoza", "Albert Camus", "Thomas a Kempi" ) quotation = ( "A candle loses nothing of its light when lighting another.", "The strongest man in the world is he who stands most alone.", "Leadership consists of nothing but taking responsibility for everything that goes wrong and giving your subordinates credit for everything that goes well.", "Even if you're on the right track, you'll get run over if you just sit there.", "I belong to no organized party. I am a Democrat.", "Patience and time do more than strength or passion.", "Never regret. If it's good, it's wonderful. If it's bad, it's experience.", "I have made a ceaseless effort not to ridicule, not to bewail, not to scorn human actions, but to understand them.", "In the depth of winter I finally learned there was in me an invincible summer.", "Who has a harder fight than he who is striving to overcome himself." ) numAuthors = len(author) printAuthor = random.randrange(numAuthors) print(quotation[printAuthor]) print("by ", author[printAuthor]) input("\nPress the enter key to exit.") -------------------------------------------------------- I would suggest storing the authors and quotes in a list[] instead of a tuple(). This will allow you make modifications directly to the list. Lists are mutable (changeable) while tuples are not. This will leave you in better shape if you decide to use pickle/shelve to store the lists in a file for reuse. # tuple example >>> t = (1,2,3) >>> t (1, 2, 3) >>> t[0] 1 >>> t[0] = 5 TypeError: 'tuple' object does not support item assignment # list example >>> l = [1,2,3] >>> l [1, 2, 3] >>> l[0] 1 >>> l[0] = 5 >>> l[0] 5 >>> l.append( 2100 ) # allows you to easily add new elements >>> l [5, 2, 3, 2100] As for string splitting, storing the full string as you are is the best option. You should leave your client (commandline/text, web, GUI) to decide what is appropriate for splitting and where it should be split. Although, if you want my opinion, I would probably create a quote class that stores some information. This way it is easier to make modifications and additions to the capabilities of the Quote. Not to mention this bundles the information together and you never have to worry about your author list and quote list getting out of sync. And if you derive Quote from object you *should* be able to pickle the list of Quotes very easily. (The following is untested). class Quote(object): def __init__(self, quote, author, date=None, misc=None): self.quote = quote ..... Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From lisi.reisz at gmail.com Wed Aug 31 21:35:43 2011 From: lisi.reisz at gmail.com (Lisi) Date: Wed, 31 Aug 2011 20:35:43 +0100 Subject: [Tutor] meaning of % in: if n % x == 0: Message-ID: <201108312035.43801.lisi.reisz@gmail.com> ?? If either n or x or both were 0, and % were the same thing as *, the statement would be true, but from the context I don't think that % does mean the same as *, because * appears very soon after in the same fragment of code. Lisi I'm sorry I am making such heavy weather of all this. Blame 2 things: anno domini and an exaggerated (obsessive) need to understand language. From hugo.yoshi at gmail.com Wed Aug 31 21:58:44 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 31 Aug 2011 21:58:44 +0200 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <201108312035.43801.lisi.reisz@gmail.com> References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: On Wed, Aug 31, 2011 at 9:35 PM, Lisi wrote: > ?? ?If either n or x or both were 0, and % were the same thing as *, the > statement would be true, but from the context I don't think that % does mean > the same as *, because * appears very soon after in the same fragment of > code. > > Lisi > > I'm sorry I am making such heavy weather of all this. ?Blame 2 things: anno > domini and an exaggerated (obsessive) need to understand language. % is the remainder operator: http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex it is how much remains after you perform an integer division, e.g. 23 % 5 == 3, since 20 / 5 == 4 and then you are left with 3. n % y == 0 if n is divisible by y. This is useful in factoring prime numbers, and in the case of y == 2, for checking if the number n is even. Hugo From joel.goldstick at gmail.com Wed Aug 31 22:15:21 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 31 Aug 2011 16:15:21 -0400 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: On Wed, Aug 31, 2011 at 3:58 PM, Hugo Arts wrote: > On Wed, Aug 31, 2011 at 9:35 PM, Lisi wrote: > > ?? If either n or x or both were 0, and % were the same thing as *, the > > statement would be true, but from the context I don't think that % does > mean > > the same as *, because * appears very soon after in the same fragment of > > code. > > > > Lisi > > > > I'm sorry I am making such heavy weather of all this. Blame 2 things: > anno > > domini and an exaggerated (obsessive) need to understand language. > > % is the remainder operator: > > > http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex > > it is how much remains after you perform an integer division, e.g. 23 > % 5 == 3, since 20 / 5 == 4 and then you are left with 3. > > n % y == 0 if n is divisible by y. This is useful in factoring prime > numbers, and in the case of y == 2, for checking if the number n is > even. > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Here is a little example that shows how using the 'mod' or 'modulus' operator can select only values that are divisible by 3. >>> for i in range(16): ... if not i % 3: ... print i ... 0 3 6 9 12 15 -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Wed Aug 31 22:43:23 2011 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Thu, 1 Sep 2011 06:43:23 +1000 Subject: [Tutor] urllib2 issue getting realm In-Reply-To: References: <007a01cc67b2$12db3fe0$3891bfa0$@com.au> Message-ID: Thanks Sanders Will give that a go Johan Sent from my iPhone 4 On 31/08/2011, at 23:03, Sander Sweers wrote: > On 31 August 2011 14:27, Johan Geldenhuys wrote: >> On 31/08/2011, at 22:09, Sander Sweers wrote: >>> On 31 August 2011 09:46, Johan Geldenhuys wrote: >>>> I am trying to use a very simple piece of code to get the realm from >>>> different HTTPS URLs. >>>> >>>> This realm is essential for successful authentication on the HTTPS session. >>> >>> I think you got 2 things mixed up, http authentication and encrypted >>> http (https). Just having a https url does not mean you need to >>> authenticate. Take 'https://mail.google.com' as an example. >>> >>>> If have to run this for a few different hosts and capture the realm. >>>> For one host, it works perfectly, but when I try the same code to get the >>>> next realm, it fails. I suspect that I need to close some type of >>>> connections or something, but I can't put my finger on it. >>> >>> >>>> For the next one: >>>> >>>>>>> try: >>>> ... req = urllib2.Request(URL % ips[1]) >>>> ... handle = urllib2.urlopen(req) >>>> ... except IOError, e: >>>> ... print `e` >>>> ... >>>>>>> >>>> >>>> See, no "e" printed which means that something worked. The exception didn't >>>> happen and I don't know why...Anybody? >>> >>> Yes, when you type the url into your browser. I suspect it does not >>> ask you to authenticate via http authentication. Therefor no exception >>> is raised and you never print the headers. > > Top posting is evil ;-). > >> Focusing on the code below, do you know why it would raise the exception for the first >> IP and not for the second? > > Run this and you should see which error is being raise. Do note we > catch urllib2.HTTPError instead of IOError. > > try: > req = urllib2.Request(URL % ips[1]) > handle = urllib2.urlopen(req) > print 'Success' > print handle.getcode() > print handle.headers > except urllib2.HTTPError as e: > print 'Exception caught' > print e > print e.getcode() > print e.hdrs > > Greets > Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sander.sweers at gmail.com Wed Aug 31 23:52:40 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 31 Aug 2011 23:52:40 +0200 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: References: Message-ID: On 31 August 2011 21:14, Cranky Frankie wrote: > I made some headway on the quote of the day program. I just tried to > do it simple using two assumptions: > > - long quotes are going to print funny until I figure out the string > splitting stuff Define funny? Normally the linux console will wrap everything up nicely for you. On a desktop (Gnome/Kde) there are other ways to display notify texts. > - hard coding the quotes and authors in the program is simple, and I > can use a spreadsheet to generate the strings when I put in the rest > of the quotes (I have a lot of them). Think about how to store and retrieve these quotes. You could read from a file and pick a random quotes. > This code works. Now I just have to figure out: > > - how to get Ubuntu to run it at startup Highly dependant on how and where you login. > - how to associate .py files in Ubuntu to IDLE This depends on a couple of factors and not really about learning python. The Ubuntu forums and wiki are the best place to start. > Pyhton is fun! Lets make it more fun :-). Consider the below example (also on [1]) which introduces a different approach to printing quotes. Do not hesitate to ask questions as I added tuple unpacking and string formatting which you might not have covered in depth yet in your tutorial. import random quotes = ( ("Kahlil Gibran", "A candle loses nothing of its light when lighting another."), ("Henrik Ibsen", "The strongest man in the world is he who stands most alone."), ("Dwight Eisenhower", "Leadership consists of nothing but taking responsibility for everything that goes wrong and giving your subordinates credit for everything that goes well."), ("Will Rogers", "Even if you're on the right track, you'll get run over if you just sit there."), ("Will Rogers", "I belong to no organized party. I am a Democrat."), ("Jean de LaFontaine", "Patience and time do more than strength or passion."), ("Eleanor Hibbert", "Never regret. If it's good, it's wonderful. If it's bad, it's experience."), ("Baruch Spinoza", "I have made a ceaseless effort not to ridicule, not to bewail, not to scorn human actions, but to understand them."), ("Albert Camus", "In the depth of winter I finally learned there was in me an invincible summer."), ("Thomas a Kempi", "Who has a harder fight than he who is striving to overcome himself.")) author, quote = random.choice(quotes) print "%s\n\tBy %s" % (quote, author) Greets Sander [1] http://pastebin.com/bdE2ynaG http://pastebin.com/bdE2ynaG