From john_re at fastmail.us Sat Aug 1 10:52:55 2009 From: john_re at fastmail.us (john_re) Date: Sat, 01 Aug 2009 01:52:55 -0700 Subject: [Tutor] Aug 1 & 16- Global VOIP Free SW HW Culture meeting, BerkeleyTIP, For Forwarding Message-ID: <1249116775.25770.1327808167@webmail.messagingengine.com> Interested in joining the friendly global Free SW HW & Culture communities in a global Voice meeting? You?re invited. :) You can join from your home, or better: get a local meeting together. Tip: a college WiFi cafe could be a great local meeting place. Make sure you have a VOIP headset! For all details, see the website (I?m leaving out many sublinks to make this email smaller). http://sites.google.com/site/berkeleytip Start by joining #berkeleytip on IRC freenode.net. We?ll help you get your VOIP connection working. :) ===== MARK YOUR CALENDARS: 1st Sat & 3rd Sunday each month. August 1 & 16. 10A - 6P Pacific US time (+7H GMT, IIRC) = 1P-9P Eastern US time = 5P - 1A GMT ? Or, come to the local meeting on the UC Berkeley campus. NOTE: SPECIAL LOCATION AUG 1: SEE BTIP WEBSITE FOR LOCATION, & RSVP TO ME OR THE BTIP LISTS. AUG 1 MEETING WILL BE 12N - 3P AT THE BTIP VOIP SERVER LOCATION ON THE UCB CAMPUS. SEE THE WEBSITE FOR ROOM LOCATION. We?ll hack on the new BTIP Asterisk VOIP server, in its presence. PLEASE RSVP TO ME (John) OR THE LIST IF YOU WANT TO MEET AT OUR USUAL LOCATION, THE FREE SPEECH CAFE, 10A-12n, 3-6PM, (otherwise i might not be there). ===== MEETING TOPICS FOR AUGUST: 1) Whatever _you_ want to work on - Email the BTIPGlobal list & let us know what your interests are. 2) Our VOIP conference server, using Asterisk. 3) Planning for year 2. ===== JOIN FOR THE START OF YEAR 2 GLOBAL MEETINGs: We had a great first year. We had local attendees from around the San Francisco Bay Area & Northern California. High School, College, Grad Students, & working & retired people attended. >From the US, people joined the meeting (IRC or VOIP) from Hawaii to Virgina, Washington to Michigan to Florida. (+ California & other states.) Globally, Sweden, Germany, England, Ireland, Iran & India (& maybe others I don?t recall right now.) :) In May Richard Stallman joined the global meeting for Q & A about free SW & HW. == YEAR 2 FOCUS: COLLEGE LOCAL MEETINGS, & AMERICAS? ANNOUNCEMENTS. Two main things I?ll focus on this year: 1) Inviting groups to join at colleges & universities - BTIP is educational. My hope: if more students learn about free SW hw & culture, some of them will then go on to become _contributors_. :) 2) I?ll try to get monthly announcements out to the biggest LUGs in the 10 largest countries in the Americas. == What would _YOU_ like to accomplish this year? Email the BTIP mail list, say ?hi?, tell us about your interests, projects & desires. ===== FOR FORWARDING - You are invited to forward this announcement wherever you think it might be appreciated. From robert.johansson at math.umu.se Sat Aug 1 11:05:12 2009 From: robert.johansson at math.umu.se (Robert Johansson) Date: Sat, 1 Aug 2009 11:05:12 +0200 Subject: [Tutor] Tkinter Message-ID: <000601ca1287$2e260910$8a721b30$@johansson@math.umu.se> Dear all, I have a problem with Tkinter and swedish letters such as ? (or '\xe4'). Here?s a small code example that counts the number of occurrences of the letter ?a? is in a string given by the user: from Tkinter import * root=Tk() def callback(): a=textLine.get() print a.count('a') textLine=Entry(root) textLine.pack(side=LEFT) searchButton=Button(root,command=callback,text='Search') searchButton.pack(side=RIGHT) root.mainloop() This works fine for strings containing all letters in my alphabet. However if I change it to count ?:s it works only for strings without our special letters (line 5: print a.count('?')): in callback print a.count('?') UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) The following works fine from command line: 'r?t'.count('?') And if I change line 5 to just printing a it works fine to. Anyone who knows how to fix this? Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Aug 1 13:28:33 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 07:28:33 -0400 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <9e3fac840907312142n73721c62xe3eca4a6b7c7c950@mail.gmail.com> References: <9e3fac840907302129g76731d05s661441f3058972f1@mail.gmail.com> <4A72C6EF.4030506@ieee.org> <9e3fac840907312142n73721c62xe3eca4a6b7c7c950@mail.gmail.com> Message-ID: <4A7426E1.9040300@ieee.org> (You replied off-list, so I'm copying your email, plus my response, to the list) prasad rao wrote: > >I still see four problems. > > > Hello Dave.I made modification as suggested by you. > > > You made the first three. But the problem of zlib.compress() producing a string with an embedded (0a) still hasn't been addressed. And I suspect this is your next problem. If you don't give the whole string that zlib.compress() produced to zlib.uncompress(), then it'll fail as you saw here. >>>> import mcript >>>> > > Traceback (most recent call last): > File "", line 1, in > import mcript > File "C:\Python26\mcript.py", line 84, in > a.main() > File "C:\Python26\mcript.py", line 65, in main > nl= self.__shorten(self.__undigi(self.__decompress(line.strip())))+'\n' > File "C:\Python26\mcript.py", line 47, in __decompress > astring=zlib.decompress(astring) > error: Error -5 while decompressing data > > on interactive mode it is(decompress())working well. > > What should I do to rectifi this error? > > I dont know java,know basics of c++ > > I started to lear python hardly onyear back. > > This is my 1st program using classes. > > Thanks for your time. > > > > #! usr/bin/env python > > import ast,random,os,zlib,string > key=5 > class Cripto(object): > def __init__(self,afile): > self.afile=afile > def __digi(self,astring): > y=[] > for x in astring: > y.append(ord(x)) > y=str(y) > > return y > def __undigi(self,astring): > > alist=ast.literal_eval(astring) > y=[] > for x in alist: > y.append(chr(x)) > astring=''.join(y) > return astring > def __gen_string(self): > s='' > nl=random.sample(string.ascii_letters,key) > for x in nl:s+=x > return s > > def __lengthen(self,astring): > s=list(astring) > ns='' > for x in s: > ns+=x > ns+=self.__gen_string() > return ns > def __shorten(self,astring): > > s=list(astring) > ns='' > for x in range(0,len(s),key+1): > ns+=s[x] > return ns > def __compress(self,astring): > astring=zlib.compress(astring) > return astring > def __decompress(self,astring): > astring=zlib.decompress(astring) > return astring > def main(self): > sorce=open(self.afile,'r') > data=(sorce.readlines()) > dest=open((os.path.split(self.afile)[0]+os.sep+'temp'),'w') > if (data[0]).strip()=='flag1': > > ns='flag0\n' > data=data[1:] > for line in data: > nl= > self.__compress(self.__digi(self.__lengthen(line.strip())))+'\n' > ns+=nl > dest.write(ns) > elif data[0].strip()=='flag0': > ns='flag1\n' > data=data[1:] > for line in data: > nl= > self.__shorten(self.__undigi(self.__decompress(line.strip())))+'\n' > ns+=nl > dest.write(ns) > else: > print 'File does not begin with the flag' > sorce.close() > dest.close() > os.remove(os.path.split(self.afile)[0]+os.sep+'temp') > return > > sorce.close() > dest.close() > > os.remove(self.afile) > os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) > > > #======== > a=Cripto('C:/pp.txt') > a.main() > > There are a couple of places where indentation has been broken. For example, in method __shorten(), the for loop body isn't indented. Are you retyping these, or are you using tabs in your source, or is paste broken on your system? What Python version are you using? It's clear that you're using Windows, so you will need to store the encoded file as binary. Furthermore, something I didn't spot before is that strip() isn't safe on the compressed data. You said you tested the lower-level functions manually. But they're not correct, so clearly it's past time to put in place some form of test harness. To properly test the code, you'll need to remove most of those double-underscores. And I'd suggest factoring out two methods, encode() and decode(), as follows: def encode(self, unencoded): nl= self.__compress(self.digi(self.lengthen(unencoded.strip())))+'\n' return nl def decode(self, encoded): nl= self.shorten(self.undigi(self.__decompress(encoded.strip())))+'\n' return nl I don't have your data file to test with, so I may not get exactly the same errors. In fact, multiple runs with the same data give different results. Sometimes I get bad data, and sometimes an exception like yours. Probably that's because of the random string you append in lengthen(). But the crash itself is probably caused by the bug I described in #4 of my previous message. zlib.compress() produces binary data, and you're assuming leading and trailing whitespace is irrelevant, and that there are no embedded 0a codes. So the first test I wrote was: def test_lengthen(line): xx = a.lengthen(line) yy = a.shorten(xx) if yy != line: print "shorten did not reproduce original data for ", line #else: #test_digi(xx, line) #this will be the next level of testing. Make up a few strings, and call this function. It fails every time. Your shorten() and lengthen() methods are not inverses. shorten() does not recreate the original text passed to lengthen. You'll have to fix that before you can do anything else. From kent37 at tds.net Sat Aug 1 14:26:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 1 Aug 2009 08:26:25 -0400 Subject: [Tutor] Tkinter In-Reply-To: <122635754149941682@unknownmsgid> References: <122635754149941682@unknownmsgid> Message-ID: <1c2a2c590908010526q4d6aab82s164df74507bc40da@mail.gmail.com> On Sat, Aug 1, 2009 at 5:05 AM, Robert Johansson wrote: > Dear all, I have a problem with Tkinter and swedish letters such as ? (or > ?'\xe4'). Here?s a small code example that counts the number of occurrences > of the letter ?a? is in a string given by the user: > > > > from Tkinter import * > > > > root=Tk() > > > > def callback(): > > ??? a=textLine.get() > > ??? print a.count('a') > > > > textLine=Entry(root) > > textLine.pack(side=LEFT) > > searchButton=Button(root,command=callback,text='Search') > > searchButton.pack(side=RIGHT) > > > > root.mainloop() > > > > This works fine for strings containing all letters in my alphabet. However > if I change it to count ?:s it works only for strings without our special > letters (line 5: print a.count('?')): > > > > in callback > > ??? print a.count('?') > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: > ordinal not in range(128) The problem is that when you enter non-ascii characters into the tkinter text box, it will return a unicode string. The count() method then needs to convert it's argument from an encoded byte string to a unicode string. It does this with the default (ascii) encoder and fails. Try passing a unicode string to count() like this: print a.count(u'?') Kent From ldl08 at gmx.net Sat Aug 1 16:03:24 2009 From: ldl08 at gmx.net (David) Date: Sat, 01 Aug 2009 22:03:24 +0800 Subject: [Tutor] [pygame] why does my window not close? Message-ID: <4A744B2C.9000106@gmx.net> Dear Tutors, I have written a simple pygame program: import pygame, sys pygame.init() screen = pygame.display.set_mode([640, 480]) screen.fill([255,255,255,255]) pygame.draw.circle(screen, [0,255,0], [150,200,], 30, 0) my_rect = (250, 150, 300, 200) pygame.draw.rect(screen, [0,0,255], my_rect, 0) pygame.display.flip() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() I am using Ubuntu Jaunty, Python 2.6.2: When I try to quit the program (clicking on the windows' [X] button), nothing happens. When I press CTRL-C on the Python interpreter, triggering a KeyboardInterrupt, the windows' content vanishes (turns black), but the window itself remains and can't be killed except by killing the Python interpreter from which I started my program. What is going on? I obviously want the window to disappear once I hit the [X] button! Cheers for a hint, David From mohannadmohammad at hotmail.com Sat Aug 1 18:12:49 2009 From: mohannadmohammad at hotmail.com (Mohannad Mohammad) Date: Sat, 1 Aug 2009 16:12:49 +0000 Subject: [Tutor] Question about the FONT in Tkinter Message-ID: Hello all, Kindly refer to the attached photo. There are two sentences appearing when the user checked two checkbutton, I make it as a practice. ok I want to change the font of these two sentences. how? This is the code I use to make this simple application: from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() self.font = ("tahoma", 10) def create_widgets(self): self.lbl1 = Label(self, text = "Choose your favorite movie types") self.lbl1.grid(row = 0, column = 0, columnspan = 2, sticky = W) self.lbl2 = Label(self, text = "Select all that apply:") self.lbl2.grid(row = 1, column = 0, columnspan = 2, sticky = W) self.likes_drama = BooleanVar() Checkbutton(self, text = "Drama", variable = self.likes_drama, command = self.update_text).grid(row = 2, column = 0, sticky = W) self.likes_comedy = BooleanVar() Checkbutton(self, text = "Comedy", variable = self.likes_comedy, command = self.update_text).grid(row = 3, column = 0, sticky = W) self.likes_sport = BooleanVar() Checkbutton(self, text = "Sport", variable = self.likes_sport, command = self.update_text).grid(row = 4, column = 0, sticky = W) self.box = Text(self, width = 400, height = 10, wrap = WORD) self.box.grid(row = 5, column = 0, columnspan = 2, sticky = W) def update_text(self): likes = "" if self.likes_drama.get(): likes += "You like Drama movies\n" if self.likes_comedy.get(): likes += "You like Comedy movies\n" if self.likes_sport.get(): likes += "You like Sport movies\n" self.box.delete(0.0, END) self.box.insert(0.0, likes) win = Tk() win.title("Choose any one..") win.geometry("400x300") app = Application(win) win.mainloop() _________________________________________________________________ Celebrate a decade of Messenger with free winks, emoticons, display pics, and more. http://clk.atdmt.com/UKM/go/157562755/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: font.gif Type: image/gif Size: 11429 bytes Desc: not available URL: From goodpotatoes at yahoo.com Sun Aug 2 20:55:39 2009 From: goodpotatoes at yahoo.com (gpo) Date: Sun, 2 Aug 2009 11:55:39 -0700 (PDT) Subject: [Tutor] New Issues with REGEX Greediness: Message-ID: <24764404.post@talk.nabble.com> Thanks for the replies in the last thread. I'm still trying to figure out how Python is handling RegEx. I'm converting my thoughts from Perl (the mother of regex) to Python, and expect the same results. Why are they different? Perl: $line='>Checking Privilege for UserId: {874BE70A-194B-DE11-BE5C-000C297901A5}, PrivilegeId: {prvReadSdkMessage}. Returned hr = 0' $line=~/(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}/; print "$1" RESULT: UserId This is the result I want. I'm trying to get the name's of GUID's from log files. Python: line='>Checking Privilege for UserId: {874BE70A-194B-DE11-BE5C-000C297901A5}, PrivilegeId: {prvReadSdkMessage}. Returned hr = 0' (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(0) RESULT 'UserId: {874BE70A-194B-DE11-BE5C-000C297901A5' How/Why are these results different? What is Python doing differently in regex, that I need to adjust to? -- View this message in context: http://www.nabble.com/New-Issues-with-REGEX-Greediness%3A-tp24764404p24764404.html Sent from the Python - tutor mailing list archive at Nabble.com. From malaclypse2 at gmail.com Mon Aug 3 16:49:46 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 Aug 2009 10:49:46 -0400 Subject: [Tutor] New Issues with REGEX Greediness: In-Reply-To: <24764404.post@talk.nabble.com> References: <24764404.post@talk.nabble.com> Message-ID: <16651e80908030749r6de74c4fp40f13a018bc7711f@mail.gmail.com> On Sun, Aug 2, 2009 at 2:55 PM, gpo wrote: > > Python: > line='>Checking Privilege for UserId: > {874BE70A-194B-DE11-BE5C-000C297901A5}, PrivilegeId: {prvReadSdkMessage}. > Returned hr = 0' > (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(0) > RESULT > 'UserId: {874BE70A-194B-DE11-BE5C-000C297901A5' > > How/Why are these results different? ?What is Python doing differently in > regex, that I need to adjust to? The group(0) method returns the entire portion of the string that matched your regex. Group(1) gives you what you want -- the portion that matched the first parenthesized capture group: >>> import re >>> line='>Checking Privilege for UserId: {874BE70A-194B-DE11-BE5C-000C297901A5}, PrivilegeId: {prvReadSdkMessage}. Returned hr = 0' >>> (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(0) 'UserId: {874BE70A-194B-DE11-BE5C-000C297901A5' >>> (re.search('(\w+)\:.+.{8}-.{4}-.{4}-.{4}-.{12}',line)).group(1) 'UserId' >>> The section of the docs on the group method of MatchObjects may be helpful: http://docs.python.org/library/re.html#re.MatchObject.group -- Jerry From prasadaraon50 at gmail.com Mon Aug 3 11:24:42 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Mon, 3 Aug 2009 14:54:42 +0530 Subject: [Tutor] How to pass arguments to struct.pack()? Message-ID: <9e3fac840908030224w4b481bf4pe7731bde9f4a1b7e@mail.gmail.com> Hello I am finding it difficult to pass arguments to struct.pack(). Please some one tell me how to do it. >>> def structpack(alist): import struct a='%di'%len(alist) print a b=[a] print alist print b for x in alist: b.append(x) arg1=b[0] arg2=b[1:] return struct.pack.tuple(arg1,arg2) >>> structpack([112, 114, 97, 115, 97, 100, 97, 32, 114, 97, 111, 32, 110]) 13i [112, 114, 97, 115, 97, 100, 97, 32, 114, 97, 111, 32, 110] ['13i'] Traceback (most recent call last): File "", line 1, in pstruct([112, 114, 97, 115, 97, 100, 97, 32, 114, 97, 111, 32, 110]) File "", line 16, in pstruct return struct.pack.tuple(b) AttributeError: 'builtin_function_or_method' object has no attribute 'tuple' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Aug 3 19:53:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Aug 2009 18:53:00 +0100 Subject: [Tutor] How to pass arguments to struct.pack()? References: <9e3fac840908030224w4b481bf4pe7731bde9f4a1b7e@mail.gmail.com> Message-ID: "prasad rao" wrote > I am finding it difficult to pass arguments to struct.pack(). You are not actually passing argments to struct.pack you are trying to access a non existent tuple() method of struct.pack. Hence the error message. But your code has several strangenesses... so simplifying >>>> def structpack(alist): > a='%di'%len(alist) > return struct.pack( a, *aList ) Should be all you need. However from a practical point of view you might find it useful to write the length of the list in front: def structpack(aList): ln = len (aList) fmt = "i%di" % ln return struct.pack(fmt, ln, *aList) That makes it easier to decode if/when you want to read it back. You will find an example in my tutorial under Handling files. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Mon Aug 3 20:23:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 3 Aug 2009 14:23:53 -0400 Subject: [Tutor] Question about the FONT in Tkinter In-Reply-To: References: Message-ID: <1c2a2c590908031123i3c7562a3ya4a54f39279346fb@mail.gmail.com> On Sat, Aug 1, 2009 at 12:12 PM, Mohannad Mohammad wrote: > Kindly refer to the attached photo. > There are two sentences appearing when the user checked two checkbutton, I > make it as a practice. > ok > I want to change the font of these two sentences. how? > ??????? self.box = Text(self, width = 400, height = 10, wrap = WORD) Add a font= parameter, for example self.box = Text(self, width = 400, height = 10, wrap = WORD, font=("Helvetica", 10, "bold italic") http://www.pythonware.com/library/tkinter/introduction/x444-fonts.htm Kent From alemi at sissa.it Mon Aug 3 19:20:53 2009 From: alemi at sissa.it (Alireza Alemi) Date: Mon, 03 Aug 2009 19:20:53 +0200 Subject: [Tutor] nonlinear fittinig Message-ID: <4A771C75.7010604@sissa.it> Dear All I am not sure if here is the right place to ask this question. Anyway, the question is: Is there a pythonic counterpart for Matlab nonlinear fitting ( which is " nlinfit() " function )? Thanks, Alireza From rondosxx at yahoo.com Mon Aug 3 20:27:48 2009 From: rondosxx at yahoo.com (ron) Date: Mon, 3 Aug 2009 11:27:48 -0700 (PDT) Subject: [Tutor] New Issues with REGEX Greediness: (gpo) Message-ID: <552442.19312.qm@web52503.mail.re2.yahoo.com> psst, there is NO standardized reg-ex. you've been living in a perl bubble. undoubtedly other people will have better advice. "Life can only be understood backwards; But it must be lived forwards" --S.K. From ali.jan at gmail.com Tue Aug 4 06:25:41 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Tue, 4 Aug 2009 10:25:41 +0600 Subject: [Tutor] [pygame] why does my window not close? In-Reply-To: <4A744B2C.9000106@gmx.net> References: <4A744B2C.9000106@gmx.net> Message-ID: <8acb5ef80908032125n2d21a78g7234166cd61b0c1f@mail.gmail.com> Hi, I have the same problem running pygame programs from the interpreter. I now just put a shebang line on top of the script like #!/usr/bin/env python and do chmod +x on the script and then run it from the terminal by doing ./script.py or double clicking on the file. It works fine when run directly instead of from the interpreter. Regards, Ali On Sat, Aug 1, 2009 at 8:03 PM, David wrote: > Dear Tutors, > > I have written a simple pygame program: > > > import pygame, sys > pygame.init() > screen = pygame.display.set_mode([640, 480]) > screen.fill([255,255,255,255]) > pygame.draw.circle(screen, [0,255,0], [150,200,], 30, 0) > my_rect = (250, 150, 300, 200) > pygame.draw.rect(screen, [0,0,255], my_rect, 0) > pygame.display.flip() > while True: > for event in pygame.event.get(): > if event.type == pygame.QUIT: > sys.exit() > > > I am using Ubuntu Jaunty, Python 2.6.2: > > When I try to quit the program (clicking on the windows' [X] button), > nothing happens. > When I press CTRL-C on the Python interpreter, triggering a > KeyboardInterrupt, the windows' content vanishes (turns black), but the > window itself remains and can't be killed except by killing the Python > interpreter from which I started my program. > What is going on? I obviously want the window to disappear once I hit > the [X] button! > > Cheers for a hint, > > David > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ali.jan at gmail.com Tue Aug 4 06:48:37 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Tue, 4 Aug 2009 10:48:37 +0600 Subject: [Tutor] nonlinear fittinig In-Reply-To: <4A771C75.7010604@sissa.it> References: <4A771C75.7010604@sissa.it> Message-ID: <8acb5ef80908032148v28e2bfedj35efb78a3936ffb2@mail.gmail.com> Don't know about nlinfit but you can check numpy, scipy and matplotlib that provide matlab like functionality. Ali On Mon, Aug 3, 2009 at 11:20 PM, Alireza Alemi wrote: > Dear All > > I am not sure if here is the right place to ask this question. > Anyway, the question is: Is there a pythonic counterpart for Matlab > nonlinear fitting ( which is " nlinfit() " function )? > > Thanks, > Alireza > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mohannadmohammad at hotmail.com Tue Aug 4 07:57:25 2009 From: mohannadmohammad at hotmail.com (Mohannad Mohammad) Date: Tue, 4 Aug 2009 05:57:25 +0000 Subject: [Tutor] Buffering when reading files ! Message-ID: Hello Tutor, I have a question about reading files using: file = open("filename.txt", "r", ........ ) The third argument ( ......... ) filled by buffering status, 0 or 1 or negative value or positive value greater than 1. I know the meaning of every value. but my question about the meaning of buffering, and to be more accurate, what is the different when I use buffering and when I disable it while reading files?! I hope any detailed answer, or a useful link. Thanks _________________________________________________________________ Windows Live Messenger: Thanks for 10 great years?enjoy free winks and emoticons. http://clk.atdmt.com/UKM/go/157562755/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 4 10:19:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Aug 2009 09:19:09 +0100 Subject: [Tutor] Buffering when reading files ! References: Message-ID: "Mohannad Mohammad" wrote > my question about the meaning of buffering, and to be more accurate, > what is the different when I use buffering and when I disable it while > reading files?! In practice I doubt if you will find much difference. Buffering should produce a small performance gain and in theory it can improve stability if you have an unreliable storage device, but nowadays thats rarely an issue. There is a slight chance that someone could change the underlying file and you wouldn't notice because you are working from data in the buffer. (Although most modern OS will lock the file even for reading) Personally I've never found buffering to be of any real impact for reading files. Writing files is another matter of course. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mland at us.ibm.com Tue Aug 4 19:43:28 2009 From: mland at us.ibm.com (Megan Land) Date: Tue, 4 Aug 2009 13:43:28 -0400 Subject: [Tutor] Program to Simulate Keystrokes Message-ID: Hi, I'm working on a python script to automate a program we run at work. The program is run from one command. The only problem is that it asks you to hit enter to continue after it runs. Is there a way I can do this? If at all possible I need a program that will work on Windows and Linux (I know a tall order). I'm trying to keep this simple but if I have to use two different programs I will. Thanks for the help! Megan Land FVT Blade EMET Test Engineer mland at us.ibm.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 4 19:55:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Aug 2009 18:55:52 +0100 Subject: [Tutor] Program to Simulate Keystrokes References: Message-ID: "Megan Land" wrote > I'm working on a python script to automate a program we run at work. The > program is run from one command. The only problem is that it asks you to > hit enter to continue after it runs. Is there a way I can do this? Assuming it is using stdin/out to read the keystrokes you shjould be able to use the subprocess module to communicate with the process. Read stdout, detect the message and send a newline character to the process. > If at all possible I need a program that will work on Windows and Linux > (I > know a tall order). I'm trying to keep this simple but if I have to use > two different programs I will. stdin/out should work on both. If its a GUI program then things get much more complicated! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Tue Aug 4 20:00:01 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 4 Aug 2009 13:00:01 -0500 Subject: [Tutor] Program to Simulate Keystrokes In-Reply-To: References: Message-ID: <333efb450908041100x662cc32asaa85511d4941fdd6@mail.gmail.com> On Tue, Aug 4, 2009 at 12:43 PM, Megan Land wrote: > Hi, > > I'm working on a python script to automate a program we run at work. The > program is run from one command. The only problem is that it asks you to hit > enter to continue after it runs. Is there a way I can do this? > > If at all possible I need a program that will work on Windows and Linux (I > know a tall order). I'm trying to keep this simple but if I have to use two > different programs I will. > I just tested and this seems to work: import subprocess p = subprocess.Popen(['python', 'asdf.py'], stdout=subprocess.PIPE, stdin=subpro cess.PIPE) p.stdin.write('\r\n') print p.stdout.readlines() - the contents of asdf.py are just these: raw_input("Press enter to continue") print "Works!" HTH! -Wayne, who just learned a little something about the subprocess module -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Aug 4 21:01:56 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 4 Aug 2009 14:01:56 -0500 Subject: [Tutor] Program to Simulate Keystrokes In-Reply-To: References: Message-ID: <200908041401.56879.cfuller084@thinkingplanet.net> On Tuesday 04 August 2009 12:43, Megan Land wrote: > Hi, > > I'm working on a python script to automate a program we run at work. The > program is run from one command. The only problem is that it asks you to > hit enter to continue after it runs. Is there a way I can do this? > > If at all possible I need a program that will work on Windows and Linux (I > know a tall order). I'm trying to keep this simple but if I have to use > two different programs I will. > > Thanks for the help! > > Megan Land > FVT Blade EMET Test Engineer > mland at us.ibm.com If your needs are basic, popen will probably suffice. But, there is a module, Pexpect, that is made just for this job. http://sourceforge.net/projects/pexpect/ Cheers From kent37 at tds.net Tue Aug 4 21:45:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 4 Aug 2009 15:45:54 -0400 Subject: [Tutor] Program to Simulate Keystrokes In-Reply-To: <200908041401.56879.cfuller084@thinkingplanet.net> References: <200908041401.56879.cfuller084@thinkingplanet.net> Message-ID: <1c2a2c590908041245w77553b67rd8e192cbd42f7eab@mail.gmail.com> On Tue, Aug 4, 2009 at 3:01 PM, Chris Fuller wrote: > On Tuesday 04 August 2009 12:43, Megan Land wrote: >> If at all possible I need a program that will work on Windows and Linux (I >> know a tall order). ?I'm trying to keep this simple but if I have to use >> two different programs I will. > If your needs are basic, popen will probably suffice. ?But, there is a module, > Pexpect, that is made just for this job. > http://sourceforge.net/projects/pexpect/ IIRC Pexpect requires pty and doesn't run on Windows. Kent From craig.a.mcd at googlemail.com Wed Aug 5 12:34:28 2009 From: craig.a.mcd at googlemail.com (Craig McDonald) Date: Wed, 5 Aug 2009 11:34:28 +0100 Subject: [Tutor] Scope of exceptions Message-ID: <29bd9a600908050334icad930fk59b1e37881939838@mail.gmail.com> Howdy, I am in the process of moving all my perl scripts to python and also trying to learn to program rather than just know enough to automate sections of my job. I am trying exit cleanly if I force the script to exit early. I am working my way through core python but not yet read properly about exceptions so this is how I guessed exceptions to work. try: statements extractData() more_statements even_more_statements except KeyboardInterrupt: exit('Exiting') Once it enters/runs the extractData func and if I choose to exit (control c) it throws an exception rather than exiting cleanly. Do I need to put a 'KeyboardInterrupt' exception for every function? Thanks in advance, Craig From ali.jan at gmail.com Wed Aug 5 13:12:40 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Wed, 5 Aug 2009 17:12:40 +0600 Subject: [Tutor] Scope of exceptions In-Reply-To: <29bd9a600908050334icad930fk59b1e37881939838@mail.gmail.com> References: <29bd9a600908050334icad930fk59b1e37881939838@mail.gmail.com> Message-ID: <8acb5ef80908050412n6a133f12k6ea4c26a4da27550@mail.gmail.com> Instead of putting it in every function, you could probably do it once in your "main" function that does all the work... On Wed, Aug 5, 2009 at 4:34 PM, Craig McDonald wrote: > Howdy, > > I am in the process of moving all my perl scripts to python and also > trying to learn to program rather than just know enough to automate > sections of my job. I am trying exit cleanly if I force the script to > exit early. I am working my way through core python but not yet read > properly about exceptions so this is how I guessed exceptions to work. > > try: > statements > extractData() > more_statements > even_more_statements > except KeyboardInterrupt: > exit('Exiting') > > Once it enters/runs the extractData func and if I choose to exit > (control c) it throws an exception rather than exiting cleanly. Do I > need to put a 'KeyboardInterrupt' exception for every function? > > Thanks in advance, > > Craig > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 5 20:19:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Aug 2009 19:19:51 +0100 Subject: [Tutor] Scope of exceptions References: <29bd9a600908050334icad930fk59b1e37881939838@mail.gmail.com> Message-ID: "Craig McDonald" wrote > try: > statements > extractData() > more_statements > even_more_statements > except KeyboardInterrupt: > exit('Exiting') > > Once it enters/runs the extractData func and if I choose to exit > (control c) it throws an exception rather than exiting cleanly. Do I > need to put a 'KeyboardInterrupt' exception for every function? It should work as you've shown. What should happen is that if you type Ctrl-C while the script is executing extractData() then Python will raise the exception and the function will not know what to do with it, so it raises it to the next level where your handler should catch it. So what does your real handler look like? And what does the exception that is raised look like? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From allen.fowler at yahoo.com Thu Aug 6 01:14:24 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Wed, 5 Aug 2009 16:14:24 -0700 (PDT) Subject: [Tutor] Configuaration files and paths? Message-ID: <883418.38051.qm@web45606.mail.sp1.yahoo.com> Hello, What is the recommended way to configure my application find the various database and/or configuration files it needs? For instance my folder layout: /path_to_app/app.py /path_to_app/lib/ /path_to_app/database/ /path_to_app/config/ /path_to_app/photos .... and so on. (app.py being the main file, and the lib folder containing my custom modules.) I would like to make an .ini in the config folder that contains entries that point to the other folders. Seems like a resonable idea. So my questions are: 1) How does my main app file find the config file in the first place? 2) How should I point to those other folders in the ini file? Thank you From alan.gauld at btinternet.com Thu Aug 6 02:04:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Aug 2009 01:04:05 +0100 Subject: [Tutor] Configuaration files and paths? References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > What is the recommended way to configure my application > find the various database and/or configuration files it needs? Recommemded by whom? A lot depends on the OS. Apple for example have one set of recommendations for MacOS, Windows has another and Linux has several to choose from! > For instance my folder layout: > > /path_to_app/app.py > /path_to_app/lib/ > /path_to_app/database/ > /path_to_app/config/ > /path_to_app/photos > > .... and so on. > I would like to make an .ini in the config folder Seems fair enough, however on a Unix system you should also consider allowing the user to have their own personalised version in their home directory. Thus at startup you get the current user ID / home directory and look for a suitable config file. If it exists read it, if not read the default one in your config directory. > 1) How does my main app file find the config file in the first place? Generally use a relative path so normally your app will run from its home folder so you can look in ./config. You might also set a system environment variable - for example the CLASSPATH or PYTHONPATH variables, or the ORACLE_HOME used by Oracle for their database. If the environment var is not set then look in ./config > 2) How should I point to those other folders in the ini file? Once you locate config the others are simply ../xxx relative to config. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From allen.fowler at yahoo.com Thu Aug 6 06:15:37 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Wed, 5 Aug 2009 21:15:37 -0700 (PDT) Subject: [Tutor] Configuaration files and paths? In-Reply-To: References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> Message-ID: <946488.25329.qm@web45608.mail.sp1.yahoo.com> > > What is the recommended way to configure my application find the various > database and/or configuration files it needs? > > Recommemded by whom? A lot depends on the OS. Apple for example have one set of > recommendations for MacOS, Windows has another and Linux has several to choose > from! > Thank you.... good point. Planning on using a ConfigParser based .ini file located in the ./config folder. > > For instance my folder layout: > > > > /path_to_app/app.py > > /path_to_app/lib/ > > /path_to_app/database/ > > /path_to_app/config/ > > /path_to_app/photos > > > > .... and so on. I would like to make an .ini in the config folder > > Seems fair enough, however on a Unix system you should also consider allowing > the user to have their own personalised version in their home directory. Thus at > startup you get the current user ID / home directory and look for a suitable > config file. If it exists read it, if not read the default one in your config > directory. > > > 1) How does my main app file find the config file in the first place? > > Generally use a relative path so normally your app will run from its home folder > so you can look in ./config. You might also set a system environment variable - > for example the CLASSPATH or PYTHONPATH variables, or the ORACLE_HOME used by > Oracle for their database. If the environment var is not set then look in > ./config > Assuming the application could be invoked in odd ways that may alter the notion of the current working directory, how do I unambiguously find the absolute path to the current python source file? (So I can load the nearby .ini) As a follow-up question, how do give my modules stored under ./lib access to the data in my ConfigParser object? (For instance, database connection string, storage path, etc.) I guess a global ConfigParser object would work, but that seems wrong. From davea at ieee.org Thu Aug 6 08:03:02 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Aug 2009 02:03:02 -0400 Subject: [Tutor] Configuaration files and paths? In-Reply-To: <946488.25329.qm@web45608.mail.sp1.yahoo.com> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> Message-ID: <4A7A7216.4060202@ieee.org> Allen Fowler wrote: >>> What is the recommended way to configure my application find the various >>> >> database and/or configuration files it needs? >> >> Recommemded by whom? A lot depends on the OS. Apple for example have one set of >> recommendations for MacOS, Windows has another and Linux has several to choose >> from! >> >> > > > Thank you.... good point. > > Planning on using a ConfigParser based .ini file located in the ./config folder. > > >>> For instance my folder layout: >>> >>> /path_to_app/app.py >>> /path_to_app/lib/ >>> /path_to_app/database/ >>> /path_to_app/config/ >>> /path_to_app/photos >>> >>> .... and so on. I would like to make an .ini in the config folder >>> >> Seems fair enough, however on a Unix system you should also consider allowing >> the user to have their own personalised version in their home directory. Thus at >> startup you get the current user ID / home directory and look for a suitable >> config file. If it exists read it, if not read the default one in your config >> directory. >> >> >>> 1) How does my main app file find the config file in the first place? >>> >> Generally use a relative path so normally your app will run from its home folder >> so you can look in ./config. You might also set a system environment variable - >> for example the CLASSPATH or PYTHONPATH variables, or the ORACLE_HOME used by >> Oracle for their database. If the environment var is not set then look in >> ./config >> >> > > Assuming the application could be invoked in odd ways that may alter the notion of the current working directory, how do I unambiguously find the absolute path to the current python source file? (So I can load the nearby .ini) > > > As a follow-up question, how do give my modules stored under ./lib access to the data in my ConfigParser object? (For instance, database connection string, storage path, etc.) > > I guess a global ConfigParser object would work, but that seems wrong. > > > Regardless of the OS, you need to consider whether more than one user is going to share the code and constant data, but have independent versions of the variable data. If so, then putting the .ini file in the code tree makes no sense. You also have to decide whether there is going to be an install process, or whether the program files will be simply unzipped or copied to a single target directory. And if there is an install, the library you use could very likely influence what you wind up doing. But for raw answers: you can tell where a running python module is located, simply by using the __file__ attribute. You can then parse this with os.path.dirname() to get the directory the file is located in. Then you can use ..\config to get to the config directory. You're right; don't use current directory to find any of this. Use it to find user data, usually, if the command is entered interactively. And don't use it at all, for things started by Explorer (in Windows). I would expect to have two directory structures, one fixed, and one variable. The fixed one is stuff that doesn't get modified once install (or copy) is complete. And the variable one is derived in some way from the user's login. On Windows, that could be a registry entry (HKCU), or it could be the HOMEPATH ( c:\Documents and Settings\username, on XP ). Once you've calculated this initial variable directory, create an INI file that says where all the rest of the variable data is. I claim that this would be an absolute path, set up the first time the user runs File->Configuration. The default would be relative to the same directory, but it should be changeable. I try to set up my personal systems with two main partitions. One has (mostly) constant data and programs, modified each install. It also has junk, like temp files, the swapfile, etc. All user data is on a different partition, with very different backup rules. Windows puts my HOMEPATH on the C: drive, but I avoid programs that force me to leave any quantity of information there. As for how various library modules should find data gathered in your main script, you just pass an instance of the object containing that data. DaveA From joshharper27 at gmail.com Thu Aug 6 09:44:45 2009 From: joshharper27 at gmail.com (Joshua Harper) Date: Thu, 6 Aug 2009 03:44:45 -0400 Subject: [Tutor] noob question (Windows, Python 3.1) Message-ID: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Ok, so I am trying to learn python, and I am reading many tutorial type things and I am kind of stuck with implementing some of the code... so for example the tutorial says "*To get the examples working properly, write the programs in a text file and then run that with the interpreter*" Alright...simple enough so I wirte the example program: x = input("Please enter a number: ") print "The square of that number is I save this as a .py and Open With>python.exe. OK, so that gives me the terminal ansking me to enter a number, I enter a number and click enter and then it prints in like half a nanosecond and the cmd line window closes. I want to know how to have the window stay open so that, in future scripts I may be able to actually see what was printed. I talked to my friend and he said that he has the same problem...anybody?...help??? -- - JH -------------- next part -------------- An HTML attachment was scrubbed... URL: From connorsml at gmail.com Thu Aug 6 09:52:10 2009 From: connorsml at gmail.com (Michael Connors) Date: Thu, 6 Aug 2009 09:52:10 +0200 Subject: [Tutor] noob question (Windows, Python 3.1) In-Reply-To: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> References: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Message-ID: 2009/8/6 Joshua Harper > Ok, so I am trying to learn python, and I am reading many tutorial type > things and I am kind of stuck with implementing some of the code... so for > example the tutorial says "*To get the examples working properly, write > the programs in a text file and then run that with the interpreter*" > Alright...simple enough so I wirte the example program: > > x = input("Please enter a number: ") > print "The square of that number is > > I save this as a .py and Open With>python.exe. OK, so that gives me the > terminal ansking me to enter a number, I enter a number and click enter and > then it prints in like half a nanosecond and the cmd line window closes. I > want to know how to have the window stay open so that, in future scripts I > may be able to actually see what was printed. I talked to my friend and he > said that he has the same problem...anybody?...help??? > > It closes because it is finished. If you want to see the result, you could either: - Place another input("") after the print statement. - Run the program from the command prompt (in which case you will probably need to set the path) -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Aug 6 14:32:03 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 06 Aug 2009 08:32:03 -0400 Subject: [Tutor] noob question (Windows, Python 3.1) In-Reply-To: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> References: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Message-ID: <1249561923.32682.19.camel@bermanrl-desktop> On Thu, 2009-08-06 at 03:44 -0400, Joshua Harper wrote: > Ok, so I am trying to learn python, and I am reading many tutorial > type things and I am kind of stuck with implementing some of the > code... so for example the tutorial says "To get the examples working > properly, write the programs in a text file and then run that with the > interpreter" Alright...simple enough so I wirte the example program: > > > x = input("Please enter a number: ") > print "The square of that number is raw_input('Press Enter to end>>') > I save this as a .py and Open With>python.exe. OK, so that gives me > the terminal ansking me to enter a number, I enter a number and click > enter and then it prints in like half a nanosecond and the cmd line > window closes. I want to know how to have the window stay open so > that, in future scripts I may be able to actually see what was > printed. I talked to my friend and he said that he has the same > problem...anybody?...help??? > > -- > - JH Hope this helps, Robert > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 6 16:03:57 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Aug 2009 10:03:57 -0400 Subject: [Tutor] noob question (Windows, Python 3.1) In-Reply-To: References: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Message-ID: <4A7AE2CD.2010609@ieee.org> Michael Connors wrote: > 2009/8/6 Joshua Harper > > >> Ok, so I am trying to learn python, and I am reading many tutorial type >> things and I am kind of stuck with implementing some of the code... so for >> example the tutorial says "*To get the examples working properly, write >> the programs in a text file and then run that with the interpreter*" >> Alright...simple enough so I wirte the example program: >> >> x = input("Please enter a number: ") >> print "The square of that number is >> >> I save this as a .py and Open With>python.exe. OK, so that gives me the >> terminal ansking me to enter a number, I enter a number and click enter and >> then it prints in like half a nanosecond and the cmd line window closes. I >> want to know how to have the window stay open so that, in future scripts I >> may be able to actually see what was printed. I talked to my friend and he >> said that he has the same problem...anybody?...help??? >> >> >> > It closes because it is finished. > > If you want to see the result, you could either: > > - Place another input("") after the print statement. > - Run the program from the command prompt (in which case you will probably > need to set the path) > > Michael is correct, but I'd like to expand on the answer. In Windows, there are two kinds of applications, console apps and gui apps. A console app uses stdin and stdout (character mode, like input and print). A gui app has buttons, menus, and dialog boxes. Console apps are much easier to write and debug, they tend to run faster, and tutorials always start there. A console app can be run from an Explorer shortcut, or from the context menu as you're doing, but you're missing a lot. As you've already noticed, the console is deleted immediately after the program terminates. So you can put an extra input("Press OK to finish") at the end of your code. But for various reasons (eg. bugs) your program may never reach that line. And if it doesn't, any error messages will also vanish when the console does. While there are workarounds for this, the real answer is to learn to use a command prompt. At least until a program is bug-free. A "command prompt" (aka "Dos Box", or console, or shell) can be started from the "Run" command on the start menu -- just type "Cmd" as the program to run. There's also a shortcut called "Command Prompt" in Start->Accesssories. The default installation on Windows sets up a file association for both .py and .pyw files, so you should be able to just type example.py at the command prompt to run the program. The command prompt window will scroll to hold more input than would otherwise fit on screen. And you can copy & paste from and to a command prompt, though it's tricky (another discussion). You may want to create a few batch files to make your life at the command prompt a bit easier. For example, the path to the python interpreter is not normally added to the PATH variable, and I don't think it should. So if you want to run Python.exe explicitly, it helps to make a batch file to make that easier. We can help with that as well. When you run the program from the command prompt, the print output stays there till you either close the command prompt, or run enough other stuff that it scrolls off the top end of the buffer. DaveA From fomcl at yahoo.com Thu Aug 6 17:25:49 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 6 Aug 2009 08:25:49 -0700 (PDT) Subject: [Tutor] easy way to pupulate a dict with functions In-Reply-To: <4A7AE2CD.2010609@ieee.org> Message-ID: <868681.68703.qm@web110708.mail.gq1.yahoo.com> Hi, I was playing with the code below, and I was wondering if there was a way to populate the dictionary called 'commands' (in the function 'check_command()'). Suppose I would add another function, which I would also like to store as a value in 'commands', could it simply be programmed, or would every update/addition require the definition of the dictionary to be extended? It would be most desirable if one could simply add another function without there being the need to touch any of the other code. Cheers!! Albert-Jan() def foo (a): return "foo" * a def bletch (q): for i in range(20): print i * q def stilton (n): print "yes sir, " * n def romans (z): print "what have the romans really done for us?\n" * z def check_command(): commands = {'1': foo, '2': bletch, '3': stilton, '4': romans} while True: select = raw_input("choose an option [%s]: " % "|".join(sorted(commands.keys()))) if select in commands.keys(): check_parameter(commands, select) break else: print "illegal option (%s)" % select def check_parameter(commands, select): while True: parameter = raw_input("choose a parameter [integer]: ") if parameter.isdigit(): commands[select](int(parameter)) break else: print "illegal parameter (%s)" % parameter check_command() From bgailer at gmail.com Thu Aug 6 19:28:19 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Aug 2009 13:28:19 -0400 Subject: [Tutor] easy way to populate a dict with functions Message-ID: <4A7B12B3.2010802@gmail.com> Please start a new email when starting a new topic. Otherwise it gets linked to the previous one in email clients that follow threads! To avoid that here I am responding in a new email. Also fixed spelling in subject. Albert-Jan Roskam wrote: > Hi, > > I was playing with the code below, and I was wondering if there was a way to populate the dictionary called 'commands' (in the function 'check_command()'). > > Suppose I would add another function, which I would also like to store as a value in 'commands', could it simply be programmed, or would every update/addition require the definition of the dictionary to be extended? > It would be most desirable if one could simply add another function without there being the need to touch any of the other code. > > > Here's how I'd do it. Others may have other solutions. Put the command functions in a separate module, e.g., commands.py: # -------- code --------------- def foo (a): return "foo" * a def bletch (q): for i in range(20): print i * q def stilton (n): print "yes sir, " * n def romans (z): print "what have the romans really done for us?\n" * z # -------- end code --------------- Put the "main" program (in another module) e.g., main.py: # -------- code --------------- import commands import inspect cmds = inspect.getmembers(commands, inspect.isfunction) num_cmds = len(cmds) option_list = "|".join(str(c) for c in range(1, num_cmds+1)) prompt = "choose an option [%s]: " % option_list def check_command(): while True: select = raw_input(prompt) try: command = cmds[int(select)][1] except ValueError: print "non-numeric option (%s)" % select except IndexError: print "option out of range (%s)" % select else: check_parameter(command) break def check_parameter(command): while True: parameter = raw_input("choose a parameter [integer]: ") if parameter.isdigit(): command(int(parameter)) break else: print "illegal parameter (%s)" % parameter check_command() # -------- end code --------------- cmds is a list similar to: [('bletch', ), ('foo', ), ('romans', ), ('stilton', )] -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Thu Aug 6 19:37:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Aug 2009 18:37:37 +0100 Subject: [Tutor] noob question (Windows, Python 3.1) References: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Message-ID: "Joshua Harper" wrote > Ok, so I am trying to learn python, and I am reading many tutorial type If you are just learning Python downgrade from 3.1 to v2.6. Most tutorials are not up to 3.1 yet and there are many differences. v3.1 was a big change to the language. eg. The following code is for v2, it needs changing for v3: > x = input("Please enter a number: ") x = int( input("Please enter a number: ") ) > print "The square of that number is print ( "The square of that number is ) > I save this as a .py and Open With>python.exe. OK, so that gives me the > terminal ansking me to enter a number, I enter a number and click enter > and > then it prints in like half a nanosecond and the cmd line window closes. Others have answered this. You really need an option though that will display the error message that I suspect you are getting... Start a CMD window and run the python command by typing the command at the DOS prompt. eg C:\Windows> python some\path\to\myscript.py That way you will still see the error message after the program finishes. HTH, BTW My tutorial is nearly half way to being converted to v3 now, you might find it useful if you don;t want to revert to 2.6. But personally I'd go back! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From fomcl at yahoo.com Thu Aug 6 20:54:25 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 6 Aug 2009 11:54:25 -0700 (PDT) Subject: [Tutor] easy way to populate a dict with functions In-Reply-To: <4A7B12B3.2010802@gmail.com> Message-ID: <314582.78242.qm@web110716.mail.gq1.yahoo.com> Hi Bob, Very neat solution, thanks a lot! I didn't know the inspect module, but it's just what's needed here. Cool! And sorry about not starting a new mail. I'll keep it in mind for next time. Best wishes, Albert-Jan --- On Thu, 8/6/09, bob gailer wrote: > From: bob gailer > Subject: RE: [Tutor] easy way to populate a dict with functions > To: fomcl at yahoo.com > Cc: "tutorpythonmailinglist Python" > Date: Thursday, August 6, 2009, 7:28 PM > Please start a new email when > starting a new topic. Otherwise it gets linked to the > previous one in email clients that follow threads! > > To avoid that here I am responding in a new email. Also > fixed spelling in subject. > > Albert-Jan Roskam wrote: > > Hi, > > > > I was playing with the code below, and I was wondering > if there was a way to populate the dictionary called > 'commands' (in the function 'check_command()'). > > > > Suppose I would add another function, which I would > also like to store as a value in 'commands', could it simply > be programmed, or would every update/addition require the > definition of the dictionary to be extended? > > It would be most desirable if one could simply add > another function without there being the need to touch any > of the other code. > > > >??? > Here's how I'd do it. Others may have other solutions. > > Put the command functions in a separate module, e.g., > commands.py: > # -------- code --------------- > def foo (a): > return "foo" * a > > def bletch (q): > for i in range(20): > ???print i * q > > def stilton (n): > print "yes sir, " * n > > def romans (z): > print "what have the romans really done for us?\n" * z > # -------- end code --------------- > > Put the "main" program (in another module) e.g., main.py: > > # -------- code --------------- > import commands > import inspect > cmds = inspect.getmembers(commands, inspect.isfunction) > num_cmds = len(cmds) > option_list = "|".join(str(c) for c in range(1, > num_cmds+1)) > prompt = "choose an option [%s]: " % option_list > > def check_command(): > while True: > ???select = raw_input(prompt) > ???try: > ? ???command = cmds[int(select)][1] > ???except ValueError: > ? ???print "non-numeric option? > ???(%s)" % select > ???except IndexError: > ? ???print "option out of range (%s)" % > select > ???else: > ? ???check_parameter(command) > ? ???break > > def check_parameter(command): > while True: > ???parameter = raw_input("choose a parameter > [integer]: ") > ???if parameter.isdigit(): > ? ???command(int(parameter)) > ? ???break > ???else: > ? ???print "illegal parameter (%s)" % > parameter > > check_command() > # -------- end code --------------- > > cmds is a list similar to: > [('bletch', ), > ('foo', ), > ('romans', ), > ('stilton', )] > > -- Bob Gailer > Chapel Hill NC > 919-636-4239 > > From fomcl at yahoo.com Thu Aug 6 21:18:17 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 6 Aug 2009 12:18:17 -0700 (PDT) Subject: [Tutor] easy way to populate a dict with functions In-Reply-To: <4A7B12B3.2010802@gmail.com> Message-ID: <484980.47042.qm@web110711.mail.gq1.yahoo.com> ...Still one more question: cmds = inspect.getmembers(commands, inspect.isfunction) print cmds #will generate [('bletch', ), ('foo', ), ('romans', ), ('stilton', )] This looks okay, but the order in which the functions appear in the module (commands.py) is different: foo, bletch, stilton, romans Do you know why? Cheers again, Albert-Jan --- On Thu, 8/6/09, bob gailer wrote: > From: bob gailer > Subject: RE: [Tutor] easy way to populate a dict with functions > To: fomcl at yahoo.com > Cc: "tutorpythonmailinglist Python" > Date: Thursday, August 6, 2009, 7:28 PM > Please start a new email when > starting a new topic. Otherwise it gets linked to the > previous one in email clients that follow threads! > > To avoid that here I am responding in a new email. Also > fixed spelling in subject. > > Albert-Jan Roskam wrote: > > Hi, > > > > I was playing with the code below, and I was wondering > if there was a way to populate the dictionary called > 'commands' (in the function 'check_command()'). > > > > Suppose I would add another function, which I would > also like to store as a value in 'commands', could it simply > be programmed, or would every update/addition require the > definition of the dictionary to be extended? > > It would be most desirable if one could simply add > another function without there being the need to touch any > of the other code. > > > >??? > Here's how I'd do it. Others may have other solutions. > > Put the command functions in a separate module, e.g., > commands.py: > # -------- code --------------- > def foo (a): > return "foo" * a > > def bletch (q): > for i in range(20): > ???print i * q > > def stilton (n): > print "yes sir, " * n > > def romans (z): > print "what have the romans really done for us?\n" * z > # -------- end code --------------- > > Put the "main" program (in another module) e.g., main.py: > > # -------- code --------------- > import commands > import inspect > cmds = inspect.getmembers(commands, inspect.isfunction) > num_cmds = len(cmds) > option_list = "|".join(str(c) for c in range(1, > num_cmds+1)) > prompt = "choose an option [%s]: " % option_list > > def check_command(): > while True: > ???select = raw_input(prompt) > ???try: > ? ???command = cmds[int(select)][1] > ???except ValueError: > ? ???print "non-numeric option? > ???(%s)" % select > ???except IndexError: > ? ???print "option out of range (%s)" % > select > ???else: > ? ???check_parameter(command) > ? ???break > > def check_parameter(command): > while True: > ???parameter = raw_input("choose a parameter > [integer]: ") > ???if parameter.isdigit(): > ? ???command(int(parameter)) > ? ???break > ???else: > ? ???print "illegal parameter (%s)" % > parameter > > check_command() > # -------- end code --------------- > > cmds is a list similar to: > [('bletch', ), > ('foo', ), > ('romans', ), > ('stilton', )] > > -- Bob Gailer > Chapel Hill NC > 919-636-4239 > > From pedrooconnell at gmail.com Thu Aug 6 21:33:49 2009 From: pedrooconnell at gmail.com (pedro) Date: Thu, 6 Aug 2009 15:33:49 -0400 Subject: [Tutor] monitor number of files in a folder Message-ID: Hi I am rendering image sequences on a basic render farm that I am building. Once all the files in the sequence have been rendered I would like to make a quicktime of the sequence automatically. The problem I am having is that if one of the computers on the farm is rendering slow the quicktime gets made before all the files are rendered. The variable below called "theNumberOfImages" is the actual # of images that have been rendered which is working fine. The variable below called "theNumberOfFrames" is the total # of images that are supposed to be rendered. What I am trying to do but am not sure how is to say: As soon as theNumberOfImages is equal to or greater than theNumberOfFrames, render the quicktime. Here is my very bad solution if theNumberOfImages <= theNumberOfFrames: time.sleep(60) if theNumberOfImages <= theNumberOfFrames: time.sleep(60) if theNumberOfImages <= theNumberOfFrames: time.sleep(60) else: os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.sh') An help would be greatly appreciated Pete From pine508 at hotmail.com Thu Aug 6 21:37:01 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 6 Aug 2009 15:37:01 -0400 Subject: [Tutor] noob question (Windows, Python 3.1) In-Reply-To: References: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Message-ID: > Start a CMD window and run the python command by typing the command > at the DOS prompt. > > eg > > C:\Windows> python some\path\to\myscript.py > > > That way you will still see the error message after the > program finishes. Or what about using IDLE? _________________________________________________________________ Express your personality in color! Preview and select themes for Hotmail?. http://www.windowslive-hotmail.com/LearnMore/personalize.aspx?ocid=PID23391::T:WLMTAGL:ON:WL:en-US:WM_HYGN_express:082009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Thu Aug 6 21:29:57 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 06 Aug 2009 14:29:57 -0500 Subject: [Tutor] Configuaration files and paths? In-Reply-To: <946488.25329.qm@web45608.mail.sp1.yahoo.com> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> Message-ID: <4A7B2F35.3050101@mwalsh.org> Allen Fowler wrote: > > > >>> What is the recommended way to configure my application find the various >> database and/or configuration files it needs? >> >> Recommemded by whom? A lot depends on the OS. Apple for example have one set of >> recommendations for MacOS, Windows has another and Linux has several to choose >> from! >> > > > Thank you.... good point. > > Planning on using a ConfigParser based .ini file located in the ./config folder. > >>> For instance my folder layout: >>> >>> /path_to_app/app.py >>> /path_to_app/lib/ >>> /path_to_app/database/ >>> /path_to_app/config/ >>> /path_to_app/photos >>> >>> .... and so on. I would like to make an .ini in the config folder >> Seems fair enough, however on a Unix system you should also consider allowing >> the user to have their own personalised version in their home directory. Thus at >> startup you get the current user ID / home directory and look for a suitable >> config file. If it exists read it, if not read the default one in your config >> directory. >> >>> 1) How does my main app file find the config file in the first place? >> Generally use a relative path so normally your app will run from its home folder >> so you can look in ./config. You might also set a system environment variable - >> for example the CLASSPATH or PYTHONPATH variables, or the ORACLE_HOME used by >> Oracle for their database. If the environment var is not set then look in >> ./config >> > > Assuming the application could be invoked in odd ways that may alter the notion of the current working directory, how do I unambiguously find the absolute path to the current python source file? (So I can load the nearby .ini) I use a helper function that calculates the absolute path of my app script, then I am able to os.path.join relative elements to my heart's content. I haven't had a problem with this approach so far, which of course doesn't mean it's the right way, or even a correct implementation for that matter. Something like this ... # lib/mypaths.py # -------------- import os def script_path(base): return os.path.realpath(os.path.abspath(base)) def script_dir(base): return os.path.dirname(script_path(base)) def join_relative(base, path): return os.path.join(script_dir(base), path) # app.py # ------ ... from lib.mypaths import join_relative print join_relative(__file__, 'config/prefs.ini') # this may work when calling from # other modules, I suppose (untested) import sys print join_relative(sys.argv[0], 'config/prefs.ini') ... HTH, Marty From srilyk at gmail.com Thu Aug 6 21:49:35 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 6 Aug 2009 14:49:35 -0500 Subject: [Tutor] monitor number of files in a folder In-Reply-To: References: Message-ID: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> On Thu, Aug 6, 2009 at 2:33 PM, pedro wrote: > Hi I am rendering image sequences on a basic render farm that I am > building. Once all the files in the sequence have been rendered I would like > to make a quicktime of the sequence automatically. The problem I am having > is that if one of the computers on the farm is rendering slow the quicktime > gets made before all the files are rendered. > > The variable below called "theNumberOfImages" is the actual # of images > that have been rendered which is working fine. > The variable below called "theNumberOfFrames" is the total # of images that > are supposed to be rendered. What I am trying to do but am not sure how is > to say: > As soon as theNumberOfImages is equal to or greater than theNumberOfFrames, > render the quicktime. > > Here is my very bad solution > > if theNumberOfImages <= theNumberOfFrames: > time.sleep(60) > if theNumberOfImages <= theNumberOfFrames: > time.sleep(60) > if theNumberOfImages <= theNumberOfFrames: > time.sleep(60) > else: > os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.sh') You really just want a while loop: while imagecount >= framecount: time.sleep(60) # Call script here I guess that's the easiest way. Probably not the most effective, but I'm not sure if the implementation of an alternate solution would be worth the cost. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Aug 6 22:20:26 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Aug 2009 16:20:26 -0400 Subject: [Tutor] easy way to populate a dict with functions In-Reply-To: <314582.78242.qm@web110716.mail.gq1.yahoo.com> References: <314582.78242.qm@web110716.mail.gq1.yahoo.com> Message-ID: <4A7B3B0A.5070606@gmail.com> Albert-Jan Roskam wrote: > Hi Bob, > > Very neat solution, thanks a lot! I didn't know the inspect module, but it's just what's needed here. Cool! Great. Regarding the ordering of functions in the list - variable names in namespaces (such as modules) are stored in dictionaries. Any ordering is lost in this process. Why is order important to you here? There are other things that could be said about your program and my revision. 1 - it is better to have functions return values and have the main program decide whether to print them or take some other action. (Also note you were not consistent - foo returns the others print!) 2 - since the list contains the function names as well as references to the functions you could present the names to the user. You could even ask the user to enter the first letter(s) of the names instead of a number. 3 - with a slight enhancement to things you can preserve the order: # -------- commands.py --------------- cmds = [] def collect(func): 'a "decorator" that adds each function to the cmds list' cmds.append((func.__name__, func)) @collect def foo (a): return "foo" * a @collect def bletch (q): for i in range(20): return i * q @collect def stilton (n): return "yes sir, " * n @collect def romans (z): return "what have the romans really done for us?\n" * z # -------- end code --------------- # -------- main.py --------------- import commands cmds = commands.cmds # etc. -- Bob Gailer Chapel Hill NC 919-636-4239 From annasophie at dautzenberg.org Thu Aug 6 21:08:55 2009 From: annasophie at dautzenberg.org (Anna - Sophie Maeser) Date: Thu, 6 Aug 2009 21:08:55 +0200 Subject: [Tutor] Noobish Syntay Error? Message-ID: <02B25B25-A722-474D-BFDD-614E511F814F@dautzenberg.org> Hi! I want to ask you a quick question.. when I type in print '' hello world'' and then press enter, it says there is a syntax error... I really don't know what im doing wrong. I downloaded python 3.1 and am using IDLE with it.. im using mac. Please help me findt he problem because its a very simple thing and I dont know what I am doing wrong.. -Anna From srilyk at gmail.com Thu Aug 6 22:33:02 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 6 Aug 2009 15:33:02 -0500 Subject: [Tutor] Fwd: Noobish Syntay Error? In-Reply-To: <333efb450908061332r37cce7afm4c22ca078f8b9ce0@mail.gmail.com> References: <02B25B25-A722-474D-BFDD-614E511F814F@dautzenberg.org> <333efb450908061332r37cce7afm4c22ca078f8b9ce0@mail.gmail.com> Message-ID: <333efb450908061333k6266b9a5n7b5d118698731df7@mail.gmail.com> Forgot reply-all ---------- Forwarded message ---------- From: Wayne Date: Thu, Aug 6, 2009 at 3:32 PM Subject: Re: [Tutor] Noobish Syntay Error? To: Anna - Sophie Maeser On Thu, Aug 6, 2009 at 2:08 PM, Anna - Sophie Maeser < annasophie at dautzenberg.org> wrote: > Hi! > I want to ask you a quick question.. when I type in print '' hello world'' > and then press enter, it says there is a syntax error... I really don't know > what im doing wrong. I downloaded python 3.1 There's your problem - downgrade to python 2.6 or type print('hello world') HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Thu Aug 6 22:37:32 2009 From: pedrooconnell at gmail.com (pedro) Date: Thu, 6 Aug 2009 16:37:32 -0400 Subject: [Tutor] monitor number of files in a folder References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> Message-ID: On 2009-08-06 15:49:35 -0400, Wayne said: > > > On Thu, Aug 6, 2009 at 2:33 PM, pedro wrote: > >> Hi I am rendering image sequences on a basic render farm that I am >> building. Once all the files in the sequence have been rendered I would like >> to make a quicktime of the sequence automatically. The problem I am having >> is that if one of the computers on the farm is rendering slow the quicktime >> gets made before all the files are rendered. >> >> The variable below called "theNumberOfImages" is the actual # of images >> that have been rendered which is working fine. >> The variable below called "theNumberOfFrames" is the total # of images that >> are supposed to be rendered. What I am trying to do but am not sure how is >> to say: >> As soon as theNumberOfImages is equal to or greater than theNumberOfFrames, >> render the quicktime. >> >> Here is my very bad solution >> >> if theNumberOfImages <= theNumberOfFrames: >> time.sleep(60) >> if theNumberOfImages <= theNumberOfFrames: >> time.sleep(60) >> if theNumberOfImages <= theNumberOfFrames: >> time.sleep(60) >> else: >> os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.sh') > > > You really just want a while loop: > > while imagecount >= framecount: > time.sleep(60) > > # Call script here > > I guess that's the easiest way. Probably not the most effective, but I'm not > sure if the implementation of an alternate solution would be worth the cost. > > HTH, > Wayne > > >

On Thu, Aug 6, 2009 at 2:33 PM, pedro pan dir=3D"ltr"><pedrooconnel= > l at gmail.com> wrote:
e=3D"border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; = > padding-left: 1ex;"> > > Hi I am rendering image sequences on a basic render farm that I am building= > . Once all the files in the sequence have been rendered I would like to mak= > e a quicktime of the sequence automatically. The problem I am having is tha= > t if one of the computers on the farm is rendering slow the quicktime gets = > made before all the files are rendered.
> > >
> The variable below called "theNumberOfImages" is the actual # of = > images that have been rendered which is working fine.
> The variable below called "theNumberOfFrames" is the total # of i= > mages that are supposed to be rendered. What I am trying to do but am not s= > ure how is to say:
> As soon as theNumberOfImages is equal to or greater than theNumberOfFrames,= > render the quicktime.
>
> Here is my very bad solution
>
> if theNumberOfImages <=3D theNumberOfFrames:
> =A0 time.sleep(60)
> =A0 if theNumberOfImages <=3D theNumberOfFrames:
> =A0 =A0 =A0 time.sleep(60)
> =A0 =A0 =A0 if theNumberOfImages <=3D theNumberOfFrames:
> =A0 =A0 =A0 =A0 =A0 time.sleep(60)
> else:
> =A0 os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.s= > h')

You really just want a=A0 while loop:
=A0 r>while imagecount >=3D framecount:
=A0=A0=A0 time.sleep(60)

#= > Call script here
> >
I guess that's the easiest way. Probably not the most effective, bu= > t I'm not sure if the implementation of an alternate solution would be = > worth the cost.

HTH,
Wayne

> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hi Wayne, but if I do it that way won't it create an infinite loop if the images don't all render? Pete From pedrooconnell at gmail.com Thu Aug 6 22:45:02 2009 From: pedrooconnell at gmail.com (pedro) Date: Thu, 6 Aug 2009 16:45:02 -0400 Subject: [Tutor] monitor number of files in a folder References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> Message-ID: On 2009-08-06 15:49:35 -0400, Wayne said: > > > On Thu, Aug 6, 2009 at 2:33 PM, pedro wrote: > >> Hi I am rendering image sequences on a basic render farm that I am >> building. Once all the files in the sequence have been rendered I would like >> to make a quicktime of the sequence automatically. The problem I am having >> is that if one of the computers on the farm is rendering slow the quicktime >> gets made before all the files are rendered. >> >> The variable below called "theNumberOfImages" is the actual # of images >> that have been rendered which is working fine. >> The variable below called "theNumberOfFrames" is the total # of images that >> are supposed to be rendered. What I am trying to do but am not sure how is >> to say: >> As soon as theNumberOfImages is equal to or greater than theNumberOfFrames, >> render the quicktime. >> >> Here is my very bad solution >> >> if theNumberOfImages <= theNumberOfFrames: >> time.sleep(60) >> if theNumberOfImages <= theNumberOfFrames: >> time.sleep(60) >> if theNumberOfImages <= theNumberOfFrames: >> time.sleep(60) >> else: >> os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.sh') > > > You really just want a while loop: > > while imagecount >= framecount: > time.sleep(60) > > # Call script here > > I guess that's the easiest way. Probably not the most effective, but I'm not > sure if the implementation of an alternate solution would be worth the cost. > > HTH, > Wayne > > >

On Thu, Aug 6, 2009 at 2:33 PM, pedro pan dir=3D"ltr"><pedrooconnel= > l at gmail.com> wrote:
e=3D"border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; = > padding-left: 1ex;"> > > Hi I am rendering image sequences on a basic render farm that I am building= > . Once all the files in the sequence have been rendered I would like to mak= > e a quicktime of the sequence automatically. The problem I am having is tha= > t if one of the computers on the farm is rendering slow the quicktime gets = > made before all the files are rendered.
> > >
> The variable below called "theNumberOfImages" is the actual # of = > images that have been rendered which is working fine.
> The variable below called "theNumberOfFrames" is the total # of i= > mages that are supposed to be rendered. What I am trying to do but am not s= > ure how is to say:
> As soon as theNumberOfImages is equal to or greater than theNumberOfFrames,= > render the quicktime.
>
> Here is my very bad solution
>
> if theNumberOfImages <=3D theNumberOfFrames:
> =A0 time.sleep(60)
> =A0 if theNumberOfImages <=3D theNumberOfFrames:
> =A0 =A0 =A0 time.sleep(60)
> =A0 =A0 =A0 if theNumberOfImages <=3D theNumberOfFrames:
> =A0 =A0 =A0 =A0 =A0 time.sleep(60)
> else:
> =A0 os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.s= > h')

You really just want a=A0 while loop:
=A0 r>while imagecount >=3D framecount:
=A0=A0=A0 time.sleep(60)

#= > Call script here
> >
I guess that's the easiest way. Probably not the most effective, bu= > t I'm not sure if the implementation of an alternate solution would be = > worth the cost.

HTH,
Wayne

> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I got it working but it seems little clunky. If I have a folder with 6 files in it, python will print out "waiting, still waiting, waiting, still waiting..." if I add 3 new file to the folder python prints "eight". This is the basic behaviour I want but is there a more pythonic way to write this. import os, time theFilesAsList = [] for anItem in os.listdir('/Volumes/sgtb/lac/comps/Z353_002/renders/Z353_002_comp/Z353_002_comp_v04/2048x1556'): if anItem[0] != ".": theFilesAsList.append(anItem) theNumberOfImages = len(theFilesAsList) while theNumberOfImages <= 8: print 'waiting' time.sleep(5) print 'still waiting' time.sleep(5) theFilesAsList = [] for anItem in os.listdir('/Volumes/sgtb/lac/comps/Z353_002/renders/Z353_002_comp/Z353_002_comp_v04/2048x1556'): if anItem[0] != ".": theFilesAsList.append(anItem) theNumberOfImages = len(theFilesAsList) print 'eight' From mwalsh at mwalsh.org Thu Aug 6 22:57:30 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 06 Aug 2009 15:57:30 -0500 Subject: [Tutor] Configuaration files and paths? In-Reply-To: <946488.25329.qm@web45608.mail.sp1.yahoo.com> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> Message-ID: <4A7B43BA.6090108@mwalsh.org> Allen Fowler wrote: > > > As a follow-up question, how do give my modules stored under ./lib access to the data in my ConfigParser object? (For instance, database connection string, storage path, etc.) > > I guess a global ConfigParser object would work, but that seems wrong. > And yet, to me it seems wrong to have more than one instance of config data floating around. Instead of using a global you can pass the config object, or just the appropriate attributes, around to your lib functions/classes, as necessary -- and keep the flow in your main script. For example (highly speculative, FWIW), # app.py from database.connection import getcursor from lib.persist import Storage def main(): confp = ConfigParser() confp.read(join_relative(__file__, 'config/prefs.ini')) config = confp.defaults() curs = getcursor(config[db_connection_string]) ... storage = Storage(config[storage_path]) ... HTH, Marty From davea at ieee.org Thu Aug 6 23:12:14 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Aug 2009 17:12:14 -0400 Subject: [Tutor] monitor number of files in a folder In-Reply-To: References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> Message-ID: <4A7B472E.5050603@ieee.org> pedro wrote: >
On > 2009-08-06 15:49:35 -0400, Wayne said: > >> >> >> On Thu, Aug 6, 2009 at 2:33 PM, pedro wrote: >> >>> Hi I am rendering image sequences on a basic render farm that I am >>> building. Once all the files in the sequence have been rendered I >>> would like >>> to make a quicktime of the sequence automatically. The problem I am >>> having >>> is that if one of the computers on the farm is rendering slow the >>> quicktime >>> gets made before all the files are rendered. >>> >>> The variable below called "theNumberOfImages" is the actual # of images >>> that have been rendered which is working fine. >>> The variable below called "theNumberOfFrames" is the total # of >>> images that >>> are supposed to be rendered. What I am trying to do but am not sure >>> how is >>> to say: >>> As soon as theNumberOfImages is equal to or greater than >>> theNumberOfFrames, >>> render the quicktime. >>> >>> Here is my very bad solution >>> >>> if theNumberOfImages <= theNumberOfFrames: >>> time.sleep(60) >>> if theNumberOfImages <= theNumberOfFrames: >>> time.sleep(60) >>> if theNumberOfImages <= theNumberOfFrames: >>> time.sleep(60) >>> else: >>> os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.sh') >> >> >> You really just want a while loop: >> >> while imagecount >= framecount: >> time.sleep(60) >> >> # Call script here >> >> I guess that's the easiest way. Probably not the most effective, but >> I'm not >> sure if the implementation of an alternate solution would be worth >> the cost. >> >> HTH, >> Wayne >> >> >>

On Thu, Aug 6, 2009 at 2:33 PM, >> pedro > pan dir=3D"ltr"><> href=3D"mailto:pedrooconnell at gmail.com">pedrooconnel= >> l at gmail.com> wrote:
> class=3D"gmail_quote" styl= >> e=3D"border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt >> 0.8ex; = >> padding-left: 1ex;"> >> >> Hi I am rendering image sequences on a basic render farm that I am >> building= >> . Once all the files in the sequence have been rendered I would like >> to mak= >> e a quicktime of the sequence automatically. The problem I am having >> is tha= >> t if one of the computers on the farm is rendering slow the quicktime >> gets = >> made before all the files are rendered.
>> >> >>
>> The variable below called "theNumberOfImages" is the actual >> # of = >> images that have been rendered which is working fine.
>> The variable below called "theNumberOfFrames" is the total >> # of i= >> mages that are supposed to be rendered. What I am trying to do but am >> not s= >> ure how is to say:
>> As soon as theNumberOfImages is equal to or greater than >> theNumberOfFrames,= >> render the quicktime.
>>
>> Here is my very bad solution
>>
>> if theNumberOfImages <=3D theNumberOfFrames:
>> =A0 time.sleep(60)
>> =A0 if theNumberOfImages <=3D theNumberOfFrames:
>> =A0 =A0 =A0 time.sleep(60)
>> =A0 =A0 =A0 if theNumberOfImages <=3D theNumberOfFrames:
>> =A0 =A0 =A0 =A0 =A0 time.sleep(60)
>> else:
>> =A0 >> os.system('/Volumes/sgtb/lac/common/temp/theQuicktimeCommandTest.s= >> h')

You really just want a=A0 while >> loop:
=A0> r>while imagecount >=3D framecount:
=A0=A0=A0 >> time.sleep(60)

#= >> Call script here
>> >>
I guess that's the easiest way. Probably not the most >> effective, bu= >> t I'm not sure if the implementation of an alternate solution >> would be = >> worth the cost.

HTH,
Wayne

>> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > Hi Wayne, but if I do it that way won't it create an infinite loop if > the images don't all render? > Pete > > > >
> (Please post as a text message when using mailing lists like this one. All that html junk clutters readability something awful.) You have to choose your poison. Your original approach (which you called "very bad") had the problem of only waiting 90 seconds max. Wayne's has the problem of waiting forever if some rendering aborts. So you need to choose how much of a timeout, and what you want to do when you exceed it. You also have the problem in this code that it's just checking variables, rather than calling a function that actually looks for the files. And finally, I think the comparison operator isn't quite right (if I understand your two variables anyway). Perhaps something like: timeoutcount = 0 while filecount() < framecount and timeoutcount < 10: timeoutcount += 1 time.sleep(30) if filecount() < framecount: print "you lose, because it took longer than ", timeoutcount /2, "minutes" else: os.system(....) From chase.mp at gmail.com Thu Aug 6 23:18:55 2009 From: chase.mp at gmail.com (chase pettet) Date: Thu, 6 Aug 2009 16:18:55 -0500 Subject: [Tutor] Looking up a value in a dictionary from user input problem Message-ID: I am trying to write a script to work our LVS implementation. I want to be able to have user do something like this "./script SITE SERVER" and have the script look up the ip value of the site on that server and issue the command to pull the status from LVS. I am almost there but for some reason when I try to pass the site parameter dynamically (the name of the dictionary) I keep getting errors about value type. I have two example that work where the dictionary name is hard coded to to speak in the script, and the value I want to pull is dynamic using sys.argv[1], and one where I'm trying to pass the dictionary name and it does not work. I tried to slim thse examples down, so hopefully they are helpful: works #1... ./script.py t #!/usr/bin/env python site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} def runBash(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out = p.stdout.read().strip() return out class LVS_Site: def show(self, site): showsite = "ipvsadm -L -t %s:443" % (site) showsiteresult = runBash(showsite) return showsiteresult a = LVS_Site() b = site["%s" % (sys.argv[1])] c = a.show(b) print "" print "" print "" print c works #2... ./script.py t #!/usr/bin/env python site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} def runBash(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out = p.stdout.read().strip() return out class LVS_Site: def show(self, site): showsite = "ipvsadm -L -t %s:443" % (site) showsiteresult = runBash(showsite) return showsiteresult a = LVS_Site() z = site b = z["%s" % (sys.argv[1])] c = a.show(b) print "" print "" print "" print c Not working... ./script.py t site #!/usr/bin/env python site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} def runBash(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out = p.stdout.read().strip() return out class LVS_Site: def show(self, site): showsite = "ipvsadm -L -t %s:443" % (site) showsiteresult = runBash(showsite) return showsiteresult a = LVS_Site() z = sys.argv[2] b = b["%s" % (sys.argv[1])] c = a.show(b) print "" print "" print "" print c Error: Traceback (most recent call last): File "./python2.py", line 22, in ? b = z["%s" % (sys.argv[1])] TypeError: string indices must be integers I don't understand why the third one does not work. Thanks for any help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Thu Aug 6 23:23:52 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 6 Aug 2009 23:23:52 +0200 Subject: [Tutor] monitor number of files in a folder In-Reply-To: <4A7B472E.5050603@ieee.org> References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> <4A7B472E.5050603@ieee.org> Message-ID: 2009/8/6 Dave Angel : > > You have to choose your poison. I prefer no poison. This is exactly what inotiy was made for and although I never used it there is a python module for it [1]. It would be great if you can post your experience with it. Greets Sander [1] http://trac.dbzteam.org/pyinotify/wiki From davea at ieee.org Thu Aug 6 23:29:03 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Aug 2009 17:29:03 -0400 Subject: [Tutor] Noobish Syntay Error? In-Reply-To: <02B25B25-A722-474D-BFDD-614E511F814F@dautzenberg.org> References: <02B25B25-A722-474D-BFDD-614E511F814F@dautzenberg.org> Message-ID: <4A7B4B1F.60505@ieee.org> Anna - Sophie Maeser wrote: >
Hi! > I want to ask you a quick question.. when I type in print '' hello > world'' and then press enter, it says there is a syntax error... I > really don't know what im doing wrong. I downloaded python 3.1 and am > using IDLE with it.. im using mac. > Please help me findt he problem because its a very simple thing and I > dont know what I am doing wrong.. > > -Anna > >
> Two syntax errors that I can see. 1) in python 3.1, print is a function, not a statement. So you need parentheses around its argument. 2) You appear to be using two single quotes at each end of your hello world string, You want to either use a single-quote at each end, or a double-quote at each end. This may just because you mistakenly used html to compose your email, instead of the preferred text mode. Try: print ("hello world") If your tutorial material is describing Python 2.x, you may not want to be learning on Python 3.1, because there are a few of these gotchas. It is possible to install both 2.6 and 3.1, and choose which one you use based on what you're working on. DaveA From vinces1979 at gmail.com Thu Aug 6 23:42:02 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 6 Aug 2009 15:42:02 -0600 Subject: [Tutor] Looking up a value in a dictionary from user input problem In-Reply-To: References: Message-ID: <1e53c510908061442w58f87358jdc352c201729cc0f@mail.gmail.com> On Thu, Aug 6, 2009 at 3:18 PM, chase pettet wrote: > I am trying to write a script to work our LVS implementation. I want to be > able to have user do something like this "./script SITE SERVER" and have > the script look up the ip value of the site on that server and issue the > command to pull the status from LVS. I am almost there but for some reason > when I try to pass the site parameter dynamically (the name of the > dictionary) I keep getting errors about value type. I have two example that > work where the dictionary name is hard coded to to speak in the script, and > the value I want to pull is dynamic using sys.argv[1], and one where I'm > trying to pass the dictionary name and it does not work. I tried to slim > thse examples down, so hopefully they are helpful: > > works #1... > > ./script.py t > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", > "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > b = site["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > works #2... > > ./script.py t > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", > "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > z = site > b = z["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > > Not working... > > ./script.py t site > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", > "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > z = sys.argv[2] > b = b["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > Error: > > Traceback (most recent call last): > File "./python2.py", line 22, in ? > b = z["%s" % (sys.argv[1])] > TypeError: string indices must be integers > > > I don't understand why the third one does not work. Thanks for any help! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > In your code z = sys.argv[2] which is a string think you want b = site[z] -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Thu Aug 6 23:43:01 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 6 Aug 2009 15:43:01 -0600 Subject: [Tutor] Looking up a value in a dictionary from user input problem In-Reply-To: <1e53c510908061442w58f87358jdc352c201729cc0f@mail.gmail.com> References: <1e53c510908061442w58f87358jdc352c201729cc0f@mail.gmail.com> Message-ID: <1e53c510908061443t1d49d682s6c7cfe05729ef439@mail.gmail.com> On Thu, Aug 6, 2009 at 3:42 PM, vince spicer wrote: > > > On Thu, Aug 6, 2009 at 3:18 PM, chase pettet wrote: > >> I am trying to write a script to work our LVS implementation. I want to >> be able to have user do something like this "./script SITE SERVER" and have >> the script look up the ip value of the site on that server and issue the >> command to pull the status from LVS. I am almost there but for some reason >> when I try to pass the site parameter dynamically (the name of the >> dictionary) I keep getting errors about value type. I have two example that >> work where the dictionary name is hard coded to to speak in the script, and >> the value I want to pull is dynamic using sys.argv[1], and one where I'm >> trying to pass the dictionary name and it does not work. I tried to slim >> thse examples down, so hopefully they are helpful: >> >> works #1... >> >> ./script.py t >> >> #!/usr/bin/env python >> site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", >> "s2":"10.1.1.5", "s3":"10.1.1.6"} >> >> def runBash(cmd): >> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) >> out = p.stdout.read().strip() >> return out >> >> class LVS_Site: >> def show(self, site): >> showsite = "ipvsadm -L -t %s:443" % (site) >> showsiteresult = runBash(showsite) >> return showsiteresult >> >> a = LVS_Site() >> b = site["%s" % (sys.argv[1])] >> c = a.show(b) >> print "" >> print "" >> print "" >> print c >> >> works #2... >> >> ./script.py t >> >> #!/usr/bin/env python >> site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", >> "s2":"10.1.1.5", "s3":"10.1.1.6"} >> >> def runBash(cmd): >> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) >> out = p.stdout.read().strip() >> return out >> >> class LVS_Site: >> def show(self, site): >> showsite = "ipvsadm -L -t %s:443" % (site) >> showsiteresult = runBash(showsite) >> return showsiteresult >> >> a = LVS_Site() >> z = site >> b = z["%s" % (sys.argv[1])] >> c = a.show(b) >> print "" >> print "" >> print "" >> print c >> >> >> Not working... >> >> ./script.py t site >> >> #!/usr/bin/env python >> site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", >> "s2":"10.1.1.5", "s3":"10.1.1.6"} >> >> def runBash(cmd): >> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) >> out = p.stdout.read().strip() >> return out >> >> class LVS_Site: >> def show(self, site): >> showsite = "ipvsadm -L -t %s:443" % (site) >> showsiteresult = runBash(showsite) >> return showsiteresult >> >> a = LVS_Site() >> z = sys.argv[2] >> b = b["%s" % (sys.argv[1])] >> c = a.show(b) >> print "" >> print "" >> print "" >> print c >> >> Error: >> >> Traceback (most recent call last): >> File "./python2.py", line 22, in ? >> b = z["%s" % (sys.argv[1])] >> TypeError: string indices must be integers >> >> >> I don't understand why the third one does not work. Thanks for any help! >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > In your code > > z = sys.argv[2] which is a string > > think you want > > b = site[z] > or even better b = site.get(z, None) if b is None: print "Not Found" -------------- next part -------------- An HTML attachment was scrubbed... URL: From airscorp at otenet.gr Thu Aug 6 23:43:34 2009 From: airscorp at otenet.gr (=?UTF-8?B?zp3Ouc66z4zOu86xzr/PgiDOoc6sz4DPhM63z4I=?=) Date: Fri, 07 Aug 2009 00:43:34 +0300 Subject: [Tutor] Looking up a value in a dictionary from user input problem In-Reply-To: References: Message-ID: <4A7B4E86.8080309@otenet.gr> Hmmm.. First of all.. In the non working code: .... a = LVS_Site() z = sys.argv[2] b = b["%s" % (sys.argv[1])] c = a.show(b) ..... Did you really mean b = b["%s" % (sys.argv[1])] or perhaps b = z["%s" % (sys.argv[1])] Also, I can't see why your doing the string formatting in there: b = z[sys.argv[1]] should work. Perhaps that's because you need it in the 'real' program? Nick chase pettet wrote: > I am trying to write a script to work our LVS implementation. I want > to be able to have user do something like this "./script SITE SERVER" > and have the script look up the ip value of the site on that server > and issue the command to pull the status from LVS. I am almost there > but for some reason when I try to pass the site parameter dynamically > (the name of the dictionary) I keep getting errors about value type. > I have two example that work where the dictionary name is hard coded > to to speak in the script, and the value I want to pull is dynamic > using sys.argv[1], and one where I'm trying to pass the dictionary > name and it does not work. I tried to slim thse examples down, so > hopefully they are helpful: > > works #1... > > ./script.py t > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", > "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > b = site["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > works #2... > > ./script.py t > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", > "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > z = site > b = z["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > > Not working... > > ./script.py t site > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", > "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > z = sys.argv[2] > b = b["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > Error: > > Traceback (most recent call last): > File "./python2.py", line 22, in ? > b = z["%s" % (sys.argv[1])] > TypeError: string indices must be integers > > > I don't understand why the third one does not work. Thanks for any help! > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From davea at ieee.org Thu Aug 6 23:56:21 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Aug 2009 17:56:21 -0400 Subject: [Tutor] Looking up a value in a dictionary from user input problem In-Reply-To: References: Message-ID: <4A7B5185.9080602@ieee.org> chase pettet wrote: > I am trying to write a script to work our LVS implementation. I want to be > able to have user do something like this "./script SITE SERVER" and have > the script look up the ip value of the site on that server and issue the > command to pull the status from LVS. I am almost there but for some reason > when I try to pass the site parameter dynamically (the name of the > dictionary) I keep getting errors about value type. I have two example that > work where the dictionary name is hard coded to to speak in the script, and > the value I want to pull is dynamic using sys.argv[1], and one where I'm > trying to pass the dictionary name and it does not work. I tried to slim > thse examples down, so hopefully they are helpful: > > --------- > > > Not working... > > ./script.py t site > > #!/usr/bin/env python > site = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", > "s2":"10.1.1.5", "s3":"10.1.1.6"} > > def runBash(cmd): > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > out = p.stdout.read().strip() > return out > > class LVS_Site: > def show(self, site): > showsite = "ipvsadm -L -t %s:443" % (site) > showsiteresult = runBash(showsite) > return showsiteresult > > a = LVS_Site() > z = sys.argv[2] > b = b["%s" % (sys.argv[1])] > c = a.show(b) > print "" > print "" > print "" > print c > > Error: > > Traceback (most recent call last): > File "./python2.py", line 22, in ? > b = z["%s" % (sys.argv[1])] > TypeError: string indices must be integers > > > I don't understand why the third one does not work. Thanks for any help! > > You didn't post the exact code, as the line that gives the error is quoted differently than it is. I suspect that the error message shows the version you actually tested. a = LVS_Site() z = sys.argv[2] at this point, z is a string, containing the characters "site" b = z["%s" % (sys.argv[1])] at this point, sys.argv[1] is a string, containing the character "t" So "s" % "t" is a string, containing the character "t" So you're trying to evaluate "site"["t"] And thus the error. Strings can be indexed only by integers, not by characters. It appears you're confusing the variable site with the string "site". The former is a dictionary, the latter is a string. Now, you could lookup that string in the current global namespace, and get the dictionary with that name. Something like (untested): b = globals().get(z, None) [ "%s" % (sys.argv[1])] But this is pretty dangerous territory. Perhaps if you tell us what you're actually trying to achieve, we might be able to help. For example, you might have a limited list of dictionaries, and want the user to be able to choose among them by keyword. site_HQ = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} site_Alternate = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} site_desperate = {"l":"10.1.1.1", "t":"10.1.1.2", "x":"10.1.1.3", "s1":"10.1.1.4", "s2":"10.1.1.5", "s3":"10.1.1.6"} sitelist = {"HQ":site_HQ, "Alternate", site_Alternate, "desperate":site_desperate} b = sitelist[sys.argv[2]] ["%s" % (sys.argv[1])] DaveA From davea at ieee.org Fri Aug 7 00:08:55 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Aug 2009 18:08:55 -0400 Subject: [Tutor] monitor number of files in a folder In-Reply-To: References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> <4A7B472E.5050603@ieee.org> Message-ID: <4A7B5477.9010709@ieee.org> Sander Sweers wrote: > 2009/8/6 Dave Angel : > >> You have to choose your poison. >> > > I prefer no poison. This is exactly what inotiy was made for and > although I never used it there is a python module for it [1]. It would > be great if you can post your experience with it. > > Greets > Sander > > [1] http://trac.dbzteam.org/pyinotify/wiki > > pyinotify solves an interesting problem, and if it worked on Windows, I already have a client with an application for it. But it has little to do with the OP's question. The problem the OP had was how to break out of a while loop, if the single condition never got satisfied. The simplest answer is to make a second condition (timeout), and use and. But that creates a second problem -- what to do if it did timeout. That's the poison he had to choose between. The time when pyinotify becomes very useful is if there are a large number of files/directories involved, and polling would be too slow. Presumably, the supported OS provides some event notification when a file is changed, and this module builds on that. DaveA From memilanuk at gmail.com Fri Aug 7 00:46:55 2009 From: memilanuk at gmail.com (Monte Milanuk) Date: Thu, 6 Aug 2009 15:46:55 -0700 Subject: [Tutor] clear screen inside python interpreter Message-ID: <6f26596c0908061546w538cca98s7be3bdb9a6241efe@mail.gmail.com> Okay, simple question: is there anything similar to to 'clear' or 'cls' to clean up a console window full of commands in the python shell? Short of exiting and restarting the interpreter I'm not having a lot of luck here. Thanks, Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From airscorp at otenet.gr Fri Aug 7 01:06:23 2009 From: airscorp at otenet.gr (Nick Raptis) Date: Fri, 07 Aug 2009 02:06:23 +0300 Subject: [Tutor] clear screen inside python interpreter In-Reply-To: <6f26596c0908061546w538cca98s7be3bdb9a6241efe@mail.gmail.com> References: <6f26596c0908061546w538cca98s7be3bdb9a6241efe@mail.gmail.com> Message-ID: <4A7B61EF.3080206@otenet.gr> I don't think there's a Python command to do this. You can always print enough newlines to clear your view of the window: print "\n" * 80 or use os.system to issue a command the shell/terminal/cmd will understand import os os.system("cls") or import os os.system("clear") I resently made a 'game of life' clone and used the first method to clear the screen. It's good enough for many things! Nick Monte Milanuk wrote: > Okay, simple question: is there anything similar to to 'clear' or > 'cls' to clean up a console window full of commands in the python > shell? Short of exiting and restarting the interpreter I'm not having > a lot of luck here. > > Thanks, > > Monte > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From allen.fowler at yahoo.com Fri Aug 7 01:23:55 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Thu, 6 Aug 2009 16:23:55 -0700 (PDT) Subject: [Tutor] Configuaration files and paths? In-Reply-To: <4A7B2F35.3050101@mwalsh.org> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B2F35.3050101@mwalsh.org> Message-ID: <835370.39181.qm@web45615.mail.sp1.yahoo.com> > > Assuming the application could be invoked in odd ways that may alter the > notion of the current working directory, how do I unambiguously find the > absolute path to the current python source file? (So I can load the nearby > .ini) > > I use a helper function that calculates the absolute path of my app > script, then I am able to os.path.join relative elements to my heart's > content. I haven't had a problem with this approach so far, which of > course doesn't mean it's the right way, or even a correct implementation > for that matter. > > Something like this ... > > # lib/mypaths.py > # -------------- > > import os > > def script_path(base): > return os.path.realpath(os.path.abspath(base)) > > def script_dir(base): > return os.path.dirname(script_path(base)) > > def join_relative(base, path): > return os.path.join(script_dir(base), path) > > # app.py > # ------ > > ... > > from lib.mypaths import join_relative > print join_relative(__file__, 'config/prefs.ini') > > # this may work when calling from > # other modules, I suppose (untested) > > import sys > print join_relative(sys.argv[0], 'config/prefs.ini') > That is really great. Thank you. I wonder why something like this is not in the standard library. Seems like an often needed function. From mindboggler12 at gmail.com Fri Aug 7 01:31:04 2009 From: mindboggler12 at gmail.com (jonathan wallis) Date: Thu, 6 Aug 2009 19:31:04 -0400 Subject: [Tutor] need help Message-ID: <57b8984c0908061631pae742e3j37311e24c7b001c2@mail.gmail.com> i am in the process of creating a simple python program, and i have come across a problem which i can not solve, here is the code *import pygame from pygame.locals import * from pygame.color import THECOLORS if not pygame.font: print 'Atention, there are no fonts.' if not pygame.mixer: print 'Atention, there is no sound.' pygame.init() blue = (0, 0, 255) red = (255, 0, 0) black = (0, 0, 0) window_width = 1280 window_height = 960 window = pygame.display.set_mode((window_width, window_height)) def circle_func(color, xpos, ypos, ray, movement_x, movment_y): circle = pygame.draw.circle(window, color, (xpos, ypos), ray) return circle circle = circle_func(red, 50, 50, 20, 3, 3) circle2 = circle_func(blue, 100, 100, 10, 3, 3) pygame.display.flip() pygame.key.set_repeat(1000, 100) while True: for event in pygame.event.get(): pass key_pressed = pygame.key.get_pressed() if key_pressed[K_LEFT]: xpos -= movement_x if key_pressed[K_RIGHT]: xpos += movement_x if key_pressed[K_UP]: ypos -= movement_y if key_pressed[K_DOWN]: ypos += movement_y window.fill(black) circle = circle_func(red, 50, 50, 20, 3, 3) circle2 = circle_func(blue, 100, 100, 10, 3, 3) pygame.display.flip()* when you try to move the circles with the left, right, down or up arrow keys it spits out an error saying "xpos is not defined" or "ypos is not defined" depending on if you hit the left/right or up/down keys, please show me what i am doing wrong! -------------- next part -------------- An HTML attachment was scrubbed... URL: From allen.fowler at yahoo.com Fri Aug 7 01:39:08 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Thu, 6 Aug 2009 16:39:08 -0700 (PDT) Subject: [Tutor] Configuaration files and paths? In-Reply-To: <4A7B43BA.6090108@mwalsh.org> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B43BA.6090108@mwalsh.org> Message-ID: <339938.50615.qm@web45615.mail.sp1.yahoo.com> > Martin Walsh > > Allen Fowler wrote: > > > > > > > As a follow-up question, how do give my modules stored under ./lib access to > the data in my ConfigParser object? (For instance, database connection string, > storage path, etc.) > > > > I guess a global ConfigParser object would work, but that seems wrong. > > > > And yet, to me it seems wrong to have more than one instance of config > data floating around. Instead of using a global you can pass the config > object, or just the appropriate attributes, around to your lib > functions/classes, as necessary -- and keep the flow in your main > script. For example (highly speculative, FWIW), > > # app.py > from database.connection import getcursor > from lib.persist import Storage > > def main(): > confp = ConfigParser() > confp.read(join_relative(__file__, 'config/prefs.ini')) > config = confp.defaults() > > curs = getcursor(config[db_connection_string]) > > ... > > storage = Storage(config[storage_path]) > > I hear your point. It makes sense. The above sample code seems like the way to go... if I can structure my modules like that. For an object that needs many settings, what about passing in an instance of ConfigParser? (Or should I extract the settings to a dict, first?) Thank you again, :) From airscorp at otenet.gr Thu Aug 6 23:25:50 2009 From: airscorp at otenet.gr (=?UTF-8?B?zp3Ouc66z4zOu86xzr/PgiDOoc6sz4DPhM63z4I=?=) Date: Fri, 07 Aug 2009 00:25:50 +0300 Subject: [Tutor] monitor number of files in a folder In-Reply-To: References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> Message-ID: <4A7B4A5E.6000808@otenet.gr> Well, os.listdir doesn't include "." or ".." anyway as you can see here So, just a simple len(os.listdir(my_directory)) will suffice.. A couple more points: -It's better looking and more readable (to me that means Pythonic) to store that ugly path to a variable first. -Whenever you see yourself repeating a chunk of code, make a function out of it! So, your program now is ------------------------------ import os, time my_directory = '/Volumes/sgtb/lac/comps/Z353_002/renders/Z353_002_comp/Z353_002_comp_v04/2048x1556' while len(os.listdir(my_directory)) <= 8: print 'waiting' time.sleep(5) print 'still waiting' time.sleep(5) print 'eight' ------------------------------- Nick (also, this is my first post) pedro wrote: > I got it working but it seems little clunky. If I have a folder with 6 > files in it, python will print out "waiting, still waiting, waiting, > still waiting..." if I add 3 new file to the folder python prints > "eight". This is the basic behaviour I want but is there a more > pythonic way to write this. > > > > import os, time > > theFilesAsList = [] > > for anItem in > os.listdir('/Volumes/sgtb/lac/comps/Z353_002/renders/Z353_002_comp/Z353_002_comp_v04/2048x1556'): > > > > if anItem[0] != ".": > theFilesAsList.append(anItem) > theNumberOfImages = len(theFilesAsList) > > while theNumberOfImages <= 8: > print 'waiting' > time.sleep(5) > print 'still waiting' > time.sleep(5) > theFilesAsList = [] > for anItem in > os.listdir('/Volumes/sgtb/lac/comps/Z353_002/renders/Z353_002_comp/Z353_002_comp_v04/2048x1556'): > > > > if anItem[0] != ".": > theFilesAsList.append(anItem) > theNumberOfImages = len(theFilesAsList) > print 'eight' > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From allen.fowler at yahoo.com Fri Aug 7 01:53:41 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Thu, 6 Aug 2009 16:53:41 -0700 (PDT) Subject: [Tutor] Configuaration files and paths? In-Reply-To: <4A7B2F35.3050101@mwalsh.org> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B2F35.3050101@mwalsh.org> Message-ID: <870768.43864.qm@web45601.mail.sp1.yahoo.com> > > Something like this ... > > # lib/mypaths.py > # -------------- > > import os > > def script_path(base): > return os.path.realpath(os.path.abspath(base)) > > def script_dir(base): > return os.path.dirname(script_path(base)) > > def join_relative(base, path): > return os.path.join(script_dir(base), path) > > # app.py > # ------ > > ... > > from lib.mypaths import join_relative > print join_relative(__file__, 'config/prefs.ini') > > # this may work when calling from > # other modules, I suppose (untested) > > import sys > print join_relative(sys.argv[0], 'config/prefs.ini') > > ... FWIW: When using relative paths I got extra ../../ terms, so I changed join_relative() to: def join_relative(base, path): return os.path.normpath(os.path.join(script_dir(base), path)) Seems to work... From alan.gauld at btinternet.com Fri Aug 7 02:40:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Aug 2009 01:40:00 +0100 Subject: [Tutor] noob question (Windows, Python 3.1) References: <7d15d3b40908060044y7da5bb8agee278b4e059ac5a1@mail.gmail.com> Message-ID: "Che M" wrote >>C:\Windows> python some\path\to\myscript.py > >> That way you will still see the error message after the >> program finishes. > > Or what about using IDLE? Good point, although IDLE can bring its own problems. But for this case IDLE would be a good choice. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/l2p From alan.gauld at btinternet.com Fri Aug 7 02:42:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Aug 2009 01:42:27 +0100 Subject: [Tutor] Configuaration files and paths? References: <883418.38051.qm@web45606.mail.sp1.yahoo.com><946488.25329.qm@web45608.mail.sp1.yahoo.com><4A7B43BA.6090108@mwalsh.org> <339938.50615.qm@web45615.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > For an object that needs many settings, what about passing > in an instance of ConfigParser? (Or should I extract the > settings to a dict, first?) Personally I usually extract an ini type settings to either global variables or an object or a dict at start up., I then pass that data around in my functions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 7 02:49:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Aug 2009 01:49:25 +0100 Subject: [Tutor] clear screen inside python interpreter References: <6f26596c0908061546w538cca98s7be3bdb9a6241efe@mail.gmail.com> Message-ID: "Monte Milanuk" wrote > Okay, simple question: is there anything similar to to 'clear' or 'cls' > to > clean up a console window full of commands in the python shell? Short of > exiting and restarting the interpreter I'm not having a lot of luck here. Terminal control is very system dependant. Fred Lundh did crate a platform independant console module that allowed cursor control and clearing of screens etc. Google should find it for you. But in your case os.system() or subprocess.call() are probably your best bet. or just print('\n' *100) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 7 02:53:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Aug 2009 01:53:51 +0100 Subject: [Tutor] need help References: <57b8984c0908061631pae742e3j37311e24c7b001c2@mail.gmail.com> Message-ID: "jonathan wallis" wrote > from pygame.locals import * > from pygame.color import THECOLORS > > if not pygame.font: > print 'Atention, there are no fonts.' > > if not pygame.mixer: > print 'Atention, there is no sound.' > > pygame.init() > > blue = (0, 0, 255) > red = (255, 0, 0) > black = (0, 0, 0) > > window_width = 1280 > window_height = 960 > > window = pygame.display.set_mode((window_width, window_height)) > > def circle_func(color, xpos, ypos, ray, movement_x, movment_y): > circle = pygame.draw.circle(window, color, (xpos, ypos), ray) > return circle > > key_pressed = pygame.key.get_pressed() > > if key_pressed[K_LEFT]: > xpos -= movement_x > > if key_pressed[K_DOWN]: > ypos += movement_y > when you try to move the circles with the left, right, down or up arrow > keys > it spits out an error saying "xpos is not defined" or "ypos is not > defined" So where do you think you define xpos and ypos? You cannot use them until you define them by assigning a value. xpos -= movement_x is just shorthand for xpos = xpos - movement_x You cannot use xpos on the right before you give it an initial value. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tim at johnsons-web.com Fri Aug 7 02:47:39 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 6 Aug 2009 16:47:39 -0800 Subject: [Tutor] regex problem with colon Message-ID: <20090807004739.GE499@johnsons-web.com> using python 2.5. I'm having a problem with including a colon as part of a substring bounded by whitespace or beginning of line. Here's an example: p = re.compile(r'\bcc:\b',re.IGNORECASE) >>> res = p.findall('malicious cc: here CC: there') >>> res [] ## Darn! I'd hope that the 'cc:' and 'CC:' substrings would be found. So how to compose the expression correctly? TIA -- Tim tim at johnsons-web.com http://www.akwebsoft.com From mwalsh at mwalsh.org Fri Aug 7 03:46:46 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 06 Aug 2009 20:46:46 -0500 Subject: [Tutor] Configuaration files and paths? In-Reply-To: <870768.43864.qm@web45601.mail.sp1.yahoo.com> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B2F35.3050101@mwalsh.org> <870768.43864.qm@web45601.mail.sp1.yahoo.com> Message-ID: <4A7B8786.8060702@mwalsh.org> Allen Fowler wrote: > > > >> Something like this ... >> >> # lib/mypaths.py >> # -------------- >> >> import os >> >> def script_path(base): >> return os.path.realpath(os.path.abspath(base)) >> >> def script_dir(base): >> return os.path.dirname(script_path(base)) >> >> def join_relative(base, path): >> return os.path.join(script_dir(base), path) >> >> # app.py >> # ------ >> >> ... >> >> from lib.mypaths import join_relative >> print join_relative(__file__, 'config/prefs.ini') >> >> # this may work when calling from >> # other modules, I suppose (untested) >> >> import sys >> print join_relative(sys.argv[0], 'config/prefs.ini') >> >> ... > > > FWIW: > > When using relative paths I got extra ../../ terms, so I changed join_relative() to: > > def join_relative(base, path): > return os.path.normpath(os.path.join(script_dir(base), path)) > > > Seems to work... Yeah, good catch ... looks great, and thanks for sharing your mod. Marty From mwalsh at mwalsh.org Fri Aug 7 03:47:24 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 06 Aug 2009 20:47:24 -0500 Subject: [Tutor] Configuaration files and paths? In-Reply-To: <339938.50615.qm@web45615.mail.sp1.yahoo.com> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B43BA.6090108@mwalsh.org> <339938.50615.qm@web45615.mail.sp1.yahoo.com> Message-ID: <4A7B87AC.5040609@mwalsh.org> Allen Fowler wrote: > > >> Martin Walsh >> > >> Allen Fowler wrote: >>> As a follow-up question, how do give my modules stored under ./lib access to >> the data in my ConfigParser object? (For instance, database connection string, >> storage path, etc.) >>> I guess a global ConfigParser object would work, but that seems wrong. >>> >> And yet, to me it seems wrong to have more than one instance of config >> data floating around. Instead of using a global you can pass the config >> object, or just the appropriate attributes, around to your lib >> functions/classes, as necessary -- and keep the flow in your main >> script. For example (highly speculative, FWIW), >> >> # app.py >> from database.connection import getcursor >> from lib.persist import Storage >> >> def main(): >> confp = ConfigParser() >> confp.read(join_relative(__file__, 'config/prefs.ini')) >> config = confp.defaults() >> >> curs = getcursor(config[db_connection_string]) >> >> ... >> >> storage = Storage(config[storage_path]) >> >> > > > I hear your point. It makes sense. > > > The above sample code seems like the way to go... if I can structure my modules like that. > > For an object that needs many settings, what about passing in an instance of ConfigParser? (Or should I extract the settings to a dict, first?) > > Thank you again, > :) > I don't see a problem with either of those approaches -- I suppose it depends a little on the kind of config data you're working with, the overall design of your app, which approach would be easiest to maintain. If your intent is to package software that the general public will use, then I believe Alan and Dave have correctly advised to follow the packaging conventions for your target platform(s), and to be consistent with user expectations (ie. how do popular apps typically handle config?) I tend to write a lot of system automation scripts (sysadmin-style), where I'm one of the few internal end users, and my toolbox module contains wrappers for the various sources of config data (configparser, optparse, os.environ, etc) each providing a common interface that I like to use (and remember easily!) for dealing with config data in new function and class definitions. But I use these a lot, and wouldn't necessarily recommend the approach if you only need to consume config data now and again. I think the point I may be trying to make is that it took me a while to settle, after much trial and error, to find the approach that works best for me -- others will have a different story to tell, and I hope they do! :) Good luck! Marty From kent37 at tds.net Fri Aug 7 04:12:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 6 Aug 2009 22:12:05 -0400 Subject: [Tutor] regex problem with colon In-Reply-To: <20090807004739.GE499@johnsons-web.com> References: <20090807004739.GE499@johnsons-web.com> Message-ID: <1c2a2c590908061912j12b67968ycce269a440cc54e3@mail.gmail.com> On Thu, Aug 6, 2009 at 8:47 PM, Tim Johnson wrote: > using python 2.5. > I'm having a problem with including a colon as part of a substring > bounded by whitespace or beginning of line. > Here's an example: > p = re.compile(r'\bcc:\b',re.IGNORECASE) >>>> res = p.findall('malicious cc: here CC: there') >>>> res > [] > ## Darn! I'd hope that the 'cc:' and 'CC:' substrings would be > found. So how to compose the expression correctly? The problem is that : is not a "word" character, so there is no word boundary between : and space for \b to match. How about this: In [9]: p = re.compile(r'\bcc:',re.IGNORECASE) In [10]: p.findall('malicious cc: here CC: there') Out[10]: ['cc:', 'CC:'] Kent From tim at johnsons-web.com Fri Aug 7 05:37:06 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 6 Aug 2009 19:37:06 -0800 Subject: [Tutor] regex problem with colon In-Reply-To: <1c2a2c590908061912j12b67968ycce269a440cc54e3@mail.gmail.com> References: <20090807004739.GE499@johnsons-web.com> <1c2a2c590908061912j12b67968ycce269a440cc54e3@mail.gmail.com> Message-ID: <20090807033706.GF499@johnsons-web.com> * Kent Johnson [090806 18:31]: > On Thu, Aug 6, 2009 at 8:47 PM, Tim Johnson wrote: > > using python 2.5. > > I'm having a problem with including a colon as part of a substring > > bounded by whitespace or beginning of line. > > Here's an example: > > p = re.compile(r'\bcc:\b',re.IGNORECASE) > >>>> res = p.findall('malicious cc: here CC: there') > >>>> res > > [] > > ## Darn! I'd hope that the 'cc:' and 'CC:' substrings would be > > found. So how to compose the expression correctly? > > The problem is that : is not a "word" character, so there is no word > boundary between : and space for \b to match. How about this: > In [9]: p = re.compile(r'\bcc:',re.IGNORECASE) Yes. You nailed it Kent. I had grokked the logic but not entirely the syntax. I'm looking thru docs now. Just curious .. is there a flag that enables adding a ':' to the internal list of "word" characters? > In [10]: p.findall('malicious cc: here CC: there') > Out[10]: ['cc:', 'CC:'] thanks again. -- Tim tim at johnsons-web.com http://www.akwebsoft.com From kent37 at tds.net Fri Aug 7 13:20:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 7 Aug 2009 07:20:10 -0400 Subject: [Tutor] regex problem with colon In-Reply-To: <20090807033706.GF499@johnsons-web.com> References: <20090807004739.GE499@johnsons-web.com> <1c2a2c590908061912j12b67968ycce269a440cc54e3@mail.gmail.com> <20090807033706.GF499@johnsons-web.com> Message-ID: <1c2a2c590908070420j27428591g69a8ca6ff1d5036e@mail.gmail.com> On Thu, Aug 6, 2009 at 11:37 PM, Tim Johnson wrote: > ?Yes. You nailed it Kent. > ?I had grokked the logic but not entirely the syntax. > ?I'm looking thru docs now. Just curious .. is there a flag that > ?enables adding a ':' to the internal list of "word" characters? No. The list is affected by UNICODE and LOCALE flags but you can't add to it explicitly. Kent From pedrooconnell at gmail.com Fri Aug 7 18:29:43 2009 From: pedrooconnell at gmail.com (pedro) Date: Fri, 7 Aug 2009 12:29:43 -0400 Subject: [Tutor] monitor number of files in a folder References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> <4A7B4A5E.6000808@otenet.gr> Message-ID: On 2009-08-06 17:25:50 -0400, ???????? ?????? said: > Well, os.listdir doesn't include "." or ".." anyway as you can see here On my machine (a Mac), os.listdir does include files that begin with "." Having the while loop timeout after 10 or 20 times through as was suggested a couple posts back will work fine for my particular situation. Thanks From allen.fowler at yahoo.com Fri Aug 7 22:19:36 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Fri, 7 Aug 2009 13:19:36 -0700 (PDT) Subject: [Tutor] Configuaration files and paths? In-Reply-To: <4A7B8786.8060702@mwalsh.org> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B2F35.3050101@mwalsh.org> <870768.43864.qm@web45601.mail.sp1.yahoo.com> <4A7B8786.8060702@mwalsh.org> Message-ID: <988495.89094.qm@web45615.mail.sp1.yahoo.com> > > > > FWIW: > > > > When using relative paths I got extra ../../ terms, so I changed > join_relative() to: > > > > def join_relative(base, path): > > return os.path.normpath(os.path.join(script_dir(base), path)) > > > > > > Seems to work... > > > Yeah, good catch ... looks great, and thanks for sharing your mod. > Glad I could return the favor. :) Since then, I took it a bit further for use in my code... I am not finished with it yet, but am curios what you think. (I am not sure named things right or structured it logically....) ################### import os class HomePath(object): """For finding paths based on a home/install directory. """ def __init__(self, home_dir = None, home_file = None): """Must be called with either a path to a directory or, as a shortcut, a file in that directory. """ if home_file != None: # Set home based on a path to a file in its directory self.home = os.path.normpath(self.fix_path(home_file)) elif home_dir != None: # Set home based on its path self.home = os.path.normpath(self.get_dir(home_dir)) else: raise Exception("Must call with either a path to a directory or, as a shortcut, a file in that directory.") def abs(self, rel_from_home): """Return an absolute path when passed a path relative to home. """ return self.join_relative(self.home, rel_from_home) def fix_path(self, base): return os.path.realpath(os.path.abspath(base)) def get_dir(self, base): return os.path.dirname(self.fix_path(base)) def join_relative(self, base, path): return os.path.normpath(self.fix_path(os.path.join(self.home, path))) ############################# From davidkim05 at gmail.com Fri Aug 7 23:35:46 2009 From: davidkim05 at gmail.com (David Kim) Date: Fri, 7 Aug 2009 17:35:46 -0400 Subject: [Tutor] building database with sqlite3 and matplotlib Message-ID: Hello everyone, I've been learning python in a vacuum for the past few months and I was wondering whether anyone would be willing to take a look at some code? I've been messing around with sqlite and matplotlib, but I couldn't get all the string substitution (using ?s). I ended up getting the script to work, but i stupidly didn't save the version of the script that I thought would work but didn't. (did that make sense?). The code can be found at http://notestoself.posterous.com/use-python-and-sqlite3-to-build-a-database-co A short summary of what I did is at http://notestoself.posterous.com/use-python-and-sqlite3-to-build-a-database (Or should I have pasted the code in this message?) I've been trying to learn from books, but some critique would be very appreciated. I'm just trying to get a sense of whether I'm doing things in a unnecessarily convoluted way. -- morenotestoself.wordpress.com From tim at johnsons-web.com Sat Aug 8 04:18:57 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 7 Aug 2009 18:18:57 -0800 Subject: [Tutor] Overriding MySQLdb.cursors.DictCursor.execute() Message-ID: <20090808021857.GK499@johnsons-web.com> Hello: I am currently using python 2.5 and do a lot of database programming with MySQLdb. I have developed a wrapper class that uses two cursors: 1)a MySQLdb.cursors.DictCursor object 2)a MySQLdb.cursors.Cursor object #1 returning a dictionary from query results, #2 returning a tuple from query results - :) but you all know that. I need to tighten up control over queries since I am concerned about malicious injections. It would seem to me that overriding the execute() methods for both objects would entail the least amount of code maintenance and modification. I've used python for a long time, but not done much with object inheritance. The following code: class mysql_row_cursor(MySQLdb.cursors.DictCursor): def __init__(self): pass # results in the following error message: class mysql_row_cursor(MySQLdb.cursors.DictCursor): AttributeError: 'module' object has no attribute 'cursors' # say what? MySQLdb has been imported... I would welcome both comments on why I am getting this error message and whether my original thinking is correct. thanks -- forever and always a noob -- -- Tim tim at johnsons-web.com http://www.akwebsoft.com From marky1991 at gmail.com Sat Aug 8 04:31:02 2009 From: marky1991 at gmail.com (Mark Young) Date: Fri, 7 Aug 2009 22:31:02 -0400 Subject: [Tutor] this module Message-ID: Hi, I was reading a tutorial, and it mentioned the "import this" easter egg. I was curious, and looked up the contents of the module, and dscovered that it had attributes c, d, i, and s. I was wondering if anyone had any clue what these attributes were supposed to mean. I think (this.s) is the zen of python in some foreign language (dutch maybe?), but I have no clue what the significance of the others are. Just wondering if anyone knew, (or if they mean anything at all). Also, I was wondering, when a user first imports this, how does the module print the zen of python? I can't figure out how it does it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Sat Aug 8 09:10:56 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 8 Aug 2009 02:10:56 -0500 Subject: [Tutor] this module In-Reply-To: References: Message-ID: <200908080210.56838.cfuller084@thinkingplanet.net> On Friday 07 August 2009 21:31, Mark Young wrote: > Hi, I was reading a tutorial, and it mentioned the "import this" easter > egg. I was curious, and looked up the contents of the module, and dscovered > that it had attributes c, d, i, and s. I was wondering if anyone had any > clue what these attributes were supposed to mean. I think (this.s) is the > zen of python in some foreign language (dutch maybe?), but I have no clue > what the significance of the others are. Just wondering if anyone knew, (or > if they mean anything at all). > > Also, I was wondering, when a user first imports this, how does the module > print the zen of python? I can't figure out how it does it. "Use the source, Luke!" You can find this.py, along with the rest of the standard library (most of which is written in Python, as opposed to being compiled C code) wherever your Python was installed. For instance, /usr/lib/pythonx.y on unixy machines (including macs), and C:\Pythonxy\Lib on that other operating system. Cheers From alan.gauld at btinternet.com Sat Aug 8 09:37:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Aug 2009 08:37:29 +0100 Subject: [Tutor] this module References: Message-ID: "Mark Young" wrote > I was curious, and looked up the contents of the module, and dscovered > that > it had attributes c, d, i, and s. I was wondering if anyone had any clue > what these attributes were supposed to mean. Mostly they are just variables used to construct the message. The values are the fibnal values of loops etc. > I think (this.s) is the zen of python in some foreign language (dutch > maybe?), No, its not Dutch, its a caesar encrypted version of the zen and the variable d holds the translation table. > significance of the others are. Just wondering if anyone knew, (or if > they > mean anything at all). Just look at the source of the module in this.py, its in the Libs folder > Also, I was wondering, when a user first imports this, how does the > module > print the zen of python? I can't figure out how it does it. It builds the table then it applies it to the encrypted string. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cfuller084 at thinkingplanet.net Sat Aug 8 09:35:33 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 8 Aug 2009 02:35:33 -0500 Subject: [Tutor] this module In-Reply-To: References: Message-ID: <200908080235.33585.cfuller084@thinkingplanet.net> Something else to note: you can find any module's location by looking it up in the dictionary sys.modules. For instance: Python 2.4.4 (#2, Oct 22 2008, 19:52:44) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! >>> import sys >>> sys.modules['this'] Cheers From kent37 at tds.net Sat Aug 8 14:51:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 8 Aug 2009 08:51:05 -0400 Subject: [Tutor] Overriding MySQLdb.cursors.DictCursor.execute() In-Reply-To: <20090808021857.GK499@johnsons-web.com> References: <20090808021857.GK499@johnsons-web.com> Message-ID: <1c2a2c590908080551j4abcc30etf635113a91a602d8@mail.gmail.com> On Fri, Aug 7, 2009 at 10:18 PM, Tim Johnson wrote: > Hello: > I am currently using python 2.5 and do a lot of database programming > with MySQLdb. > > I need to tighten up control over queries since I am concerned about > malicious injections. If you use the two argument form of cursor.execute - passing the parameter values in a sequence, rather than substituting them yourself - then you have to worry about injection attacks. The DB-API module should take care of any required escaping. > It would seem to me that overriding the execute() methods for both > objects would entail the least amount of code maintenance and > modification. I've used python for a long time, but not done much > with object inheritance. > The following code: > class mysql_row_cursor(MySQLdb.cursors.DictCursor): > ? ? ? ?def __init__(self): > ? ? ? ? ? ? ? ? ? ? ? ?pass > # results in the following error message: > ? ?class mysql_row_cursor(MySQLdb.cursors.DictCursor): > ? ? ? ?AttributeError: 'module' object has no attribute 'cursors' > # say what? MySQLdb has been imported... You have to explicitly import subpackages. Try import MySQLdb.cursors Kent From davea at ieee.org Sat Aug 8 15:51:36 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 08 Aug 2009 09:51:36 -0400 Subject: [Tutor] this module In-Reply-To: References: Message-ID: <4A7D82E8.3030503@ieee.org> Mark Young wrote: > Hi, I was reading a tutorial, and it mentioned the "import this" easter egg. > I was curious, and looked up the contents of the module, and dscovered that > it had attributes c, d, i, and s. I was wondering if anyone had any clue > what these attributes were supposed to mean. I think (this.s) is the zen of > python in some foreign language (dutch maybe?), but I have no clue what the > significance of the others are. Just wondering if anyone knew, (or if they > mean anything at all). > > Also, I was wondering, when a user first imports this, how does the module > print the zen of python? I can't figure out how it does it. > > Each module runs when you import it. So if there are print statements that are not either inside definitions, classes or conditionals, you'll see their output. As for this.py, take a look at it. The "dutch" is actually an encoding currently popularly referred to as ROT13, a substitution cipher where each letter is replaced by the one halfway (13 characters) around the alphabet. If you look at d, you'll see it's a dictionary with the mapping between 'a' and 'o', 'b' and 'p', and so on. DaveA From tim at johnsons-web.com Sat Aug 8 17:38:23 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 8 Aug 2009 07:38:23 -0800 Subject: [Tutor] Overriding MySQLdb.cursors.DictCursor.execute() In-Reply-To: <1c2a2c590908080551j4abcc30etf635113a91a602d8@mail.gmail.com> References: <20090808021857.GK499@johnsons-web.com> <1c2a2c590908080551j4abcc30etf635113a91a602d8@mail.gmail.com> Message-ID: <20090808153823.GL499@johnsons-web.com> * Kent Johnson [090808 05:06]: > On Fri, Aug 7, 2009 at 10:18 PM, Tim Johnson wrote: > > If you use the two argument form of cursor.execute - passing the > parameter values in a sequence, rather than substituting them yourself > - then you have to worry about injection attacks. The DB-API module > should take care of any required escaping. Oh! Good to hear. Never use the two argument form. > > You have to explicitly import subpackages. Try > import MySQLdb.cursors Understood. And now probably now not necessary. thanks -- Tim tim at johnsons-web.com http://www.akwebsoft.com From kent37 at tds.net Sat Aug 8 20:28:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 8 Aug 2009 14:28:15 -0400 Subject: [Tutor] building database with sqlite3 and matplotlib In-Reply-To: References: Message-ID: <1c2a2c590908081128j182d4a1ah7e01387bc39ecf2b@mail.gmail.com> On Fri, Aug 7, 2009 at 5:35 PM, David Kim wrote: > I've been learning python in a vacuum for the past few months and I > was wondering whether anyone would be willing to take a look at some > code? I've been messing around with sqlite and matplotlib, but I > couldn't get all the string substitution (using ?s). > The code can be found at > http://notestoself.posterous.com/use-python-and-sqlite3-to-build-a-database-co > A short summary of what I did is at > http://notestoself.posterous.com/use-python-and-sqlite3-to-build-a-database > > (Or should I have pasted the code in this message?) No, it's a bit long for that. pastebin.com is another option that doesn't require others to download the code. > I've been trying to learn from books, but some critique would be very > appreciated. Mostly it looks pretty good. sql = "select asset_id from assets where ticker='%s'" % ticker #change this! c.execute(sql) Try (I think, I don't have DB-API docs at the moment...) sql = "select asset_id from assets where ticker='?'" c.execute(sql, [ticker]) date_raw = datetime.datetime.fromordinal(int(quote[0])) year, month, day = date_raw.year, date_raw.month, date_raw.day date_string = str(year)+'-'+str(month)+'-'+str(day) See datetime.strptime() for simpler date formatting marks = len(data_dict['headers'])*'?,' marks_string = marks[:-1] or marks = ','.join(['?'] * len(data_dict['headers'])) if (__name__ == '__main__'): main() You don't seem to actually have a main(). Are you running this by importing it? I would make a separate function to create the database and call that from build_database(). Kent From paras80 at gmail.com Sat Aug 8 20:33:33 2009 From: paras80 at gmail.com (Paras K.) Date: Sat, 8 Aug 2009 14:33:33 -0400 Subject: [Tutor] How to Split a String Message-ID: What I am trying to do is find the mail folder for our lotus notes files. I get it by doing the following: lotusnotesmaildir = glob.glob('C:\Documents and Settings/pkinariwala/Local Settings/Application Data/lotus/notes/data/'+'*mail*/') That returns: ['C:\\Documents and Settings/pkinariwala/Local Settings/Application Data/lotus/notes/data\\mail02\\'] What I am trying to do is split the mail folder, in this case it would be mail02, but not all users would have that same mail folder. How can I split it so I get mail02. Any help in greatly appreciated. Thanx, -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 8 21:42:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Aug 2009 20:42:41 +0100 Subject: [Tutor] How to Split a String References: Message-ID: "Paras K." wrote > lotusnotesmaildir = glob.glob('C:\Documents and > Settings/pkinariwala/Local > Settings/Application Data/lotus/notes/data/'+'*mail*/') You don't need the plus. lotusnotesmaildir = glob.glob('C:\Documents and Settings/pkinariwala/Local Settings/Application Data/lotus/notes/data/'*mail*/') > That returns: ['C:\\Documents and Settings/pkinariwala/Local > Settings/Application Data/lotus/notes/data\\mail02\\'] Are you sure it isn't ['C:\\Documents and Settings\\pkinariwala\\Local Settings\\Application Data/lotus\\notes\\data\\mail02\\'] > What I am trying to do is split the mail folder, in this case it would be > mail02, but not all users would have that same mail folder. If so then you can use var[0].split('\\')[-1] to get the last item. You might also find the path manipulation and basename functions useful for mamnipulating paths. Especially if you need to do it on multiple different computers/OS. These are in the os/os.path module family. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sat Aug 8 22:28:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 8 Aug 2009 16:28:22 -0400 Subject: [Tutor] How to Split a String In-Reply-To: References: Message-ID: <1c2a2c590908081328y2c5e9cc2r7b6f147e3f0d3841@mail.gmail.com> On Sat, Aug 8, 2009 at 2:33 PM, Paras K. wrote: > What I am trying to do is find the mail folder for our lotus notes files. > > I get it by doing the following: > > lotusnotesmaildir = glob.glob('C:\Documents and Settings/pkinariwala/Local > Settings/Application Data/lotus/notes/data/'+'*mail*/') > > That returns: ['C:\\Documents and Settings/pkinariwala/Local > Settings/Application Data/lotus/notes/data\\mail02\\'] > > What I am trying to do is split the mail folder, in this case it would be > mail02, but not all users would have that same mail folder. See os.path.basename() Kent From davidkim05 at gmail.com Sat Aug 8 21:15:55 2009 From: davidkim05 at gmail.com (David Kim) Date: Sat, 8 Aug 2009 15:15:55 -0400 Subject: [Tutor] building database with sqlite3 and matplotlib In-Reply-To: <1c2a2c590908081128j182d4a1ah7e01387bc39ecf2b@mail.gmail.com> References: <1c2a2c590908081128j182d4a1ah7e01387bc39ecf2b@mail.gmail.com> Message-ID: Thanks so much for the comments! I appreciate the look. It's hard to know what the best practices are (or if they even exist). On Sat, Aug 8, 2009 at 2:28 PM, Kent Johnson wrote: > > You don't seem to actually have a main(). Are you running this by importing > it? > > I would make a separate function to create the database and call that > from build_database(). > I was running it as a standalone to see if it worked but forgot to move the code to main(). I cut but never pasted! -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Sun Aug 9 00:33:13 2009 From: pedrooconnell at gmail.com (pedro) Date: Sat, 8 Aug 2009 18:33:13 -0400 Subject: [Tutor] droplet like behaviour in Python Message-ID: Hi I am porting some of my code over from Applescript to Python. There is one thing I am not really sure how to do. I want to be able to drop a file onto a python script (or app I guess) and have the python script use the path to the file that was dropped on it as sys.argv[1] In applescript it looks like this: on open theNukeScript tell application "Terminal" activate tell application "Terminal" do script "python /Volumes/rugged/programming/python/bin/nkDoesFileExist.py " & theNukeScript --etc.... Where theNukeScript is the path to of the file that was dropped. I am hoping to make the code cross platform. Any advice would be greatly appreciated. Pete From alan.gauld at btinternet.com Sun Aug 9 01:34:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Aug 2009 00:34:44 +0100 Subject: [Tutor] droplet like behaviour in Python References: Message-ID: "pedro" wrote > is one thing I am not really sure how to do. I want to be able to drop > a file onto a python script (or app I guess) and have the python script > use the path to the file that was dropped on it as sys.argv[1] I may be wrong but I thought that, provided you had the path and shebang etc set up properly that it just happened. Have you tried a simpe script that just prints argv say? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marky1991 at gmail.com Sun Aug 9 03:15:44 2009 From: marky1991 at gmail.com (Mark Young) Date: Sat, 8 Aug 2009 21:15:44 -0400 Subject: [Tutor] this module In-Reply-To: <4A7D82E8.3030503@ieee.org> References: <4A7D82E8.3030503@ieee.org> Message-ID: Thanks everybody, I didn't know modules ran code when you imported them, I just thought they defined the functions, etc. in them. Thanks for the info. I'm going to go look at the module's code now that I know where it's at. Mark Young -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 9 09:29:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Aug 2009 08:29:55 +0100 Subject: [Tutor] this module References: <4A7D82E8.3030503@ieee.org> Message-ID: "Mark Young" wrote > Thanks everybody, I didn't know modules ran code when you imported them, > I > just thought they defined the functions, etc. in them. They do that too. But in Python a function definition is created by running the code! So you write def foo(): return 42 To define foo you need to execute those two lines of code. The result is that you create a function object. So when you import a moduile it runs all of the code in there, and most of the code usually consists of function and variable definitions. But it can be anything at all. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From malathiramya at gmail.com Sun Aug 9 10:07:08 2009 From: malathiramya at gmail.com (malathi selvaraj) Date: Sun, 9 Aug 2009 13:37:08 +0530 Subject: [Tutor] hi everyone! Message-ID: i am new one to this programming language. i like to learn python,what i do? what i do to learn python in proper manner. -- Regards, S.Malathi. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Aug 9 12:44:08 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 09 Aug 2009 06:44:08 -0400 Subject: [Tutor] this module In-Reply-To: References: <4A7D82E8.3030503@ieee.org> Message-ID: <4A7EA878.8040706@gmail.com> Alan Gauld wrote: > > "Mark Young" wrote > >> Thanks everybody, I didn't know modules ran code when you imported >> them, I >> just thought they defined the functions, etc. in them. > > They do that too. > But in Python a function definition is created by running the code! > > So you write > > def foo(): > return 42 > > To define foo you need to execute those two lines of code. > The result is that you create a function object. > > So when you import a moduile it runs all of the code in there Almost. It runs all the top-level code. def foo(): print 3 def foo(): will run, defining the function foo print 3 will NOT run unless some other top-level code CALLs foo such as foo() > most of the code usually consists of function and variable and class > definitions. > But it can be anything at all. > Note also that "usually" is very hard to measure unless you read and or write many many modules. -- Bob Gailer Chapel Hill NC 919-636-4239 From mwalsh at mwalsh.org Sun Aug 9 21:07:05 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sun, 09 Aug 2009 14:07:05 -0500 Subject: [Tutor] Configuaration files and paths? In-Reply-To: <988495.89094.qm@web45615.mail.sp1.yahoo.com> References: <883418.38051.qm@web45606.mail.sp1.yahoo.com> <946488.25329.qm@web45608.mail.sp1.yahoo.com> <4A7B2F35.3050101@mwalsh.org> <870768.43864.qm@web45601.mail.sp1.yahoo.com> <4A7B8786.8060702@mwalsh.org> <988495.89094.qm@web45615.mail.sp1.yahoo.com> Message-ID: <4A7F1E59.3090502@mwalsh.org> Allen Fowler wrote: >>> FWIW: >>> >>> When using relative paths I got extra ../../ terms, so I changed >> join_relative() to: >>> def join_relative(base, path): >>> return os.path.normpath(os.path.join(script_dir(base), path)) >>> >>> >>> Seems to work... >> >> Yeah, good catch ... looks great, and thanks for sharing your mod. >> > > > Glad I could return the favor. :) > > Since then, I took it a bit further for use in my code... I am not finished with it yet, but am curios what you think. (I am not sure named things right or structured it logically....) > > > ################### > > import os > class HomePath(object): > """For finding paths based on a home/install directory. > > """ > > def __init__(self, home_dir = None, home_file = None): > """Must be called with either a path to a directory or, as a shortcut, a file in that directory. > > """ > > if home_file != None: > # Set home based on a path to a file in its directory > self.home = os.path.normpath(self.fix_path(home_file)) > > elif home_dir != None: > # Set home based on its path > self.home = os.path.normpath(self.get_dir(home_dir)) > > else: > raise Exception("Must call with either a path to a directory or, as a shortcut, a file in that directory.") > > def abs(self, rel_from_home): > """Return an absolute path when passed a path relative to home. > > """ > > return self.join_relative(self.home, rel_from_home) > > def fix_path(self, base): > return os.path.realpath(os.path.abspath(base)) > > def get_dir(self, base): > return os.path.dirname(self.fix_path(base)) > > def join_relative(self, base, path): > return os.path.normpath(self.fix_path(os.path.join(self.home, path))) > ############################# I'm not sure I understand your end goal, given the args to __init__. I'd guess, perhaps incorrectly, that you may be trying to shoehorn conflicting purposes. If your only aim is to calculate an absolute path to a resource's parent, or home, folder then your class can be simplified a lot, IMHO. Specifically, I don't see a reason to differentiate between home_dir and home_file. Please feel free to clarify if I'm missing the point. import os class HomePath(object): def __init__(self, path): # fix_path and get_dir on base path self.home = os.path.dirname( os.path.realpath( os.path.abspath(path) ) ) def join(self, relative_path): return os.path.normpath(os.path.join(self.home, relative_path)) Also, have a look at http://docs.python.org/library/os.path.html#os.path.abspath ... the main point is that your initial path element must have enough information in it to construct an abspath, otherwise os.getcwd() can pollute the calculation. I believe if you use __file__ you're good, and sys.argv[0], while potentially relative in nature should always be relative to os.getcwd() AFAICT, so you're good there too. Otherwise avoid constructing a HomePath object with a relative start path. HTH, Marty From alan.gauld at btinternet.com Mon Aug 10 00:43:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Aug 2009 23:43:46 +0100 Subject: [Tutor] hi everyone! References: Message-ID: "malathi selvaraj" wrote >i am new one to this programming language. Hello and welcome. > what i do to learn python in proper manner. First of all make sure you download Python v2.6 rather than v3. v3 is not ideal for learning just yet it is still rather new. Do you know any other programming language? If so go to the official tutorial on the python web site (or download the docs) and work through it. That should be enough to get you started. Ask questions here, show us the code and any errors you get (in full) http://docs.python.org/tutorial/ If this is your first programming language then well done, you made a good choice! :-) Go to here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers pick a tutorial(not the official one!) and work through it. Every time you get stuck - and you will, so don't worry - send a question here explaining what is bugging you and any code plus error messages. (It also helps to mention the Python version, the OS and the tutorial you are using) Either way have fun. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pedrooconnell at gmail.com Mon Aug 10 02:58:17 2009 From: pedrooconnell at gmail.com (pedro) Date: Sun, 9 Aug 2009 20:58:17 -0400 Subject: [Tutor] droplet like behaviour in Python References: Message-ID: On 2009-08-08 19:34:44 -0400, "Alan Gauld" said: > > "pedro" wrote > > >> is one thing I am not really sure how to do. I want to be able to drop >> a file onto a python script (or app I guess) and have the python script >> use the path to the file that was dropped on it as sys.argv[1] > > I may be wrong but I thought that, provided you had the path and > shebang etc set up properly that it just happened. Have you tried > a simpe script that just prints argv say? Well I made a script called droplet.py which looks like this: #!/usr/bin/env python # encoding: utf-8 import sys theFilePath = sys.argv[1] print theFilePath But when I try to drop something on it nothing happens. Sorry I guess there is something fundamental that I am missing. Pete From alan.gauld at btinternet.com Mon Aug 10 09:52:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Aug 2009 08:52:37 +0100 Subject: [Tutor] droplet like behaviour in Python References: Message-ID: "pedro" wrote > Well I made a script called droplet.py which looks like this: > > #!/usr/bin/env python > # encoding: utf-8 > import sys > theFilePath = sys.argv[1] > print theFilePath > > > But when I try to drop something on it nothing happens. Sorry I guess > there is something fundamental that I am missing. Sorry, obviously I was wrong. FWIW in XP I get python to start up but there is no filename in argv. I'll go and have a hunt in my MacOS books but sadly I don't have my iBook available just now to try anything. Alan G. From srilyk at gmail.com Mon Aug 10 14:54:30 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 10 Aug 2009 07:54:30 -0500 Subject: [Tutor] droplet like behaviour in Python In-Reply-To: References: Message-ID: <333efb450908100554p3bbd7300q683349259d8e55a7@mail.gmail.com> On Mon, Aug 10, 2009 at 2:52 AM, Alan Gauld wrote: > "pedro" wrote > >> Well I made a script called droplet.py which looks like this: >> >> #!/usr/bin/env python >> # encoding: utf-8 >> import sys >> theFilePath = sys.argv[1] >> print theFilePath >> >> >> But when I try to drop something on it nothing happens. Sorry I guess >> there is something fundamental that I am missing. >> > > Sorry, obviously I was wrong. FWIW in XP I get python to start up but there > is no filename in argv. > I'll go and have a hunt in my MacOS books but sadly I don't have my iBook > available just now to try anything. I'm not sure if this will be of any help: http://docs.python.org/library/carbon.html http://sourceforge.net/projects/appscript/ But that's all I could come up with, without a mac or a whole lot of experience with a mac. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Aug 10 15:49:51 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Aug 2009 09:49:51 -0400 Subject: [Tutor] droplet like behaviour in Python In-Reply-To: References: Message-ID: <4A80257F.6040004@gmail.com> Alan Gauld wrote: > "pedro" wrote >> Well I made a script called droplet.py which looks like this: >> >> #!/usr/bin/env python >> # encoding: utf-8 >> import sys >> theFilePath = sys.argv[1] >> print theFilePath >> >> >> But when I try to drop something on it nothing happens. Sorry I guess >> there is something fundamental that I am missing. > > Sorry, obviously I was wrong. FWIW in XP I get python to start up but > there is no filename in argv. That depends on the file association settings for .py. Start -> Settings -> Control Panel -> Folder Options -> File Types Find py extension. Click Advanced Choose open Click Edit in my system I see "H:\Python30\python.exe" "%1" %* which means fire up python.exe, pass the dropped file name as the first argument. BTW a nice 1 python line version independent droplet: #!/usr/bin/env python # encoding: utf-8 input(__import__('sys').argv) -- Bob Gailer Chapel Hill NC 919-636-4239 From rick at niof.net Mon Aug 10 19:08:41 2009 From: rick at niof.net (Rick Pasotto) Date: Mon, 10 Aug 2009 13:08:41 -0400 Subject: [Tutor] MySQLdb field type Message-ID: <20090810170840.GA8169@niof.net> After executing a query that returns values, cursor.description contains a list of tuples, one tuple for each field. Each tuple has seven values consisting of (name,type_code,display_size,internal_size,precision,scale,null_ok). Where can I find a listing of what the various type_codes are? Do I need to experiment and make my own list? -- "As empty vessels make the loudest sound, so they that have the least wit are the greatest blabbers." -- Plato Rick Pasotto rick at niof.net http://www.niof.net From kent37 at tds.net Mon Aug 10 20:50:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Aug 2009 14:50:01 -0400 Subject: [Tutor] MySQLdb field type In-Reply-To: <20090810170840.GA8169@niof.net> References: <20090810170840.GA8169@niof.net> Message-ID: <1c2a2c590908101150t574ab3f9vcc11bb3a448b14f8@mail.gmail.com> On Mon, Aug 10, 2009 at 1:08 PM, Rick Pasotto wrote: > After executing a query that returns values, cursor.description contains > a list of tuples, one tuple for each field. Each tuple has seven values > consisting of (name,type_code,display_size,internal_size,precision,scale,null_ok). > > Where can I find a listing of what the various type_codes are? Do I need > to experiment and make my own list? See the section "Type Objects and Constructors" in the DB-API spec: http://dinsdale.python.org/dev/peps/pep-0249/ Kent From rick at niof.net Mon Aug 10 21:52:52 2009 From: rick at niof.net (Rick Pasotto) Date: Mon, 10 Aug 2009 15:52:52 -0400 Subject: [Tutor] MySQLdb field type In-Reply-To: <1c2a2c590908101150t574ab3f9vcc11bb3a448b14f8@mail.gmail.com> References: <20090810170840.GA8169@niof.net> <1c2a2c590908101150t574ab3f9vcc11bb3a448b14f8@mail.gmail.com> Message-ID: <20090810195252.GB8169@niof.net> On Mon, Aug 10, 2009 at 02:50:01PM -0400, Kent Johnson wrote: > On Mon, Aug 10, 2009 at 1:08 PM, Rick Pasotto wrote: > > After executing a query that returns values, cursor.description contains > > a list of tuples, one tuple for each field. Each tuple has seven values > > consisting of (name,type_code,display_size,internal_size,precision,scale,null_ok). > > > > Where can I find a listing of what the various type_codes are? Do I need > > to experiment and make my own list? > > See the section "Type Objects and Constructors" in the DB-API spec: > http://dinsdale.python.org/dev/peps/pep-0249/ Not exactly what I'm looking for. The type_code in the tuple is a number. For one of my tables I see the following numbers: 1, 2, 10, 252, 253, 254. What I wanted was a listing telling me which number was which type_code. -- "The dichotomy between personal liberties and property rights is a false one. Property does not have rights. People have rights. ... In fact, a fundamental interdependence exists between the personal right to liberty and the personal right to property." -- Potter Stewart, U.S. Supreme Court Justice, Lynch v. Household Finance Corp., 1972 Rick Pasotto rick at niof.net http://www.niof.net From alan.gauld at btinternet.com Mon Aug 10 23:13:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Aug 2009 22:13:40 +0100 Subject: [Tutor] Tutorial update Message-ID: Just a note to say that the v3.1 version of my tutor has reached another milestone. I just uploaded the last topic in the Basics section which means the tutorial is now sufficiently complete that it could be used by a beginner to learn V3 Python. It hasn't had enough traffic to call it good quality yet - I'm sure there are lots of mistakes to find - but its definitely useable. The remaining two sections will progress and my usual snails pace :-( Then I might get started on finishing the remaining topics in the Applications section - andmaybe even add a few more new ones!. Enjoy, Alan G. From alan.gauld at btinternet.com Mon Aug 10 23:36:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Aug 2009 22:36:49 +0100 Subject: [Tutor] Tutorial update References: Message-ID: "Alan Gauld" wrote > I just uploaded the last topic in the Basics section which means the > tutorial is now sufficiently complete that it could be used by a > beginner to learn V3 Python. > And the v3 url is, of course: -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From allen.fowler at yahoo.com Tue Aug 11 00:34:38 2009 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 10 Aug 2009 15:34:38 -0700 (PDT) Subject: [Tutor] Fixing "nearly ASCII" data file? Message-ID: <157520.41763.qm@web45607.mail.sp1.yahoo.com> Hello, I have some CSV data from Office / OpenOffice in "nearly ASCII" format. This is just basic text but it it stored as UTF-8, and has curly quotes, etc. Is there a way to easily read the file as ASCII by forcing these to the standard ASCII equivalents? Thank you From jkrukoff at ltgc.com Tue Aug 11 00:56:26 2009 From: jkrukoff at ltgc.com (John Krukoff) Date: Mon, 10 Aug 2009 16:56:26 -0600 Subject: [Tutor] Fixing "nearly ASCII" data file? In-Reply-To: <157520.41763.qm@web45607.mail.sp1.yahoo.com> References: <157520.41763.qm@web45607.mail.sp1.yahoo.com> Message-ID: <1249944986.1475.10.camel@localhost.localdomain> On Mon, 2009-08-10 at 15:34 -0700, Allen Fowler wrote: > Hello, > > I have some CSV data from Office / OpenOffice in "nearly ASCII" format. This is just basic text but it it stored as UTF-8, and has curly quotes, etc. > > Is there a way to easily read the file as ASCII by forcing these to the standard ASCII equivalents? > > Thank you I found this library "ASCII, Dammit", from the author of Beautiful Soup, to be a good starting point when I had to write my own force to ASCII conversion routine, maybe it'll work for you too: http://www.crummy.com/cgi-bin/msm/map.cgi/ASCII%2C+Dammit -- John Krukoff Land Title Guarantee Company From alan.gauld at btinternet.com Tue Aug 11 01:12:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Aug 2009 00:12:20 +0100 Subject: [Tutor] Fixing "nearly ASCII" data file? References: <157520.41763.qm@web45607.mail.sp1.yahoo.com> Message-ID: "Allen Fowler" wrote > I have some CSV data from Office / OpenOffice in "nearly ASCII" format. > This is just basic text but it it stored as UTF-8, and has curly quotes, > etc. > > Is there a way to easily read the file as ASCII by forcing these to the > standard ASCII equivalents? You should be able to process it using the string translation methods with a one to one conversion. try help(''.translate) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Tue Aug 11 01:22:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Aug 2009 19:22:03 -0400 Subject: [Tutor] MySQLdb field type In-Reply-To: <20090810195252.GB8169@niof.net> References: <20090810170840.GA8169@niof.net> <1c2a2c590908101150t574ab3f9vcc11bb3a448b14f8@mail.gmail.com> <20090810195252.GB8169@niof.net> Message-ID: <1c2a2c590908101622m5f82462fof676aa29e5dd96c3@mail.gmail.com> On Mon, Aug 10, 2009 at 3:52 PM, Rick Pasotto wrote: > Not exactly what I'm looking for. > > The type_code in the tuple is a number. For one of my tables I see the > following numbers: 1, 2, 10, 252, 253, 254. What I wanted was a listing > telling me which number was which type_code. Ah, right. I guess this will vary for different db modules. Which one are you using? Kent From jeff at drinktomi.com Tue Aug 11 01:15:34 2009 From: jeff at drinktomi.com (Jeff Younker) Date: Mon, 10 Aug 2009 16:15:34 -0700 Subject: [Tutor] monitor number of files in a folder In-Reply-To: References: <333efb450908061249r2cc7bc3bnb2c8c64b856af725@mail.gmail.com> <4A7B4A5E.6000808@otenet.gr> Message-ID: On Aug 7, 2009, at 9:29 AM, pedro wrote: > On my machine (a Mac), os.listdir does include files that begin with > "." Having the while loop timeout after 10 or 20 times through as > was suggested a couple posts back will work fine for my particular > situation. > Thanks Yes, it does include files that begin with '.', but it does not include the entries '.' and '..'. -jeff From davea at ieee.org Tue Aug 11 04:40:14 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 10 Aug 2009 22:40:14 -0400 Subject: [Tutor] droplet like behaviour in Python In-Reply-To: <4A80257F.6040004@gmail.com> References: <4A80257F.6040004@gmail.com> Message-ID: <4A80DA0E.70901@ieee.org> bob gailer wrote: >
Alan > Gauld wrote: >> "pedro" wrote >>> Well I made a script called droplet.py which looks like this: >>> >>> #!/usr/bin/env python >>> # encoding: utf-8 >>> import sys >>> theFilePath = sys.argv[1] >>> print theFilePath >>> >>> >>> But when I try to drop something on it nothing happens. Sorry I >>> guess there is something fundamental that I am missing. >> >> Sorry, obviously I was wrong. FWIW in XP I get python to start up but >> there is no filename in argv. > > That depends on the file association settings for .py. > Start -> Settings -> Control Panel -> Folder Options -> File Types > Find py extension. > Click Advanced > Choose open > Click Edit > in my system I see "H:\Python30\python.exe" "%1" %* > which means fire up python.exe, pass the dropped file name as the > first argument. > > BTW a nice 1 python line version independent droplet: > #!/usr/bin/env python > # encoding: utf-8 > input(__import__('sys').argv) > > Unfortunately, you're not describing a droplet, but only the usual Windows file association scheme. (Incidentally, the OP was asking about the Mac) The filename that goes into the %1 of the shortcut is the name of the script. So that will show up in sys.argv[0]. The OP wanted to drop a data file, and have its name show up as sys.argv[1]. I don't know the Mac, so I stayed out of this thread. But I haven't found any way to do real Python droplets on Windows. Closest I found was adding my python app to the right-click menu, so one can right-click on a data file to get the Python code to run on it. What a droplet needs is for the user to be able to drag a data file to a python script, and have the script start, with sys.argv[1] pointing to the data file. I'd love to know how to do it in Windows, and the OP would love to know how to do it on the Mac. DaveA From pedrooconnell at gmail.com Tue Aug 11 07:09:28 2009 From: pedrooconnell at gmail.com (pedro) Date: Tue, 11 Aug 2009 01:09:28 -0400 Subject: [Tutor] droplet like behaviour in Python References: <4A80257F.6040004@gmail.com> <4A80DA0E.70901@ieee.org> Message-ID: On 2009-08-10 22:40:14 -0400, Dave Angel said: > bob gailer wrote: >>
Alan >> Gauld wrote: >>> "pedro" wrote >>>> Well I made a script called droplet.py which looks like this: >>>> >>>> #!/usr/bin/env python >>>> # encoding: utf-8 >>>> import sys >>>> theFilePath = sys.argv[1] >>>> print theFilePath >>>> >>>> >>>> But when I try to drop something on it nothing happens. Sorry I >>>> guess there is something fundamental that I am missing. >>> >>> Sorry, obviously I was wrong. FWIW in XP I get python to start up but >>> there is no filename in argv. >> >> That depends on the file association settings for .py. >> Start -> Settings -> Control Panel -> Folder Options -> File Types >> Find py extension. >> Click Advanced >> Choose open >> Click Edit >> in my system I see "H:\Python30\python.exe" "%1" %* >> which means fire up python.exe, pass the dropped file name as the >> first argument. >> >> BTW a nice 1 python line version independent droplet: >> #!/usr/bin/env python >> # encoding: utf-8 >> input(__import__('sys').argv) >> >> > Unfortunately, you're not describing a droplet, but only the usual > Windows file association scheme. (Incidentally, the OP was asking about > the Mac) > > The filename that goes into the %1 of the shortcut is the name of the > script. So that will show up in sys.argv[0]. The OP wanted to drop a > data file, and have its name show up as sys.argv[1]. > > I don't know the Mac, so I stayed out of this thread. But I haven't > found any way to do real Python droplets on Windows. Closest I found > was adding my python app to the right-click menu, so one can right-click > on a data file to get the Python code to run on it. > > What a droplet needs is for the user to be able to drag a data file to a > python script, and have the script start, with sys.argv[1] pointing to > the data file. I'd love to know how to do it in Windows, and the OP > would love to know how to do it on the Mac. > > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Exactly, thanks for clarifying Dave. Pete From pedrooconnell at gmail.com Tue Aug 11 07:16:39 2009 From: pedrooconnell at gmail.com (pedro) Date: Tue, 11 Aug 2009 01:16:39 -0400 Subject: [Tutor] run python script on another computer's terminal (LAN) Message-ID: Hi, does anyone know how to send a command that is within a python script to another computer's terminal. This is what it looks like in Applescript. tell application "Terminal" of machine "eppc://USERNAME:PASSWORD at COMPUTER2.local" do script "ls" end tell I basically want os.system('ls') to be run on another computer in my LAN. Merci Pete From fomcl at yahoo.com Tue Aug 11 09:35:42 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Aug 2009 00:35:42 -0700 (PDT) Subject: [Tutor] easy way to populate a dict with functions In-Reply-To: <4A7B3B0A.5070606@gmail.com> Message-ID: <187026.99539.qm@web110711.mail.gq1.yahoo.com> Hi Bob, Sorry for the late reply, but thank you for your code. I still haven't completely wrappped my brain around decorator functions, but thanks to your reply at least now my frontal lobe is touching it. ;-) Re: the ordering of functions: I thought it mattered because the inspect module returns a list of two-tuples (in this case, a list of four two-tuples). Therefore, e.g. option #1 should always cause the same function to be run. But apparently I'm wrong here somewhere. Best wishes, Albert-Jan Netherlands --- On Thu, 8/6/09, bob gailer wrote: > From: bob gailer > Subject: Re: [Tutor] easy way to populate a dict with functions > To: "Albert-Jan Roskam" > Cc: "tutorpythonmailinglist Python" > Date: Thursday, August 6, 2009, 10:20 PM > Albert-Jan Roskam wrote: > > Hi Bob, > > > > Very neat solution, thanks a lot! I didn't know the > inspect module, but it's just what's needed here. Cool! > > Great. > > Regarding the ordering of functions in the list - variable > names in namespaces (such as modules) are stored in > dictionaries. Any ordering is lost in this process. Why is > order important to you here? > > There are other things that could be said about your > program and my revision. > > 1 - it is better to have functions return values and have > the main program decide whether to print them or take some > other action. (Also note you were not consistent - foo > returns the others print!) > > 2 - since the list contains the function names as well as > references to the functions you could present the names to > the user. You could even ask the user to enter the first > letter(s) of the names instead of a number. > > 3 - with a slight enhancement to things you can preserve > the order: > > # -------- commands.py --------------- > cmds = [] > def collect(func): > 'a "decorator" that adds each function to the cmds list' > cmds.append((func.__name__, func)) > > @collect > def foo (a): > return "foo" * a > > @collect > def bletch (q): > for i in range(20): > ? return i * q > > @collect > def stilton (n): > return "yes sir, " * n > > @collect > def romans (z): > return "what have the romans really done for us?\n" * z > > # -------- end code --------------- > > # -------- main.py --------------- > import commands > cmds = commands.cmds > > # etc. > > -- Bob Gailer > Chapel Hill NC > 919-636-4239 > From alan.gauld at btinternet.com Tue Aug 11 11:27:19 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Aug 2009 10:27:19 +0100 Subject: [Tutor] run python script on another computer's terminal (LAN) References: Message-ID: "pedro" wrote > Hi, does anyone know how to send a command that is within a python > script to another computer's terminal. This is what it looks like in > Applescript. > > tell application "Terminal" of machine > "eppc://USERNAME:PASSWORD at COMPUTER2.local" > do script "ls" > end tell > You might be better asking these kind of questions on the MacPython mailing lists/forums since more folks there will be familiar with what are fairly MacOS specific issues. Also you can get Python to talk to Applescript which might be the easiest way... However in a general sense you can use ssh (or rsh?) to do that. You might also be able to avoid using subprocess or os.system by mounting the remote filesystem? That would let you you os.listdir() on the remote machine? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From prasadaraon50 at gmail.com Tue Aug 11 11:24:20 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 11 Aug 2009 14:54:20 +0530 Subject: [Tutor] To write data in two different fonts? Message-ID: <9e3fac840908110224l478b6b4fs307c5f684e5ee02@mail.gmail.com> Hello I am wtriting some dat on to a file in which headings should be of different size than other data. Is it possible?If possible please tell me how to do it. def sc(adir): import os,myfiles dest=open('C:/scripts.txt','w') s=myfiles.myfiles(adir) for x in s: if os.path.isfile(x): sorce=open(x,'r') data=sorce.readlines() dest.write(x+'\n','bold') dest.write(('-'*len(x))+'\n') for l in data: dest.write(l) sorce.close() else:pass dest.close() >>> sc('C:\Python26\mscripts') Traceback (most recent call last): File "", line 1, in sc('C:\Python26\mscripts') File "", line 9, in sc dest.write(x+'\n','bold') TypeError: function takes exactly 1 argument (2 given) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Aug 11 12:50:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Aug 2009 06:50:34 -0400 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <9e3fac840908110224l478b6b4fs307c5f684e5ee02@mail.gmail.com> References: <9e3fac840908110224l478b6b4fs307c5f684e5ee02@mail.gmail.com> Message-ID: <1c2a2c590908110350l6bb6a444p2e902c5511bbe768@mail.gmail.com> On Tue, Aug 11, 2009 at 5:24 AM, prasad rao wrote: > Hello > ???? I am wtriting some dat on to a file in which > headings should be of different size than other data. > Is it possible?If possible please tell me how to do it. > > > > def sc(adir): > ????? import os,myfiles > ????? dest=open('C:/scripts.txt','w') > ????? s=myfiles.myfiles(adir) > ????? for x in s: > ???????????? if os.path.isfile(x): > ???????????????? sorce=open(x,'r') > ???????????????? data=sorce.readlines() > ???????????????? dest.write(x+'\n','bold') > > ???????????????? dest.write(('-'*len(x))+'\n') > ???????????????? for l in data: > ???????????????????? ?dest.write(l) > ???????????????? sorce.close() > ?????????? else:pass > ?? dest.close() Plain text files don't have style information. You have to write structured data such as HTML or PDF. HTML is probably the simplest. Kent From davea at ieee.org Tue Aug 11 13:03:27 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 11 Aug 2009 07:03:27 -0400 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <9e3fac840908110224l478b6b4fs307c5f684e5ee02@mail.gmail.com> References: <9e3fac840908110224l478b6b4fs307c5f684e5ee02@mail.gmail.com> Message-ID: <4A814FFF.4020404@ieee.org> prasad rao wrote: > Hello > I am wtriting some dat on to a file in which > headings should be of different size than other data. > Is it possible?If possible please tell me how to do it. > > > > def sc(adir): > import os,myfiles > dest=open('C:/scripts.txt','w') > s=myfiles.myfiles(adir) > for x in s: > if os.path.isfile(x): > sorce=open(x,'r') > data=sorce.readlines() > dest.write(x+'\n','bold') > > dest.write(('-'*len(x))+'\n') > for l in data: > dest.write(l) > sorce.close() > else:pass > dest.close() > > > >>>> sc('C:\Python26\mscripts') >>>> > > Traceback (most recent call last): > File "", line 1, in > sc('C:\Python26\mscripts') > File "", line 9, in sc > dest.write(x+'\n','bold') > TypeError: function takes exactly 1 argument (2 given) > > > > I figure you're asking two questions here. First is the syntax error. All you need to do to fix that is to combine the strings in the write() function into a single string, instead of trying to pass two separate arguments. So change from: dest.write(x+'\n','bold') to dest.write(x + '\n' + 'bold') The second question was harder for me to understand. Finally, I noticed the subject line, which made it clear what you meant by "different size." I had been assuming you meant "different number of characters." You're writing a text file here, and plain text files have no notion of fonts. Without knowing the contents/format of the files you're combining, and/or the kind of program that's going to be interpreting this resulting file, I could only make wild guesses. If all the source files are html pieces, and the resultant file is to be interpreted as html, you could put and around the text you wanted to be bold. But of course, you'd have lots of other formatting text, just to be a valid html file. If the result file is supposed to be rtf (to be displayed in Wordpad, or WinWord), you could put its escape sequences in it. I'm sure there's a spec for rtf out there somewhere in internet land. If the result file is to be printed by an ancient Epson MX80 printer I sort-of recall, you'd put \x0e before the part you wanted bold, and \x0f after it. Or something like that. If the resultant file is a message for this newsgroup, you could put an asterisk before and after the part you want bold. I think you have to do it for each "word," but I've never seen a spec on it. But if the files are pure printable text files, and the result is to be viewable in Notepad, Metapad, or the like, then it can't be done, to the best of my knowledge. DaveA From proportional at msn.com Tue Aug 11 14:17:15 2009 From: proportional at msn.com (proportional at msn.com) Date: Tue, 11 Aug 2009 22:17:15 +1000 Subject: [Tutor] list question Message-ID: hi i am currently doing the 'livewires' python tutorial lesson 5. i am making a little game that makes a few squares chase a circle around a little grid. i can get the 1 square acting on 1 variable to come up, but the tutorial now wants me to create a list of variables that act under the same class. this is what i have to make the 1 square appear (which works)(i have also cut a lot of the program out to make this email smaller.) class Robot: pass def place_robot(): global robot robot = Robot() robot.x=random_between(0,63) robot.y=random_between(0,47) draw_robot() print robot.x and i cant figure out what to write to make the variable 'robot' work as a list, and then follow all the instructions 3 times. this is what i tried to put in. class Robot: pass def place_robot(): global robot r1 = Robot() r2 = Robot() r3 = Robot() robot = [r1,r2,r3] robot.x=random_between(0,63) robot.y=random_between(0,47) draw_robot() print robot.x i was under the assumption that the instruction robot.x=random_between(0,63) would return a value 3 times for r1 r2 and r3, but instead i get AttributeError: 'list' object has no attribute 'x'. so i got no idea heh. i hope this makes sense, as im really new to programming. thanks if anyone can help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ataulla at gmail.com Tue Aug 11 14:48:20 2009 From: ataulla at gmail.com (Ataulla S H) Date: Tue, 11 Aug 2009 18:18:20 +0530 Subject: [Tutor] list question In-Reply-To: References: Message-ID: On Tue, Aug 11, 2009 at 5:47 PM, wrote: > hi i am currently doing the 'livewires' python tutorial lesson 5. i am > making a little game that makes a few squares chase a circle around a little > grid. i can get the 1 square acting on 1 variable to come up, but the > tutorial now wants me to create a list of variables that act under the same > class. > > this is what i have to make the 1 square appear (which works)(i have also > cut a lot of the program out to make this email smaller.) > > class Robot: > pass > > def place_robot(): > global robot > robot = Robot() > robot.x=random_between(0,63) > robot.y=random_between(0,47) > draw_robot() > print robot.x > > and i cant figure out what to write to make the variable 'robot' work as a > list, and then follow all the instructions 3 times. this is what i tried to > put in. > > class Robot: > pass > > def place_robot(): > global robot > r1 = Robot() > r2 = Robot() > r3 = Robot() > robot = [r1,r2,r3] > mydict = {} x=random_between(0,63) y=random_between(0,47) mydict[str(robot)] = {'x':x,'y':y} > #robot.x=random_between(0,63) > # robot.y=random_between(0,47) > draw_robot() > print robot.x > > i was under the assumption that the instruction > robot.x=random_between(0,63) would return a value 3 times for r1 r2 and r3, > but instead i get AttributeError: 'list' object has no attribute 'x'. so i > got no idea heh. i hope this makes sense, as im really new to programming. > thanks if anyone can help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ataulla SH web:www.kring.com personal blog:www.ataulla.objectis.net KRING Technologies India Pvt. Ltd. 1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002 -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Aug 11 14:55:33 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 11 Aug 2009 07:55:33 -0500 Subject: [Tutor] list question In-Reply-To: References: Message-ID: <333efb450908110555h571cb8a0gcc05097a656cdc90@mail.gmail.com> On Tue, Aug 11, 2009 at 7:17 AM, wrote: > hi i am currently doing the 'livewires' python tutorial lesson 5. i am > making a little game that makes a few squares chase a circle around a little > grid. i can get the 1 square acting on 1 variable to come up, but the > tutorial now wants me to create a list of variables that act under the same > class. > > this is what i have to make the 1 square appear (which works)(i have also > cut a lot of the program out to make this email smaller.) > > class Robot: > pass > > def place_robot(): > global robot > robot = Robot() > robot.x=random_between(0,63) > robot.y=random_between(0,47) > draw_robot() > print robot.x > > and i cant figure out what to write to make the variable 'robot' work as a > list, and then follow all the instructions 3 times. this is what i tried to > put in. > > class Robot: > pass > > def place_robot(): > global robot > r1 = Robot() > r2 = Robot() > r3 = Robot() > robot = [r1,r2,r3] > robot.x=random_between(0,63) > robot.y=random_between(0,47) > draw_robot() > print robot.x > > i was under the assumption that the instruction > robot.x=random_between(0,63) would return a value 3 times for r1 r2 and r3, > but instead i get AttributeError: 'list' object has no attribute 'x'. so i > got no idea heh. i hope this makes sense, as im really new to programming. > I think what you want is: for r in robot: r.x = random_between(0,63) r.y = random_between(0,47) draw_robot() print r.x Now for the why: robot is a list of objects - you declared it such with robot = [r1, r2, r3] (incidentally you could just do robots = [Robot(), Robot(), Robot()] ), and lists don't have x y attributes, which you're trying to access. I presume you're really trying to access the x y attributes of your Robot() class, which is an entirely different object from your list. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Tue Aug 11 15:04:13 2009 From: pedrooconnell at gmail.com (pedro) Date: Tue, 11 Aug 2009 09:04:13 -0400 Subject: [Tutor] run python script on another computer's terminal (LAN) References: Message-ID: On 2009-08-11 05:27:19 -0400, "Alan Gauld" said: > "pedro" wrote > >> Hi, does anyone know how to send a command that is within a python >> script to another computer's terminal. This is what it looks like in >> Applescript. >> >> tell application "Terminal" of machine >> "eppc://USERNAME:PASSWORD at COMPUTER2.local" >> do script "ls" >> end tell >> > > You might be better asking these kind of questions on the MacPython > mailing lists/forums since more folks there will be familiar with what > are fairly MacOS specific issues. Also you can get Python to talk to > Applescript which might be the easiest way... > > However in a general sense you can use ssh (or rsh?) to do that. > You might also be able to avoid using subprocess or os.system > by mounting the remote filesystem? That would let you you > os.listdir() on the remote machine? > > HTH Hi Alan, I am trying to make my code as cross-platform as possible, so I am trying to avoid Applescript altogether. I'll try out your ssh suggestion and mounting the remote filesystem? Thanks Pete From ataulla at gmail.com Tue Aug 11 15:05:33 2009 From: ataulla at gmail.com (Ataulla S H) Date: Tue, 11 Aug 2009 18:35:33 +0530 Subject: [Tutor] list question In-Reply-To: <333efb450908110555h571cb8a0gcc05097a656cdc90@mail.gmail.com> References: <333efb450908110555h571cb8a0gcc05097a656cdc90@mail.gmail.com> Message-ID: if u want to add new attributes into ur list u need to import list object in ur class class customlist(list): x = 'your val' c = customlist() >>> dir(c) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', '__weakref__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort', *'x'*] >>> c.x 'your val' On Tue, Aug 11, 2009 at 6:25 PM, Wayne wrote: > > > On Tue, Aug 11, 2009 at 7:17 AM, wrote: > >> hi i am currently doing the 'livewires' python tutorial lesson 5. i am >> making a little game that makes a few squares chase a circle around a little >> grid. i can get the 1 square acting on 1 variable to come up, but the >> tutorial now wants me to create a list of variables that act under the same >> class. >> >> this is what i have to make the 1 square appear (which works)(i have also >> cut a lot of the program out to make this email smaller.) >> >> class Robot: >> pass >> >> def place_robot(): >> global robot >> robot = Robot() >> robot.x=random_between(0,63) >> robot.y=random_between(0,47) >> draw_robot() >> print robot.x >> >> and i cant figure out what to write to make the variable 'robot' work as a >> list, and then follow all the instructions 3 times. this is what i tried to >> put in. >> >> class Robot: >> pass >> >> def place_robot(): >> global robot >> r1 = Robot() >> r2 = Robot() >> r3 = Robot() >> robot = [r1,r2,r3] >> robot.x=random_between(0,63) >> robot.y=random_between(0,47) >> draw_robot() >> print robot.x >> >> i was under the assumption that the instruction >> robot.x=random_between(0,63) would return a value 3 times for r1 r2 and r3, >> but instead i get AttributeError: 'list' object has no attribute 'x'. so i >> got no idea heh. i hope this makes sense, as im really new to programming. >> > > I think what you want is: > > for r in robot: > r.x = random_between(0,63) > r.y = random_between(0,47) > draw_robot() > print r.x > > Now for the why: > robot is a list of objects - you declared it such with robot = [r1, r2, r3] > (incidentally you could just do robots = [Robot(), Robot(), Robot()] ), and > lists don't have x y attributes, which you're trying to access. I presume > you're really trying to access the x y attributes of your Robot() class, > which is an entirely different object from your list. > > HTH, > Wayne > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ataulla SH web:www.kring.com personal blog:www.ataulla.objectis.net KRING Technologies India Pvt. Ltd. 1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002 -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Aug 11 16:07:41 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 11 Aug 2009 10:07:41 -0400 Subject: [Tutor] list question In-Reply-To: <333efb450908110555h571cb8a0gcc05097a656cdc90@mail.gmail.com> References: <333efb450908110555h571cb8a0gcc05097a656cdc90@mail.gmail.com> Message-ID: <4A817B2D.7000701@ieee.org> Wayne wrote: > On Tue, Aug 11, 2009 at 7:17 AM, wrote: > > >> hi i am currently doing the 'livewires' python tutorial lesson 5. i am >> making a little game that makes a few squares chase a circle around a little >> grid. i can get the 1 square acting on 1 variable to come up, but the >> tutorial now wants me to create a list of variables that act under the same >> class. >> >> this is what i have to make the 1 square appear (which works)(i have also >> cut a lot of the program out to make this email smaller.) >> >> class Robot: >> pass >> >> def place_robot(): >> global robot >> robot = Robot() >> robot.x=random_between(0,63) >> robot.y=random_between(0,47) >> draw_robot() >> print robot.x >> >> and i cant figure out what to write to make the variable 'robot' work as a >> list, and then follow all the instructions 3 times. this is what i tried to >> put in. >> >> class Robot: >> pass >> >> def place_robot(): >> global robot >> r1 = Robot() >> r2 = Robot() >> r3 = Robot() >> robot = [r1,r2,r3] >> robot.x=random_between(0,63) >> robot.y=random_between(0,47) >> draw_robot() >> print robot.x >> >> i was under the assumption that the instruction >> robot.x=random_between(0,63) would return a value 3 times for r1 r2 and r3, >> but instead i get AttributeError: 'list' object has no attribute 'x'. so i >> got no idea heh. i hope this makes sense, as im really new to programming. >> >> > > I think what you want is: > > for r in robot: > r.x = random_between(0,63) > r.y = random_between(0,47) > draw_robot() > print r.x > > Now for the why: > robot is a list of objects - you declared it such with robot = [r1, r2, r3] > (incidentally you could just do robots = [Robot(), Robot(), Robot()] ), and > lists don't have x y attributes, which you're trying to access. I presume > you're really trying to access the x y attributes of your Robot() class, > which is an entirely different object from your list. > > HTH, > Wayne > > This illustrates the danger of global variables. The draw_robot() function probably accesses the global variable robot, which has now changed its meaning. So probably it should be a method of the Robot class, in which case you'd use r.draw_robot() Alternatively, if it must be a function rather than a method, you should add a parameter to it, and call it as draw_robot(r) If this were my code, I'd probably have created a new global variable robots, indicating that it's now a list. And change the function place_robot() to place_robots(). DaveA From bgailer at gmail.com Tue Aug 11 16:22:07 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 11 Aug 2009 10:22:07 -0400 Subject: [Tutor] easy way to populate a dict with functions In-Reply-To: <187026.99539.qm@web110711.mail.gq1.yahoo.com> References: <187026.99539.qm@web110711.mail.gq1.yahoo.com> Message-ID: <4A817E8F.7010807@gmail.com> Albert-Jan Roskam wrote: > Hi Bob, > > Sorry for the late reply, but thank you for your code. I still haven't completely wrappped my brain around decorator functions, but thanks to your reply at least now my frontal lobe is touching it. ;-) > Decorator functions: def collect(func): 'a "decorator" that adds each function to the cmds list' cmds.append((func.__name__, func)) # once collect is defined it may be used as a decorator: @collect def foo (a): return "foo" * a # this means # 1 - define foo # 2 - run the following statement foo = collect(foo) # that # 1 - appends foo to the cmds list # 2 - returns None # 3 - assigns None to foo (since we no longer need that name) Admittedly this is not how decorators were intended to be used. The intention was to create some new function (presumably derived from foo in some useful way), return that and assign it to foo. > Re: the ordering of functions: I thought it mattered because the inspect module returns a list of two-tuples (in this case, a list of four two-tuples). Therefore, e.g. option #1 should always cause the same function to be run. But apparently I'm wrong here somewhere. > The only "wrong" is expecting order to be preserved, which dictionaries do not guarantee. -- Bob Gailer Chapel Hill NC 919-636-4239 From prasadaraon50 at gmail.com Tue Aug 11 16:38:53 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 11 Aug 2009 20:08:53 +0530 Subject: [Tutor] To write data in two different fonts? Message-ID: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> Hello I modified my code.But I am gettingmy my lines stripped of indentation. What should I do to avoid it?Sorry if it is not about Python. def sc(adir): import os,myfiles dest=open('C:/scripts.html','w') s=myfiles.myfiles(adir) dest.write('') for x in s: if os.path.isfile(x): sorce=open(x,'r') dest.write('

') dest.write(x) dest.write('

') for l in sorce: dest.write('

') dest.write(l) dest.write('

') sorce.close() else:pass dest.write('') dest.close()
-------------- next part -------------- An HTML attachment was scrubbed... URL: From rick at niof.net Tue Aug 11 17:10:22 2009 From: rick at niof.net (Rick Pasotto) Date: Tue, 11 Aug 2009 11:10:22 -0400 Subject: [Tutor] MySQLdb field type In-Reply-To: <1c2a2c590908101622m5f82462fof676aa29e5dd96c3@mail.gmail.com> References: <20090810170840.GA8169@niof.net> <1c2a2c590908101150t574ab3f9vcc11bb3a448b14f8@mail.gmail.com> <20090810195252.GB8169@niof.net> <1c2a2c590908101622m5f82462fof676aa29e5dd96c3@mail.gmail.com> Message-ID: <20090811151022.GD8169@niof.net> On Mon, Aug 10, 2009 at 07:22:03PM -0400, Kent Johnson wrote: > On Mon, Aug 10, 2009 at 3:52 PM, Rick Pasotto wrote: > > Not exactly what I'm looking for. > > > > The type_code in the tuple is a number. For one of my tables I see the > > following numbers: 1, 2, 10, 252, 253, 254. What I wanted was a listing > > telling me which number was which type_code. > > Ah, right. I guess this will vary for different db modules. Which one > are you using? I didn't realize there were different MySQLdb modules. -- "Wit has truth in it; wise cracking is simply calisthenics with words." -- Dorothy Parker Rick Pasotto rick at niof.net http://www.niof.net From davea at ieee.org Tue Aug 11 17:41:38 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 11 Aug 2009 11:41:38 -0400 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> Message-ID: <4A819132.3000201@ieee.org> prasad rao wrote: > Hello > I modified my code.But I am gettingmy my lines stripped of indentation. > What should I do to avoid it?Sorry if it is not about Python. > > > > > def sc(adir): > import os,myfiles > dest=open('C:/scripts.html','w') > s=myfiles.myfiles(adir) > dest.write('') > for x in s: > if os.path.isfile(x): > sorce=open(x,'r') > > dest.write('

') > dest.write(x) > dest.write('

') > > > for l in sorce: > dest.write('

') > dest.write(l) > dest.write('

') > sorce.close() > else:pass > dest.write('') > dest.close() > >
> > This question is about html. You knew enough to put the html tags around it, and the p tags around each line. But within a p tag, the element content is transparent to whitespace. That's usually a good thing, as it means paragraphs automatically wordwrap according to the size and shape of the browser. But you want the text here to be unformatted, preserving indents, and preserving embedded spaces. The brute-force way might be to replace each space in "l" with   which is a "nonbreaking space." But I think you want the
 
tag, which means the text is pre-formatted.  And you could put that 
around the whole sorce file, instead of doing 

for each line. See http://www.w3schools.com/tags/tag_pre.asp Incidentally, I think you ought to add as well. And maybe some other boilerplate to eliminate warnings in a browser. You'll also get into trouble if any of the lines have "&" or "<" in them. DaveA From michael at shamirlens.co.uk Tue Aug 11 17:51:16 2009 From: michael at shamirlens.co.uk (Michael M Mason) Date: Tue, 11 Aug 2009 16:51:16 +0100 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <4A819132.3000201@ieee.org> References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> <4A819132.3000201@ieee.org> Message-ID: <64FDBE5D11B902469AB33D1EFD0D37C2A4666B@sirius.shamirlens.co.uk> Dave Angel wrote on 11 August 2009 at 16:42:- > The brute-force way might be to replace each space in "l" with >   which is a "nonbreaking space." But I think you want the

 
> tag, which means the text is pre-formatted.  And you could put that 
> around the whole sorce file, instead of doing 

for each line. I think the

 tag will work, but it will force the font to be
monospaced, overriding the "" tag that the OP has
included.

-- 
Michael

From airscorp at otenet.gr  Tue Aug 11 21:45:48 2009
From: airscorp at otenet.gr (Nick Raptis)
Date: Tue, 11 Aug 2009 22:45:48 +0300
Subject: [Tutor] droplet like behaviour in Python
In-Reply-To: 
References:  
	
Message-ID: <4A81CA6C.3010403@otenet.gr>

pedro wrote:
>
> #!/usr/bin/env python
> # encoding: utf-8
> import sys
> theFilePath = sys.argv[1]
> print theFilePath
>
>
> But when I try to drop something on it nothing happens. Sorry I guess 
> there is something fundamental that I am missing.
> Pete
>
>

Pedro, I'll reply to this message instead of the last one because, I 
actually tried the little script you have there, and it does work
I'm on Windows though.

Well, my version of your script is this:
-------------------------
import sys
for arg in sys.argv:
    print arg

raw_input()
-------------------------

The raw_input() at the end is what keeps the window open so I can see 
that something really happened before the window closed.
When I drop a file into my script, it prints two lines: The script 
filename and the filename of the file I dropped.
So I call it a win.

I don't know how it behaves in mac, but please try and tell. (Also put 
your usual #!/usr/bin/env python in there to work for you)

Nick

From kent37 at tds.net  Tue Aug 11 22:31:41 2009
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Aug 2009 16:31:41 -0400
Subject: [Tutor] easy way to populate a dict with functions
In-Reply-To: <4A817E8F.7010807@gmail.com>
References: <187026.99539.qm@web110711.mail.gq1.yahoo.com>
	<4A817E8F.7010807@gmail.com>
Message-ID: <1c2a2c590908111331p23a94f67g6e441c88d608a50@mail.gmail.com>

On Tue, Aug 11, 2009 at 10:22 AM, bob gailer wrote:

> Decorator functions:
>
> def collect(func):
> 'a "decorator" that adds each function to the cmds list'
> cmds.append((func.__name__, func))

Decorators must return a callable, add to the above:

  return func

Kent

From kent37 at tds.net  Tue Aug 11 22:45:30 2009
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 11 Aug 2009 16:45:30 -0400
Subject: [Tutor] MySQLdb field type
In-Reply-To: <20090811151022.GD8169@niof.net>
References: <20090810170840.GA8169@niof.net>
	<1c2a2c590908101150t574ab3f9vcc11bb3a448b14f8@mail.gmail.com>
	<20090810195252.GB8169@niof.net>
	<1c2a2c590908101622m5f82462fof676aa29e5dd96c3@mail.gmail.com>
	<20090811151022.GD8169@niof.net>
Message-ID: <1c2a2c590908111345l7b028e71k4f4c9e3410cba7c9@mail.gmail.com>

On Tue, Aug 11, 2009 at 11:10 AM, Rick Pasotto wrote:

> I didn't realize there were different MySQLdb modules.

I didn't realize you had specified MySQLdb...sorry, I'm not being very
helpful. I don't know where to find that information for MySQLdb.

Kent

From airscorp at otenet.gr  Tue Aug 11 23:49:57 2009
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 12 Aug 2009 00:49:57 +0300
Subject: [Tutor] droplet like behaviour in Python
In-Reply-To: <4A81CA6C.3010403@otenet.gr>
References: 
		
	<4A81CA6C.3010403@otenet.gr>
Message-ID: <4A81E785.9020000@otenet.gr>

For the Windows users out there:

A google search returned me this:
Make Python Scripts Droppable in Windows 


I checked my registry and the extension was there. That must be why my 
drop script works.
No idea how it got there though. FWIW, I have installed Python through 
the .msi installer.

PS: What I like is that the page I linked actually has my little test 
script in it :D
       I must be doing something right.

PS2: I guess I'm starting to deduce that the answer is 
platform/installation specific rather than python/script specific.
        That turns the question it to a whole new direction for me.

Nick

Nick Raptis wrote:
> pedro wrote:
>>
>> #!/usr/bin/env python
>> # encoding: utf-8
>> import sys
>> theFilePath = sys.argv[1]
>> print theFilePath
>>
>>
>> But when I try to drop something on it nothing happens. Sorry I guess 
>> there is something fundamental that I am missing.
>> Pete
>>
>>
>
> Pedro, I'll reply to this message instead of the last one because, I 
> actually tried the little script you have there, and it does work
> I'm on Windows though.
>
> Well, my version of your script is this:
> -------------------------
> import sys
> for arg in sys.argv:
>    print arg
>
> raw_input()
> -------------------------
>
> The raw_input() at the end is what keeps the window open so I can see 
> that something really happened before the window closed.
> When I drop a file into my script, it prints two lines: The script 
> filename and the filename of the file I dropped.
> So I call it a win.
>
> I don't know how it behaves in mac, but please try and tell. (Also put 
> your usual #!/usr/bin/env python in there to work for you)
>
> Nick
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

From srilyk at gmail.com  Wed Aug 12 00:18:05 2009
From: srilyk at gmail.com (Wayne)
Date: Tue, 11 Aug 2009 17:18:05 -0500
Subject: [Tutor] droplet like behaviour in Python
In-Reply-To: <4A81E785.9020000@otenet.gr>
References:   
	 <4A81CA6C.3010403@otenet.gr> 
	<4A81E785.9020000@otenet.gr>
Message-ID: <333efb450908111518n11189047r6e70bc4770acc2e1@mail.gmail.com>

On Tue, Aug 11, 2009 at 4:49 PM, Nick Raptis  wrote:

>
> PS2: I guess I'm starting to deduce that the answer is
> platform/installation specific rather than python/script specific.
>       That turns the question it to a whole new direction for me.


It's probably even more than that - my guess is it's very dependent on the
window manager (or whatever happens to produce your icons, which is usually
the WM). I don't know how different the various WM's are on linux, but I
know there are several to choose from. Having this cross-platform may not be
the easiest thing - you'd probably have to use an os module call to check
the system to determine the proper course of action or something otherwise
technically advanced.

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From allen.fowler at yahoo.com  Wed Aug 12 01:37:31 2009
From: allen.fowler at yahoo.com (Allen Fowler)
Date: Tue, 11 Aug 2009 16:37:31 -0700 (PDT)
Subject: [Tutor] string.title(): correct?
Message-ID: <142964.88841.qm@web45603.mail.sp1.yahoo.com>


Hello,

"He's a great guy".title()

Gives me:
 
"He'S A Great Guy"


I expected:

"He's A Great Guy"

Did i miss something here?

Thank you,
:)


      


From davea at ieee.org  Wed Aug 12 01:41:51 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 19:41:51 -0400
Subject: [Tutor] To write data in two different fonts?
In-Reply-To: <64FDBE5D11B902469AB33D1EFD0D37C2A4666B@sirius.shamirlens.co.uk>
References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com>	<4A819132.3000201@ieee.org>
	<64FDBE5D11B902469AB33D1EFD0D37C2A4666B@sirius.shamirlens.co.uk>
Message-ID: <4A8201BF.5040508@ieee.org>

Michael M Mason wrote:
> Dave Angel wrote on 11 August 2009 at 16:42:-
>
>   
>> The brute-force way might be to replace each space in "l" with    
>>     which is a "nonbreaking space."  But I think you want the
>>     
> 
 
>   
>> tag, which means the text is pre-formatted.  And you could put that 
>> around the whole sorce file, instead of doing 

for each line. >> > > I think the

 tag will work, but it will force the font to be
> monospaced, overriding the "" tag that the OP has
> included.
>
>   
That font= syntax was probably bogus.  But in any case, I meant to put 
the 
 around each sorce file expansion, not around the whole 
destination file, and implied that the 

and

lines go away. Something like: dest.write('

dest.write(x) dest.write('

') dest.write("
")
                  for l in sorce:
                       dest.write(l)
                  sorce.close()
                  dest.write("
") DaveA From bgailer at gmail.com Wed Aug 12 03:27:59 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 11 Aug 2009 21:27:59 -0400 Subject: [Tutor] easy way to populate a dict with functions In-Reply-To: <1c2a2c590908111331p23a94f67g6e441c88d608a50@mail.gmail.com> References: <187026.99539.qm@web110711.mail.gq1.yahoo.com> <4A817E8F.7010807@gmail.com> <1c2a2c590908111331p23a94f67g6e441c88d608a50@mail.gmail.com> Message-ID: <4A821A9F.9060005@gmail.com> Kent Johnson wrote: > On Tue, Aug 11, 2009 at 10:22 AM, bob gailer wrote: > > >> Decorator functions: >> >> def collect(func): >> 'a "decorator" that adds each function to the cmds list' >> cmds.append((func.__name__, func)) >> > > Decorators must return a callable The docs indeed say that, but the interpreter does not enforce it. My example works as I designed it. -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Wed Aug 12 03:31:13 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 11 Aug 2009 21:31:13 -0400 Subject: [Tutor] string.title(): correct? In-Reply-To: <142964.88841.qm@web45603.mail.sp1.yahoo.com> References: <142964.88841.qm@web45603.mail.sp1.yahoo.com> Message-ID: <4A821B61.4050508@gmail.com> Allen Fowler wrote: > Hello, > > "He's a great guy".title() > > Gives me: > > "He'S A Great Guy" > > > I expected: > > "He's A Great Guy" > > Did i miss something here? > The docs state: "title( ) - Return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase." It depends on the definition of "word". -- Bob Gailer Chapel Hill NC 919-636-4239 From prasadaraon50 at gmail.com Wed Aug 12 06:16:34 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 12 Aug 2009 09:46:34 +0530 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <4A819132.3000201@ieee.org> References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> <4A819132.3000201@ieee.org> Message-ID: <9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com> > > But I think you want the
 tag, which means the text is
> pre-formatted.  And you could >put that around the whole sorce file, instead
> of doing 

for each line. > > >See http://www.w3schools.com/tags/tag_pre.asp Thank you Dave. I put in tag

 and it worked. But at one particular line in a module
the font changed colour.After that all the lines are in blue colour and
under lined.
I removed that module from the directory and now it is working well.I could
not
figure out why the change of colour of font took place.

Thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From proportional at msn.com  Wed Aug 12 08:19:28 2009
From: proportional at msn.com (proportional at msn.com)
Date: Wed, 12 Aug 2009 16:19:28 +1000
Subject: [Tutor] creating an exe
Message-ID: 

hi, thanks to all that helped with my list question yesterday. i have now finished my program the way i want it. is there a way to compile my program so that people without python can see what i have made?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From timomlists at gmail.com  Wed Aug 12 09:07:16 2009
From: timomlists at gmail.com (Timo)
Date: Wed, 12 Aug 2009 09:07:16 +0200
Subject: [Tutor] creating an exe
In-Reply-To: 
References: 
Message-ID: <4A826A24.6040306@gmail.com>

proportional at msn.com schreef:
> hi, thanks to all that helped with my list question yesterday. i have 
> now finished my program the way i want it. is there a way to compile 
> my program so that people without python can see what i have made?
Works great with py2exe.

Timo


> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


From alan.gauld at btinternet.com  Wed Aug 12 10:41:50 2009
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 12 Aug 2009 09:41:50 +0100
Subject: [Tutor] To write data in two different fonts?
References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com><4A819132.3000201@ieee.org>
	<9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com>
Message-ID: 


"prasad rao"  wrote 

> I put in tag 
 and it worked. But at one particular line in a module
> the font changed colour.After that all the lines are in blue colour and
> under lined.

How are you viewing the file?
As Kent poinred out pure text files have no fonts or colours.
So the blue colour must be coming from the tyool you are using 
to display the contents. It is interpreting sometjhing in the data 
as a command to switch format. Since you are using HTML
it is probably a  tag. Have you checked the data for any 
 figure out why the change of colour of font took place.

Open it in a simple text editor like notepad or nano and see what 
it looks like.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Wed Aug 12 10:48:49 2009
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 12 Aug 2009 09:48:49 +0100
Subject: [Tutor] creating an exe
References: 
Message-ID: 

 wrote 

>  i have now finished my program the way i want it. is there a way 
> to compile my program so that people without python can see 
> what i have made?

Yes, you package your program with a version of python.
You can either do that with a standard installer which installs 
python and your program or you use a tool like py2exe which 
installs a cut down version of python - just enough to run your 
code - and your program

The advantage of the first method is that the user has a full python 
that they can use to run other python programs with minimal download etc
The disadvantage is that its a bigger package to doawnload/install
in the first place.

The advantage of the second method is that it is a smaller package
but the disadvantage is that they now have a version of python installed 
which can't do anything but run your program. If you write another 
program they have to install yet another version of python, and so on, 
which very rapidly becomes more wasteful than the first method.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From airscorp at otenet.gr  Wed Aug 12 11:51:15 2009
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 12 Aug 2009 12:51:15 +0300
Subject: [Tutor] To write data in two different fonts?
In-Reply-To: 
References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com><4A819132.3000201@ieee.org>	<9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com>
	
Message-ID: <4A829093.3090407@otenet.gr>

Your main concern when displaying plain text in HTML is actually only 5 
characters:
&, <, >, ", '
which you should escape(replace) with their coresponding HTML entities.
Here's a few lines of code to give you an idea how to do it:

--------------------------------------------------------
#put this somewhere in the beginning of your script,
#tailor it as you like
entities = {'&' : '&',
            '<' : '<',
            '>' : '>',
            '"' : '"',
            "'" : '''}

......

#put this in the file crunching loop
#I'll use *line* as the text variable, like it would happen
#in a *for line in file* scenario
    ....
    for character, entity in entities.items():
         line = line.replace(character, entity)
    .....
    ..... #do the rest of your stuff with the line
-------------------------------------------------------

That's a simple implementation and it actually performs 5 replacements 
on every line of your file (which
is not as slow as you might think though) but should get you started if 
you need it.

You also might want to consider escaping other characters as well (maybe 
spaces to preserve whitespace without a 
)
Get your hands on an online HTML entity reference online.

Extra points:
Include a CSS file with your HTML output to handle representation.
With some more lines in your script you can then code different fonts or 
sizes according to any logic you want.
Won't go into explaining HTML though (hint: use the class HTML attribute)

If it sounds more complex than you'd like, it's ok. It's more powerful 
and more rewarding too.
Once you get the basic structure in, you can extend your script to do 
pretty much anything with your text.

Nick


Alan Gauld wrote:
>
> "prasad rao"  wrote
>> I put in tag 
 and it worked. But at one particular line in a module
>> the font changed colour.After that all the lines are in blue colour and
>> under lined.
>
> How are you viewing the file?
> As Kent poinred out pure text files have no fonts or colours.
> So the blue colour must be coming from the tyool you are using to 
> display the contents. It is interpreting sometjhing in the data as a 
> command to switch format. Since you are using HTML
> it is probably a  tag. Have you checked the data for any  sequences (or and other < characters for that matter)?
>
>
>> figure out why the change of colour of font took place.
>
> Open it in a simple text editor like notepad or nano and see what it 
> looks like.
>
> HTH,
>
>

From davea at ieee.org  Wed Aug 12 12:41:17 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 06:41:17 -0400
Subject: [Tutor] To write data in two different fonts?
In-Reply-To: <9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com>
References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com>	
	<4A819132.3000201@ieee.org>
	<9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com>
Message-ID: <4A829C4D.9010407@ieee.org>

prasad rao wrote:
>>> But I think you want the 
 tag, which means the text is
>>>       
>> pre-formatted.  And you could >put that around the whole sorce file, instead
>> of doing 

for each line. >> >> >>> See http://www.w3schools.com/tags/tag_pre.asp >>> > > > Thank you Dave. > I put in tag

 and it worked. But at one particular line in a module
> the font changed colour.After that all the lines are in blue colour and
> under lined.
> I removed that module from the directory and now it is working well.I could
> not
> figure out why the change of colour of font took place.
>
> Thank you
>
>   
As I said, you'd probably get in trouble if any of the lines had '&' or 
'<' characters in them.  The following function from the standard 
library can be used to escape the line directly, or of course you could 
use the function Nick supplied.

xml.sax.saxutils.escape(/data/[, /entities/])

    Escape '&', '<', and '>' in a string of data.

    You can escape other strings of data by passing a dictionary as the
    optional /entities/ parameter. The keys and values must all be
    strings; each key will be replaced with its corresponding value. The
    characters '&', '<' and '>' are always escaped, even if /entities/
    is provided.

Let us know if that doesn't do the trick.

DaveA


From davidkim05 at gmail.com  Wed Aug 12 06:51:20 2009
From: davidkim05 at gmail.com (David Kim)
Date: Wed, 12 Aug 2009 00:51:20 -0400
Subject: [Tutor] Automating creation of presentation slides?
Message-ID: 

Hi everyone,

I'm wondering what people consider the most efficient and brain-damage free
way to automate the creation of presentation slides with Python. Scripting
Powerpoint via COM? Generating a Keynote XML file? Something else that's
easier (hopefully)?

I'm imagining a case where one does certain analyses periodically with
updated data, with charts generated by matplotlib (or something similar)
that ultimately need to end up in the presentation.

Many thanks,

DK
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From kent37 at tds.net  Wed Aug 12 14:28:17 2009
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Aug 2009 08:28:17 -0400
Subject: [Tutor] easy way to populate a dict with functions
In-Reply-To: <4A821A9F.9060005@gmail.com>
References: <187026.99539.qm@web110711.mail.gq1.yahoo.com>
	<4A817E8F.7010807@gmail.com>
	<1c2a2c590908111331p23a94f67g6e441c88d608a50@mail.gmail.com>
	<4A821A9F.9060005@gmail.com>
Message-ID: <1c2a2c590908120528o5e95edb1v8be3d1f48110534d@mail.gmail.com>

On Tue, Aug 11, 2009 at 9:27 PM, bob gailer wrote:
> Kent Johnson wrote:
>>
>> On Tue, Aug 11, 2009 at 10:22 AM, bob gailer wrote:
>>
>>
>>>
>>> Decorator functions:
>>>
>>> def collect(func):
>>> 'a "decorator" that adds each function to the cmds list'
>>> cmds.append((func.__name__, func))
>>>
>>
>> Decorators must return a callable
>
> The docs indeed say that, but the interpreter does not enforce it. My
> example works as I designed it.

I guess if you just want to populate cmds it is OK but if you want the
name 'foo' to be bound to a function it fails:

In [20]: cmds = []

In [21]: def collect(func):
   ....:     cmds.append((func.__name__, func))

In [22]: @collect
   ....: def foo(a):
   ....:     return 'foo' * a
   ....:

In [23]: cmds
Out[23]: [('foo', )]

In [24]: foo

In [25]: foo(3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/Users/kent/ in ()

TypeError: 'NoneType' object is not callable

Kent

From srilyk at gmail.com  Wed Aug 12 14:46:26 2009
From: srilyk at gmail.com (Wayne)
Date: Wed, 12 Aug 2009 07:46:26 -0500
Subject: [Tutor] Automating creation of presentation slides?
In-Reply-To: 
References: 
Message-ID: <333efb450908120546q39f7399dl19ccb616fe183117@mail.gmail.com>

On Tue, Aug 11, 2009 at 11:51 PM, David Kim  wrote:

> Hi everyone,
>
> I'm wondering what people consider the most efficient and brain-damage free
> way to automate the creation of presentation slides with Python. Scripting
> Powerpoint via COM? Generating a Keynote XML file? Something else that's
> easier (hopefully)?
>
> I'm imagining a case where one does certain analyses periodically with
> updated data, with charts generated by matplotlib (or something similar)
> that ultimately need to end up in the presentation.


You could always export/save images. IIRC that feature may be included in
matplotlib.

I don't know what other methods are available, but I'd probably do a quick
google search for the options.

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From kent37 at tds.net  Wed Aug 12 14:52:52 2009
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 12 Aug 2009 08:52:52 -0400
Subject: [Tutor] Automating creation of presentation slides?
In-Reply-To: 
References: 
Message-ID: <1c2a2c590908120552g110682c0p76fae154b493a68@mail.gmail.com>

On Wed, Aug 12, 2009 at 12:51 AM, David Kim wrote:
> Hi everyone,
>
> I'm wondering what people consider the most efficient and brain-damage free
> way to automate the creation of presentation slides with Python. Scripting
> Powerpoint via COM? Generating a Keynote XML file? Something else that's
> easier (hopefully)?

Maybe this:
http://pypi.python.org/pypi/bruce

Kent

From prasadaraon50 at gmail.com  Wed Aug 12 16:24:38 2009
From: prasadaraon50 at gmail.com (prasad rao)
Date: Wed, 12 Aug 2009 19:54:38 +0530
Subject: [Tutor] To write data in two different fonts?
In-Reply-To: <4A829C4D.9010407@ieee.org>
References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com>
	<4A819132.3000201@ieee.org>
	<9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com>
	<4A829C4D.9010407@ieee.org>
Message-ID: <9e3fac840908120724y5c5e6b2kb921371eedeb4f1f@mail.gmail.com>

> >xml.sax.saxutils.escape(/data/[, /entities/])
>
> >  Escape '&', '<', and '>' in a string of data.
>
>  > You can escape other strings of data by passing a dictionary as the
>   >optional /entities/ parameter. The keys and values must all be
>   >strings; each key will be replaced with its corresponding value. The
>   >characters '&', '<' and '>' are always escaped, even if /entities/
>   >is provided.
>
> >Let us know if that doesn't do the trick.
>
> >DaveA


Thank you Dave

         It is working perfectly with the modifications you suggested.

    


def sc(adir):
        entities = {'&' : '&',
           '<' : '<',
           '>' : '>',
           '"' : '"',
           "'" : '''}

        import os,myfiles,xml.sax.saxutils
        dest=open('C:/scripts.html','w')
        s=myfiles.myfiles(adir)
        dest.write('')
        for x in s:
              if os.path.isfile(x):
                   sorce=open(x,'r')

                   dest.write('

') dest.write(x) dest.write('

')


                   for l in sorce:
                        l=xml.sax.saxutils.escape(l,entities)
                        dest.write('')
                        dest.write(l)
                   dest.write('
')
                   sorce.close()
              else:pass
        dest.write('')
        dest.close()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From davea at ieee.org  Wed Aug 12 19:20:42 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 13:20:42 -0400
Subject: [Tutor] To write data in two different fonts?
In-Reply-To: <9e3fac840908120724y5c5e6b2kb921371eedeb4f1f@mail.gmail.com>
References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com>	
	<4A819132.3000201@ieee.org>	
	<9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com>	
	<4A829C4D.9010407@ieee.org>
	<9e3fac840908120724y5c5e6b2kb921371eedeb4f1f@mail.gmail.com>
Message-ID: <4A82F9EA.50903@ieee.org>

prasad rao wrote:
>>> xml.sax.saxutils.escape(/data/[, /entities/])
>>>       
>>>  Escape '&', '<', and '>' in a string of data.
>>>       
>>  > You can escape other strings of data by passing a dictionary as the
>>   >optional /entities/ parameter. The keys and values must all be
>>   >strings; each key will be replaced with its corresponding value. The
>>   >characters '&', '<' and '>' are always escaped, even if /entities/
>>   >is provided.
>>
>>     
>>> Let us know if that doesn't do the trick.
>>>       
>>> DaveA
>>>       
>
>
> Thank you Dave
>
>          It is working perfectly with the modifications you suggested.
>
>     
>
>
> def sc(adir):
>         entities = {'&' : '&',
>            '<' : '<',
>            '>' : '>',
>            '"' : '"',
>            "'" : '''}
>
>         import os,myfiles,xml.sax.saxutils
>         dest=open('C:/scripts.html','w')
>         s=myfiles.myfiles(adir)
>         dest.write('')
>         for x in s:
>               if os.path.isfile(x):
>                    sorce=open(x,'r')
>
>                    dest.write('

') > dest.write(x) > dest.write('

')
>
>
>                    for l in sorce:
>                         l=xml.sax.saxutils.escape(l,entities)
>                         dest.write('')
>                         dest.write(l)
>                    dest.write('
')
>                    sorce.close()
>               else:pass
>         dest.write('')
>         dest.close()
>
>   
There are still a few problems.  First one is that you have two 
translations going on.  You only want to list those things in 'entities' 
that aren't already done in the escape() function already.  So get rid 
of entities, unless you come up with some other character that needs 
translating besides  ampersand, less-than, and greater-than.

Second is that you have 
 at begin and end of file, while the latter 
should be 
, to close the
 section.

Besides that, you have lots of illegal html going on, which most browser 
will ignore.  But you might as well get it as close as you can.  Note 
that your font logic was just plain wrong.  But you don't need it, since 
it looked good when it was broken anyway.

The following produced valid xhtml, according to S3 tester, when used 
with my files.


import os,xml.sax.saxutils
import myfiles

BOILERPLATE ="""\



    
        My Python Scripts
    


"""
def sc(adir):

        dest=open('M:/scripts.html','w')
        filelist = myfiles.myfiles(adir)

        dest.write(BOILERPLATE)
        for filename in filelist:
              if os.path.isfile(filename):
                   sorce=open(filename,'r')

                   dest.write('

') dest.write(filename) dest.write('

')

                   for line in sorce:
                        line=xml.sax.saxutils.escape(line)
                        dest.write(line)
                   dest.write('
') sorce.close() else:pass dest.write('') dest.close() DaveA From davidkim05 at gmail.com Wed Aug 12 20:59:26 2009 From: davidkim05 at gmail.com (David Kim) Date: Wed, 12 Aug 2009 14:59:26 -0400 Subject: [Tutor] Automating creation of presentation slides? In-Reply-To: <1c2a2c590908120552g110682c0p76fae154b493a68@mail.gmail.com> References: <1c2a2c590908120552g110682c0p76fae154b493a68@mail.gmail.com> Message-ID: Thanks for the suggestion Kent, I was not familiar with reStructuredText. Looks very interesting and more practical than than scripting Powerpoint or recreating Apple's Keynote XML format. This nugget also led me to rst2pdf, for those who care. Cheers, DK On Wed, Aug 12, 2009 at 8:52 AM, Kent Johnson wrote: > On Wed, Aug 12, 2009 at 12:51 AM, David Kim wrote: > > Hi everyone, > > > > I'm wondering what people consider the most efficient and brain-damage > free > > way to automate the creation of presentation slides with Python. > Scripting > > Powerpoint via COM? Generating a Keynote XML file? Something else that's > > easier (hopefully)? > > Maybe this: > http://pypi.python.org/pypi/bruce > > Kent > -- morenotestoself.wordpress.com financialpython.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Wed Aug 12 21:43:22 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 12 Aug 2009 12:43:22 -0700 Subject: [Tutor] Automating creation of presentation slides? In-Reply-To: References: Message-ID: <78b3a9580908121243j1aaabe15hb762e080770ce016@mail.gmail.com> > I'm wondering what people consider the most efficient and brain-damage free > way to automate the creation of presentation slides with Python. Scripting Powerpoint via COM? this is how i'm doing it. i'm working on a Python script that takes plain text with minimal markup that then uses COM to execute within PowerPoint to build the presentation. at the end of the run, users can then save the PPT or start the slideshow. fwiw, it's still in dev now, but i plan on releasing it to the world in the next edition of Core Python Programming in the next couple of years. for those who have already seen me give talks, i sometimes use this in a live setting now, including tonite. if any of you are in the silicon valley area and are interested in hearing me talk about Python 2 vs. 3 swing by for the talk and my interesting use of PowerPoint and Python. :-) more info at http://accu.org/index.php/accu_branches/accu_usa/next cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Wed Aug 12 22:15:02 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 12 Aug 2009 13:15:02 -0700 Subject: [Tutor] Automating creation of presentation slides? In-Reply-To: References: <78b3a9580908121243j1aaabe15hb762e080770ce016@mail.gmail.com> Message-ID: <78b3a9580908121315w94f8182r3ae3e7688d4c6ce1@mail.gmail.com> On Wed, Aug 12, 2009 at 1:07 PM, David Kim wrote: > Unfortunately I live on the East Coast, otherwise I'd definitely attend! I > am attracted to the declarative nature of reStructuredText, but I also > recognize that A LOT of people use Powerpoint and are comfortable with it. > Going with something else might freak people out. > > It also occurs to me that Excel integration might also matter. i also do Excel with COM and Python. the seeds of the work i described and other Office apps is prototyped in Chp 23 of the current (2nd) edition of Core Python, should any of you have a copy. OTOH, i also like reST, esp when used with docutils, and a powerful tool like http://sphinx.pocoo.org ... FWIW, i gave a *non*-Python talk at OSCON several weeks ago where i describe how some authors will be using reST to write future manuscripts with ... http://en.oreilly.com/oscon2009/public/schedule/detail/8038 cheers, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From zstumgoren at gmail.com Wed Aug 12 22:36:53 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 12 Aug 2009 16:36:53 -0400 Subject: [Tutor] best approach to db-api imports and cursor calls Message-ID: Hi everyone, Was wondering if you could advise on best practices when it comes to reusing a database cursor. I'm working on a program that must hit a database several times. Basically, I pull some data, process it, and then use a portion of that data as parameters for the next call. And then I rinse and repeat. So my question: Is it better to start off my program (or main function) with a global import of the database module and a global cursor object, and then pass that cursor to each method that requires it? >>> import cx_Oracle >>> db = cx_Oracle.connect() >>> cur = db.cursor() >>> x = MyObject() >>> x.getData(cur) >>> x.processData() >>> x.getMoreData(cur) Or is it better to import, connect and create the cursor inside each method where it's needed? On the one hand, I know you're supposed to avoid polluting the global namespace, but on the other, it seems like I'd be generating a lot of duplicate code by adding import/connect/cursor to each method. Or should I use some middle road like creating a global function that returns a cursor object, and then call that inside each method that needs it? Advice, as always, is greatly appreciated. Regards, Serdar From davidkim05 at gmail.com Wed Aug 12 22:07:36 2009 From: davidkim05 at gmail.com (David Kim) Date: Wed, 12 Aug 2009 16:07:36 -0400 Subject: [Tutor] Automating creation of presentation slides? In-Reply-To: <78b3a9580908121243j1aaabe15hb762e080770ce016@mail.gmail.com> References: <78b3a9580908121243j1aaabe15hb762e080770ce016@mail.gmail.com> Message-ID: Unfortunately I live on the East Coast, otherwise I'd definitely attend! I am attracted to the declarative nature of reStructuredText, but I also recognize that A LOT of people use Powerpoint and are comfortable with it. Going with something else might freak people out. It also occurs to me that Excel integration might also matter. For example, if someone is using R, Scipy, and/or matplotlib, etc etc to generate analysis, then I can't really see them caring too much. Just generate PNGs and build the presentation. Those entrenched in excel and ms-office will naturally gravitate toward VBA, I guess. Python is my first language, so I'd like to gain some proficiency with it before branching out. On Wed, Aug 12, 2009 at 3:43 PM, wesley chun wrote: > > I'm wondering what people consider the most efficient and brain-damage > free > > way to automate the creation of presentation slides with Python. > Scripting Powerpoint via COM? > > > this is how i'm doing it. i'm working on a Python script that takes > plain text with minimal markup that then uses COM to execute within > PowerPoint to build the presentation. at the end of the run, users can > then save the PPT or start the slideshow. > > fwiw, it's still in dev now, but i plan on releasing it to the world > in the next edition of Core Python Programming in the next couple of > years. for those who have already seen me give talks, i sometimes use > this in a live setting now, including tonite. > > if any of you are in the silicon valley area and are interested in > hearing me talk about Python 2 vs. 3 swing by for the talk and my > interesting use of PowerPoint and Python. :-) more info at > http://accu.org/index.php/accu_branches/accu_usa/next > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -- morenotestoself.wordpress.com financialpython.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Aug 12 23:19:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Aug 2009 17:19:31 -0400 Subject: [Tutor] Automating creation of presentation slides? In-Reply-To: References: <78b3a9580908121243j1aaabe15hb762e080770ce016@mail.gmail.com> Message-ID: <1c2a2c590908121419o3654cbc7u9d9a18ceb7bd6b4a@mail.gmail.com> On Wed, Aug 12, 2009 at 4:07 PM, David Kim wrote: > I > am attracted to the declarative nature of reStructuredText, but I also > recognize that A LOT of people use Powerpoint and are comfortable with it. > Going with something else might freak people out. You might also look at S5: http://meyerweb.com/eric/tools/s5/ S5 presentations are viewable in a browser, so if you want to make something for distribution, it may be better than Bruce (which IIUC requires Python to view). Or you could use Bruce for presentation and convert to HTML or PDF for distribution (http://groups.google.com/group/bruce-users/browse_thread/thread/a117867ec7a65761) Here are two projects that convert reST to LaTex that then can be converted to PDF: http://github.com/agapow/rst2beamer/tree/master http://code.google.com/p/tevisa/ Kent From airscorp at otenet.gr Wed Aug 12 23:20:58 2009 From: airscorp at otenet.gr (Nick Raptis) Date: Thu, 13 Aug 2009 00:20:58 +0300 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <4A829C4D.9010407@ieee.org> References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> <4A819132.3000201@ieee.org> <9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com> <4A829C4D.9010407@ieee.org> Message-ID: <4A83323A.900@otenet.gr> Dave Angel wrote: > As I said, you'd probably get in trouble if any of the lines had '&' > or '<' characters in them. The following function from the standard > library can be used to escape the line directly, or of course you > could use the function Nick supplied. > > xml.sax.saxutils.escape(/data/[, /entities/]) > > Escape '&', '<', and '>' in a string of data. > > You can escape other strings of data by passing a dictionary as the > optional /entities/ parameter. The keys and values must all be > strings; each key will be replaced with its corresponding value. The > characters '&', '<' and '>' are always escaped, even if /entities/ > is provided. > > Let us know if that doesn't do the trick. > > DaveA > Thanks Dave for the info on xml.sax.saxutils.escape Didn't know about this one. For the rest: It is sometimes This is the source code of the xml.sax.saxutils.escape function: --------------------------------------- def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s def escape(data, entities={}): """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ # must do ampersand first data = data.replace("&", "&") data = data.replace(">", ">") data = data.replace("<", "<") if entities: data = __dict_replace(data, entities) return data ----------------------------------------- As you can see, it too uses string.replace to do the job. However, using a built-in function that works for what you want to do is preferable. It's tested and might also be optimized to be faster. It's easy and fun to look into the source though and know exactly what something does. It's also one of the ways for a begginer (me too) to progress. From the source code I can see this for example: *Don' t pass the entity dictionary I proposed earlier to this function:* entities = {'&' : '&', '<' : '<', '>' : '>', '"' : '"', "'" : '''} If you pass an entity for '&' into escape(), it will escape it in the already partially escaped string, resulting in chaos. Think of it, this function not checking for a '&' entity passed to it might worth qualifying as a bug :) Nick From zstumgoren at gmail.com Thu Aug 13 02:10:06 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 12 Aug 2009 20:10:06 -0400 Subject: [Tutor] best approach to db-api imports and cursor calls In-Reply-To: <1c2a2c590908121425j7b69d853xebf9a929e78313b4@mail.gmail.com> References: <1c2a2c590908121425j7b69d853xebf9a929e78313b4@mail.gmail.com> Message-ID: > My understanding is that it is relatively expensive to connect() and > cheap to create cursors. Cursors are also associated with > transactions. So a common practice seems to be to create a connection > that is shared in some way, and to create a cursor for each > transaction / operation. > > Kent Is there any reason why you can't reuse the same cursor object? I know when you're writing to a database, you have to be sure to commit your changes. But if I'm just issuing execute statements and then fetching data, is it okay to reuse the same cursor? From kent37 at tds.net Thu Aug 13 04:46:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Aug 2009 22:46:49 -0400 Subject: [Tutor] Automating creation of presentation slides? In-Reply-To: <1c2a2c590908121419o3654cbc7u9d9a18ceb7bd6b4a@mail.gmail.com> References: <78b3a9580908121243j1aaabe15hb762e080770ce016@mail.gmail.com> <1c2a2c590908121419o3654cbc7u9d9a18ceb7bd6b4a@mail.gmail.com> Message-ID: <1c2a2c590908121946q53841c1au214ff6d9cefba598@mail.gmail.com> On Wed, Aug 12, 2009 at 5:19 PM, Kent Johnson wrote: > You might also look at S5: > http://meyerweb.com/eric/tools/s5/ > > S5 presentations are viewable in a browser, so if you want to make > something for distribution, it may be better than Bruce (which IIUC > requires Python to view). Or you could use Bruce for presentation and > convert to HTML or PDF for distribution > (http://groups.google.com/group/bruce-users/browse_thread/thread/a117867ec7a65761) And yet another option - convert reST to S5: http://docutils.sourceforge.net/docs/user/slide-shows.html Kent From alan.gauld at btinternet.com Thu Aug 13 10:11:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Aug 2009 09:11:33 +0100 Subject: [Tutor] best approach to db-api imports and cursor calls References: <1c2a2c590908121425j7b69d853xebf9a929e78313b4@mail.gmail.com> Message-ID: "Serdar Tumgoren" wrote > Is there any reason why you can't reuse the same cursor object? I know > when you're writing to a database, you have to be sure to commit your > changes. But if I'm just issuing execute statements and then fetching > data, is it okay to reuse the same cursor? No, there is no reason. You can reuse a single cursor as often as you like provided you are happy to take responsibility for keeping the transactions clean - eg not trying to read data from one while writing at the same time, or combining two different selects, and committing between each change transaction. But most folks find multiple cursors easier to manage in the same way that they find multiple variables easier than reusing a minimal number. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Thu Aug 13 13:21:08 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 07:21:08 -0400 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <4A83323A.900@otenet.gr> References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> <4A819132.3000201@ieee.org> <9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com> <4A829C4D.9010407@ieee.org> <4A83323A.900@otenet.gr> Message-ID: <4A83F724.9030207@ieee.org> Nick Raptis wrote: >
Dave > Angel wrote: >> As I said, you'd probably get in trouble if any of the lines had '&' >> or '<' characters in them. The following function from the standard >> library can be used to escape the line directly, or of course you >> could use the function Nick supplied. >> >> xml.sax.saxutils.escape(/data/[, /entities/]) >> >> Escape '&', '<', and '>' in a string of data. >> >> You can escape other strings of data by passing a dictionary as the >> optional /entities/ parameter. The keys and values must all be >> strings; each key will be replaced with its corresponding value. The >> characters '&', '<' and '>' are always escaped, even if /entities/ >> is provided. >> >> Let us know if that doesn't do the trick. >> >> DaveA >> > Thanks Dave for the info on xml.sax.saxutils.escape > Didn't know about this one. > > For the rest: > It is sometimes > This is the source code of the xml.sax.saxutils.escape function: > > --------------------------------------- > def __dict_replace(s, d): > """Replace substrings of a string using a dictionary.""" > for key, value in d.items(): > s = s.replace(key, value) > return s > > def escape(data, entities={}): > """Escape &, <, and > in a string of data. > > You can escape other strings of data by passing a dictionary as > the optional entities parameter. The keys and values must all be > strings; each key will be replaced with its corresponding value. > """ > > # must do ampersand first > data = data.replace("&", "&") > data = data.replace(">", ">") > data = data.replace("<", "<") > if entities: > data = __dict_replace(data, entities) > return data > ----------------------------------------- > > As you can see, it too uses string.replace to do the job. > However, using a built-in function that works for what you want to do > is preferable. > It's tested and might also be optimized to be faster. > It's easy and fun to look into the source though and know exactly what > something does. > It's also one of the ways for a begginer (me too) to progress. > > From the source code I can see this for example: > *Don' t pass the entity dictionary I proposed earlier to this function:* > entities = {'&' : '&', > '<' : '<', > '>' : '>', > '"' : '"', > "'" : '''} > If you pass an entity for '&' into escape(), it will escape it in the > already partially escaped string, resulting in chaos. > > Think of it, this function not checking for a '&' entity passed to it > might worth qualifying as a bug :) > > Nick > > Yes, duplicating the & entitity would be a bug in the caller's code in this case. (see my posted improvements to the OP code, which removed the variable entities entirely) The question is whether this function's doc should have such a warning, or whether the function should make sure double-substitution does not happen. The & entity is the only predefined entity in the S3 standard that has this problem. For example, there's no entity that replaces the letter 'a' or the semicolon. And a quote sign is never used within an encoded entity. I think perhaps an improved version would either ignore a & key in the supplied dictionary, or throw an exception if one is encountered. The question that must always be answered is whether this could break existing code. There are legitimate reasons for a string to be escaped twice. Think what happens when a website wants to quote some html source code. Or a little less recursively, suppose you have a website teaching xml. The examples posted would need to be double-escaped. However, if someone had tried to do that in a single call to the current function, their code would already be broken because the dictionary doesn't preserve order, so the & substitution might not happen first. Such a user must call the escape function twice, without passing & at all. DaveA From zstumgoren at gmail.com Thu Aug 13 14:10:02 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 13 Aug 2009 08:10:02 -0400 Subject: [Tutor] best approach to db-api imports and cursor calls In-Reply-To: References: <1c2a2c590908121425j7b69d853xebf9a929e78313b4@mail.gmail.com> Message-ID: > But most folks find multiple cursors easier to manage in the same way that > they find multiple variables easier than reusing a minimal number. > That makes sense. I think I'll try using a global import/connect, and then create cursors inside each method. Thanks to you both for the advice! From cwitts at compuscan.co.za Thu Aug 13 14:56:31 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 13 Aug 2009 14:56:31 +0200 Subject: [Tutor] best approach to db-api imports and cursor calls In-Reply-To: References: <1c2a2c590908121425j7b69d853xebf9a929e78313b4@mail.gmail.com> Message-ID: <4A840D7F.4060904@compuscan.co.za> Serdar Tumgoren wrote: >> But most folks find multiple cursors easier to manage in the same way that >> they find multiple variables easier than reusing a minimal number. >> >> > That makes sense. I think I'll try using a global import/connect, and > then create cursors inside each method. > > Thanks to you both for the advice! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > You can also pass the connection object around from your __main__ so you can call .commit() and .rollback() when you need without polluting globals. -- Kind Regards, Christian Witts From airscorp at otenet.gr Thu Aug 13 15:33:49 2009 From: airscorp at otenet.gr (Nick Raptis) Date: Thu, 13 Aug 2009 16:33:49 +0300 Subject: [Tutor] To write data in two different fonts? In-Reply-To: <4A83F724.9030207@ieee.org> References: <9e3fac840908110738h74f0f91dp8e35d5ca99c36db4@mail.gmail.com> <4A819132.3000201@ieee.org> <9e3fac840908112116u324529adude8196a04e5ce992@mail.gmail.com> <4A829C4D.9010407@ieee.org> <4A83323A.900@otenet.gr> <4A83F724.9030207@ieee.org> Message-ID: <4A84163D.5040903@otenet.gr> Dave Angel wrote: > > However, if someone had tried to do that in a single call to the > current function, their code would already be broken because the > dictionary doesn't preserve order, so the & substitution might not > happen first. > Wow, I never thought about the dictionary not being sorted messing things up. Thanks for the insight. Nick From quasipedia at gmail.com Thu Aug 13 20:09:28 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 13 Aug 2009 20:09:28 +0200 Subject: [Tutor] Web framework: looking for python-tutor's angle. Message-ID: <1250186968.894.41.camel@jabbar> A couple of months ago I took the time to read a few articles on python web application frameworks and I got the impression that the two most mature and active projects are Zope and Django. Zope vs. Django hits 879.000 pages on google but much of the debate - or at least this is my impression - falls into the class "vi vs. emacs" or "gtk vs. qt" with many people singling out a single characteristics that for them is THE characteristic making one framework better than the other. This [1] graph seems to corroborate my final impression (i.e. that django is the way to go). Yet, I would be very interested in hearing what the members of this list think, as I particularly enjoy the "learner centered" approach that most of the people seems to have here. I believe my needs are quite ordinary: my customers are typically small businesses needing to process their data on a single server, sometime exposing part of the application as front-end to the customers (hence easy and flexible theming is important). I would definitively be happy to sacrifice some functionality in exchange for a leaner and cleaner design (i.e. more modular, elegant and intuitive), though. Thank you in advance for your time, Mac. [1] http://www.google.com/trends?q=python+zope%2C+python+django From oberoc at gmail.com Thu Aug 13 20:18:30 2009 From: oberoc at gmail.com (Tino Dai) Date: Thu, 13 Aug 2009 14:18:30 -0400 Subject: [Tutor] Web framework: looking for python-tutor's angle. In-Reply-To: <1250186968.894.41.camel@jabbar> References: <1250186968.894.41.camel@jabbar> Message-ID: <2ac5d4850908131118h5e7e7b9btbe5164ce0b7dae5a@mail.gmail.com> On Thu, Aug 13, 2009 at 2:09 PM, Mac Ryan wrote: > A couple of months ago I took the time to read a few articles on python > web application frameworks and I got the impression that the two most > mature and active projects are Zope and Django. > > Zope vs. Django hits 879.000 pages on google but much of the debate - or > at least this is my impression - falls into the class "vi vs. emacs" or > "gtk vs. qt" with many people singling out a single characteristics that > for them is THE characteristic making one framework better than the > other. > I have worked with both Zope and Django. When I worked with Zope, it had a lot of powerful features like their version of interfaces and zodb (zope object database - think of a high performance dictionary) but the learning curve was very high. After a couple of weeks of messing with it, my partner and I drop it for Django. Django allows you to get up and doing productive work in a couple of hours instead of a couple of days or weeks. If you are under any time constraints and do not have experience with either one, go with Django. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Aug 13 20:51:13 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 13 Aug 2009 14:51:13 -0400 Subject: [Tutor] Web framework: looking for python-tutor's angle. In-Reply-To: <2ac5d4850908131118h5e7e7b9btbe5164ce0b7dae5a@mail.gmail.com> References: <1250186968.894.41.camel@jabbar> <2ac5d4850908131118h5e7e7b9btbe5164ce0b7dae5a@mail.gmail.com> Message-ID: I've never used Zope so I can't speak to its strengths or weaknesses. But I can say that Django is quite natural if you already know Python. It certainly is modular, with a ton of apps that you can plug in to gain added functionality. And there's also a project called Pinax that provides layers of CMS-type functionality (e.g. authentication, blogging, wiki, etc.) that can save you from reinventing the wheel. Here are a few places to explore: http://djangoplugables.com/ http://pinaxproject.com/ Search Google Code for django HTH, Serdar From mland at us.ibm.com Thu Aug 13 21:30:41 2009 From: mland at us.ibm.com (Megan Land) Date: Thu, 13 Aug 2009 15:30:41 -0400 Subject: [Tutor] Dynamic Function Calls Message-ID: Hi, I'm trying to call a function from a dictionary. I did some googling and from what I can tell my code should work, but doesn't. Here's an example: def myFunc(self, inputList): dict={0: func0, 1: func1, 2:func2} for element in inputList: dict[element]() When I go to run this I get an error saying func0 is not defined. Does anyone have any ideas as to why this won't work? I'm using Python 2.6 if that makes any difference. Thanks! Megan Land FVT Blade EMET Test Engineer mland at us.ibm.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Aug 13 23:17:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Aug 2009 17:17:10 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: References: Message-ID: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: > Hi, > > I'm trying to call a function from a dictionary. I did some googling and > from what I can tell my code should work, but doesn't. Here's an example: > > def myFunc(self, inputList): > dict={0: func0, 1: func1, 2:func2} > for element in inputList: > dict[element]() > > When I go to run this I get an error saying func0 is not defined. Does > anyone have any ideas as to why this won't work? I'm using Python 2.6 if > that makes any difference. You don't show any definition for func0 in the above snippet. Where is it defined? Kent From alan.gauld at btinternet.com Fri Aug 14 01:50:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Aug 2009 00:50:18 +0100 Subject: [Tutor] Dynamic Function Calls References: Message-ID: "Megan Land" wrote > I'm trying to call a function from a dictionary. I did some googling and > from what I can tell my code should work, but doesn't. Here's an > example: > > def myFunc(self, inputList): The fact you have a self in there suggests that this is a method of some class? Is it? If not remove the self. > dict={0: func0, 1: func1, 2:func2} What do you think this is doing? What are func0, func1 etc? Where are they defined? > for element in inputList: > dict[element]() This will work provided element exists in dict and dict[element] is a callable object, eg a function. But I recommend putting some error handling in for the cases where either of those two conditions is not true > When I go to run this I get an error saying func0 is not defined. Does > anyone have any ideas as to why this won't work? Because you haven't defined func0! try adding def func0(): print 'func0' def func1(): print 'func1' def func2(): print 'func2' above your function. Then it might work if you call you function like this: myFunc([func2,func0,func1]) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 14 01:55:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Aug 2009 00:55:05 +0100 Subject: [Tutor] Web framework: looking for python-tutor's angle. References: <1250186968.894.41.camel@jabbar> Message-ID: "Mac Ryan" wrote >A couple of months ago I took the time to read a few articles on python > web application frameworks and I got the impression that the two most > mature and active projects are Zope and Django. They are both mature and widely used, but for quite different markets. TurboGears is a more direct competitor to Django and there is no competitor (in the Python world) to Zope > This [1] graph seems to corroborate my final impression (i.e. that > django is the way to go). > > I believe my needs are quite ordinary: my customers are typically small > businesses needing to process their data on a single server, sometime > exposing part of the application as front-end to the customers That sounds like Django to me. Zope is better suited to large scale corporate type scenarios with high volumes. If Zope can't cope you really need to move to the big guns like BEA Weblogic etc.. But for SMEs Django (et al) is ideal. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mland at us.ibm.com Fri Aug 14 15:06:52 2009 From: mland at us.ibm.com (Megan Land) Date: Fri, 14 Aug 2009 09:06:52 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> Message-ID: All three methods are defined below the snippet I provided. def func(): code... def func0(): do stuff def func1(): do stuff def func2(): do stuff Megan Land FVT Blade EMET Test Engineer mland at us.ibm.com From: Kent Johnson To: Megan Land/Raleigh/Contr/IBM at IBMUS Cc: tutor at python.org Date: 08/13/2009 05:18 PM Subject: Re: [Tutor] Dynamic Function Calls Sent by: kent3737 at gmail.com On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: > Hi, > > I'm trying to call a function from a dictionary. I did some googling and > from what I can tell my code should work, but doesn't. Here's an example: > > def myFunc(self, inputList): > dict={0: func0, 1: func1, 2:func2} > for element in inputList: > dict[element]() > > When I go to run this I get an error saying func0 is not defined. Does > anyone have any ideas as to why this won't work? I'm using Python 2.6 if > that makes any difference. You don't show any definition for func0 in the above snippet. Where is it defined? Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: graycol.gif Type: image/gif Size: 105 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ecblank.gif Type: image/gif Size: 45 bytes Desc: not available URL: From zstumgoren at gmail.com Fri Aug 14 17:26:53 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 14 Aug 2009 11:26:53 -0400 Subject: [Tutor] rationale for nested classes? Message-ID: Hi everyone, I was wondering if there's anyone who can offer a use case/rationale for nested class? For, instance, in the following example (taken from here: http://www.brpreiss.com/books/opus7/html/page598.html): class A(object): def __init__(self): self.y = 0 class B(object): def __init__(self): self.x = 0 def f(self): pass My initial thought was that perhaps they inherit the behavior of parent classes, but that apparently is not the case: Are there specific situations when nested classes come in handy (perhaps for grouping conceptually related classes that don't share attributes?). Or is it typically better to keep all classes on the same level of a heirarchy, and then just use inheritance to establish parent-child relationships where appropriate? Thanks! From zstumgoren at gmail.com Fri Aug 14 17:33:53 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 14 Aug 2009 11:33:53 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: <200908141528.n7EFSxMo018574@tlgmlp01.teamlog.com> References: <200908141528.n7EFSxMo018574@tlgmlp01.teamlog.com> Message-ID: 2009/8/14 Genevi?ve DIAGORN : > Bonjour, > Je suis absente jusqu'au 02/09 inclus. > Good to know. From bgailer at gmail.com Fri Aug 14 18:30:18 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Aug 2009 12:30:18 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> Message-ID: <4A85911A.3050203@gmail.com> Megan Land wrote: > > All three methods are defined below the snippet I provided. > In Python names must be defined before they are referenced. Put these defs above the snippet. > > def func(): > code... > def func0(): > do stuff > def func1(): > do stuff > def func2(): > do stuff > > Megan Land > FVT Blade EMET Test Engineer > mland at us.ibm.com > > Inactive hide details for Kent Johnson ---08/13/2009 05:18:10 PM---On > Thu, Aug 13, 2009 at 3:30 PM, Megan Land ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan > Land wrote: > Hi, > > > From: > Kent Johnson > > To: > Megan Land/Raleigh/Contr/IBM at IBMUS > > Cc: > tutor at python.org > > Date: > 08/13/2009 05:18 PM > > Subject: > Re: [Tutor] Dynamic Function Calls > > Sent by: > kent3737 at gmail.com > > ------------------------------------------------------------------------ > > > > On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: > > Hi, > > > > I'm trying to call a function from a dictionary. I did some googling and > > from what I can tell my code should work, but doesn't. Here's an > example: > > > > def myFunc(self, inputList): > > dict={0: func0, 1: func1, 2:func2} > > for element in inputList: > > dict[element]() > > > > When I go to run this I get an error saying func0 is not defined. Does > > anyone have any ideas as to why this won't work? I'm using Python 2.6 if > > that makes any difference. > > You don't show any definition for func0 in the above snippet. Where is > it defined? > > Kent > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From wan at walrus.us Fri Aug 14 17:56:19 2009 From: wan at walrus.us (Vincent Wan) Date: Fri, 14 Aug 2009 11:56:19 -0400 Subject: [Tutor] awk, test Message-ID: <14A14F7E-FC4C-4D32-B5B0-0F059EBC7821@walrus.us> Hi Todd, Did you get your searches running? Have you had a chance to look at my exam? Are you planning to go next door for beer some day next week? If so, do you know when. I'd like to stop by and chat. Best, Vincent ---------------------------------------------------------------------- Assistant Professor of Biology Farmingdale State College (State University of New York) PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago Ending soon! From bgailer at gmail.com Fri Aug 14 19:21:39 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Aug 2009 13:21:39 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: References: Message-ID: <4A859D23.8020904@gmail.com> Serdar Tumgoren wrote: > Hi everyone, > > I was wondering if there's anyone who can offer a use case/rationale > for nested class? > In my Python Pipelines program I have: class Count: ... class Counter: ... When an instance of Count is created, one or more instances of Counter are created, belonging to that instance. There is no need for the Counter class to be visible anywhere outside the Count class. Nesting the definition makes that clear and puts the definition where it is easy to find. Also some day (down the road) there might be some other class in which I'd like to create instances of another class named Counter. Nesting the Counter classes makes that possible. > For, instance, in the following example (taken from here: > http://www.brpreiss.com/books/opus7/html/page598.html): > > class A(object): > > def __init__(self): > self.y = 0 > > class B(object): > > def __init__(self): > self.x = 0 > > def f(self): > pass > > My initial thought was that perhaps they inherit the behavior of > parent classes, but that apparently is not the case: > > Are there specific situations when nested classes come in handy > (perhaps for grouping conceptually related classes that don't share > attributes?). > > Or is it typically better to keep all classes on the same level of a > heirarchy, and then just use inheritance to establish parent-child > relationships where appropriate? > > -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Fri Aug 14 19:40:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Aug 2009 18:40:42 +0100 Subject: [Tutor] rationale for nested classes? References: Message-ID: "Serdar Tumgoren" wrote > I was wondering if there's anyone who can offer a use case/rationale > for nested class? It provides another level of name hiding but personally I don;t think there is much benefit. If you keep the related classses in the same module that should be good enough IMHO. But the fact that you can have nested classes isn't a bad thing, it keeps Python consistent, but its not too userful in my view. > class A(object): > class B(object): > My initial thought was that perhaps they inherit the behavior of > parent classes, but that apparently is not the case: Nope, inheritance is done by inheritance! :-) > Are there specific situations when nested classes come in handy > (perhaps for grouping conceptually related classes that don't share > attributes?). Really only used if you have a special kind of thing that is only ever going to be used inside your outer class. But its only an indicator because you can still use A.B to access the class from outside! So its a mild deterrant not a real barrier. > Or is it typically better to keep all classes on the same level of a > heirarchy, and then just use inheritance to establish parent-child > relationships where appropriate? Yes, but nesting really has nothing to do with inheritance. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Fri Aug 14 19:52:34 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 13:52:34 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: <4A85911A.3050203@gmail.com> References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> <4A85911A.3050203@gmail.com> Message-ID: <4A85A462.2040504@ieee.org> bob gailer wrote: >
Megan > Land wrote: >> >> All three methods are defined below the snippet I provided. >> > > In Python names must be defined before they are referenced. Put these > defs above the snippet. > >> >> def func(): >> code... >> def func0(): >> do stuff >> def func1(): >> do stuff >> def func2(): >> do stuff >> >> Megan Land >> FVT Blade EMET Test Engineer >> mland at us.ibm.com >> >> Inactive hide details for Kent Johnson ---08/13/2009 05:18:10 PM---On >> Thu, Aug 13, 2009 at 3:30 PM, Megan Land> ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan >> Land wrote: > Hi, >> >> >> From: >> Kent Johnson >> >> To: >> Megan Land/Raleigh/Contr/IBM at IBMUS >> >> Cc: >> tutor at python.org >> >> Date: >> 08/13/2009 05:18 PM >> >> Subject: >> Re: [Tutor] Dynamic Function Calls >> >> Sent by: >> kent3737 at gmail.com >> >> ------------------------------------------------------------------------ >> >> >> >> On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: >> > Hi, >> > >> > I'm trying to call a function from a dictionary. I did some >> googling and >> > from what I can tell my code should work, but doesn't. Here's an >> example: >> > >> > def myFunc(self, inputList): >> > dict={0: func0, 1: func1, 2:func2} >> > for element in inputList: >> > dict[element]() >> > >> > When I go to run this I get an error saying func0 is not defined. Does >> > anyone have any ideas as to why this won't work? I'm using Python >> 2.6 if >> > that makes any difference. >> >> You don't show any definition for func0 in the above snippet. Where is >> it defined? >> >> Kent >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > You can put these defs in any order. But when you invoke the function from your outerlevel code, all of them need to have been defined. I'm guessing you had these in this order: def myFunc(self, inputList): dictionary={0: func0, 1: func1, 2:func2} for element in inputList: dictionary[element]() ... myFunc(3, 1, 2, 1) #this is too early in the file, because the following defs have not been defined yet def func(): code... def func0(): do stuff def func1(): do stuff def func2(): do stuff #move the call to myFunc() here Move the outerlevel code to the end, and you're usually better off. You also might want to put it inside an if __name__ == "__main__": clause. Note, I also changed the variable 'dict' to 'dictionary,' since dict already has a meaning in Python. Not a big deal in this particular case, but if you ever wanted to convert a list to a dict, and called dict(), you'd wonder what went wrong. Better to kill the habit early. DaveA From mland at us.ibm.com Fri Aug 14 19:59:05 2009 From: mland at us.ibm.com (Megan Land) Date: Fri, 14 Aug 2009 13:59:05 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: <4A85A462.2040504@ieee.org> References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> <4A85911A.3050203@gmail.com> <4A85A462.2040504@ieee.org> Message-ID: From: Dave Angel To: bob gailer Cc: Megan Land/Raleigh/Contr/IBM at IBMUS, tutor at python.org Date: 08/14/2009 01:53 PM Subject: Re: Re: [Tutor] Dynamic Function Calls bob gailer wrote: >
Megan > Land wrote: >> >> All three methods are defined below the snippet I provided. >> > > In Python names must be defined before they are referenced. Put these > defs above the snippet. > >> >> def func(): >> code... >> def func0(): >> do stuff >> def func1(): >> do stuff >> def func2(): >> do stuff >> >> Megan Land >> FVT Blade EMET Test Engineer >> mland at us.ibm.com >> >> Inactive hide details for Kent Johnson ---08/13/2009 05:18:10 PM---On >> Thu, Aug 13, 2009 at 3:30 PM, Megan Land> ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan >> Land wrote: > Hi, >> >> >> From: >> Kent Johnson >> >> To: >> Megan Land/Raleigh/Contr/IBM at IBMUS >> >> Cc: >> tutor at python.org >> >> Date: >> 08/13/2009 05:18 PM >> >> Subject: >> Re: [Tutor] Dynamic Function Calls >> >> Sent by: >> kent3737 at gmail.com >> >> ------------------------------------------------------------------------ >> >> >> >> On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: >> > Hi, >> > >> > I'm trying to call a function from a dictionary. I did some >> googling and >> > from what I can tell my code should work, but doesn't. Here's an >> example: >> > >> > def myFunc(self, inputList): >> > dict={0: func0, 1: func1, 2:func2} >> > for element in inputList: >> > dict[element]() >> > >> > When I go to run this I get an error saying func0 is not defined. Does >> > anyone have any ideas as to why this won't work? I'm using Python >> 2.6 if >> > that makes any difference. >> >> You don't show any definition for func0 in the above snippet. Where is >> it defined? >> >> Kent >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > You can put these defs in any order. But when you invoke the function from your outerlevel code, all of them need to have been defined. I'm guessing you had these in this order: def myFunc(self, inputList): dictionary={0: func0, 1: func1, 2:func2} for element in inputList: dictionary[element]() ... myFunc(3, 1, 2, 1) #this is too early in the file, because the following defs have not been defined yet def func(): code... def func0(): do stuff def func1(): do stuff def func2(): do stuff #move the call to myFunc() here Move the outerlevel code to the end, and you're usually better off. You also might want to put it inside an if __name__ == "__main__": clause. Note, I also changed the variable 'dict' to 'dictionary,' since dict already has a meaning in Python. Not a big deal in this particular case, but if you ever wanted to convert a list to a dict, and called dict(), you'd wonder what went wrong. Better to kill the habit early. DaveA I have the method inside a main method at the end of my program. The weird thing is that I typed up my small example and ran it and it worked fine. But when I run my big program, I still get the error that func0, as I call it in my example, is not defined. Do you think there could be something else in my program that is making this go wrong? Megan Land FVT Blade EMET Test Engineer mland at us.ibm.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: graycol.gif Type: image/gif Size: 105 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ecblank.gif Type: image/gif Size: 45 bytes Desc: not available URL: From zstumgoren at gmail.com Fri Aug 14 20:05:34 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 14 Aug 2009 14:05:34 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: References: Message-ID: Okay, those explanations definitely help. I thought I had run into a situation where nested classes might be called for, but I think plain-old inheritance is really what I'm after. Many thanks! From questions.anon at gmail.com Fri Aug 14 20:22:37 2009 From: questions.anon at gmail.com (questions anon) Date: Fri, 14 Aug 2009 11:22:37 -0700 Subject: [Tutor] calculate values of raster from vector Message-ID: Is there a way I could read in a raster image, read in a shapefile image and then calculate the mean and standard deviation of the raster values within the shapefile? -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.miesner at gmail.com Fri Aug 14 19:08:44 2009 From: michael.miesner at gmail.com (Michael Miesner) Date: Fri, 14 Aug 2009 13:08:44 -0400 Subject: [Tutor] write program to extract data Message-ID: <8f6846bb0908141008v6c495204he0aef2c99a3e3511@mail.gmail.com> Hi- I work in a research lab and part of the lab I'm not usually associated with uses a program that outputs data in a .txt file for each participant that is run. The participant # is the title of the text document (ie E00343456.txt) style and I'd like to be able to take this and other data in the file and draw it into a spreadsheet. The first 3/4 of the output is the scenario. I've bolded the areas that I really want to be able to draw out. In case some people cant see the bold, they are the sections called "driver mistakes" and individual mistakes. Preferably, what I'd really like to do is make the script so that I execute it, and in doing so, tell it what folder to look in, and it takes all the .txt's out of that folder, and adds them to the spreadsheet. I'd like the title of the .txt to be the first column, and the data held in the spreadsheet to be the be the next columns. Below is output of 1 data file. ---------------------------------------------------------------- Date: August 13, 2009 Time: 12:16:18:151 PM ID: Scenario file: C:\Documents and Settings\APL02\Desktop\Driving Sim Files\Sim 10-21-08.txt Configuration file: C:\STISIM\2-49444.Cfg STISIM Drive kernel build: Build 2.10.00 Name: Run #: Comments: Scenario: 0,ROAD,12,2,1,2,1,10,10,.5,.5, 300, -1,-1, -5,6,-5,6, 60,20,-70,30, 0,0,0, C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 0,TREE, 150, 0,*1~18;-15;-4, 20,100,0 0, SIGN, 100, 200, C:\STISIM\Data\Signs\SP55MPH.3DS, 0, 0, 0 0, c,0,500,1000,500,0.0010472 200,LS,55,0 990, SIGN, 100, 1500, C:\STISIM\Data\Signs\RGTCRV30.3DS, 0, 0, 0 1000,VC,500, 0.0077 2000, SIGN, 100, 1150, C:\STISIM\Data\Signs\SLIPPERY.3DS, 0, 0, 0 2200,A,*1,1000,-6,*19~24 2500, c,0,60,500,60,0.0042075 3000,VC,500,-0.0077 3120, c,0,60,500,60,-0.0042075 3740, c,0,60,500,60, 0.0052075 4360, c,0,60,500,60,-0.0042075 4500, SIGN, 100, 1480, C:\STISIM\Data\Signs\LFTCRV40.3DS, 0, 0, 0 5000,VC,500, 0.0075 5700,A,65,1000,-4,15 5700,A,65,1010,-8,15 5700,A,65,1020,-3,15 5700,A,65,1030,-8,15 5700,A,65,1040,-3,15 5700,A,65,1050,-8,15 5700,A,65,1060,-3,15 5700,A,65,1085,-6,15 5980, c,0,60,500,60,-0.0042075 6600, c,0,60,500,60, 0.0042075 6600,A,*10,1000,-6,*34~35 7000,VC,500,-0.0075 7300, c,0,500,1000,500, 0.0010472 7800,ROAD,12,2,1,1,1,10,10,.5,.5, 100, -1,-1, -5,6,-5,6, -30,10,-30,10, 0,0,0, C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 8000, TREE, 50, 0,*1~16;-15;-4;-10;-7;-2;-6, 50,100,0 8000, SIGN, 100, 200, C:\STISIM\Data\Signs\SP55MPH.3DS, 0, 0, 0 8000,V, 25, 800, 6, 1, 17, 8200,LS,55,0 8200, PR,C:\STISIM\SOUND\truck passing.wav,0 8600,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 9150,A, 88,1000, -6, *30~34, 4,0,160,.5 9350,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 9450,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 9500,C,0,100,750,100,-.00016 9600,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 10000,VC,400,0.0065 10150,A, 88,1000, -6, *30~34, 4,0,160,.5 10350,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 10450,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 10500,C,0,100,750,100, .00016 10600,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 10700,BLDG, 2100, 60, H2 10700,BLDG, 2160,-60, H*2;4~7;9;13 10700,BLDG, 2200, 60, H*2;4~7;9;13 10700,BLDG, 2250,-60, H*2;4~7;9;13 10700,BLDG, 2300, 60, H7 10700,BLDG, 2350,-60, H*2;4~7;9;13 10700,BLDG, 2400, 60, H*2;4~7;9;13 10700,BLDG, 2450,-60, H*2;4~7;9;13 10700,BLDG, 2500, 60, H*2;4~7;9;13 10700,BLDG, 2550,-60, H4 10700,BLDG, 2600, 60, H*4;5 10700,BLDG, 2650,-60, H*2;4~7;9;13 10700,BLDG, 2710, 60, H*2;4~7;9;13 10700,BLDG, 2750,-60, H*2;4~7;9;13 10700,BLDG, 2800, 60, H*2;4~7;9;13 10700,BLDG, 2850,-60, H*2;4~7;9;13 10700,BLDG, 2950,-60, H*2;4~7;9;13 10700,BLDG, 3000, 60, H*2;4~7;9;13 10700,BLDG, 3040,-60, H5 10700,BLDG, 3100,-60, H*4;5 10900,BLDG, 2700, 60, H7 10900,BLDG, 2900, 60, H*4;5 11000,VC,400,-0.0065 11000,SIGN,100,200,C:\STISIM\Data\Signs\SP35MPH.3ds 11150,A, 88,1000, -6, *30~34, 4,0,160,.5 11350,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 11400,BLDG, 2510, 60, H*2;4~7;9;13 11400,BLDG, 2510,-60, H*2;4~7;9;13 11400,BLDG, 2600, 60, H*2;4~7;9;13 11400,BLDG, 2630,-60, H10 11400,BLDG, 2700, 60, H*2;4~7;9;13 11400,BLDG, 2750,-60, H*2;4~7;9;13 11400,BLDG, 2800, 60, H*2;4~7;9;13 11400,BLDG, 2850,-60, H*2;4~7;9;13 11400,BLDG, 2900, 60, H*2;4~7;9;13 11400,BLDG, 2950,-60, H*2;4~7;9;13 11450,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 11600,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 4,0,160,.5 12000,ROAD,18,2,1,0,1,0,0,0,0,100,-1,-1, 0,6,0,6, 0,5,0,5, 0, 0,0, C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 12500,C,0,100,750,100, .00016 12500, SIGN, 100, 120, C:\STISIM\Data\Signs\SP25MPH.3DS, 0, 0, 0 12500, BLDG, 2050, 60, S1 12500, BLDG, 2170, 60, S3 12500, BLDG, 2270, 56, S4 12500, BLDG, 2400, 60, S5 12500, BLDG, 2450, 60, S6 12500, BLDG, 2530, 65, S7 12500, BLDG, 2630, 60, S17 12500, BLDG, 2730, 60, S9 12500, BLDG, 2820, 65, G1 12500, BLDG, 2890, 60, G7 12500, BLDG, 2930, 55, G8 12500, BLDG, 2050,-60, S10 12500, BLDG, 2150,-60, S11 12500, BLDG, 2250,-63, S12 12500, BLDG, 2350,-60, S13 12500, BLDG, 2450,-68, S15 12500, BLDG, 2550,-60, S16 12500, BLDG, 2670,-60, S14 12500, BLDG, 2755,-60, S8 12500, BLDG, 2844,-60, S1 12500, BLDG, 2924,-60, G3 12500, BLDG, 2930, 170, S1, 90 12500, BLDG, 2930, 270, S3, 90 12700,TREE, 70,0,*1~18,31,60,0 12700,CT, 300, 5, 40, 0, L, 4, 1 12700,CT, 515, 5, 40, 0, L, *21~23;1;2;30;31, 1 12700,CT, 515, 5, -40, 0, L, *21~23;1;2;30;31, 1 12700,V, 0, 400, 17, 1, 20 12700,V, 0, 500, 17, 1, 21 12700,V, 0, 550, 17, 1, 22 12700,A, 0, 440,-14, 23 12700,A, 0, 530,-14, 35 12700,A, 0, 660,-15, 24 12700,CT, 166, 5, 65, 0, R, 33, 1 12700,CT, 700, 5, 40, 0, L, *21~23;1;2;30;31, 1 12700,CT, 1060, 5, -40, 0, R, *21~23;1;2;30;31, 1 12700,V, 10, 550, 10, 1, 36 12800,I,1,550,0,0,0 12800, SIGN,12, 500, 0, 0, 0, 0 12900,V, 0, 500, 17, 1, *18~35 12900,V, 0, 530, 17, 1, *18~35 12900,V, 0, 620, 17, 1, *18~35 12900,V, 0, 800, 17, 1, *18~35 12900,A, 0, 545,-14, *18~35 12900,A, 0, 624,-14, *18~35 12900,A, 0, 750,-14, *10-13 12900,A, 0, 800,-14, *10~13 12900,A, 0, 830,-15, *19 12900,PED, 840, 3, 8.5, -23, L, 11 12900,PED, 842, 0, 0, 45, R, *4~5 12900,A, 0, 885,-14, *35 12900,CT, 936, 5, 60, 0, L, 18, 1 12900,I,0,950,0,0,0 12900,SIGN,7,-950,5,0,0,0 12900, A, 40, 1030, -6, *20~27 12900,PED, 930, 6, 6, 26, F, *6 12900,I,0,2600,0,4,4 12920,LS,25,0 13246,ROAD,18,2,1,0,1,0,0,0,0,65,0,0,0,6,0,6,0,5,0,5, 0 13325,TREE, 0,0,0,0,0,0 13389,ROAD,18,2,1,0,1,0,0,0,0,65,-1,-1, 0,6,0,6, 0,5,0,5, 0, 0,0, C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 13500,PED, 170, 6, 5.3, 26, F, *1~10 13500, BLDG, 2091, 45, B4 13500, BLDG, 2160, 60, S10 13500, BLDG, 2250, 60, S11 13500, BLDG, 2350, 63, S12 13500, BLDG, 2450, 60, S13 13500, BLDG, 2550, 68, S15 13500, BLDG, 2650, 60, S16 13500, BLDG, 2770, 60, S14 13500, BLDG, 2855, 60, S8 13500, BLDG, 2944, 60, S1 13500, BLDG, 3015, 60, G3 13500, BLDG, 2081, -60,G11 13500, BLDG, 2150, -60, S1 13500, BLDG, 2270, -60, S3 13500, BLDG, 2370, -56, S4 13500, BLDG, 2500, -60, S5 13500, BLDG, 2550, -60, S6 13500, BLDG, 2630, -65, S7 13500, BLDG, 2730, -60, S17 13500, BLDG, 2830, -60, S9 13500, BLDG, 2920, -65, G1 13500, BLDG, 2990, -60, G7 13500, BLDG, 2100, 190, S10, -90 13500, BLDG, 2100, 290, S11, -90 13500, BLDG, 2100,-290, S12,-90 13500, BLDG, 2100, 490, S13,-90 13500, BLDG, 2100,-490, S13,-90 13580,I,0,3000,1,4,4 13746,ROAD,18,2,1,0,1,0,0,0,0,65,0,0,0,6,0,6,0,5,0,5, 0 13825,TREE, 0,0,0,0,0,0 13889,ROAD,18,2,1,0,1,0,0,0,0,65,-1,-1, 0,6,0,6, 0,5,0,5, 0, 0,0, C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 13890,TREE, 70,0,*1~18,31,60,0 14000, C,0, 300, 400, 500, .002 14190,TREE, 70,0,*1~18,31,60,0 14425,TREE, 0,0,0,0,0,0 14500,ROAD, 12,6,3,2,4.5,10,10,.4,.4, 0, -1,-1,0,0,0,0,0,10,0,10,4, , , C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 14500,SIGN,100,200,C:\STISIM\Data\Signs\SP35MPH.3ds 14500, TREE, 50, 0, 1, 40, 41, 0 14500,V, 0, 240, 34, 1, 3, -3,-16,40,2, 2,0,/0,1 14500,V, 0, 280, 34, 1, *18~35 14500,V, 0, 460, 34, 1, *18~35 14500,V, 0, 500, 34, 1, *18~35 14500,V, 0, 580, 34, 1, *18~35 14500,V, 0, 620, 34, 1, 3 14500,V, .01, 920, 32, 1, 8, 10,0,-120,1 14500,A, 0, 470,-34, 3 14500,A, 0, 680,-34, *18~35 14500,A, 0, 700,-34, *18~35, 6,16, 50, 2 14500,A, 0, 760,-34, *18~35 14500,A, 0, 800,-34, *18~35 14500,A, 0, 820,-34, *18~35 14500,A, 0, 840,-34, *18~35 14500, A, 40, 800,-7,3 14500, A, 40, 840,-21,*1~5 14500, V, /5, 320, 7, 1, 3 14500,SL,-1000, 0, 2, 8, 2, 24, 6 14500,PED, 250, 1.7, 5,30,R,*1~8 14500,PED,900, 0, 0, 42,R,*1~8 14500,PED,925, 0, 0, 45,R,*1~8 14500,PED,945, 0, 0, 48,R,*1~8 14500,PED,950, 4, 4, 47,F,*1~8 14500, CT, 994,5, -1000, 45, L, *21~27;30~32, 1 14500, CT, 994,5, -1000, 45, L, *21~27;30~32, 1 14500, Ct, 982,5, -1030, 43, L, *21~23;19;35, 1 14500, Ct, 982,5, -1030, 43, L, *21~23;19;35, 1 14500, CT, 1006,5, 1000, 50, R, *21~27;30~32, 1 14500, Ct, 1018,5, 1000, 45, R, *21~23;19;35, 1 14500, CT, 1006,5, 1030, 50, R, *21~27;30~32, 1 14500, Ct, 1018,5, 1030, 43, R, *21~23;19;35, 1 14500,CT, 971, 5, 70, 0, L, 8, 1 14675, BLDG, 2000, 85, B5, -90 14675, BLDG, 2000, 175, B10, -90 14680, V, 0, 1000, 27,1, 36, 4,0,20,2, -.5,0,/-5,1 14700,LS,35,0 15000,V, 0, 620, 34, 1, 3 15000,V, 0, 640, 34, 1, *18~35 15000,V, 0, 660, 34, 1, *18~35 15000,V, 0, 780, 34, 1, *18~35 15000,V, 0, 900, 34, 1, *3 15000,V, 0, 940, 34, 1, *18~35 15000,V, 0, 1060, 34, 1, *18~35 15000,A, 0, 640,-34, *18~35 15000,A, 0, 700,-34, 3 15050,V, 0, 1245, 32, 1, 16 15050,V, 0, 1275, 34.5, 1, 3, 3,-13,10,1 15050,V, 0, 1330, 34, 1, 3 15050,PED, 1220,7, 5, 44,F,*1~8;-4;-5 15050,PED, 1220,7, 5, 46,F,*1~8;-4;-5 15100, A, 40,1000,-7,*1~13 15100, A, 45,1000,-21,*29~34 15185,V, .1,1000, 6,1,*18~35, 15255,V, .1,1000, 6,1,*18~35, 10,0,-150,2, 15285,V, .1,1000, 6,1,*18~35, 10,0,-150,2, 7,12,65,2 15325,V, .1,1000, 6,1,*18~35, 11,0,-150,2, 15365,V, .1,1000, 6,1,*18~35, 12,0,-150,2 15379,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,0,0,0,0,0,0,0,10,0,10,4 15405,V, .1,1000, 6,1,*18~35, 13,0,-150,2 15444,TREE, 0, 0, 0, 0, 0, 0 15445,V, .1,1000, 6,1,*18~35, 14,0,-150,2 15556,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65, -1,-1,0,0,0,0,0,10,0,10,4, , , C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 15556,TREE, 30, 0, 1, 40, 41, 0 15556,TREE, 30, 0, 1, 40, 41, 0 15560,PR,C:\STISIM\SOUND\nextright.wav,0 15580, SL,-1000,5,5,10,0,24,6,1 15585,V, .1,1000, 6,1,*18~35, 14,0,-150,2 15615,V, .1,1000, 6,1,*18~35, 15,0,-150,2 16200,CSET,0,18 16459,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,0,0,0,0,0,0,0,10,0,10,4 16530,TREE, 0, 0, 0, 0, 0, 0 16636,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65, -1,-1,0,0,0,0,0,10,0,10,4, , , C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 18000,0,ROAD,12,2,1,2,1,10,10,.5,.5, 300, -1,-1, -5,6,-5,6, 60,20,-70,30, 0,0,0, C:\STISIM\Data\Textures\Dirt09.Jpg,12,C:\STISIM\Data\Textures\Grass03.Jpg,12 18000, SIGN, 100, 200, C:\STISIM\Data\Signs\SP55MPH.3DS, 0, 0, 0 18000,BARL,1000,0,0,0,0,0,0,0, 0,2,1 18000,A,66,1000,-16,*1~8 18000,BLDG, 2100, 80,H*12~16 18000,BLDG, 2150,-80,H*12~16 18000,BLDG, 2200, 80,H*12~16 18000,BLDG, 2250,-80,H*12~16 18000,BLDG, 2300, 80,H*12~16 18000,BLDG, 2350,-80,H*12~16 18000,BLDG, 2400, 80,H*12~16 18000,BLDG, 2450,-80,H*12~16 18000,BLDG, 2500, 80,H*12~16 18000,BLDG, 2550,-80,H*12~16;-15 18000,BLDG, 2600, 80,H*12~16;-15 18000,BLDG, 2750,-80,H*12~16;-15 18000,BLDG, 2700, 80,H*12~16;-15 18000,BLDG, 2750,-80,H*12~16;-15 18000,BLDG, 2800, 80,H*12~16;-15 18000,BLDG, 2850,-80,H*12~16;-15 18000,BLDG, 2950, 80,H*12~16;-15 18030,BARL,1000,0,0,0,0,0,0,0, -3,2,1 18030,BARL,1000,0,0,0,0,0,0,0, 3,2,1 18060,BARL,1000,0,0,0,0,0,0,0, -5,2,1 18060,BARL,1000,0,0,0,0,0,0,0, 5,2,1 18087, PED, 1000, 0,0, 33, R,1 18090,BARL,1000,0,0,0,0,0,0,0, -7,2,1 18090,BARL,1000,0,0,0,0,0,0,0, 7,2,1 18090, PED, 1000, 0,0, 30, L,1 18100, V, 0, 1000, 30, 1, 14 18100,A,66,1000,-16,*1~8 18110,V,0,1000,0,1,6 18120,BARL,1000,0,0,0,0,0,0,0, -10,2,1 18120,BARL,1000,0,0,0,0,0,0,0, 10,2,1 18140, V, 0, 1000, 29, 1, 14 18150,BARL,1000,0,0,0,0,0,0,0, -13,2,1 18150,BARL,1000,0,0,0,0,0,0,0, 13,2,1 18150,BLCK,1000,0,-10,.3,20,.5,30,1, 18180,BARL,1000,0,0,0,0,0,0,0, -13,2,1 18180,BARL,1000,0,0,0,0,0,0,0, 13,2,1 18200,LS,55,0 18200,BLCK,1000,0,-10,.3,20,.5,30,1, 18200, V,0, 1000, 31, 1, 14 18200,A,66,1000,-16,*1~8 18210,BARL,1000,0,0,0,0,0,0,0, -13,2,1 18210,BARL,1000,0,0,0,0,0,0,0, 13,2,1 18240,BARL,1000,0,0,0,0,0,0,0, -13,2,1 18240,BARL,1000,0,0,0,0,0,0,0, 13,2,1 18250,BLCK,1000,0,-10,.3,20,.5,30,1, 18270,BARL,1000,0,0,0,0,0,0,0, -13,2,1 18270,BARL,1000,0,0,0,0,0,0,0, 13,2,1 18300,BARL,1000,0,0,0,0,0,0,0, -13,2,1 18300, SOBJ, 1000, 14.5, .4,10,20,90,C:\STISIM\Data\Barriers\Tube.3ds 18300,PED,1000,10,5,11.7,F,1 18300,A,66,1000,-16,*1~8 18305,V,0,1000,-1,1,7 18310,BARL,1000,0,0,0,0,0,0,0, 13,2,1 18330,BARL,1000,0,0,0,0,0,0,0, -10,2,1 18330,BARL,1000,0,0,0,0,0,0,0, 10,2,1 18350,A,0,1000,1,6 18360,BARL,1000,0,0,0,0,0,0,0, -7,2,1 18360,BARL,1000,0,0,0,0,0,0,0, 7,2,1 18385, PED, 1000, 0,0, 30, F,1 18390,BARL,1000,0,0,0,0,0,0,0, -5,2,1 18390,BARL,1000,0,0,0,0,0,0,0, 5,2,1 18390, SOBJ, 1000, 25, .4,10,20,-90,C:\STISIM\Data\Barriers\cone.3ds 18400,VC,500, 0.0075 18400,PED,1000,10,4,10,F,1 18400,A,66,1000,-16,*1~8 18410,BARL,1000,0,0,0,0,0,0,0,32,3,1 18410,BARL,1000,0,0,0,0,0,0,0,36,3,1 18420,BARL,1000,0,0,0,0,0,0,0, -3,2,1 18420,BARL,1000,0,0,0,0,0,0,0, 3,2,1 18440,V,0,1000,33,1,7 18450,BARL,1000,0,0,0,0,0,0,0, 0,2,1 18460,BARL,1000,0,0,0,0,0,0,0,22,1,1 18480,BARL,1000,0,0,0,0,0,0,0, 0,2,1 18480,BARL,1000,0,0,0,0,0,0,0,18,1,1 18485,I,0,3000,1,1,1 18500,A,66,1000,-16,*1~8 18505,BARL,1000,0,0,0,0,0,0,0,15,1,1 18525,BARL,1000,0,0,0,0,0,0,0,12.5,1,1 18545,BARL,1000,0,0,0,0,0,0,0,12.5,1,1 18555,BLCK,1000,0,13.5,.3,10,.5,20,1, 18565,BARL,1000,0,0,0,0,0,0,0,12.5,1,1 18585,BARL,1000,0,0,0,0,0,0,0,12.5,1,1 18600,A,66,1000,-16,*1~8 18605,BARL,1000,0,0,0,0,0,0,0,17.5,1,1 18625,BARL,1000,0,0,0,0,0,0,0,22,1,1 18700,A,66,1000,-16,*1~8 18735,I,0,3000,1,1,1 18800,C,0,400,900,400,0.0010472 18800,A,66,1000,-16,*1~8 18900,ROAD,12,4,2,2,1,10,10,.5,.5,100,-1,-1, 0,20,0,6, 30,15,0,10, 0 18900,A,66,1000,-16,*1~8 19000,VC,500,-0.0075 19000,CSET,0,18 19000,A,66,1000,-16,*1~8 19000,BLDG,2000,-80,H*12~16;-15 19000,BLDG,2050, 80,H*12~16;-15 19000,BLDG,2100,-80,H*12~16;-15 19000,BLDG,2150, 80,H*12~16;-15 19000,BLDG,2200,-80,H*12~16;-15 19000,BLDG,2250, 80,H*12~16;-15 19000,BLDG,2300,-80,H*12~16;-15 19000,BLDG,2350, 80,H*12~16;-15 19000,BLDG,2420, 40,B1 19100,A,66,1000,-16,*1~8 19200,A,66,1000,-16,*1~8 19300,A,66,1000,-16,*1~8 19505,CSET,0,6 19600,BLDG,2000, 80,H*12~16;-15 19650,BLDG,2000,-80,H*12~16;-15 19700,BLDG,2000, 80,H*12~16;-15 19750,BLDG,2000,-80,H*12~16;-15 19800,BLDG,2000, 80,H*12~16;-15 19850,BLDG,2000,-80,H*12~16;-15 19900,BLDG,2000, 80,H*12~16;-15 19950,BLDG,2000,-80,H*12~16;-15 20000,ROAD,12,4,2,4,.5,10,10,.4,.4,0, -1,-1, 0,6,0,6, 2,15,0,15, 10, C:\STISIM\Data\Textures\Road04.Jpg,12,C:\STISIM\Data\Textures\Road04.Jpg, 12,C:\STISIM\Data\Textures\Grass10.Jpg, 12, C:\STISIM\Data\Textures\Dirt04.Jpg,12,C:\STISIM\Data\Textures\Road04.Jpg, 12 20000, CSET,0,11 20000,TREE,100,0,*4;15, 40,50,0 20000, SIGN, 100, 200, C:\STISIM\Data\Signs\SP45MPH.3DS, 0, 0, 0 20000,V,0,1040,30,1,*1~4;18~35 20000,V,0,1100,30,1,*10~12;18~35 20000,V,.1,1175, 0,1,*1~4;18~35, 10,0,-150,3, 20000,V,0,1200,30,1,19 20000,A,0,500,-30,29 20000,A,0,650,-30,*2~4;18~35 20000,A,0,870,-30,*1;18~35 20000,A,0,990,-30,15, 10,13,65,2 20000,PED,1300,9,4,-25,F,*1~3 20000,A,0,1030,-30,*10~12 20000,A,0,1070,-30,*1~12;-9;-8;-5;18~35 20000,A,0,1110,-30,*1~12;-9;-8;-5 20000,A,0,1240,-30,*1~12;-9;-8;-5;18~35 20000,A,0,1280,-30,*1~12;-9;-8;-5 20000,A,0,1315,-30,*1~12;-9;-8;-5;18~35 20000,V,0,1735,30,1,*1~3 20000,V,0,1800,30,1,*10~12 20000,A,0,1770,-30,*1~12;-9;-8;-5 20000,A,0,1820,-30,*1~12;-9;-8;-5;18~35 20000,A,0,1860,-30,*1~12;-9;-8;-5 20000,A,0,1900,-30,*1~5;18~35 20000,A,0,2000,-30,*6~7 20000,PED,2500,8,7,35,F,*1~4 20000,BLDG,2000, 80,H*12~16;-15 20050,BLDG,2000,-80,H*12~16;-15 20100,BLDG,2000, 80,H*12~16;-15 20150,BLDG,2000,-80,H*12~16;-15 20200,LS,45,0 20200,BLDG,2000, 80,H*12~16;-15 20250,BLDG,2000,-80,H*12~16;-15 20300,BLDG,2000, 80,H*12~16;-15 20350,BLDG,2000,-80,H*12~16;-15 20380,TREE,0,0,0,0,0,0 20400,VC,600,0.0055 20400,BLDG,2000, 80,H*12~16;-15 20450,BLDG,2000,-80,H*12~16;-15 20500,PED,955,0,0,-28,L,*1~4, Left PED 20500,PED,955,0,0, 28,B,*1~4, Right Ped 20500, SIGN, 8, 750 20500,CT,977,5,-34,0,L,*1~4;18~35 20500,SL,-985,2,5,10,0, 24,6,1 20500,BLDG,2000, 80,H*12~16;-15 20550,BLDG,2000,-80,H*12~16;-15 20570,TREE,100,0,*1~18,37,50,0 20600,BLDG,2000, 80,H*12~16;-15 20650,BLDG,2000,-80,H*12~16;-15 20675,BLDG,2000, 50, B6 20750,PED,951,5,4.5,-28,L,*1~4, Left PED 20750,PED,955,4,4, 28,R,*1~4, Right Ped 20750, SIGN, 8, 750 20750,SL,-985,2,5,10,0, 30,6,1 20765,PED,1000,6,4,-28,L,*1~4 20850,BLDG,2000,-80,H*12~16;-15 20900,BLDG,2000, 80,H*12~16;-15 20950,BLDG,2000,-80,H*12~16;-15 21000,C,0,600,1000,600,-0.0009472 21000,VC,600,-0.0065 21000,BLDG,2000, 80,H*12~16;-15 21365,ROAD,12,4,2,4,.5,10,10,.4,.4,65,0,0,0,6,0,6,0,15,0,15, 10 21540,ROAD,12,4,2,4,.5,10,10,.4,.4,65, -1,-1, 0,6,0,6, 2,15,0,15, 10, C:\STISIM\Data\Textures\Road04.Jpg,12,C:\STISIM\Data\Textures\Road04.Jpg, 12,C:\STISIM\Data\Textures\Grass10.Jpg, 12, C:\STISIM\Data\Textures\Dirt04.Jpg,12,C:\STISIM\Data\Textures\Road04.Jpg, 12 21615,ROAD,12,4,2,4,.5,10,10,.4,.4,65,0,0,0,6,0,6,0,15,0,15, 10 21790,ROAD,12,4,2,4,.5,10,10,.4,.4,65, -1,-1, 0,6,0,6, 2,15,0,15, 10, C:\STISIM\Data\Textures\Road04.Jpg,12,C:\STISIM\Data\Textures\Road04.Jpg, 12,C:\STISIM\Data\Textures\Grass10.Jpg, 12, C:\STISIM\Data\Textures\Dirt04.Jpg,12,C:\STISIM\Data\Textures\Road04.Jpg, 12 21800,V,0,1000,30,1,*1~4 21830,A,0,1000,-30,*6~7 21835,V,0,1000,30,1,*6~7 21860,A,0,1000,-30,*1~4 21865,V,0,1000,30,1,*1~4 21900,A,0,1000,-30,*6~7 21920,V,0,1000,30,1,*6~7 21940,V,0,1000,30,1,*1~4 22540,PED,1000,7,5,-20,F,*1~4 22640,TREE,0,0,0,0,0,0 22820,TREE,100,0,*1~18,37,50,0 23000,ROAD,12,4,2,2,1,10,10,.5,.5,0,-1,-1, 0,6,0,6, 0,10,0,10, 0 23000, SIGN, 100, 200, C:\STISIM\Data\Signs\SP55MPH.3DS, 0, 0, 0 23000,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23000,A,66,1000,-16,*1~8 23030,BARL,1000,0,0,0,0,0,0,0, -3,2,1 23030,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23060,BARL,1000,0,0,0,0,0,0,0, -5,2,1 23060,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23087, PED, 1000, 0,0, 33, R,1 23090,BARL,1000,0,0,0,0,0,0,0, -7,2,1 23090,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23090, PED, 1000, 0,0, 30, L,1 23100, V, 0, 1000, 30, 1, 14 23100,A,66,1000,-16,*1~8 23110,V,0,1000,-6,1,6 23120,BARL,1000,0,0,0,0,0,0,0, -10,2,1 23120,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23140, V, 0, 1000, 29, 1, 14 23150,BARL,1000,0,0,0,0,0,0,0, -13,2,1 23150,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23180,BARL,1000,0,0,0,0,0,0,0, -13,2,1 23180,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23200,LS,55,0 23200, V,0, 1000, 31, 1, 14 23200,A,66,1000,-16,*1~8 23210,BARL,1000,0,0,0,0,0,0,0, -13,2,1 23210,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23240,BARL,1000,0,0,0,0,0,0,0, -13,2,1 23240,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23270,BARL,1000,0,0,0,0,0,0,0, -13,2,1 23270,BARL,1000,0,0,0,0,0,0,0, 0,2,1 23300,BARL,1000,0,0,0,0,0,0,0, -13,2,1 23300,PED,1000,10,5,-2.7,F,1 23300,A,66,1000,-16,*1~8 23305,V,0,1000,-7,1,7 23310,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23330,BARL,1000,0,0,0,0,0,0,0, -10,2,1 23330,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23350,A,0,1000,-6,6 23360,BARL,1000,0,0,0,0,0,0,0, -7,2,1 23360,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23385, PED, 1000, 0,0, 30, F,1 23390,BARL,1000,0,0,0,0,0,0,0, -5,2,1 23390,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23400,VC,500,0.0075 23400,PED,1000,10,4,-2,F,1 23400,A,66,1000,-16,*1~8 23420,BARL,1000,0,0,0,0,0,0,0, -3,2,1 23420,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23440,V,0,1000,33,1,7 23450,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23470,V,0,1000,40,1,14R, 2.5, -19,0,2, 23480,BARL,1000,0,0,0,0,0,0,0, 24,2,1 23500,A,66,1000,-16,*1~8 23505,BARL,1000,0,0,0,0,0,0,0,26,1,1 23525,BARL,1000,0,0,0,0,0,0,0,26.5,1,1 23545,BARL,1000,0,0,0,0,0,0,0,26,1,1 23565,BARL,1000,0,0,0,0,0,0,0,26,1,1 23585,BARL,1000,0,0,0,0,0,0,0,26.5,1,1 23600,A,66,1000,-16,*1~8 23605,BARL,1000,0,0,0,0,0,0,0,26.5,1,1 23625,BARL,1000,0,0,0,0,0,0,0,25,1,1 23700,A,66,1000,-16,*1~8 23800,C,0,400,900,400,0.0010472 23800,A,66,1000,-16,*1~8 23900,ROAD,12,4,2,2,1,10,10,.5,.5,100,-1,-1, 0,20,0,6, 30,15,0,10, 0 23900,A,66,1000,-16,*1~8 24000,VC,500,-0.0075 24000,CSET,0,18 24000,A,66,1000,-16,*1~8 24100,A,66,1000,-16,*1~8 24200,A,66,1000,-16,*1~8 24300,A,66,1000,-16,*1~8 24505,CSET,0,6 24600,ROAD,12,2,1,1,1,10,10,.5,.5, 100, -1,-1, -5,6,-5,6, -30,10,-30,10, 0,0,0, C:\STISIM\Data\Textures\Grass01.Jpg,12, 0,0, C:\STISIM\Data\Textures\Grass04.Jpg,12 24600, TREE, 50, 0,*1~16;-15;-4;-10;-7;-2;-6, 50,100,0 24600, SIGN, 100, 200, C:\STISIM\Data\Signs\SP55MPH.3DS, 0, 0, 0 24600,V, /1, 500, 6, 1, 17, 24800,LS,55,0 25600,VC,400,0.0075 25850,A,*1,1000,-6,*10~14 25950,A,*1,1000,-6,*1~35;-8;-9;-16;-3;-5 26000,VC,400,-0.0075 26050,A,*1,1000,-6,*1~35;-8;-9;-16;-3;-5 26100,C,0,100,750,100,-.00016 26500,A,*1,1000,-6,*1~35;-8;-9;-16;-3;-5 26600, BLCK, 300,0, 0, 3,3,3,3,7 26600,A,*1,1000,-6,*10~14 26602, BARL, 300,0,0,0,0,0,0,0, 1.5, 3,1 26700,A,*1,1000,-6,*30~34 26710, BLCK, 300,0, 13, 3,3,3,3,7 26712, BARL, 300,0,0,0,0,0,0,0, 14.5, 3,1 26800,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 26820, BLCK, 300,0, 2, 3,3,3,3,7 26822, BARL, 300,0,0,0,0,0,0,0, 3.5, 3,1 26900,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5, 27000, BLCK, 300,0, 2, 3,3,3,3,7 27002, BARL, 300,0,0,0,0,0,0,0, 3.5, 3,1 27050,A, 88,1000, -6, *1~35;-8;-9;-16;-17;-3;-5 27100,C,0,100,750,100, .00016 27150,A, 88,1200, -6, *1~35;-8;-9;-16;-17;-3;-5 27200, ROAD,12,2,1,1,1,10,10,.5,.5, 300, -1,-1, -5,6,-5,6, -30,10,-30,10, 0,0,0, C:\STISIM\Data\Textures\Grass01.Jpg,12, 0,0, C:\STISIM\Data\Textures\Grass04.Jpg,12 27200, TREE, 100, 0,*1~18;-15;-4, 50,100,0 27200, SIGN, 100, 100, C:\STISIM\Data\Signs\SP55MPH.3DS, 0, 0, 0 27300, LS,55,0 27450,A,*1,1000,-6,*10~14 27550,A,*1,1000,-6,*1~35;-8;-9;-16;-3;-5 27650,A,*1,1000,-6,*1~35;-8;-9;-16;-3;-5 27900,A,*1,1000,-6,17 28000, BLDG, 2050, 60, S1 28000, BLDG, 2170, 60, S3 28000, BLDG, 2270, 56, S4 28000, BLDG, 2400, 60, S5 28000, BLDG, 2450, 60, S6 28000, BLDG, 2530, 65, S7 28000, BLDG, 2630, 60, S17 28000, BLDG, 2730, 60, S9 28000, BLDG, 2820, 65, G1 28000, BLDG, 2890, 60, G7 28000, BLDG, 2930, 55, G8 28000, BLDG, 2050,-60, S10 28000, BLDG, 2150,-60, S11 28000, BLDG, 2250,-63, S12 28000, BLDG, 2350,-60, S13 28000, BLDG, 2450,-68, S15 28000, BLDG, 2550,-60, S16 28000, BLDG, 2670,-60, S14 28000, BLDG, 2755,-60, S8 28000, BLDG, 2844,-60, S1 28000, BLDG, 2924,-60, G3 28000,I,0,3000,3,4,4 28000, BLDG, 3100,-145, G6, 28000, BLDG, 3120,-280, S12,-90 28000, BLDG, 3135,-370, S13,-90 28000, BLDG, 3135,-490, S1, -90 28000, BLDG, 2885, -190, G1, 90 28000, BLDG, 2890, -290, G4, 90 28000, BLDG, 2825, -410, G10, 90 28000, BLDG, 2865, -550, S1, 90 28000, BLDG, 3091, 45, B4 28000, BLDG, 3160, 60, S10 28000, BLDG, 3250, 60, S11 28000, BLDG, 3350, 63, S12 28000, BLDG, 3450, 60, S13 28000, BLDG, 3550, 68, S15 28000, BLDG, 3650, 60, S16 28000, BLDG, 3770, 60, S14 28000, BLDG, 3855, 60, S8 28000, BLDG, 3074, -60,G11 28000, BLDG, 3150, -60, S1 28000, BLDG, 3270, -60, S3 28000, BLDG, 3370, -56, S4 28000, BLDG, 3500, -60, S5 28000, BLDG, 3550, -60, S6 28000, BLDG, 3630, -65, S7 28000, BLDG, 3730, -60, S17 28000, BLDG, 3830, -60, S9 28600,A,40,1000,-6, 17 28600,CSET, 0, 6, 15, 50 28675,A,40,1000,-6, *18~26, 10,11,75,2, 5B,-11,45,1 28700,CSET, 0, 6, 5, 50 28700,C,0,100,750,100,-.00016 28800,I,0,3000,1,4,4 29000,VC,500,0.0075 29200,A,*1,1000,-6,*10~14 29300,A,*1,1000,-6,*30~34 29700,C,0,100,750,100, .00016 29900, BLDG, 2050, 60, S1 29900, BLDG, 2170, 60, S3 29900, BLDG, 2270, 56, S4 29900, BLDG, 2400, 60, S5 29900, BLDG, 2450, 60, S6 29900, BLDG, 2530, 65, S7 29900, BLDG, 2630, 60, S17 29900, BLDG, 2730, 60, S9 29900, BLDG, 2820, 65, G1 29900, BLDG, 2890, 60, G7 29900, BLDG, 2930, 55, G8 29900, BLDG, 2050,-60, S10 29900, BLDG, 2150,-60, S11 29900, BLDG, 2250,-63, S12 29900, BLDG, 2350,-60, S13 29900, BLDG, 2450,-68, S15 29900, BLDG, 2550,-60, S16 29900, BLDG, 2670,-60, S14 29900, BLDG, 2755,-60, S8 29900, BLDG, 2844,-60, S1 29900, BLDG, 2924,-60, G3 29900, BLDG, 3091, 45, B4 29900, BLDG, 3160, 60, S10 29900, BLDG, 3250, 60, S11 29900, BLDG, 3350, 63, S12 29900, BLDG, 3450, 60, S13 29900, BLDG, 3550, 68, S15 29900, BLDG, 3650, 60, S16 29900, BLDG, 3770, 60, S14 29900, BLDG, 3855, 60, S8 29900, BLDG, 3944, 60, S1 29900, BLDG, 4024, 60, G3 29900, BLDG, 3081, -60,G11 29900, BLDG, 3150, -60, S1 29900, BLDG, 3270, -60, S3 29900, BLDG, 3370, -56, S4 29900, BLDG, 3500, -60, S5 29900, BLDG, 3550, -60, S6 29900, BLDG, 3630, -65, S7 29900, BLDG, 3730, -60, S17 29900, BLDG, 3830, -60, S9 29900, BLDG, 3920, -65, G1 29900, BLDG, 3990, -60, G7 29900, BLDG, 3100, 190, S10, -90 29900, BLDG, 3100, 290, S11, -90 29900, BLDG, 3100,-290, S12,-90 29900, BLDG, 3100, 490, S13,-90 29900, BLDG, 3100,-490, S13,-90 29900, BLDG, 2930, 170, S1, 90 29900, BLDG, 2930, 270, S3, 90 30000,VC,500,-0.0075 30000,ROAD, 12,6,3,2,4.5,10,10,.4,.4, 0,-1,-1,0,0,0,0,0,10,0,10,4,0,0,C:\STISIM\Data\Textures\Road07.Jpg, 24,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road01.Jpg, 12, 30000,SIGN,100,200,C:\STISIM\Data\Signs\SP35MPH.3ds 30000, TREE, 50, 0, 1, 40, 41, 0 30000, A, 40, 800,-7,3 30000, A, 17, 1000,-3, 36, 2,-12, 20, 2 30000, A, 40, 840,-21,*1~5 30000, V, /5, 320, 7, 1, *1;2;21;22;23;30 30000, V, /5, 150, 7, 1, *1;2;21;22;23;30 30000, v, /1, -40, 7,1,3, 30000,SL,-1000, 7, 3, 9, 0, 24, 6 30000, PED, 990, 2, 4, -80, B, *1~3 30000, PED, 987, 2, 3, -80, B, *6~8 30000, PED, 1030, 1, 4,-143, F, *1~10 30000, CT, 1032, 5, -80, 0, R, 8, 1 30000, CT, 1032, 5, -120, 0, R, 8, 1 30000, PED, 1047, 0,0, -65, F, 1 30000, PED, 1047, 0,0, -60, F, 2 30000, PED, 1046, 0,0, -57, F, 3 30000, CT, 966, 5, -140, 0, L, *21~27;30~32, 1 30000, CT, 966, 5, -170, 0, L, *21~27;30~32, 1 30000, CT, 966, 5, -210, 0, L, *21~27;30~32, 1 30000, PED, 960, 3, 5, 43, R, *1~10;-4;-5 30000, PED, 960, 0, 0,-40, L, *1~10;-4;-5 30050, PR,C:\STISIM\SOUND\Intersection left.wav,0 30200,LS,35,0 30500,V, 0, 620, 34, 1, 3 30500,V, 0, 640, 34, 1, *18~35 30500,A, 0, 640,-34, *18~35 30500,A, 0, 700,-34, 3 30600, A, 40,1000,-7,*1~13 30600, A, 45,1000,-21,*29~34 30700,C,0,100,750,100, .000103 30879,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,0,0,0,0,0,0,0,10,0,10,4 30944,TREE, 0, 0, 0, 0, 0, 0 30970,I,0,3000,1,4,4 31000,V, 0, 1240, 34, 1, 3, -3,-16,40,2, 2,0,/0,1 31000,V, 0, 1280, 34, 1, *18~35 31000,V, 0, 1420, 34, 1, *18~35 31000,V, 0, 1440, 34, 1, *18~35 31000,V, 0, 1460, 34, 1, *18~35 31000,V, 0, 1500, 34, 1, *18~35 31000,V, 0, 1520, 34, 1, *18~35, 4,-16, 50, 2 31000,V, 0, 1580, 34, 1, *18~35 31000,V, 0, 1600, 34, 1, 3 31000,V, 0, 1620, 34, 1, 3 31000,V, .01, 1920, 32, 1, 8, 10,0,-120,1 31000,A, 0, 1300,-34, *18~35 31000,A, 0, 1340,-34, *18~35 31000,A, 0, 1470,-34, 3 31000,A, 0, 1580,-34, *18~35 31000,A, 0, 1620,-34, 3 31000,A, 0, 1680,-34, *18~35 31000,A, 0, 1700,-34, *18~35, 6,16, 50, 2 31000,A, 0, 1760,-34, *18~35 31000,A, 0, 1800,-34, 3 31000,A, 0, 1820,-34, *18~35 31000,A, 0, 1846,-34, 3 31056,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,-1,-1,0,0,0,0,0,10,0,10,4,0,0,C:\STISIM\Data\Textures\Road07.Jpg, 24,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road01.Jpg, 12, 31056,TREE, 30, 0, 1, 40, 41, 0 31100, SL,-700,5,5,10,0, 24,6,1 31679,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,0,0,0,0,0,0,0,10,0,10,4 31856,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,-1,-1,0,0,0,0,0,10,0,10,4,0,0,C:\STISIM\Data\Textures\Road07.Jpg, 24,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road01.Jpg, 12, 31900,ROAD, 12,6,3,2,4.5,10,10,.4,.4, 0,-1,-1,0,0,0,0,0,10,0,10,4,0,0,C:\STISIM\Data\Textures\Road07.Jpg, 24,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road07.Jpg, 12,C:\STISIM\Data\Textures\Road01.Jpg, 12, 31900,SIGN,100,200,C:\STISIM\Data\Signs\SP35MPH.3ds 31900, TREE, 50, 0, 1, 40, 41, 0 32100,LS,35,0 32100,I,0,3000,0,4,4 32400,V, 0, 620, 34, 1, 3 32400,V, 0, 640, 34, 1, *18~35 32400,A, 0, 640,-34, *18~35 32400,A, 0, 700,-34, 3 32900,CT,2000,4,50,0,R,8 32970, SL,-1000,5,5,10,0,24,6,1 33849,ROAD, 12,6,3,2,4.5,10,10,.4,.4,65,0,0,0,0,0,0,0,10,0,10,4 34000, ES Time to collision results (in-lane vehicles), {Vehicle, Min range, Min T2C, Time from start}: 11 1.208 0.0302 162.70 28 4.937 0.0712 198.96 29 7.995 0.1221 199.79 30 7.358 0.1127 200.23 37 3.057 0.0465 200.69 38 6.362 0.0932 201.46 39 6.223 0.0921 201.73 40 6.894 0.1033 202.46 41 8.217 0.1276 203.96 50 4.885 0.0200 325.85 51 20.969 0.0744 244.26 52 14.964 0.7182 254.33 53 14.920 0.6945 255.29 54 15.435 0.7281 257.19 55 16.202 0.7056 259.26 56 15.514 0.5493 263.71 66 0.000 0.0000 318.46 76 17.047 0.8853 269.71 77 20.368 0.6735 267.34 78 20.386 0.6709 267.67 79 20.587 0.6738 268.01 80 21.755 0.7464 270.01 81 21.022 0.7847 272.21 82 21.319 0.8096 273.01 83 21.672 0.5760 325.85 86 2.442 1.1249 424.55 87 3.066 0.3166 425.35 88 6.165 0.9314 441.18 91 0.000 0.0000 341.91 92 14.133 2.2405 270.61 93 448.988 2.2635 271.07 94 8.824 2.5306 270.74 95 8.994 1.6392 439.58 96 9.125 0.7681 442.21 97 12.994 0.9440 443.55 98 29.597 2.4935 453.61 99 51.107 3.2436 454.94 101 5.426 0.2375 488.62 103 13.307 0.6175 488.72 104 4.217 0.2414 489.78 105 5.335 0.3240 491.58 108 15.363 0.9867 494.62 111 10.555 0.5275 499.07 121 6.432 0.1669 525.83 122 7.804 0.2232 526.71 123 8.377 0.2561 527.81 124 9.103 0.2789 528.32 135 15.110 0.8023 546.65 136 14.039 0.6035 548.10 143 17.320 0.3690 560.67 145 16.038 0.3404 561.08 147 17.047 0.3641 561.45 149 15.368 0.3238 562.05 150 16.573 0.3495 562.25 152 11.794 0.2791 575.10 154 12.746 0.2853 575.25 155 8.999 0.2286 575.65 156 7.922 0.2104 576.38 159 19.686 0.5116 577.63 162 9.311 0.2844 579.68 163 0.000 0.0000 580.45 173 465.989 1.8506 702.50 195 280.693 1.1254 702.50 196 6.238 0.0723 702.50 197 41.185 0.0611 702.50 203 17.663 0.0291 702.50 204 17.103 0.0405 702.50 209 7.961 0.2098 730.23 210 7.932 0.2133 730.79 211 4.758 0.1585 732.93 212 4.235 0.1540 733.29 213 5.084 0.2012 733.69 214 4.535 0.1935 734.59 215 26.543 1.0469 761.92 216 4.547 0.1984 736.39 217 5.099 0.2241 736.86 218 5.385 0.2337 737.33 219 6.239 0.2211 743.39 231 8.103 0.3225 745.56 232 8.491 0.3378 745.99 Time to collision results (other-lane vehicles), {Vehicle, Min range, Min T2C, Time from start}: 1 4.304 0.0490 55.36 2 4.591 0.0596 119.38 3 8.536 0.1218 119.35 4 2.871 0.0358 120.68 5 8.019 0.1047 120.78 6 3.131 0.0385 122.05 7 7.959 0.1222 122.01 8 4.643 0.0602 123.11 9 7.479 0.0998 123.25 10 8.925 0.0721 132.78 12 7.653 0.0497 160.77 13 8.353 0.0608 167.60 14 6.651 0.0389 169.74 15 6.488 0.0487 171.04 16 6.738 0.0380 172.41 17 7.539 0.0419 177.57 18 7.580 0.0507 179.37 19 7.937 0.0491 180.61 20 7.394 0.0495 181.89 21 7.773 0.0380 186.58 22 6.178 0.0356 188.28 23 6.698 0.0361 189.41 24 6.086 0.0426 190.61 31 12.916 0.1562 199.39 32 10.649 0.0792 200.09 33 13.064 0.1031 201.19 42 12.787 0.1332 201.93 43 12.012 0.0961 202.56 44 10.979 0.1030 203.63 45 10.344 0.0999 204.06 46 10.634 0.0606 211.67 47 13.941 0.0962 219.38 49 6.521 0.0538 220.48 57 40.247 0.4924 254.96 58 39.094 0.5883 259.83 59 23.788 0.2656 258.03 60 38.270 0.4428 261.26 61 38.142 0.5529 262.04 62 37.346 0.3999 262.37 63 38.056 0.4763 262.77 64 9.637 0.0702 251.83 65 25.587 0.2554 252.36 84 35.442 0.5438 268.07 85 34.268 0.4014 269.04 89 7.936 0.0759 268.84 90 22.149 0.2681 268.34 100 30.153 0.3112 479.77 102 30.133 0.3507 481.04 106 31.453 0.3792 482.45 107 31.335 0.3904 483.85 109 13.864 0.1729 496.72 110 29.607 0.2381 485.60 112 28.700 0.2578 487.27 113 28.595 0.4826 489.05 114 29.813 0.6007 490.93 115 29.526 0.2380 492.83 116 31.630 0.5907 494.97 117 30.182 0.6377 496.67 118 26.364 0.4912 499.07 119 16.082 0.2470 502.11 120 20.045 0.2392 504.88 125 45.348 1.3182 517.29 126 44.906 0.9111 520.19 127 46.143 1.2702 523.46 128 34.839 0.4236 520.78 129 41.650 0.9877 525.78 130 40.013 0.6429 526.39 131 39.777 1.1896 527.04 132 38.131 0.8682 529.14 133 36.935 0.6591 529.79 134 37.681 0.9819 530.44 137 33.795 0.6350 546.75 138 34.568 0.6823 547.90 139 34.761 0.6882 548.70 140 34.319 0.9960 549.49 141 34.229 0.6960 551.09 144 30.949 0.4940 561.18 146 31.284 0.6481 561.55 148 31.394 0.6591 562.00 151 17.024 0.1980 569.45 153 17.109 0.1938 570.70 157 17.091 0.2014 571.90 158 19.518 0.2352 573.05 160 19.065 0.1808 578.53 161 20.277 0.2535 574.20 164 22.064 0.2557 575.38 165 28.004 0.2893 576.71 166 29.984 0.4002 577.96 167 28.316 0.3334 579.23 168 28.750 0.3794 588.04 169 27.650 0.2718 590.71 170 25.729 0.1825 592.78 171 21.892 0.1112 594.66 172 17.305 0.2327 596.34 174 7.523 0.0607 616.84 175 7.092 0.0555 617.97 176 7.350 0.0609 619.12 177 11.362 0.0860 622.72 178 11.162 0.0891 623.87 179 11.918 0.1013 625.03 180 9.534 0.0803 626.05 181 8.463 0.0720 627.18 182 9.651 0.0838 628.15 183 11.372 0.0952 629.78 184 10.132 0.0801 630.88 185 9.562 0.0758 632.08 186 9.469 0.0776 633.05 187 8.592 0.0502 634.42 188 5.308 0.0400 649.96 189 5.001 0.0483 642.05 190 6.530 0.0595 654.80 191 6.940 0.0681 656.66 192 10.079 0.0775 670.46 193 20.915 0.4473 674.76 194 24.323 0.2554 670.82 205 37.942 0.4361 710.40 206 39.414 0.4906 712.03 207 10.824 0.0869 688.12 208 22.285 0.1986 690.52 220 47.381 0.5732 731.16 221 48.658 0.7577 731.76 222 51.135 0.7680 733.99 223 51.206 0.9034 736.56 224 49.895 0.7253 737.46 225 48.850 0.6760 738.83 226 35.880 0.5153 735.43 227 48.625 0.9141 740.62 228 47.675 0.6260 741.39 229 47.958 0.7575 741.82 230 47.188 0.6796 742.32 233 47.439 0.6830 746.16 234 47.682 0.6210 747.39 Tailgating results, {Vehicle #, Minimum distance, Speed at min distance}: 11 21.00 25.00 37 314.00 10.00 50 7.50 1.18 66 9.50 0.22 87 3.00 6.33 91 3.00 0.00 92 40.50 0.00 93 450.00 46.58 94 104.50 0.00 95 147.50 0.00 96 184.50 0.00 97 229.50 0.00 98 365.50 0.00 99 399.50 0.00 163 6.00 0.00 173 468.00 51.12 195 284.00 79.68 196 6.00 0.00 215 92.00 50.00 Intersection turns (Number, Expected turn, Actual turn, Correctness of turn, Vehicle #, Gap distance, Vehicle #, Gap time): 1 0 0 0 2 0 0 0 3 0 0 0 4 0 1 1 5 0 0 0 6 0 0 0 7 0 0 0 204 130.55 0 999.00 8 0 0 0 9 0 0 0 10 0 0 0 *Driver mistakes: Total number of off road accidents = 1 Total number of collisions = 3 Total number of pedestrians hit = 3 Total number of speed exceedances = 11 Total number of speeding tickets = 0 Total number of traffic light tickets = 1 Total number of stop signs missed = 0 Total number of centerline crossings = 5 Total number of road edge excursions = 4 Total number of stops at traffic lights = 2 Total number of correct DA responses = 0 Total number of incorrect DA responses = 0 Total number of DAs with no response = 0 Total run length (Drive T, X, Total T) = 761.92 34000 761.92 Total number of illegal turns = 0 Total number of low speed warnings = 0 Total number of high speed warnings = 0 Over speed limit (% Time, % Distance) = 27.15 47.77 Out of lane (% Time, % Distance) = 4.22 3.74 Individual mistakes (Time, Distance, Elapsed distance or object number, Elapsed time, Maximum value): Centerline crossing 68.16 3311.11 110.69 2.60 -3.46 Centerline crossing 94.26 4598.99 252.83 4.45 -3.19 Centerline crossing 127.85 6758.39 109.70 1.92 -2.78 Centerline crossing 162.14 9082.09 273.04 3.27 -9.72 Speed exceedance 162.80 9135.05 4596.82 48.87 120.00 Road edge excursion 166.34 9438.89 77.08 0.83 13.45 Hit pedestrian 204.46 13731.87 1 Speed exceedance 221.51 13829.40 912.17 22.75 67.13 Hit pedestrian 237.05 14741.43 5 Speed exceedance 259.93 15171.25 746.18 13.35 60.35 Centerline crossing 317.69 16126.40 14.76 8.15 -4.37 Vehicle collision (F) 318.63 16141.15 66 Vehicle collision (F) 341.91 16166.52 91 Red light ticket 452.04 16548.74 2 Speed exceedance 458.24 16802.82 1484.23 18.15 95.58 Speed exceedance 516.14 20362.78 685.87 10.13 68.67 Speed exceedance 551.24 21996.05 2111.93 24.31 91.76 Vehicle collision (F) 580.58 24459.77 163 Speed exceedance 606.49 25376.76 3929.19 42.84 120.00 Road edge excursion 622.00 26916.68 86.74 0.77 13.30 Road edge excursion 623.62 27100.59 251.81 2.17 14.42 Road edge excursion 641.31 29212.44 93.52 8.02 19.52 Off road accident 642.11 29305.93 Speed exceedance 664.99 30081.20 777.80 10.76 82.64 Hit pedestrian 695.29 31013.94 30 Speed exceedance 719.30 31513.55 915.64 14.16 71.88 Speed exceedance 742.46 32837.36 81.72 1.57 52.90 Speed exceedance 749.76 33199.52 801.52 12.16 76.04 * -- Michael Miesner Doctoral Student in Clinical Psychology East Tennessee State University -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyprog05 at gmail.com Fri Aug 14 21:05:28 2009 From: pyprog05 at gmail.com (PyProg PyProg) Date: Fri, 14 Aug 2009 21:05:28 +0200 Subject: [Tutor] [PyQt4] Parent problems with QThread and QProgressDialog Message-ID: Hi All, Benefiting from this excellent ticket: http://snippets.prendreuncafe.com/snippets/tagged/pyqt/order_by/date ... I can implement the behavior that I want and with QThread QProgressDialog (knowing that the progress bar updates whenever a new file is processed) in my application. Nevertheless I can not get rid of the parent window (the QProgressDialog comes with its parent window, which is really ugly). So I would like to get rid of this window relative to QProgressDialog that can display properly during treatment. How ?. In addition I would like to display the file being processed in the progress bar, but I can not (for now all files loaded are displayed in the bar). You can see the code here: http://pastebin.com/d71e7bd6b ... and the screenshot showing the parent window that cause me problems here: http://irruption.net/bla/ekd/ekd_developp/14_08_09_problem_avec_parent_dans_le_QThread_001.jpg Can you help me solve these problems ?. Excuse me for my bad English (it's a google translation of my message in french). I Hope you can help me. a+ -- http://ekd.tuxfamily.org http://lprod.org/wiki/doku.php/video:encodage:avchd_converter From davea at ieee.org Fri Aug 14 21:53:30 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 15:53:30 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> <4A85911A.3050203@gmail.com> <4A85A462.2040504@ieee.org> Message-ID: <4A85C0BA.4060301@ieee.org> Megan Land wrote: > > From: Dave Angel > > To: bob gailer > > Cc: Megan Land/Raleigh/Contr/IBM at IBMUS, tutor at python.org > > Date: 08/14/2009 01:53 PM > > Subject: Re: Re: [Tutor] Dynamic Function Calls > > > > > > > > > > bob gailer wrote: > >>
Megan >> Land wrote: >> >>> All three methods are defined below the snippet I provided. >>> >>> >> In Python names must be defined before they are referenced. Put these >> defs above the snippet. >> >> >>> def func(): >>> code... >>> def func0(): >>> do stuff >>> def func1(): >>> do stuff >>> def func2(): >>> do stuff >>> >>> Megan Land >>> FVT Blade EMET Test Engineer >>> mland at us.ibm.com >>> >>> Inactive hide details for Kent Johnson ---08/13/2009 05:18:10 PM---On >>> Thu, Aug 13, 2009 at 3:30 PM, Megan Land>> ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan >>> Land wrote: > Hi, >>> >>> >>> From: >>> Kent Johnson >>> >>> To: >>> Megan Land/Raleigh/Contr/IBM at IBMUS >>> >>> Cc: >>> tutor at python.org >>> >>> Date: >>> 08/13/2009 05:18 PM >>> >>> Subject: >>> Re: [Tutor] Dynamic Function Calls >>> >>> Sent by: >>> kent3737 at gmail.com >>> >>> ------------------------------------------------------------------------ >>> >>> >>> >>> On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: >>> >>>> Hi, >>>> >>>> I'm trying to call a function from a dictionary. I did some >>>> >>> googling and >>> >>>> from what I can tell my code should work, but doesn't. Here's an >>>> >>> example: >>> >>>> def myFunc(self, inputList): >>>> dict={0: func0, 1: func1, 2:func2} >>>> for element in inputList: >>>> dict[element]() >>>> >>>> When I go to run this I get an error saying func0 is not defined. Does >>>> anyone have any ideas as to why this won't work? I'm using Python >>>> >>> 2.6 if >>> >>>> that makes any difference. >>>> >>> You don't show any definition for func0 in the above snippet. Where is >>> it defined? >>> >>> Kent >>> >>> ------------------------------------------------------------------------ >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> > You can put these defs in any order. But when you invoke the function > from your outerlevel code, all of them need to have been defined. I'm > guessing you had these in this order: > > > def myFunc(self, inputList): > dictionary={0: func0, 1: func1, 2:func2} > for element in inputList: > dictionary[element]() ... > > myFunc(3, 1, 2, 1) #this is too early in the file, > because the following defs have not been defined yet > > def func(): > code... > def func0(): > do stuff > def func1(): > do stuff > def func2(): > do stuff > > #move the call to myFunc() here > > > > Move the outerlevel code to the end, and you're usually better off. You > also might want to put it inside an > if __name__ == "__main__": > > clause. > > > Note, I also changed the variable 'dict' to 'dictionary,' since dict > already has a meaning in Python. Not a big deal in this particular > case, but if you ever wanted to convert a list to a dict, and called > dict(), you'd wonder what went wrong. Better to kill the habit early. > > DaveA > > > I have the method inside a main method at the end of my program. The weird > thing is that I typed up my small example and ran it and it worked fine. > But when I run my big program, I still get the error that func0, as I call > it in my example, is not defined. Do you think there could be something > else in my program that is making this go wrong? > > > Megan Land > FVT Blade EMET Test Engineer > mland at us.ibm.com > Something's wrong with your email program's quoting logic. So your last response looks like it's part of my last email. ::: Do you think there could be something else.... Yes, certainly. Question is what. You use the word method a couple of times above, yet none of your code shows classes. Was that a typo? First thing is you should stop paraphrasing and describing, and include actual code, actual full error messages, and so on. If you had actually run a small sample, you would have found out then that it worked, and that your description doesn't match the problem you're having with the full code. Once you have a real code example that fails, use copy/paste so we see it exactly as it is. Next, you should realize that an error like : Traceback (most recent call last): File "", line 1, in NameError: name 'xyzzy' is not defined means that the symbol 'xyzzy' cannot be located in the valid namespaces of the current context. So we need to see the context. If it's a function, there is a local namespace and a global one. Despite the word, it's only global to this particular module. If it's a class method, or a nested function, the rules are different. And the whole problem has nothing to do with dynamic function calls, as the happens before you ever get to the call. In front of that "dictionary=" line, insert a real call to func0(), and see if it gives a similar error. Then try a call to print help(__name__). That should display all the global symbols for your module. If func0() doesn't work in MyFunc(), then see if it works in the function that calls it. And see if it works in your outer-level code, just before you call main(). DaveA From davea at ieee.org Fri Aug 14 22:18:47 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 16:18:47 -0400 Subject: [Tutor] write program to extract data In-Reply-To: <8f6846bb0908141008v6c495204he0aef2c99a3e3511@mail.gmail.com> References: <8f6846bb0908141008v6c495204he0aef2c99a3e3511@mail.gmail.com> Message-ID: <4A85C6A7.1050200@ieee.org> Michael Miesner wrote: > Hi- > I work in a research lab and part of the lab I'm not usually associated with > uses a program that outputs data in a .txt file for each participant that is > run. > The participant # is the title of the text document (ie E00343456.txt) style > and I'd like to be able to take this and other data in the file and draw it > into a spreadsheet. > The first 3/4 of the output is the scenario. I've bolded the areas that I > really want to be able to draw out. In case some people cant see the bold, > they are the sections called "driver mistakes" and individual mistakes. > > > Preferably, what I'd really like to do is make the script so that I execute > it, and in doing so, tell it what folder to look in, and it takes all the > .txt's out of that folder, and adds them to the spreadsheet. I'd like the > title of the .txt to be the first column, and the data held in the > spreadsheet to be the be the next columns. > > Below is output of 1 data file. > ---------------------------------------------------------------- > Date: August 13, 2009 > Time: 12:16:18:151 PM > ID: > Scenario file: C:\Documents and Settings\APL02\Desktop\Driving Sim > Files\Sim 10-21-08.txt > Configuration file: > > > > 7 0 0 0 204 130.55 0 999.00 > 8 0 0 0 > 9 0 0 0 > 10 0 0 0 > > *Driver mistakes: > > Total number of off road accidents = 1 > Total number of collisions = 3 > Total number of pedestrians hit = 3 > Total number of speed exceedances = 11 > Total number of speeding tickets = 0 > Total number of traffic light tickets = 1 > Total number of stop signs missed = 0 > Total number of centerline crossings = 5 > Total number of road edge excursions = 4 > Total number of stops at traffic lights = 2 > Total number of correct DA responses = 0 > Total number of incorrect DA responses = 0 > Total number of DAs with no response = 0 > Total run length (Drive T, X, Total T) = 761.92 34000 761.92 > > Total number of illegal turns = 0 > Total number of low speed warnings = 0 > Total number of high speed warnings = 0 > Over speed limit (% Time, % Distance) = 27.15 47.77 > Out of lane (% Time, % Distance) = 4.22 3.74 > > Individual mistakes (Time, Distance, Elapsed distance or object number, > Elapsed time, Maximum value): > > Centerline crossing 68.16 3311.11 110.69 2.60 > -3.46 > Centerline crossing 94.26 4598.99 252.83 4.45 > -3.19 > Centerline crossing 127.85 6758.39 109.70 1.92 > -2.78 > Centerline crossing 162.14 9082.09 273.04 3.27 > -9.72 > Speed exceedance 162.80 9135.05 4596.82 48.87 > 120.00 > Road edge excursion 166.34 9438.89 77.08 0.83 > 13.45 > Hit pedestrian 204.46 13731.87 1 > Speed exceedance 221.51 13829.40 912.17 22.75 > 67.13 > Hit pedestrian 237.05 14741.43 5 > Speed exceedance 259.93 15171.25 746.18 13.35 > 60.35 > Centerline crossing 317.69 16126.40 14.76 8.15 > -4.37 > Vehicle collision (F) 318.63 16141.15 66 > Vehicle collision (F) 341.91 16166.52 91 > Red light ticket 452.04 16548.74 2 > Speed exceedance 458.24 16802.82 1484.23 18.15 > 95.58 > Speed exceedance 516.14 20362.78 685.87 10.13 > 68.67 > Speed exceedance 551.24 21996.05 2111.93 24.31 > 91.76 > Vehicle collision (F) 580.58 24459.77 163 > Speed exceedance 606.49 25376.76 3929.19 42.84 > 120.00 > Road edge excursion 622.00 26916.68 86.74 0.77 > 13.30 > Road edge excursion 623.62 27100.59 251.81 2.17 > 14.42 > Road edge excursion 641.31 29212.44 93.52 8.02 > 19.52 > Off road accident 642.11 29305.93 > Speed exceedance 664.99 30081.20 777.80 10.76 > 82.64 > Hit pedestrian 695.29 31013.94 30 > Speed exceedance 719.30 31513.55 915.64 14.16 > 71.88 > Speed exceedance 742.46 32837.36 81.72 1.57 > 52.90 > Speed exceedance 749.76 33199.52 801.52 12.16 > 76.04 > > > * > Did you really have to quote all 1100 lines, when what you really wanted to say was there's a bunch of junk at the beginning of the file, then the following stuff ? Anyway, the most important question is how rigid is this file format? Will there always be exactly one line starting "* Driver mistakes"? Will the lines between that and the final "*" always be the same ones, and in the same order? Or is "Road edge excursion" somehow an optional line. or whatever? Are the numbers identified by the column they start in, or by spaces between them? Is a zero stored sometimes as an empty field? It already appears that some lines are appearing multiple times, and not in order. Assuming that's deliberate, is there a maximum number of times for any given line? If not, how do you plan to encode it in a spreadsheet, which generally has fixed columns, with a specific meaning for each one? Once you've got a spec for the file requirements, you're left with three pieces to write. And if the file requirements are tricky, you may want to write a validator for the file. GIGO, you know. 1) loop through all the txt files in a given directory. Check out glob, or os.path, or even inputfile. 2) parse the lines of the file. A simple loop, checking the line against "* Driver mistakes". Then another loop, building a list of the fields from those lines. This should do some integrity checking, in case some line is short one of its numeric fields, for example. 3) write the results to a csv file, one call per input file. Check out the csv module. I'd suggest building a dummy set of files, with just a few lines in each, but the same general format. Then when you have the program working for those, generalize it. DaveA From srilyk at gmail.com Fri Aug 14 22:14:58 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 14 Aug 2009 15:14:58 -0500 Subject: [Tutor] write program to extract data In-Reply-To: <8f6846bb0908141303lc697506i7834467bf83dac1f@mail.gmail.com> References: <8f6846bb0908141008v6c495204he0aef2c99a3e3511@mail.gmail.com> <333efb450908141254y600c2a47n9e61dc403f59ee8b@mail.gmail.com> <8f6846bb0908141303lc697506i7834467bf83dac1f@mail.gmail.com> Message-ID: <333efb450908141314l6237c6b0x271626c1f1321003@mail.gmail.com> Whoops, I forgot the reply-all. On Fri, Aug 14, 2009 at 3:03 PM, Michael Miesner wrote: > That is one distinct advantage, It'll always be just like that. However, I > dont know where to even begin; I dont know what command pulls text out > ($string?) or how to import it into a spreadsheet. > Alan Gauld has a spiffy python tutorial here: http://www.freenetpages.co.uk/hp/alan.gauld/ I presume you have at least a little programming experience. Python is really simple to pick up if you've done any other language. Check out "Handling Text" and "Handling Files" for some specific pointers. Are you familiar with comma separated value (.csv) files? It's fairly trivial to import those into a spreadsheet program, and if you're the one writing the .csv it's not too difficult to get them written the right way. HTH, Wayne > > > On Fri, Aug 14, 2009 at 3:54 PM, Wayne wrote: > >> On Fri, Aug 14, 2009 at 12:08 PM, Michael Miesner < >> michael.miesner at gmail.com> wrote: >> >>> Hi- >>> I work in a research lab and part of the lab I'm not usually associated >>> with uses a program that outputs data in a .txt file for each participant >>> that is run. >>> The participant # is the title of the text document (ie E00343456.txt) >>> style and I'd like to be able to take this and other data in the file and >>> draw it into a spreadsheet. >>> The first 3/4 of the output is the scenario. I've bolded the areas that I >>> really want to be able to draw out. In case some people cant see the bold, >>> they are the sections called "driver mistakes" and individual mistakes. >>> >>> >>> Preferably, what I'd really like to do is make the script so that I >>> execute it, and in doing so, tell it what folder to look in, and it takes >>> all the .txt's out of that folder, and adds them to the spreadsheet. I'd >>> like the title of the .txt to be the first column, and the data held in the >>> spreadsheet to be the be the next columns. >> >> >>> >>> >>> >>> *Driver mistakes: >>> >>> Total number of off road accidents = 1 >>> Total number of collisions = 3 >>> Total number of pedestrians hit = 3 >>> Total number of speed exceedances = 11 >>> Total number of speeding tickets = 0 >>> Total number of traffic light tickets = 1 >>> Total number of stop signs missed = 0 >>> Total number of centerline crossings = 5 >>> Total number of road edge excursions = 4 >>> Total number of stops at traffic lights = 2 >>> Total number of correct DA responses = 0 >>> Total number of incorrect DA responses = 0 >>> Total number of DAs with no response = 0 >>> Total run length (Drive T, X, Total T) = 761.92 34000 >>> 761.92 >>> Total number of illegal turns = 0 >>> Total number of low speed warnings = 0 >>> Total number of high speed warnings = 0 >>> Over speed limit (% Time, % Distance) = 27.15 47.77 >>> Out of lane (% Time, % Distance) = 4.22 3.74 >>> >>> Individual mistakes (Time, Distance, Elapsed distance or object number, >>> Elapsed time, Maximum value): >>> >>> Centerline crossing 68.16 3311.11 110.69 2.60 >>> -3.46 >>> Centerline crossing 94.26 4598.99 252.83 4.45 >>> -3.19 >>> Centerline crossing 127.85 6758.39 109.70 1.92 >>> -2.78 >>> Centerline crossing 162.14 9082.09 273.04 3.27 >>> -9.72 >>> Speed exceedance 162.80 9135.05 4596.82 48.87 >>> 120.00 >>> Road edge excursion 166.34 9438.89 77.08 0.83 >>> 13.45 >>> Hit pedestrian 204.46 13731.87 1 >>> Speed exceedance 221.51 13829.40 912.17 22.75 >>> 67.13 >>> Hit pedestrian 237.05 14741.43 5 >>> Speed exceedance 259.93 15171.25 746.18 13.35 >>> 60.35 >>> Centerline crossing 317.69 16126.40 14.76 8.15 >>> -4.37 >>> Vehicle collision (F) 318.63 16141.15 66 >>> Vehicle collision (F) 341.91 16166.52 91 >>> Red light ticket 452.04 16548.74 2 >>> Speed exceedance 458.24 16802.82 1484.23 18.15 >>> 95.58 >>> Speed exceedance 516.14 20362.78 685.87 10.13 >>> 68.67 >>> Speed exceedance 551.24 21996.05 2111.93 24.31 >>> 91.76 >>> Vehicle collision (F) 580.58 24459.77 163 >>> Speed exceedance 606.49 25376.76 3929.19 42.84 >>> 120.00 >>> Road edge excursion 622.00 26916.68 86.74 0.77 >>> 13.30 >>> Road edge excursion 623.62 27100.59 251.81 2.17 >>> 14.42 >>> Road edge excursion 641.31 29212.44 93.52 8.02 >>> 19.52 >>> Off road accident 642.11 29305.93 >>> Speed exceedance 664.99 30081.20 777.80 10.76 >>> 82.64 >>> Hit pedestrian 695.29 31013.94 30 >>> Speed exceedance 719.30 31513.55 915.64 14.16 >>> 71.88 >>> Speed exceedance 742.46 32837.36 81.72 1.57 >>> 52.90 >>> Speed exceedance 749.76 33199.52 801.52 12.16 >>> 76.04 >>> * >>> >> >> Is the data always going to be at the end of the file? I.e. will there be >> any more data after what you really want? >> >> If it's always going to be at the end of the file you can just check for >> the line that starts with "Driver mistakes:" >> >> Once you find that line, then you know you'll want the rest of the file. >> >> There are several different methods, but it's certainly possible. Let us >> know if you run into any roadblocks and we'll be happy to help point you in >> the right direction. >> >> -Wayne >> > > > > -- > Michael Miesner > Doctoral Student in Clinical Psychology > East Tennessee State University > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From mland at us.ibm.com Fri Aug 14 22:30:14 2009 From: mland at us.ibm.com (Megan Land) Date: Fri, 14 Aug 2009 16:30:14 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: <4A85C0BA.4060301@ieee.org> References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> <4A85911A.3050203@gmail.com> <4A85A462.2040504@ieee.org> <4A85C0BA.4060301@ieee.org> Message-ID: Dave Angel wrote on 08/14/2009 03:53:30 PM: > From: > > Dave Angel > > To: > > Megan Land/Raleigh/Contr/IBM at IBMUS > > Cc: > > bob gailer , tutor at python.org > > Date: > > 08/14/2009 03:53 PM > > Subject: > > Re: [Tutor] Dynamic Function Calls > > Megan Land wrote: > > > > From: Dave Angel > > > > To: bob gailer > > > > Cc: Megan Land/Raleigh/Contr/IBM at IBMUS, tutor at python.org > > > > Date: 08/14/2009 01:53 PM > > > > Subject: Re: Re: [Tutor] Dynamic Function Calls > > > > > > > > > > > > > > > > > > > > bob gailer wrote: > > > >>
Megan > >> Land wrote: > >> > >>> All three methods are defined below the snippet I provided. > >>> > >>> > >> In Python names must be defined before they are referenced. Put these > >> defs above the snippet. > >> > >> > >>> def func(): > >>> code... > >>> def func0(): > >>> do stuff > >>> def func1(): > >>> do stuff > >>> def func2(): > >>> do stuff > >>> > >>> Megan Land > >>> FVT Blade EMET Test Engineer > >>> mland at us.ibm.com > >>> > >>> Inactive hide details for Kent Johnson ---08/13/2009 05:18:10 PM---On > >>> Thu, Aug 13, 2009 at 3:30 PM, Megan Land >>> ---08/13/2009 05:18:10 PM---On Thu, Aug 13, 2009 at 3:30 PM, Megan > >>> Land wrote: > Hi, > >>> > >>> > >>> From: > >>> Kent Johnson > >>> > >>> To: > >>> Megan Land/Raleigh/Contr/IBM at IBMUS > >>> > >>> Cc: > >>> tutor at python.org > >>> > >>> Date: > >>> 08/13/2009 05:18 PM > >>> > >>> Subject: > >>> Re: [Tutor] Dynamic Function Calls > >>> > >>> Sent by: > >>> kent3737 at gmail.com > >>> > >>> ------------------------------------------------------------------------ > >>> > >>> > >>> > >>> On Thu, Aug 13, 2009 at 3:30 PM, Megan Land wrote: > >>> > >>>> Hi, > >>>> > >>>> I'm trying to call a function from a dictionary. I did some > >>>> > >>> googling and > >>> > >>>> from what I can tell my code should work, but doesn't. Here's an > >>>> > >>> example: > >>> > >>>> def myFunc(self, inputList): > >>>> dict={0: func0, 1: func1, 2:func2} > >>>> for element in inputList: > >>>> dict[element]() > >>>> > >>>> When I go to run this I get an error saying func0 is not defined. Does > >>>> anyone have any ideas as to why this won't work? I'm using Python > >>>> > >>> 2.6 if > >>> > >>>> that makes any difference. > >>>> > >>> You don't show any definition for func0 in the above snippet. Where is > >>> it defined? > >>> > >>> Kent > >>> > >>> ------------------------------------------------------------------------ > >>> > >>> _______________________________________________ > >>> Tutor maillist - Tutor at python.org > >>> http://mail.python.org/mailman/listinfo/tutor > >>> > >>> > > You can put these defs in any order. But when you invoke the function > > from your outerlevel code, all of them need to have been defined. I'm > > guessing you had these in this order: > > > > > > def myFunc(self, inputList): > > dictionary={0: func0, 1: func1, 2:func2} > > for element in inputList: > > dictionary[element]() ... > > > > myFunc(3, 1, 2, 1) #this is too early in the file, > > because the following defs have not been defined yet > > > > def func(): > > code... > > def func0(): > > do stuff > > def func1(): > > do stuff > > def func2(): > > do stuff > > > > #move the call to myFunc() here > > > > > > > > Move the outerlevel code to the end, and you're usually better off. You > > also might want to put it inside an > > if __name__ == "__main__": > > > > clause. > > > > > > Note, I also changed the variable 'dict' to 'dictionary,' since dict > > already has a meaning in Python. Not a big deal in this particular > > case, but if you ever wanted to convert a list to a dict, and called > > dict(), you'd wonder what went wrong. Better to kill the habit early. > > > > DaveA > > > > > > I have the method inside a main method at the end of my program. The weird > > thing is that I typed up my small example and ran it and it worked fine. > > But when I run my big program, I still get the error that func0, as I call > > it in my example, is not defined. Do you think there could be something > > else in my program that is making this go wrong? > > > > > > Megan Land > > FVT Blade EMET Test Engineer > > mland at us.ibm.com > > > Something's wrong with your email program's quoting logic. So your last > response looks like it's part of my last email. > > ::: Do you think there could be something else.... > > Yes, certainly. Question is what. You use the word method a couple of > times above, yet none of your code shows classes. Was that a typo? > > First thing is you should stop paraphrasing and describing, and include > actual code, actual full error messages, and so on. If you had actually > run a small sample, you would have found out then that it worked, and > that your description doesn't match the problem you're having with the > full code. Once you have a real code example that fails, use copy/paste > so we see it exactly as it is. > > Next, you should realize that an error like : > > Traceback (most recent call last): > File "", line 1, in > NameError: name 'xyzzy' is not defined > > means that the symbol 'xyzzy' cannot be located in the valid namespaces > of the current context. So we need to see the context. If it's a > function, there is a local namespace and a global one. Despite the > word, it's only global to this particular module. If it's a class > method, or a nested function, the rules are different. And the whole > problem has nothing to do with dynamic function calls, as the happens > before you ever get to the call. > > In front of that "dictionary=" line, insert a real call to func0(), and > see if it gives a similar error. Then try a call to print > help(__name__). That should display all the global symbols for your module. > > If func0() doesn't work in MyFunc(), then see if it works in the > function that calls it. And see if it works in your outer-level code, > just before you call main(). > > DaveA > Sorry about the email. Apparently Lotus Notes doesn't like to put replies at the end of the message. I tried what you said. I can call the function by itself (not within the dictionary). I also printed the help(__name__). All of my functions were listed. Here's a more representative example of my code (I doing this for work so I don't want to give my entire program away): import os class Test(): def func(self): funcDict={".txt":text, ".html":html} exList=os.listdir("/home/megan/test") for i in exList: (filePath, fileName)=os.path.split(i) (name, extension)=os.path.splitext(fileName) self.funcDict[extension]() def text(self): print "This is a text file" def html(self): print "This is an html file" def main(): newTest=Test() newTest.func() if __name__=="__main__": main() Traceback (most recent call last): File "test.py", line 23, in main() File "test.py", line 19, in main newTest.func() File "test.py", line 4, in func funcDict={".txt":text, ".html":html} NameError: global name 'text' is not defined It worked fine until I put it inside of a class, but I'm not sure what that would have to do with it. I don't need to have use all that, but now that everything is setup like that I want to keep it that way. Any help you can provide will be greatly appreciated. Megan Land -------------- next part -------------- An HTML attachment was scrubbed... URL: From garry.bettle at gmail.com Fri Aug 14 22:33:31 2009 From: garry.bettle at gmail.com (Garry Bettle) Date: Fri, 14 Aug 2009 22:33:31 +0200 Subject: [Tutor] Tutor Digest, Vol 66, Issue 38 In-Reply-To: References: Message-ID: Howdy all, Hope this email finds you all well - roll on the weekend. I've been tasked with replicating an Excel spreadsheet. The spreadsheet contains cells that use Excels' NORMDIST() function. I have all 3 variables required - value, mean and standard deviation - but does anyone already have equivalent python code for this function? Many thanks! Cheers, Garry PS: Excel Help: NORMDIST Returns the normal distribution for the specified mean and standard deviation. This function has a very wide range of applications in statistics, including hypothesis testing. Syntax NORMDIST(x,mean,standard_dev,cumulative) X is the value for which you want the distribution. Mean is the arithmetic mean of the distribution. Standard_dev is the standard deviation of the distribution. Cumulative is a logical value that determines the form of the function. If cumulative is TRUE, NORMDIST returns the cumulative distribution function; if FALSE, it returns the probability mass function. Remarks If mean or standard_dev is nonnumeric, NORMDIST returns the #VALUE! error value. If standard_dev ? 0, NORMDIST returns the #NUM! error value. If mean = 0, standard_dev = 1, and cumulative = TRUE, NORMDIST returns the standard normal distribution, NORMSDIST. When cumulative = TRUE, the formula is the integral from negative infinity to x of the given formula. From garry.bettle at gmail.com Fri Aug 14 22:35:08 2009 From: garry.bettle at gmail.com (Garry Bettle) Date: Fri, 14 Aug 2009 22:35:08 +0200 Subject: [Tutor] Normal Distribution Message-ID: Sorry! Now with an appropriate subject line... G. Howdy all, Hope this email finds you all well - roll on the weekend. I've been tasked with replicating an Excel spreadsheet. The spreadsheet contains cells that use Excels' NORMDIST() function. I have all 3 variables required - value, mean and standard deviation - but does anyone already have equivalent python code for this function? Many thanks! Cheers, Garry PS: ?Excel Help: NORMDIST Returns the normal distribution for the specified mean and standard deviation. This function has a very wide range of applications in statistics, including hypothesis testing. Syntax NORMDIST(x,mean,standard_dev,cumulative) X ? is the value for which you want the distribution. Mean ? is the arithmetic mean of the distribution. Standard_dev ? is the standard deviation of the distribution. Cumulative ? is a logical value that determines the form of the function. If cumulative is TRUE, NORMDIST returns the cumulative distribution function; if FALSE, it returns the probability mass function. Remarks If mean or standard_dev is nonnumeric, NORMDIST returns the #VALUE! error value. If standard_dev ? 0, NORMDIST returns the #NUM! error value. If mean = 0, standard_dev = 1, and cumulative = TRUE, NORMDIST returns the standard normal distribution, NORMSDIST. When cumulative = TRUE, the formula is the integral from negative infinity to x of the given formula. From davea at ieee.org Fri Aug 14 23:06:02 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 17:06:02 -0400 Subject: [Tutor] Dynamic Function Calls In-Reply-To: References: <1c2a2c590908131417n37f0459bje5106137845f4f3c@mail.gmail.com> <4A85911A.3050203@gmail.com> <4A85A462.2040504@ieee.org> <4A85C0BA.4060301@ieee.org> Message-ID: <4A85D1BA.4050404@ieee.org> Megan Land wrote: > > I tried what you said. I can call the function by itself (not within the > dictionary). I also printed the help(__name__). All of my functions were > listed. Here's a more representative example of my code (I doing this for > work so I don't want to give my entire program away): > > import os > class Test(): > def func(self): > funcDict={".txt":text, ".html":html} > exList=os.listdir("/home/megan/test") > for i in exList: > (filePath, fileName)=os.path.split(i) > (name, extension)=os.path.splitext(fileName) > self.funcDict[extension]() > > def text(self): > print "This is a text file" > > def html(self): > print "This is an html file" > > def main(): > newTest=Test() > newTest.func() > > > if __name__=="__main__": > main() > > > Traceback (most recent call last): > File "test.py", line 23, in > main() > File "test.py", line 19, in main > newTest.func() > File "test.py", line 4, in func > funcDict={".txt":text, ".html":html} > NameError: global name 'text' is not defined > > It worked fine until I put it inside of a class, but I'm not sure what that > would have to do with it. I don't need to have use all that, but now that > everything is setup like that I want to keep it that way. Any help you can > provide will be greatly appreciated. > > Megan Land > As you said, it worked fine till you put those two function definitions inside a class. As I guessed earlier, your use of the word "method" was a tipoff. Anyway, within the method func(), an unqualified name will be searched for locally (an attribute of func()), then globally (within the module, at global scope). It does not search for other methods. Still, the first question I have to ask is "why are text() and html() instance methods?" You're not using self anywhere in those methods, but maybe you are in your actual code. I have to assume something, so I'll assume you need self for all three methods. In this case, simply change the line to: funcDict={".txt":self.text, ".html":self.html} and it should work fine. You're creating bound methods, which already know their self-value when they're placed in the funcDict. If I assume they don't need self, I'd just move them to global scope, and forget about it. But if you just can't do that, then how about nested functions? (I had already added the parameter "name" for testing purposes, so please forgive that change below.) def func(self): def text(name): print "This", name, "is also a text file, nested" def html(name): print "This", name, "is also an html file, nested" funcDict={".txt":self.text, ".html":self.html} exList=os.listdir(".") for i in exList: (filePath, fileName)=os.path.split(i) (name, extension)=os.path.splitext(fileName) if extension in funcDict: funcDict[extension](name) I believe you could also do something with the @static decorator, but I haven't played with it, and it doesn't look like you need it anyway. DaveA From davidwilson at Safe-mail.net Sat Aug 15 10:03:58 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Sat, 15 Aug 2009 04:03:58 -0400 Subject: [Tutor] python's database Message-ID: Hello, I seem to remember that python had a native database, can someone remind me which this was. Dave From davea at ieee.org Sat Aug 15 13:50:48 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 15 Aug 2009 07:50:48 -0400 Subject: [Tutor] python's database In-Reply-To: References: Message-ID: <4A86A118.2060705@ieee.org> davidwilson at Safe-mail.net wrote: > Hello, > I seem to remember that python had a native database, can someone remind me which this was. > Dave > > Check out module sqlite3 http://docs.python.org/library/sqlite3.html From alan.gauld at btinternet.com Sat Aug 15 14:40:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Aug 2009 13:40:06 +0100 Subject: [Tutor] python's database References: Message-ID: wrote > I seem to remember that python had a native database, > can someone remind me which this was. Python doesn't have a native database per se but it supports access to many third party databases via its DBAPI. It also supports the dbm file format which is the underlying structure of many more complex databases. The shelve module can be used as a very primitive dictionary like database if you only need to persist objects However, the standard library includes sqlite which is a basic SQL database which can be based on a single file or held in memory. That may be what you were thinking of? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mohannadmohammad at hotmail.com Sat Aug 15 17:07:23 2009 From: mohannadmohammad at hotmail.com (Mohannad Mohammad) Date: Sat, 15 Aug 2009 15:07:23 +0000 Subject: [Tutor] Telnet using Python!! Message-ID: Hello everybody, I want to connect from my Windows server to Unix server using Telnet by Python code. To run some commands and save the result in a text file. I read telnetlib documentation and read many examples, but I did not understand!! I hope to read an explanation from anyone in the group. step by step please! Thanks for your help ..... Second question, I tried to connect remotely using SSH (paramiko) and I understand it, my point is: how to execute commands and read the results using SSHClient class [ I used Transport class only but the session is closed after the first command ] bye _________________________________________________________________ Windows Live Messenger: Celebrate 10 amazing years with free winks and emoticons. http://clk.atdmt.com/UKM/go/157562755/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From worminater at gmail.com Sat Aug 15 17:34:17 2009 From: worminater at gmail.com (worminater at gmail.com) Date: Sat, 15 Aug 2009 15:34:17 +0000 Subject: [Tutor] Telnet using Python!! In-Reply-To: References: Message-ID: <279483768-1250350410-cardhu_decombobulator_blackberry.rim.net-239738448-@bxe1100.bisx.prod.on.blackberry> I'd probably look into setting up an XML RPC server on the linux host. Thanks, Chris Sent via BlackBerry from T-Mobile -----Original Message----- From: Mohannad Mohammad Date: Sat, 15 Aug 2009 15:07:23 To: Subject: [Tutor] Telnet using Python!! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From emile at fenx.com Sat Aug 15 19:19:14 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Aug 2009 10:19:14 -0700 Subject: [Tutor] Telnet using Python!! In-Reply-To: References: Message-ID: On 8/15/2009 8:07 AM Mohannad Mohammad said... > > Hello everybody, > > I want to connect from my Windows server to Unix server using Telnet by > Python code. To run some commands and save the result in a text file. > I read *telnetlib* documentation and read many examples, but I did not > understand!! > Have you worked through the example from the documentation at the bottom here: http://docs.python.org/library/telnetlib.html And there's more here: http://code.activestate.com/recipes/52228/ Post examples of the specific code and errors that are giving you trouble. Emile From davidkim05 at gmail.com Sun Aug 16 16:09:32 2009 From: davidkim05 at gmail.com (David Kim) Date: Sun, 16 Aug 2009 10:09:32 -0400 Subject: [Tutor] python's database Message-ID: I don't know how much it's in use, but I thought gadfly ( http://gadfly.sourceforge.net/) was the db that's implemented in python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From goodpotatoes at yahoo.com Sun Aug 16 19:56:05 2009 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Sun, 16 Aug 2009 10:56:05 -0700 (PDT) Subject: [Tutor] Iterating through objects Message-ID: <904932.67496.qm@web51808.mail.re2.yahoo.com> I'm not sure if I've been searching using the correct terms. After I've iterated through an object, such as a cursor or webpage, how do I get back to the "top"? e.g. tutorial from http://www.daniweb.com/code/snippet563.html# print page1.readlines() >From this excercise, the first time I read page1 I get all of the lines. The next time, I only get []. What happens to all of the info after I've read it? Do I need to again get the info from the web? page1 = opener1.open(picture_page) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Aug 16 20:12:20 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 16 Aug 2009 14:12:20 -0400 Subject: [Tutor] Iterating through objects In-Reply-To: <904932.67496.qm@web51808.mail.re2.yahoo.com> References: <904932.67496.qm@web51808.mail.re2.yahoo.com> Message-ID: <4A884C04.3010501@gmail.com> GoodPotatoes wrote: > I'm not sure if I've been searching using the correct terms. After > I've iterated through an object, such as a cursor or webpage, how do I > get back to the "top"? > > e.g. > > tutorial from http://www.daniweb.com/code/snippet563.html# > > print page1.readlines() Capture the lines in a variable. foo = page1.readlines() print foo > > From this excercise, the first time I read page1 I get all of the > lines. The next time, I only get []. What happens to all of the info > after I've read it? > > Do I need to again get the info from the web? > page1 = opener1.open(picture_page) > * > * > * > * > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Aug 16 21:06:54 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Aug 2009 20:06:54 +0100 Subject: [Tutor] Iterating through objects References: <904932.67496.qm@web51808.mail.re2.yahoo.com> Message-ID: "GoodPotatoes" wrote > print page1.readlines() > >>From this excercise, the first time I read page1 I get all of the lines. The best thing to do is store them in a variable then print them. That way you can access them at will: lines = page1.readlines() print lines # all of them as a list print lines[2],lines[5], lines [-1] # 3rd, 6th and last as lines HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nathan.wing at gmail.com Sun Aug 16 23:35:00 2009 From: nathan.wing at gmail.com (Nathan Wing) Date: Sun, 16 Aug 2009 15:35:00 -0600 Subject: [Tutor] Loop help Message-ID: <9e6177960908161435g36bda890h4a83b827a40b81d3@mail.gmail.com> Hello All,I've been racking my brain trying to figure out, what I imagine to be, a very simple problem. I found the Intro to comp science MIT open course ( http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/CourseHome/index.htm) and was working on the very first homework assignment. I was successful in problem one, but having a hard time with problem two. Any help would be greatly appreciated! Regards, Nathan Here is the problem: A wealthy donor has given MIT $500,000 to be used to pay the tuition of one student every other year until the money runs out. Under the assumptions that a. The current annual tuition is $34,986 per year, b. Tuition goes up at a rate of 4.1%/year, and c. The principal will be invested so that it earns 5%/year, solve the following problems: 1) Write a program that calculates and prints the total number of students this gift will support and the tuition paid for the last student. 2)Write a program that calculates and prints the smallest gift (rounded to the nearest $100) needed to support one student every other year for 100 years. In addition, print the number of iterations your program took to arrive at the answer. Hint: you may want to use nested loops for this problem. my code that works for number 1: #!/usr/bin/env python # #scholarship.py # #initialize values year = 0 count = 0 money = 1000000.0 #fund amount ctuition = 34986.0 #current tuition rate = 1.041 # 4.1% annual increase on tuition principle = 1.05 #5% annual interest accrued on fund ###calculations while money > 0 and money >= ctuition: #while the fund has money and can cover tuition if year % 2 == 0: #if this is year 0 or every even year after year 0 money = money - ctuition ftuition = ctuition count += 1 ctuition = ctuition * rate money = money * principle year += 1 print "Total number of students aided: %d" % count print "Tuition paid for final recipient: $%.2f" % ftuition print 'Total number of years fund was operative: %s' % str(year + 1) my code for number two (this code ends up looping and does not increment the initial funding, as I had thought it would): #!/usr/bin/env python # #scholarship2.py # ### initialize values loop = 1 while loop is 1: year = 0 count = 0 initmoney = 500000.0 #initial funding money = initmoney #fund amount ctuition = 34986.0 #current tuition rate = 1.041 # 4.1% annual increase on tuition principle = 1.05 #5% annual interest accrued on fund ### calculations while money > 0 and money >= ctuition: # while the fund has money and can cover tuition if year % 2 == 0: # if this is year 0 or every even year after year 0 money = money - ctuition ftuition = ctuition count += 1 print "pass ", count ctuition = ctuition * rate money = money * principle year += 1 if year == 100: loop = 0 print "The total funding required to last 100 yrs: $%.2f" % initmoney print count print year else: print 'restart with new funding' initmoney += 100.0 year = 0 count = 0 ctuition = 34986.0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Aug 17 00:01:49 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 16 Aug 2009 18:01:49 -0400 Subject: [Tutor] Loop help In-Reply-To: <9e6177960908161435g36bda890h4a83b827a40b81d3@mail.gmail.com> References: <9e6177960908161435g36bda890h4a83b827a40b81d3@mail.gmail.com> Message-ID: <4A8881CD.6070800@ieee.org> Nathan Wing wrote: > Hello All,I've been racking my brain trying to figure out, what I imagine to > be, a very simple problem. I found the Intro to comp science MIT open > course ( > http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/CourseHome/index.htm) > and was working on the very first homework assignment. I was successful in > problem one, but having a hard time with problem two. Any help would be > greatly appreciated! > > Regards, > Nathan > > Here is the problem: > > A wealthy donor has given MIT $500,000 to be used to pay the tuition of one > student every other year until the money runs out. Under the assumptions > that > a. The current annual tuition is $34,986 per year, > b. Tuition goes up at a rate of 4.1%/year, and > c. The principal will be invested so that it earns 5%/year, > > solve the following problems: > 1) Write a program that calculates and prints the total number of students > this gift will support and the tuition paid for the last student. > 2)Write a program that calculates and prints the smallest gift (rounded to > the nearest $100) needed to support one student every other year for 100 > years. In addition, print the number of iterations your program took to > arrive at the answer. Hint: you may want to use nested loops for this > problem. > > my code that works for number 1: > > #!/usr/bin/env python > # > #scholarship.py > # > > #initialize values > year = 0 > count = 0 > money = 1000000.0 #fund amount > ctuition = 34986.0 #current tuition > rate = 1.041 # 4.1% annual increase on tuition > principle = 1.05 #5% annual interest accrued on fund > > ###calculations > while money > 0 and money >= ctuition: #while the fund has money and can > cover tuition > if year % 2 == 0: #if this is year 0 or every even year after year 0 > money = money - ctuition > ftuition = ctuition > count += 1 > > ctuition = ctuition * rate > money = money * principle > year += 1 > > print "Total number of students aided: %d" % count > print "Tuition paid for final recipient: $%.2f" % ftuition > print 'Total number of years fund was operative: %s' % str(year + 1) > > > my code for number two (this code ends up looping and does not increment the > initial funding, as I had thought it would): > > #!/usr/bin/env python > # > #scholarship2.py > # > > ### initialize values > > loop = 1 > while loop is 1: > > year = 0 > count = 0 > initmoney = 500000.0 #initial funding > money = initmoney #fund amount > ctuition = 34986.0 #current tuition > rate = 1.041 # 4.1% annual increase on tuition > principle = 1.05 #5% annual interest accrued on fund > > > ### calculations > while money > 0 and money >= ctuition: # while the fund has money and > can cover tuition > if year % 2 == 0: # if this is year 0 or every even year after year > 0 > money = money - ctuition > ftuition = ctuition > count += 1 > print "pass ", count > > ctuition = ctuition * rate > money = money * principle > year += 1 > > if year == 100: > loop = 0 > print "The total funding required to last 100 yrs: $%.2f" % > initmoney > print count > print year > else: > print 'restart with new funding' > initmoney += 100.0 > year = 0 > count = 0 > ctuition = 34986.0 > > This isn't your only problem, but the immediate difficulty you mention, the incorrect value for initmoney, is caused by initializing said value inside the while loop. Thus every time you go through the while loop, it will be set to the same value. Since you want to increment it by 100, you need to move the initialization outside of the loop: initmoney = 500000.0 #initial funding loop = 1 while loop == 1: year = 0 count = 0 money = initmoney #fund amount ... I think I'd also eliminate the loop variable in favor of a "break" statement. Make it a while True, and use break when you print out the result. DaveA From fidellira.6 at gmail.com Mon Aug 17 00:16:05 2009 From: fidellira.6 at gmail.com (Fidel Sanchez-Bueno) Date: Sun, 16 Aug 2009 18:16:05 -0400 Subject: [Tutor] Loop help In-Reply-To: <9e6177960908161435g36bda890h4a83b827a40b81d3@mail.gmail.com> References: <9e6177960908161435g36bda890h4a83b827a40b81d3@mail.gmail.com> Message-ID: <4A888525.5040104@gmail.com> Nathan Wing escribi?: > Hello All, > I've been racking my brain trying to figure out, what I imagine to be, > a very simple problem. I found the Intro to comp science MIT open > course > (http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/CourseHome/index.htm) > and was working on the very first homework assignment. I was > successful in problem one, but having a hard time with problem two. > Any help would be greatly appreciated! > > Regards, > Nathan > > Here is the problem: > > A wealthy donor has given MIT $500,000 to be used to pay the tuition > of one student every other year until the money runs out. Under the > assumptions that > a. The current annual tuition is $34,986 per year, > b. Tuition goes up at a rate of 4.1%/year, and > c. The principal will be invested so that it earns 5%/year, > > solve the following problems: > 1) Write a program that calculates and prints the total number of > students this gift will support and the tuition paid for the last student. > 2)Write a program that calculates and prints the smallest gift > (rounded to the nearest $100) needed to support one student every > other year for 100 years. In addition, print the number of iterations > your program took to arrive at the answer. Hint: you may want to use > nested loops for this problem. > > my code that works for number 1: > > #!/usr/bin/env python > # > #scholarship.py > # > > #initialize values > year = 0 > count = 0 > money = 1000000.0 #fund amount > ctuition = 34986.0 #current tuition > rate = 1.041 # 4.1% annual increase on tuition > principle = 1.05 #5% annual interest accrued on fund > > ###calculations > while money > 0 and money >= ctuition: #while the fund has money and > can cover tuition > if year % 2 == 0: #if this is year 0 or every even year after year 0 > money = money - ctuition > ftuition = ctuition > count += 1 > > ctuition = ctuition * rate > money = money * principle > year += 1 > > print "Total number of students aided: %d" % count > print "Tuition paid for final recipient: $%.2f" % ftuition > print 'Total number of years fund was operative: %s' % str(year + 1) > > > my code for number two (this code ends up looping and does not > increment the initial funding, as I had thought it would): > > #!/usr/bin/env python > # > #scholarship2.py > # > > ### initialize values > > loop = 1 > while loop is 1: > > year = 0 > count = 0 > initmoney = 500000.0 #initial funding > money = initmoney #fund amount > ctuition = 34986.0 #current tuition > rate = 1.041 # 4.1% annual increase on tuition > principle = 1.05 #5% annual interest accrued on fund > > > ### calculations > while money > 0 and money >= ctuition: # while the fund has money > and can cover tuition > if year % 2 == 0: # if this is year 0 or every even year after > year 0 > money = money - ctuition > ftuition = ctuition > count += 1 > print "pass ", count > > ctuition = ctuition * rate > money = money * principle > year += 1 > > if year == 100: > loop = 0 > print "The total funding required to last 100 yrs: $%.2f" % > initmoney > print count > print year > else: > print 'restart with new funding' > initmoney += 100.0 > year = 0 > count = 0 > ctuition = 34986.0 > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > hi.. i dont know if this is the right anwser but this is how i do it: for the first question: ************************************** money = 500000 money_rate = 0.05 tuiton_cost = 34986 tuiton_rate = 0.041 year = 1 # first year student = 0 while money >= tuiton_cost: year += 2 money -= tuiton_cost student += 1 for a in range(2): money += (money * money_rate) tuiton_cost += (tuiton_cost * tuiton_rate) print "Number of student supported is %s" % student print "Cost of the last tuiton is %s" % tuiton_cost ******************************************** for the second one: ******************************************** cost = 0 money_rate = 0.05 tuiton_cost = 34986 tuiton_rate = 0.041 year = 1 # first year while year <= 100: cost += tuiton_cost year += 2 for a in range(2): tuiton_cost += (tuiton_cost * tuiton_rate) cost -= (cost * money_rate) print "the smallest gift must be %i" % cost ******************************************* for the second one the number of iteration for the while loop is 50 From oberoc at gmail.com Mon Aug 17 17:44:28 2009 From: oberoc at gmail.com (Tino Dai) Date: Mon, 17 Aug 2009 11:44:28 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: References: Message-ID: <2ac5d4850908170844m17015a81vd516982171f052c6@mail.gmail.com> Bob, I could see where you could use a class inside of a class. Is it possible for you give a simple example of it? Thanks, Tino On Fri, Aug 14, 2009 at 2:05 PM, Serdar Tumgoren wrote: > Okay, those explanations definitely help. I thought I had run into a > situation where nested classes might be called for, but I think > plain-old inheritance is really what I'm after. > > Many thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Mon Aug 17 19:12:45 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Mon, 17 Aug 2009 19:12:45 +0200 Subject: [Tutor] rationale for nested classes? In-Reply-To: References: Message-ID: <1250529165.18338.24.camel@jabbar> On Fri, 2009-08-14 at 11:26 -0400, Serdar Tumgoren wrote: > Hi everyone, > > I was wondering if there's anyone who can offer a use case/rationale > for nested class? ... > Are there specific situations when nested classes come in handy > (perhaps for grouping conceptually related classes that don't share > attributes?). Disclaimer: I am not a python-ninja and do not have much python code under my belt, but since I thought to what I am about to write when I first read your question, and nobody else gave feedback in this direction, I though to share my idea, if not for anything else, at least to be told on why this might be a non pythonic one :) . I would use a nested class to create a particular data structure which represent a "sub-unit" of the mother class. For example if I had a class representing a table (with methods like add, delete, sort, etc...) I might wish to create a subclass that represent a record and use instantiation of that sub-class as my main way to handle data. In this way I could enforce behaviours like "not null" or "default" from within the datastructure itself (for example in the __init__ method) rather than enforcing a logic from outside (i.e. the "mother class"). I believe classes/objects are also the most elegant way to implement singletons, so maybe if you need a singleton for each object generated with the "mother class", maybe that is also an occasion in which a subclass comes handy. Finally, I somewhere read that embedded declarations are much faster than external ones in being referenced. So, if performance is an issue, maybe embedding one class within another one might bring you some benefit rather than having an object instantiated from the first class having to reference a class which is external to its generating one. [Hope that is understandable... English is not my first language... :)] Anyhow let me reiterate my disclaimer: I am not a python guru, so I would be very happy if any of the tutors would comment on what above, even if it is for disagree with it! :) Mac. From kent37 at tds.net Mon Aug 17 19:33:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Aug 2009 13:33:36 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: <1250529165.18338.24.camel@jabbar> References: <1250529165.18338.24.camel@jabbar> Message-ID: <1c2a2c590908171033h9f34ee1lb8cf6886a67ec3d8@mail.gmail.com> On Mon, Aug 17, 2009 at 1:12 PM, Mac Ryan wrote: > Finally, I somewhere read that embedded declarations are much faster > than external ones in being referenced. So, if performance is an issue, > maybe embedding one class within another one might bring you some > benefit rather than having an object instantiated from the first class > having to reference a class which is external to its generating one. > [Hope that is understandable... English is not my first language... :)] *Local* variables are faster than variables that must be looked up. Nested classes would not qualify for this. Kent From zstumgoren at gmail.com Mon Aug 17 19:36:24 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 17 Aug 2009 13:36:24 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: <1250529165.18338.24.camel@jabbar> References: <1250529165.18338.24.camel@jabbar> Message-ID: > I would use a nested class to create a particular data structure which > represent a "sub-unit" of the mother class. ... In this > way I could enforce behaviours like "not null" or "default" from within > the datastructure itself (for example in the __init__ method) rather > than enforcing a logic from outside (i.e. the "mother class"). This is an interesting idea that I'd like to hear more about and see examples. As part of a current project, this might in fact come in handy. Specifically, would the above approach be a recommended way of performing some additional data integrity checks on an object after having created it? Say that I've created a series of Campaign Committee objects from an initial data set. class Committee(object): def __init__(self, data): self.id = data[0] self.name = data[1] self.candidate = data[2] self.candidateID = data[3] In the above example, I know for certain that the returned data will always have a committee ID. But a number of other data such as the name, candidate, and candidateID are often missing or incorrect. So after the initialiization of an object, I'm using "self.id" in a series of subsequent database queries to correct and/or fill in this data. So my question, in light of Mac's suggestion, is this a case where I should add a subclass containing so-called DataIntegrity checks? For instance, something that resembles this: class Committee(object): <> class DataFixer(self): def fix_name(self): pass def fix_candidate(self):pass def fix_candidateID(self):pass Or would it be better to make this a separate class entirely, outside of the Committee object? From jfabiani at yolo.com Mon Aug 17 20:31:35 2009 From: jfabiani at yolo.com (John) Date: Mon, 17 Aug 2009 11:31:35 -0700 Subject: [Tutor] python and java report writers Message-ID: <200908171131.35960.jfabiani@yolo.com> Hi, I have been searching for a report writer to work with my python programs. I did find reportlab. But most of the other report writers are java based. I am confused by all the jargon associated with Java and have very little working knowledge of the environment. So I'm hoping someone will help out. I'd like to understand how python can integrate with Java in general and then how it would work with the Java report writers. I have read a little about jPython but do not understand how to make that work with my python programs. It would appear to me it is a way to replace python. I don't want to replace my python code. I want to just call a java report writer. Passing either the data or parameters to retrieve the data and ask it to print a report. I would think that would be straight forward. But I see nothing about python and jasper for example. Therefore, something is unusual in this case. Johnf From kent37 at tds.net Mon Aug 17 21:40:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Aug 2009 15:40:02 -0400 Subject: [Tutor] rationale for nested classes? In-Reply-To: References: <1250529165.18338.24.camel@jabbar> Message-ID: <1c2a2c590908171240h35a5e3a4g42947a4756403034@mail.gmail.com> On Mon, Aug 17, 2009 at 1:36 PM, Serdar Tumgoren wrote: > Say that I've created a series of Campaign Committee objects from an > initial data set. > > class Committee(object): > ? ?def __init__(self, data): > ? ? ? ?self.id = data[0] > ? ? ? ?self.name = data[1] > ? ? ? ?self.candidate = data[2] > ? ? ? ?self.candidateID = data[3] > > In the above example, I know for certain that the returned data will > always have a committee ID. But a number of other data such as the > name, candidate, and candidateID are often missing or incorrect. So > after the initialiization of an object, I'm using "self.id" in a > series of subsequent database queries to correct and/or fill in this > data. > > So my question, in light of Mac's suggestion, ?is this a case where I > should add a subclass containing so-called DataIntegrity checks? I would just create an ordinary fix() method of Committee, e.g. def fix(self): self.fix_name() self.fix_candidate() self.fix_candidateID() etc. Kent From kent37 at tds.net Mon Aug 17 21:49:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Aug 2009 15:49:06 -0400 Subject: [Tutor] python and java report writers In-Reply-To: <200908171131.35960.jfabiani@yolo.com> References: <200908171131.35960.jfabiani@yolo.com> Message-ID: <1c2a2c590908171249x5ac4430cl4a3f0f3991c08552@mail.gmail.com> On Mon, Aug 17, 2009 at 2:31 PM, John wrote: > Hi, > > I have been searching for a report writer to work with my python programs. ?I > did find reportlab. But most of the other report writers are java based. ?I > am confused by all the jargon associated with Java and have very little > working knowledge of the environment. ?So I'm hoping someone will help out. > > I'd like to understand how python can integrate with Java in general and then > how it would work with the Java report writers. ?I have read a little about > jPython but do not understand how to make that work with my python programs. > It would appear to me it is a way to replace python. ?I don't want to replace > my python code. ?I want to just call a java report writer. ?Passing either > the data or parameters to retrieve the data ?and ask it to print a report. ?I > would think that would be straight forward. ?But I see nothing about python > and jasper for example. ?Therefore, something is unusual in this case. Jython (it has not been called jPython for a very long time) is an implementation of Python that is written in Java and interoperates well with Java libraries, both standard libraries and third-party ones. When you use jython, you do write Python code. The main differences are in the library modules available; not all of the Python std lib is available in Jython, and third-party modules that have compiled extensions won't work. Depending on what else your program does, and how big it is already, jython may be a reasonable approach. Another possibility might be calling a report writer from the command line, if that is possible with any of the writers you are interested in. You could also look at JPype though I don't know much about its status. http://jpype.sourceforge.net/index.html Kent From moron.oxy at gmail.com Mon Aug 17 22:00:23 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Tue, 18 Aug 2009 06:00:23 +1000 Subject: [Tutor] python and java report writers In-Reply-To: <2096a7260908171248n7c11ab4cpcad51d3590278c21@mail.gmail.com> References: <200908171131.35960.jfabiani@yolo.com> <2096a7260908171248n7c11ab4cpcad51d3590278c21@mail.gmail.com> Message-ID: <2096a7260908171300r668cd59by81cb035bfbfe14a5@mail.gmail.com> (Sent to John only by mistake, now sending to list. Sorry John!) On Tue, Aug 18, 2009 at 5:48 AM, Oxymoron wrote: > Hi John, > > On Tue, Aug 18, 2009 at 4:31 AM, John wrote: >> >> I'd like to understand how python can integrate with Java in general and then >> how it would work with the Java report writers. ?I have read a little about >> jPython but do not understand how to make that work with my python programs. >> It would appear to me it is a way to replace python. ?I don't want to replace >> my python code. ?I want to just call a java report writer. ?Passing either > > I can't comment on Python reporting libs - best to google around - > since I have not worked with them. Hopefully someone more experienced > can give alternatives for this. It's definitely worth the effort if > you can use (C)Python natively. > > Since you mentioned Java and Jython however, a few things to consider > on the Java side of the equation (may be a little off topic, I > apologise): > > 1. Jasper is a java library for reporting as you have discovered. It > is meant to be fairly declarative - there should be minimal > boilerplate code or config or wrapper objects for basic cases, the > bulk of the work would be in designing your report -- an XML report > definition file. > > One complication I can think of with Jasper (best to check doco and > ask on the Jasper list for more!), is that it has the idea of > datasources - essentially classes representing data to display on the > report, Jasper provides some default ones - if you need something > specialised, then you will need to write your own (implement an > interface or extend a Jasper base class), you can do this using > Jython. My use case at the time was that I had to much data (from an > RDBMS) to load up into memory at one go - and Jython's default source > implementations did not help, so we had to write our own, again not > too nasty, just not out of the box. Things may have changed. > > 2. Jython is a Python _language_ implementation in Java, and as such > allows calling Java code seamlessly in both directions. To be more > precise, both Java and Jython code are compiled to JVM bytecode, and > share JVM semantics, it is no longer about the language at that point > - just what the runtime understands - needless to say Jython will have > various 'tricks' so that the more dynamic side of Python can fit into > the statically typed JVM model. > > Another way of looking at it is that Jython is an alternative Python > syntax on top of Java libraries (and of course, to write Jython code). > In other words, you can rely on Jython being Pythonic as far as the > language is concerned, but it may not support the standard library (or > only partially support it or is work in progress!) as you see on > CPython docs. It is meant to leverage off the existing Java libraries. > Native python types such as lists are automatically converted to the > JDK standard collection libraries (such java.util.List/Map impls, > etc.) while retaining (obviously) Python syntax and behaviour (as far > as possible) for the core language. > > Essentially if you wish to use a Java library (and I have only ever > used Jasper, so caveat emptor): > > 1. See if there already is a Java wrapper someone has written that you > can call as an external process - reports can be very simple or crazy, > so not sure how feasible this is, especially considering the diversity > of data sources and presentation, or maybe a GUI Jasper (or whatever > else) report designer of sorts that does this, generates config, etc. > - sourceforge may be a good place to search. > > 2. You could call Java libraries using Jython (and thus not have a > syntax barrier at least), and create your reporting process that you > can use as an external process, passing in params, and getting out a > value etc. It will take some effort for sure, because most examples > for using Jasper will be Java-based, and you would need to translate > this to Jython (or copy and paste). Having said that, once you get a > basic test harness up and running, Jasper's complexity will be in > defining reports in XML, nothing very Java specific. > > You _may_ need to be aware of things like Javabean conventions (also > called properties, where tooling considers x.getFoo() and > x.setFoo(bar) to have the shorthand notation to x.foo -- these may > impact the Jython classes you write - method names will need to follow > conventions to be referred to from the XML as properties (it's been a > while since I used Jasper, so do read up again if you go down this > path - can't remember if it was just something we did). Java to Python > translation is straightforward for most cases, just ignore the type > prefix on Java variable declarations (except of course to refer to the > Javadoc!) :-). > > So yes, you cannot call Jython/JVM bytecode from Python or vice versa > as easily as you would your own Python modules, since they are in > different formats, interpreted by different processes (python vs JVM). > Jython is nice however in that it supports on the fly compilation as > per regular Python code, you will not need an explicit compilation > step as with regular Java code. Java environment-wise, it has the > notion of classpath -- you will need to ensure that the Jasper > libraries (JAR files) and any dependencies (other JAR files!) and your > own files, are on the classpath (Java and Jython files are converted > to 'class files' containing the JVM bytecode). Basic Java tutorials > will explain how to set-up the classpath. > > Enough about Java on a Python list before I get banned :-). > > > Regards > Kamal > -- There is more to life than increasing its speed. -- Mahatma Gandhi From alan.gauld at btinternet.com Mon Aug 17 21:33:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Aug 2009 20:33:49 +0100 Subject: [Tutor] python and java report writers References: <200908171131.35960.jfabiani@yolo.com> Message-ID: "John" wrote > I'd like to understand how python can integrate with Java in general and > then > how it would work with the Java report writers. I have read a little > about > jPython but do not understand how to make that work with my python > programs. I assume you mean jython? jython allows you to take Python code(with af few restrictions) and compile it into Java so that it can be included in a regukar java program. Jython also allows you to import java classes into your python code as if they were python classes - this is how you would use it. The only snag are those restrictions I mentioned. You need to make sure your python code does not use any features./modules that are not supported in Jython. > It would appear to me it is a way to replace python. It doesn't replace Python the language but it lets you write Python code in a Java environment. But you cannot import your Jython code into CPython and you cannot use any C compiled modules in Jython. > my python code. I want to just call a java report writer. Passing > either > the data or parameters to retrieve the data and ask it to print a > report. I > would think that would be straight forward. But I see nothing about > python > and jasper for example. Therefore, something is unusual in this case. Provided you can separate the production of the data from the reporting then you can use your C Python code to produce the data then write a Jython module to do the reporting using the Java report writer object. You just have to run the data producer under CPython and the report writer under Jython. (Or compile it to run under Java) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Aug 17 21:27:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Aug 2009 20:27:28 +0100 Subject: [Tutor] rationale for nested classes? References: <1250529165.18338.24.camel@jabbar> Message-ID: "Mac Ryan" wrote in message news:1250529165.18338.24.camel at jabbar... > On Fri, 2009-08-14 at 11:26 -0400, Serdar Tumgoren wrote: >> Hi everyone, >> >> I was wondering if there's anyone who can > I would use a nested class to create a particular data structure which > represent a "sub-unit" of the mother class. For example if I had a class > representing a table (with methods like add, delete, sort, etc...) I > might wish to create a subclass that represent a record and use > instantiation of that sub-class as my main way to handle data. Thats a fair enough idea except there is no advantage in defining the class as a nested class. It would IMHO be better at the module level where it would be easier for a client to subclass it for different record types. It would be very useful to be able to subclass a record in this way so it would not be a candidate for hiding inside another class. OTOH the coupling between table and record makes an equally strong case for having both record and table classes defined in the same module. > way I could enforce behaviours like "not null" or "default" from within > the datastructure itself (for example in the __init__ method) rather > than enforcing a logic from outside (i.e. the "mother class"). But those features are features of the record not of the table. A table is simply a collection of records. Most of the functionality should be in the record, the table should only need to insert,delete, search, sort etc. And those methods should be written to use polymorphism to be record independent > I believe classes/objects are also the most elegant way to implement > singletons, so maybe if you need a singleton for each object generated > with the "mother class", maybe that is also an occasion in which a > subclass comes handy. I have no idea what you mean by that bit. Classes can be used for singletons but I don;t see where nested classes come into it. Nested classes should be used where you don't expect anyone outside the outer class to ever want to do anything with the inner class. (In Python this is just a statement of intent since the access is available to anyone who wants it) > Finally, I somewhere read that embedded declarations are much faster > than external ones in being referenced. Doesn't apply here. > would be very happy if any of the tutors would comment on what above, > even if it is for disagree with it! :) Be very happy! :-) More seriously, I suspect from your comments that you too are getting confused about the difference between inheritance and nesting. nesting is about hiding the class name and definition. Inheritance is about subclassing. They are very different concepts. Nesting tends to make subclassing more difficult (albeit in Python only trivially so) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From moron.oxy at gmail.com Mon Aug 17 22:08:15 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Tue, 18 Aug 2009 06:08:15 +1000 Subject: [Tutor] python and java report writers In-Reply-To: <200908171301.26752.jfabiani@yolo.com> References: <200908171131.35960.jfabiani@yolo.com> <2096a7260908171248n7c11ab4cpcad51d3590278c21@mail.gmail.com> <200908171301.26752.jfabiani@yolo.com> Message-ID: <2096a7260908171308j67ba5370j14c56e9882617b32@mail.gmail.com> (Posting to list!) On Tue, Aug 18, 2009 at 6:01 AM, John wrote: > > First I love your handle. ?And second, thanks for taking the time to explain :-) > jython world. ?But I was really looking for a simple way of calling a report > writer (like using a com object) to print a report. ?At this point in the > project changing to jython is not going to be considered. ?We are using to > many modules and I'm sure we will run into something. I wasn't suggesting changing everything to Jython - I actually meant something similar, i.e. write the reporting component in Jython (this really depends on where you get your data from I suppose, if it's all code generated may be more tricky, but for a DB-based thing, not so). You could then treat the jython/java mini-reporting-app as a blackbox. It's not COM perhaps, but plain IPC should do. > It looks like we are stuck with either reportlab or using something like > openoffice's uno. They may be a simpler solution if it amounts to the same thing. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From quasipedia at gmail.com Mon Aug 17 23:04:51 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Mon, 17 Aug 2009 23:04:51 +0200 Subject: [Tutor] rationale for nested classes? In-Reply-To: <1c2a2c590908171033h9f34ee1lb8cf6886a67ec3d8@mail.gmail.com> References: <1250529165.18338.24.camel@jabbar> <1c2a2c590908171033h9f34ee1lb8cf6886a67ec3d8@mail.gmail.com> Message-ID: <1250543091.18338.28.camel@jabbar> On Mon, 2009-08-17 at 13:33 -0400, Kent Johnson wrote: > On Mon, Aug 17, 2009 at 1:12 PM, Mac Ryan wrote: > > > Finally, I somewhere read that embedded declarations are much faster > > than external ones in being referenced. So, if performance is an issue, > > maybe embedding one class within another one might bring you some > > benefit rather than having an object instantiated from the first class > > having to reference a class which is external to its generating one. > > [Hope that is understandable... English is not my first language... :)] > > *Local* variables are faster than variables that must be looked up. > Nested classes would not qualify for this. I could not find the article I was referring to, so I ran a test myself, and - surprisingly - I found out the exact contrary of what I read. Nesting the class lower the performance of nearly 10%. FLAT: [4.0505850315093994, 4.0618939399719238, 4.0537300109863281] import timeit class Printer(object): def __init__(self): a = 3 ** 3 class Embedder(object): def __init__(self): for i in range(10000): a = Printer() if __name__ == '__main__': timer = timeit.Timer("new = triedout.Embedder()", "import triedout") print timer.repeat(3, 1000) NESTED: [4.3873238563537598, 4.3799960613250732, 4.3729050159454346] import timeit class Embedder(object): class Printer(object): def __init__(self): a = 3 ** 3 def __init__(self): for i in range(10000): a = self.Printer() if __name__ == '__main__': timer = timeit.Timer("new = triedout.Embedder()", "import triedout") print timer.repeat(3, 1000) From quasipedia at gmail.com Mon Aug 17 23:22:12 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Mon, 17 Aug 2009 23:22:12 +0200 Subject: [Tutor] rationale for nested classes? In-Reply-To: References: <1250529165.18338.24.camel@jabbar> Message-ID: <1250544132.18338.44.camel@jabbar> On Mon, 2009-08-17 at 20:27 +0100, Alan Gauld wrote: > > way I could enforce behaviours like "not null" or "default" from within > > the datastructure itself (for example in the __init__ method) rather > > than enforcing a logic from outside (i.e. the "mother class"). > > But those features are features of the record not of the table. > A table is simply a collection of records. Most of the functionality > should be in the record, the table should only need to insert,delete, > search, sort etc. And those methods should be written to use > polymorphism to be record independent I suppose one of us is missing the point of the other one, as it looks to me that we are saying the same. :) I would indeed enforce those checks and defaults in the child class (i.e. nested) so that the mother class can have "generic methods" that would work with various records. Indeed - if I truly wished to use nested classes - I would probably define certain module-wide "generic" classes for both "tables" and "records" and then I would subclass them in hierarchic form, so that the class TableA(Table) has a nested class RecordA(Record). I would think of that as a legitimate design with strong encapsulation. Again though... I am not advocating for this method as "the best one", I am just try to imagine a "rationale for nested classes" as per request of the OP. > > I believe classes/objects are also the most elegant way to implement > > singletons, so maybe if you need a singleton for each object generated > > with the "mother class", maybe that is also an occasion in which a > > subclass comes handy. > > I have no idea what you mean by that bit. Classes can be used for > singletons but I don;t see where nested classes come into it. Mmmm... giving a second thought to it, what I had in mind can be achieved with a single class. So apologies, disregard this bit! :) > > would be very happy if any of the tutors would comment on what above, > > even if it is for disagree with it! :) > > Be very happy! :-) > More seriously, I suspect from your comments that you too are > getting confused about the difference between inheritance and nesting. > nesting is about hiding the class name and definition. Inheritance is > about subclassing. They are very different concepts. Nesting tends > to make subclassing more difficult (albeit in Python only trivially so) Well, thank you for the feedback indeed. I am one of those people who get their mind clear only when they interact with others. As for the confusion between nesting and inheritance... no, I think I have that one pretty well under my belt. :) Thank you again, Mac. From jfabiani at yolo.com Tue Aug 18 00:50:45 2009 From: jfabiani at yolo.com (John) Date: Mon, 17 Aug 2009 15:50:45 -0700 Subject: [Tutor] python and java report writers In-Reply-To: <2096a7260908171308j67ba5370j14c56e9882617b32@mail.gmail.com> References: <200908171131.35960.jfabiani@yolo.com> <200908171301.26752.jfabiani@yolo.com> <2096a7260908171308j67ba5370j14c56e9882617b32@mail.gmail.com> Message-ID: <200908171550.45172.jfabiani@yolo.com> On Monday 17 August 2009 01:08:15 pm Oxymoron wrote: > (Posting to list!) > > On Tue, Aug 18, 2009 at 6:01 AM, John wrote: > > First I love your handle. ?And second, thanks for taking the time to > > explain > > > :-) > : > > jython world. ?But I was really looking for a simple way of calling a > > report writer (like using a com object) to print a report. ?At this point > > in the project changing to jython is not going to be considered. ?We are > > using to many modules and I'm sure we will run into something. > > I wasn't suggesting changing everything to Jython - I actually meant > something similar, i.e. write the reporting component in Jython (this > really depends on where you get your data from I suppose, if it's all > code generated may be more tricky, but for a DB-based thing, not so). > You could then treat the jython/java mini-reporting-app as a blackbox. > It's not COM perhaps, but plain IPC should do. > > > It looks like we are stuck with either reportlab or using something like > > openoffice's uno. > > They may be a simpler solution if it amounts to the same thing. > > -- Kamal I don't know enough about jython to understand what has to be done. Let's say I can write the code to retrieve the data in cPython. And I can write a module in jython that will accept the data passing it on to the report writer. How can I call the jython program? It can't be called from the cPython program - right? So the jython runs stand alone - right? IPC = Inter-process communication - right? Does that mean I need to write some sort of server? Johnf From eduardo.susan at gmail.com Tue Aug 18 01:00:04 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 17 Aug 2009 17:00:04 -0600 Subject: [Tutor] Problems with encoding in BeautifulSoup Message-ID: <9356b9f30908171600w6399e96cp1a7274def7df3b20@mail.gmail.com> Hello, I have this sample script from beautiful soup, but I keep getting an error because of encoding. I have google for solutions but I don't seem to understand. Even this is dealt in Beautiful Soup's doc but I am not able to understant/apply the solution successfully. from BeautifulSoup import BeautifulSoup import urllib2 page = urllib2.urlopen('http://www.yellowpages.ca/search/si/1/Signs/QC') # if I change the url to http://www.yellowpages.ca/search/si/3/Signs/ON, it works because there's no french words... soup = BeautifulSoup(page) companies = soup('h2') print soup.originalEncoding print companies[:4] However, if I do this, I don't get errors even when there are accents: for title in companies: print title Here is the Error output: utf-8 Traceback (most recent call last): File "C:\myscripts\encondingproblem.py", line 13, in print companies[:4] UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 373: ordinal not in range(128) === Thanks in advance. Eduardo www.expresssignproducts.com From moron.oxy at gmail.com Tue Aug 18 01:30:04 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Tue, 18 Aug 2009 09:30:04 +1000 Subject: [Tutor] python and java report writers In-Reply-To: <200908171550.45172.jfabiani@yolo.com> References: <200908171131.35960.jfabiani@yolo.com> <200908171301.26752.jfabiani@yolo.com> <2096a7260908171308j67ba5370j14c56e9882617b32@mail.gmail.com> <200908171550.45172.jfabiani@yolo.com> Message-ID: <2096a7260908171630p539c82cr5f1387a008d1459c@mail.gmail.com> On Tue, Aug 18, 2009 at 8:50 AM, John wrote: > I don't know enough about jython to understand what has to be done. ?Let's say > I can write the code to retrieve the data in cPython. ?And I can write a > module in jython that will accept the data passing it on to the report > writer. ?How can I call the jython program? ?It can't be called from the > cPython program - right? ?So the jython runs stand alone - right? Yes Jython runs standalone (via the Java interpreter) in this scenario. If you supply the data, chances are you need to either look if there's a Datasource implementation readily available for the data format you intend to supply - CSV, XML, etc. - or you would need to create one (on the Jython side), essentially it reads in your datafile/stream and passes it to the reporting engine appropriately. > IPC = Inter-process communication - right? ?Does that mean I need to write > some sort of server? Yep I meant interprocess communication. Using a server is one way of doing it, but probably a bit much for simple requirements. Look at the subprocess module and exec family (there have been a few posts regarding these - I personally haven't used them as such so will only refer you to docs and more able posts!), essentially you just need to invoke the jython process, hook up the stdin and stdout between the processes as necessary, e.g. let the jython program take command line params for any operation modifiers/options if you need it to, and read in your data via stdin. This way there's no server, just a simple protocol that the reader process reads from stdin, and an end of file indicates that there's no more data to read, and it can go and do it's stuff. The jython process should also eventually do a System.exit(0) for success, or System.exit(1) for failure (java.lang.System) for easy error handling by CPython; you need to decide how to handle the report output: have jython write it to a file in some predefined location, or send it back your CPython invoker (which makes the IPC a bit more involved). Just depends on your needs, and the time you have available for the task! Regards Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From kent37 at tds.net Tue Aug 18 02:43:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Aug 2009 20:43:05 -0400 Subject: [Tutor] python and java report writers In-Reply-To: <200908171304.21502.jfabiani@yolo.com> References: <200908171131.35960.jfabiani@yolo.com> <1c2a2c590908171249x5ac4430cl4a3f0f3991c08552@mail.gmail.com> <200908171304.21502.jfabiani@yolo.com> Message-ID: <1c2a2c590908171743v50b7e662o2dfb6f544b7f7a29@mail.gmail.com> Forwarding to the list with my reply. On Mon, Aug 17, 2009 at 4:04 PM, John wrote: > Thanks for taking the time to write. But I was really looking for a simple > way of calling a report writer (like using a com object) to print a report. > At this point in the project changing to jython is not going to be > considered. We are using to many modules and I'm sure we will run into > something. >From a quick look at the docs for Jasper Reports I see that it can take data from a CSV file. Perhaps you could make a Java / Jython app that generates your report from a file, then your Python program could write the CSV file and call the external program. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Tue Aug 18 04:12:11 2009 From: jfabiani at yolo.com (John) Date: Mon, 17 Aug 2009 19:12:11 -0700 Subject: [Tutor] python and java report writers In-Reply-To: <1c2a2c590908171743v50b7e662o2dfb6f544b7f7a29@mail.gmail.com> References: <200908171131.35960.jfabiani@yolo.com> <200908171304.21502.jfabiani@yolo.com> <1c2a2c590908171743v50b7e662o2dfb6f544b7f7a29@mail.gmail.com> Message-ID: <200908171912.11380.jfabiani@yolo.com> On Monday 17 August 2009 05:43:05 pm Kent Johnson wrote: > Forwarding to the list with my reply. > > On Mon, Aug 17, 2009 at 4:04 PM, John wrote: > > Thanks for taking the time to write. But I was really looking for a > > simple way of calling a report writer (like using a com object) to print > > a report. At this point in the project changing to jython is not going to > > be considered. We are using to many modules and I'm sure we will run > > into something. > > > > > >From a quick look at the docs for Jasper Reports I see that it can take > > data > > from a CSV file. Perhaps you could make a Java / Jython app that generates > your report from a file, then your Python program could write the CSV file > and call the external program. > > Kent Thanks folks I think I'll have to start playing with jython and see if I can get it to first create a report/ run a report. Then I'll see if I can get it working with python. Again thanks to all. Johnf From vincent.gulinao at gmail.com Tue Aug 18 05:02:56 2009 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Tue, 18 Aug 2009 11:02:56 +0800 Subject: [Tutor] How to format JSON output within script Message-ID: I see you could pipe your output to 'python -mjson.tool', but how do I achieve the same within my script? TIA. From alan.gauld at btinternet.com Tue Aug 18 05:30:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Aug 2009 04:30:13 +0100 Subject: [Tutor] How to format JSON output within script References: Message-ID: "Vincent Gulinao" wrote >I see you could pipe your output to 'python -mjson.tool', but how do I > achieve the same within my script? We don't charge you by the word. A wee bit more explanation and background would be useful please? What are you trying to do exactly? Alan G. From m.wanstall at gmail.com Tue Aug 18 05:41:47 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Tue, 18 Aug 2009 13:41:47 +1000 Subject: [Tutor] How to format JSON output within script In-Reply-To: References: Message-ID: <4fb9d14e0908172041y55512354v12241a67435fd90c@mail.gmail.com> On Tue, Aug 18, 2009 at 1:02 PM, Vincent Gulinao wrote: > I see you could pipe your output to 'python -mjson.tool', but how do I > achieve the same within my script? > > TIA. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > There is a JSON module in Python...the examples in the docs are pretty self explanatory: http://docs.python.org/library/json.html Can you give a bit of an example of what you're trying to do? -Mal W -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Aug 18 05:50:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Aug 2009 23:50:17 -0400 Subject: [Tutor] How to format JSON output within script In-Reply-To: References: Message-ID: <1c2a2c590908172050t4f61a679y951f15ecbcedd521@mail.gmail.com> On Mon, Aug 17, 2009 at 11:02 PM, Vincent Gulinao wrote: > I see you could pipe your output to 'python -mjson.tool', but how do I > achieve the same within my script? json.tool is a pretty simple wrapper around json.load() and json.dump(). You can look at the source code in your Python lib directory. (Lib/json/tool.py) Kent From vincent.gulinao at gmail.com Tue Aug 18 05:55:41 2009 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Tue, 18 Aug 2009 11:55:41 +0800 Subject: [Tutor] How to format JSON output within script In-Reply-To: <1c2a2c590908172050t4f61a679y951f15ecbcedd521@mail.gmail.com> References: <1c2a2c590908172050t4f61a679y951f15ecbcedd521@mail.gmail.com> Message-ID: Got it, what I need was json.dumps. Sorry I posted too early. Thanks. On Tue, Aug 18, 2009 at 11:50 AM, Kent Johnson wrote: > On Mon, Aug 17, 2009 at 11:02 PM, Vincent > Gulinao wrote: >> I see you could pipe your output to 'python -mjson.tool', but how do I >> achieve the same within my script? > > json.tool is a pretty simple wrapper around json.load() and > json.dump(). You can look at the source code in your Python lib > directory. (Lib/json/tool.py) > > Kent > From m.wanstall at gmail.com Tue Aug 18 06:18:19 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Tue, 18 Aug 2009 14:18:19 +1000 Subject: [Tutor] Problems with encoding in BeautifulSoup In-Reply-To: <9356b9f30908171600w6399e96cp1a7274def7df3b20@mail.gmail.com> References: <9356b9f30908171600w6399e96cp1a7274def7df3b20@mail.gmail.com> Message-ID: <4fb9d14e0908172118h3813b955i1d6e2ec151956c94@mail.gmail.com> On Tue, Aug 18, 2009 at 9:00 AM, Eduardo Vieira wrote: > Hello, I have this sample script from beautiful soup, but I keep > getting an error because of encoding. I have google for solutions but > I don't seem to understand. Even this is dealt in Beautiful Soup's doc > but I am not able to understant/apply the solution successfully. > > from BeautifulSoup import BeautifulSoup > import urllib2 > page = urllib2.urlopen('http://www.yellowpages.ca/search/si/1/Signs/QC') > > # if I change the url to > http://www.yellowpages.ca/search/si/3/Signs/ON, it works because > there's no french words... > > soup = BeautifulSoup(page) > > companies = soup('h2') > > print soup.originalEncoding > > print companies[:4] > > However, if I do this, I don't get errors even when there are accents: > for title in companies: > ? ?print title > > Here is the Error output: > utf-8 > Traceback (most recent call last): > ?File "C:\myscripts\encondingproblem.py", line 13, in > ? ?print companies[:4] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 373: ordinal not in range(128) > > === > Thanks in advance. > > Eduardo > www.expresssignproducts.com > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > It's caused by Python not wanting to send non-ASCII characters to your terminal. To override this you need to create a sitecustomize.py file in your /usr/lib/python/ folder and put the following in it: import sys sys.setdefaultencoding("utf-8") This will set the default encoding in Python to UTF8 and you should stop getting these parsing errors. I dealt with this recently when I was playing around with some international data. -Mal W From m.wanstall at gmail.com Tue Aug 18 06:43:26 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Tue, 18 Aug 2009 14:43:26 +1000 Subject: [Tutor] Web framework: looking for python-tutor's angle. In-Reply-To: <1250186968.894.41.camel@jabbar> References: <1250186968.894.41.camel@jabbar> Message-ID: <4fb9d14e0908172143lfd9e0d3w15ae10e4bcbf51ec@mail.gmail.com> On Fri, Aug 14, 2009 at 4:09 AM, Mac Ryan wrote: > A couple of months ago I took the time to read a few articles on python > web application frameworks and I got the impression that the two most > mature and active projects are Zope and Django. > > Zope vs. Django hits 879.000 pages on google but much of the debate - or > at least this is my impression - falls into the class "vi vs. emacs" or > "gtk vs. qt" with many people singling out a single characteristics that > for them is THE characteristic making one framework better than the > other. > > This [1] graph seems to corroborate my final impression (i.e. that > django is the way to go). Yet, I would be very interested in hearing > what the members of this list think, as I particularly enjoy the > "learner centered" approach that most of the people seems to have here. > > I believe my needs are quite ordinary: my customers are typically small > businesses needing to process their data on a single server, sometime > exposing part of the application as front-end to the customers (hence > easy and flexible theming is important). I would definitively be happy > to sacrifice some functionality in exchange for a leaner and cleaner > design (i.e. more modular, elegant and intuitive), though. > > Thank you in advance for your time, > Mac. > > [1] http://www.google.com/trends?q=python+zope%2C+python+django > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Your needs definitely favour Django. The learning curve is so much shallower for Django and it's very simple to theme not to mention a much more beginner-tolerant community IMHO. -Mal W From kent37 at tds.net Tue Aug 18 13:59:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Aug 2009 07:59:26 -0400 Subject: [Tutor] Problems with encoding in BeautifulSoup In-Reply-To: <4fb9d14e0908172118h3813b955i1d6e2ec151956c94@mail.gmail.com> References: <9356b9f30908171600w6399e96cp1a7274def7df3b20@mail.gmail.com> <4fb9d14e0908172118h3813b955i1d6e2ec151956c94@mail.gmail.com> Message-ID: <1c2a2c590908180459n3aed9988h9e46b50b156e8c82@mail.gmail.com> On Tue, Aug 18, 2009 at 12:18 AM, Mal Wanstall wrote: > On Tue, Aug 18, 2009 at 9:00 AM, Eduardo Vieira wrote: >> Here is the Error output: >> utf-8 >> Traceback (most recent call last): >> ?File "C:\myscripts\encondingproblem.py", line 13, in >> ? ?print companies[:4] >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >> position 373: ordinal not in range(128) > > It's caused by Python not wanting to send non-ASCII characters to your > terminal. To override this you need to create a sitecustomize.py file > in your /usr/lib/python/ folder and put the following in it: > > import sys > sys.setdefaultencoding("utf-8") > > This will set the default encoding in Python to UTF8 and you should > stop getting these parsing errors. I dealt with this recently when I > was playing around with some international data. Eduardo is on Windows so his terminal encoding is probably not utf-8. More likely it is cp437. Setting sys.setdefaultencoding() affects all scripts you run and will make scripts that you write non-portable. A better solution is to properly encode the output, for example for company in companies[:4]: # assuming companies is a list print company.encode('cp437') Kent From zstumgoren at gmail.com Tue Aug 18 15:37:20 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 18 Aug 2009 09:37:20 -0400 Subject: [Tutor] Problems with encoding in BeautifulSoup In-Reply-To: <1c2a2c590908180459n3aed9988h9e46b50b156e8c82@mail.gmail.com> References: <9356b9f30908171600w6399e96cp1a7274def7df3b20@mail.gmail.com> <4fb9d14e0908172118h3813b955i1d6e2ec151956c94@mail.gmail.com> <1c2a2c590908180459n3aed9988h9e46b50b156e8c82@mail.gmail.com> Message-ID: > Setting sys.setdefaultencoding() affects all scripts you run and will > make scripts that you write non-portable. A better solution is to > properly encode the output, for example > for company in companies[:4]: # assuming companies is a list > ?print company.encode('cp437') > Kent's suggestion appears to be more in line with the recommended method in the Beautiful Soup docs. Check out the below page: http://www.crummy.com/software/BeautifulSoup/documentation.html#Why%20can%27t%20Beautiful%20Soup%20print%20out%20the%20non-ASCII%20characters%20I%20gave%20it? Here's some sample code: import codecs import sys streamWriter = codecs.lookup('utf-8')[-1] sys.stdout = streamWriter(sys.stdout) You might also want to spend some time reading up on encoding. Here are a few guides that I found useful: http://eric.themoritzfamily.com/2008/11/21/python-encodings-and-unicode/ http://evanjones.ca/python-utf8.html http://wesc.livejournal.com/1743.html From eduardo.susan at gmail.com Tue Aug 18 17:01:19 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 18 Aug 2009 09:01:19 -0600 Subject: [Tutor] Problems with encoding in BeautifulSoup In-Reply-To: <1c2a2c590908180459n3aed9988h9e46b50b156e8c82@mail.gmail.com> References: <9356b9f30908171600w6399e96cp1a7274def7df3b20@mail.gmail.com> <4fb9d14e0908172118h3813b955i1d6e2ec151956c94@mail.gmail.com> <1c2a2c590908180459n3aed9988h9e46b50b156e8c82@mail.gmail.com> Message-ID: <9356b9f30908180801t17bb045by6d1e068aa695ff61@mail.gmail.com> On Tue, Aug 18, 2009 at 5:59 AM, Kent Johnson wrote: > On Tue, Aug 18, 2009 at 12:18 AM, Mal Wanstall wrote: >> On Tue, Aug 18, 2009 at 9:00 AM, Eduardo Vieira wrote: > >>> Here is the Error output: >>> utf-8 >>> Traceback (most recent call last): >>> ?File "C:\myscripts\encondingproblem.py", line 13, in >>> ? ?print companies[:4] >>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in >>> position 373: ordinal not in range(128) >> >> It's caused by Python not wanting to send non-ASCII characters to your >> terminal. To override this you need to create a sitecustomize.py file >> in your /usr/lib/python/ folder and put the following in it: >> >> import sys >> sys.setdefaultencoding("utf-8") >> >> This will set the default encoding in Python to UTF8 and you should >> stop getting these parsing errors. I dealt with this recently when I >> was playing around with some international data. > > Eduardo is on Windows so his terminal encoding is probably not utf-8. > More likely it is cp437. > > Setting sys.setdefaultencoding() affects all scripts you run and will > make scripts that you write non-portable. A better solution is to > properly encode the output, for example > for company in companies[:4]: # assuming companies is a list > ?print company.encode('cp437') > > Kent > So, I gather that you all don't get this error, then? Anyway, running sys.getdefaultencoding() I get 'ascii' The test example from BSoup docs works differently wether I use IDLE or the cmd window in my XP. The example is: latin1word = 'Sacr\xe9 bleu!' unicodeword = unicode(latin1word, 'latin-1') print unicodeword In IDLE I get "Sacr? bleu!", in the windows shell I get "Sacr\xe9 bleu!" simply trying a loop, prevents me from the error, I found out: for company in companies[:10]: print company however I can't see the accents displayed properly. This is corrected when I use this encoding: company.encode("iso-8859-1"). This way I get the right results. Thanks for pointing me to this. What remains a question is why when printing a list it throws an error and when printing the strings in the list it doesn't. Regards, Eduardo From zstumgoren at gmail.com Tue Aug 18 19:47:06 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 18 Aug 2009 13:47:06 -0400 Subject: [Tutor] yet another question on OO inheritance Message-ID: Hi all, I've hit another gray area for an application I'm working on. Specifically, I have a campaign Committee object, and then subclasses called CandidateCommittee and PresidentialCommittee. Depending on the type of committee, I have to execute a series of SQL statements to pull data (used to populate instance attributes of each committee type). Several of these queries are identical, except for the table names from which I'm pulling the data: Committee(object):... CandidateCommittee(Committee): def get_data(self): sql = """ select id, name from table_candidates """ # execute sql and do stuff with the data PresidentialCommittee(Committee): def get_data(self): sql = """ select id, name from table_prez """ # execute sql and do stuff with the data So I'm thinking I could reduce code duplication by moving the SQL queries to the Committee object: Committee(object):... def get_data(self): sql = """ select id, name from table_'%(tablename)s' """ % {'tablename':name} CandidateCommittee(Committee):... def __init__(self): super(CandidateCommittee, self).__init() PresidentialCommittee(Committee): def __init__(self): super(PresidentialCommittee, self).__init() But if I do this, how would I set the "name" variable inside the "get_data" method when I instantiate one of the subclasses? Would I need to do type-checking with "isinstance"? And if so, how does one implement that in this case? I figured overriding the get_data method would simply clobber the sql I'm trying to inherit, which of course defeats the purpose. Can anyone suggest an approach? Regards, Serdar From kent37 at tds.net Tue Aug 18 20:23:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Aug 2009 14:23:05 -0400 Subject: [Tutor] yet another question on OO inheritance In-Reply-To: References: Message-ID: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> On Tue, Aug 18, 2009 at 1:47 PM, Serdar Tumgoren wrote: > Hi all, > > I've hit another gray area for an application I'm working on. > Specifically, I have a campaign Committee object, and then subclasses > called CandidateCommittee and PresidentialCommittee. Depending on the > type of committee, I have to execute a series of SQL statements to > pull data (used to populate instance attributes of each committee > type). > > Several of these queries are identical, except for the table names > from which I'm pulling the data: > So I'm thinking I could reduce code duplication by moving the SQL > queries to the Committee object: > > Committee(object):... > > ? ?def get_data(self): > ? ? ? ?sql = """ > ? ? ? ?select id, name > ? ? ? ?from table_'%(tablename)s' > ? ? ? ?""" % {'tablename':name} > > CandidateCommittee(Committee):... > ? ?def __init__(self): > ? ? ? ?super(CandidateCommittee, self).__init() > > PresidentialCommittee(Committee): > ? ?def __init__(self): > ? ? ? ?super(PresidentialCommittee, self).__init() > > But if I do this, how would I set the "name" variable inside the > "get_data" method when I instantiate one of the subclasses? A nice way to do this is with a class attribute. For example: class Committee(object): def get_data(self): sql = """ select id, name from table_'%(tablename)s' """ % {'tablename':self.tablename} class CandidateCommittee(Committee): tablename = 'CandidateTable' PresidentialCommittee(Committee): tablename = 'PresidentialTable' When you call Committee.get_data() it will get tablename from the class of the instance being used. Kent From zstumgoren at gmail.com Tue Aug 18 20:51:49 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 18 Aug 2009 14:51:49 -0400 Subject: [Tutor] yet another question on OO inheritance In-Reply-To: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> References: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> Message-ID: Thanks to you both for the suggestions. I think I'll try the approach below. But just one follow-up: should I be setting "self.tablename", or is a static attribute ("tablename") the correct approach? > A nice way to do this is with a class attribute. For example: > class Committee(object): > > ? def get_data(self): > ? ? ? sql = """ > ? ? ? select id, name > ? ? ? from table_'%(tablename)s' > ? ? ? """ % {'tablename':self.tablename} > > class CandidateCommittee(Committee): > ? tablename = 'CandidateTable' > > PresidentialCommittee(Committee): > ? tablename = 'PresidentialTable' > > When you call Committee.get_data() it will get tablename from the > class of the instance being used. > From zstumgoren at gmail.com Tue Aug 18 21:16:55 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 18 Aug 2009 15:16:55 -0400 Subject: [Tutor] yet another question on OO inheritance In-Reply-To: References: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> Message-ID: On Tue, Aug 18, 2009 at 2:51 PM, Serdar Tumgoren wrote: > Thanks to you both for the suggestions. I think I'll try the approach > below. But just one follow-up: should I be setting "self.tablename", > or is a static attribute ("tablename") the correct approach? > Looks like it's the former (i.e. "self.tablename") Thanks again! From kent37 at tds.net Tue Aug 18 22:36:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Aug 2009 16:36:14 -0400 Subject: [Tutor] yet another question on OO inheritance In-Reply-To: References: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> Message-ID: <1c2a2c590908181336v41518736l6bc6ee58248a10b0@mail.gmail.com> On Tue, Aug 18, 2009 at 3:16 PM, Serdar Tumgoren wrote: > On Tue, Aug 18, 2009 at 2:51 PM, Serdar Tumgoren wrote: >> Thanks to you both for the suggestions. I think I'll try the approach >> below. But just one follow-up: should I be setting "self.tablename", >> or is a static attribute ("tablename") the correct approach? >> > Looks like it's the former (i.e. "self.tablename") It's as I wrote it. The atttribute is created in the class definition (not in any method) as just "tablename". This creates an attribute of the class, rather than of the instance. It is accessed as "self.tablename". The attribute lookup rules will look first in the instance, fail to find 'tablename', then look in the class and find it. Here is a complete example: In [1]: class Base(object): ...: def show_name(self): ...: print self.name In [2]: class Derived1(Base): ...: name = 'Derived1' In [3]: class Derived2(Base): ...: name = 'Derived2' In [4]: d1 = Derived1() In [5]: d1.show_name() Derived1 In [6]: d2 = Derived2() In [7]: d2.show_name() Derived2 Kent From zstumgoren at gmail.com Tue Aug 18 22:44:33 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 18 Aug 2009 16:44:33 -0400 Subject: [Tutor] yet another question on OO inheritance In-Reply-To: <1c2a2c590908181336v41518736l6bc6ee58248a10b0@mail.gmail.com> References: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> <1c2a2c590908181336v41518736l6bc6ee58248a10b0@mail.gmail.com> Message-ID: > ..The atttribute is created in the class definition > (not in any method) as just "tablename". This creates an attribute of > the class, rather than of the instance. It is accessed as > "self.tablename". The attribute lookup rules will look first in the > instance, fail to find 'tablename', then look in the class and find > it. Aha! A very smart solution indeed. I initially had errors with this approach because I was continuing to define "table" inside of __init__: class Derived(Base): def __init__(self): table = "TableName" But as you suggested, moving the table name outside of the constructor method (__init__) resolved the situation: class Derived(Base): table = "TableName" def __init__(self): #etc... As always, many many thanks!! Regards, Serdar From davea at dejaviewphoto.com Wed Aug 19 00:54:26 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Tue, 18 Aug 2009 18:54:26 -0400 Subject: [Tutor] yet another question on OO inheritance In-Reply-To: References: <1c2a2c590908181123h1c9abfb7n79b34d3dca91ca42@mail.gmail.com> Message-ID: <4A8B3122.4040107@dejaviewphoto.com> Serdar Tumgoren wrote: > Thanks to you both for the suggestions. I think I'll try the approach > below. But just one follow-up: should I be setting "self.tablename", > or is a static attribute ("tablename") the correct approach? > > >> A nice way to do this is with a class attribute. For example: >> class Committee(object): >> >> def get_data(self): >> sql ="" >> select id, name >> from table_'%(tablename)s' >> """ % {'tablename':self.tablename} >> >> class CandidateCommittee(Committee): >> tablename =CandidateTable' >> >> PresidentialCommittee(Committee): >> tablename =PresidentialTable' >> >> When you call Committee.get_data() it will get tablename from the >> class of the instance being used. >> >> > > (You top-posted. On this list, you should put your response at the end, or inline if needed. It makes it much easier to follow the thread) Since you presumaby want the value tablename to be the same for all instances of a given class, you should use a class attribute, as Kent said. DaveA From jramak345 at gmail.com Wed Aug 19 01:57:49 2009 From: jramak345 at gmail.com (Jramak) Date: Tue, 18 Aug 2009 16:57:49 -0700 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically Message-ID: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> Hello We have developed three custom applications in Python. Each one of these applications needs a different PYTHONPATH, in addition to different environment variables to work. Instead of manually setting the environment variables for each application, what would be the best way to set PYTHONPATH and other environment variables for a specific application? We only run one application at a time, not all of them. We are running Python 2.5.2 and Python 2.4.1 on Win2K. Is a bash script that sets the environment variables on the application start-up way to go? Any ideas? I was not aware of site.py until a co-worker bandied it about - he says site.py is better than PYTHONPATH. Ideas and recommendations welcome.. Regards Jramak From kent37 at tds.net Wed Aug 19 02:54:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Aug 2009 20:54:08 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> Message-ID: <1c2a2c590908181754y36b0075cifcabf6a529673f65@mail.gmail.com> On Tue, Aug 18, 2009 at 7:57 PM, Jramak wrote: > Hello > We have developed three custom applications in Python. Each one of > these applications needs a different PYTHONPATH, in addition to > different environment variables to work. Instead of manually setting > the environment variables for each application, what would be the best > way to set PYTHONPATH and other environment variables for a specific > application? We only run one application at a time, not all of them. > We are running Python 2.5.2 and Python 2.4.1 on Win2K. Is a bash > script that sets the environment variables on the application start-up > ?way to go? You can modify the search path in each program my adding to sys.path. Kent From dgou at mac.com Wed Aug 19 03:21:18 2009 From: dgou at mac.com (Douglas Philips) Date: Tue, 18 Aug 2009 21:21:18 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> Message-ID: <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> On 2009 Aug 18, at 7:57 PM, Jramak wrote: > Hello > We have developed three custom applications in Python. Each one of > these applications needs a different PYTHONPATH, in addition to > different environment variables to work. Instead of manually setting > the environment variables for each application, what would be the best > way to set PYTHONPATH and other environment variables for a specific > application? We only run one application at a time, not all of them. > We are running Python 2.5.2 and Python 2.4.1 on Win2K. Is a bash > script that sets the environment variables on the application start-up > way to go? > > Any ideas? I was not aware of site.py until a co-worker bandied it > about - he says site.py is better than PYTHONPATH. Ok, well, if you are on Windows and your talking about bash scripts, it sounds like you might be using cygwin? Typically "scripts" on Windows are .BAT files, so I am not sure what you're referring to here. I think you have five-ish general options: a) set variables by hand. run program(s) by hand. (not very much fun, and possibly error prone.) b) create scripts (bash or .BAT or whatever, depending on your situation) that set the variables and runs your program(s). c) install whatever your programs need under the site-packages directory of your python install. This assumes that all the packages your programs need have unique names. I can't tell from your description if they are different pacakges or if they might just be different versions of the same package. If they are just different versions of the same package, probably this option wouldn't work, it all depends on the specific files. It also depends on where you have Python 2.5.2. and Python 2.4.1 installed and if you use them at the same time. This option still requires another option for setting the other environment variables. d) Set up your environments in each of your main programs. Here is the boilerplate you might use: # This needs to be at the top of the program after the module doc string (if any) and before any other statements or imports: import sys sys.path.append("dir1/dir2") # Add dir1/dir2 to your Python search path. Can be absolute path or relative. sys.path.append("dir3/dir4") # ... import os os.environ['MYVARIABLE'] = 'MyVALUE' os.environ['ANOTHERONE'] = 'someothervalue' # ... This has the nice property that everything is self contained. But that also can be a downside if the values need to be changed by someone else, they'd have to go and edit .py files. e) option d and a (seems unlikely), option d and b, option d and c. Depending on what you variables are, and how often they change, it might make sense to put some of them (Python path or environment) into the programs, and the rest in scripts. Hope this helps, --Doug From darthkaboda at msn.com Wed Aug 19 07:52:50 2009 From: darthkaboda at msn.com (Darth Kaboda) Date: Tue, 18 Aug 2009 22:52:50 -0700 Subject: [Tutor] Question if my reasoning is right Message-ID: I'm questioning my reason for why the follwoing code doesn't behave as I thought it would upon first coding a project. m = 8 n = 10 cb = [[[0, None]] * (n + 1)] * (m + 1) cb[3][2][0] = 10 This last statement causes the every first element in the list to update. Is this becuase this method of initializing a list is just a copy of the same list in memory? To get around this I'm now doing the folowing: m = 8 n = 10 cb = [[[0,None] for x in range(n+1)] for y in range(m+1)] cb[3][2][0] = 10 This is working by updating only the one list as I want it to. Is this an acceptable practice? Or should I use the standard nested for loops like you'd do in most other languages? Any insight would be greatly appreciated. Thanks, Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: From llvirta at gmail.com Wed Aug 19 09:13:59 2009 From: llvirta at gmail.com (Olli Virta) Date: Wed, 19 Aug 2009 10:13:59 +0300 Subject: [Tutor] handling a textfile Message-ID: <17042c3d0908190013y4b9d6ee8m7b1950a56004e903@mail.gmail.com> Hi! I have a textfile (job.txt) that needs modifying. The structure of this file is like this: AAA1... BBB1... CCC1... AAA2... BBB2... CCC2... etc... Question is how can I turn this all to a textfile (done.txt) that is suppose to look like this: AAA1...BBB1...CCC1... AAA2...BBB2...CCC2... etc. Thanks! OV -------------- next part -------------- An HTML attachment was scrubbed... URL: From fidellira.6 at gmail.com Wed Aug 19 10:12:23 2009 From: fidellira.6 at gmail.com (Fidel Sanchez-Bueno) Date: Wed, 19 Aug 2009 04:12:23 -0400 Subject: [Tutor] handling a textfile In-Reply-To: <17042c3d0908190013y4b9d6ee8m7b1950a56004e903@mail.gmail.com> References: <17042c3d0908190013y4b9d6ee8m7b1950a56004e903@mail.gmail.com> Message-ID: <4A8BB3E7.9040309@gmail.com> Olli Virta escribi?: > Hi! > > I have a textfile (job.txt) that needs modifying. The structure of > this file is like this: > > AAA1... > BBB1... > CCC1... > AAA2... > BBB2... > CCC2... > etc... > > > > Question is how can I turn this all to a textfile (done.txt) that is > suppose to look like this: > > AAA1...BBB1...CCC1... > AAA2...BBB2...CCC2... > etc. > > Thanks! OV > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > hi... i dont think this is the best way of doing it, but you can have an idea by reading the code: some_file="""AAA1... BBB1... CCC1... AAA2... BBB2... CCC2...""" some_tuple=some_file.split() def change(some_tuple): temp="" temp2="" for x in some_tuple: if "1" in x: temp+=x else: temp2+=x done= temp +"\n" +temp2 return done done_file=change(some_tuple) is not perfect but you can get the idea.. From alan.gauld at btinternet.com Wed Aug 19 11:30:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Aug 2009 10:30:11 +0100 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> Message-ID: "Jramak" wrote > We have developed three custom applications in Python. Each one of > these applications needs a different PYTHONPATH, in addition to > different environment variables to work. Environment variables should control the users (or oprocess) environment and as such should really be fairly static, you could cause real problems if you start changing the users environment dynamically because that might affect how other applications run that also rely on PYTHONPATH or whatever. Now, its true that each process gets a copy of the shell environment so changing it within the process shouldn't affect the external environment but to me it is still the wrong way to go about it. At the very least it means your environment variables no longer accurately reflect the users environment so you might get surprises if you try and launch a shell process or batch job which picks up the original environment! In this case I'd much rather change sys.path. That is a Python list and much easier to add items at startup rather than mess with the environment. > the environment variables for each application, what would be the best > way to set PYTHONPATH and other environment variables for a specific > application? Use config values in an ini file and set global variables in your program at startup, and for paths use sys.path. (So far as I can tell thats what Python does with PYTHONPATYH - it loads the values into sys.path at startup...) > We only run one application at a time, not all of them. > We are running Python 2.5.2 and Python 2.4.1 on Win2K. Is a bash > script that sets the environment variables on the application start-up > way to go? That is only slightly better since the environment no longer reflects the users normal environment. It does mean the bash script could launch multiple programs etc andd they would at lest share a common environment but in your case I don't think its the best solution. > Any ideas? I was not aware of site.py until a co-worker bandied it > about - he says site.py is better than PYTHONPATH. They do different things! site.py is about customising Python on that site - which may be a shared installation - and environment variables are about describing a users environment, and can be different for each user. Now, there is an overlap, but Pythonpath is not one of them since multiple users can share a site! (site.py is probably better than setting a System wide PYTHONPATH though....) But again site.py applies to every application you should not start modifying it with application specific startup code - yuck! It could soon turn into spaghetti and seriously slow down startup of everything. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Aug 19 11:34:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Aug 2009 10:34:30 +0100 Subject: [Tutor] Question if my reasoning is right References: Message-ID: "Darth Kaboda" wrote > cb = [[[0, None]] * (n + 1)] * (m + 1) > cb[3][2][0] = 10 > > This last statement causes the every first element in the list to update. > Is this becuase this method of initializing a list is just a copy Yes exactly. > To get around this I'm now doing the folowing: > cb = [[[0,None] for x in range(n+1)] for y in range(m+1)] Yes, that's what list comprehensions are for, to create lists. > Is this an acceptable practice? Absolutely. It is one of the most common uses for comprehensions. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Aug 19 11:54:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Aug 2009 10:54:56 +0100 Subject: [Tutor] handling a textfile References: <17042c3d0908190013y4b9d6ee8m7b1950a56004e903@mail.gmail.com> Message-ID: "Olli Virta" wrote > I have a textfile (job.txt) that needs modifying. The structure of this > file > is like this: > > AAA1... > BBB1... > CCC1... > AAA2... > BBB2... > CCC2... > etc... > Question is how can I turn this all to a textfile (done.txt) that is > suppose > to look like this: > > AAA1...BBB1...CCC1... > AAA2...BBB2...CCC2... Lots of ways to do it. The simplest is to read the variables line by line, so, in pseudo code: while infile not empty a = f.readline() b = f.readline() c = f.readline() outfile.write("%s,%s,%s" % (a,b,c) ) If the data is manageable you could read it all into a list then use list slicing to achieve the same data = infile.readlines() for start in range(len(data))[::3]: # get every third index outfile.write("%s\t%s\t%s" % tuple(data[start :start+3]) ) I suspect you can do even clever things with itertools using groupby and such, but I'm no itertools expert - its on my list of things to learn... :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From evosweet at hotmail.com Wed Aug 19 13:32:57 2009 From: evosweet at hotmail.com (Rayon) Date: Wed, 19 Aug 2009 07:32:57 -0400 Subject: [Tutor] python telnet Message-ID: using python telnet lib to connect to a Nortel switch, and dump some tables. My problem is that every now and then the connection is reset by peer . Telnet Error : (10054, Connection reset by peer) I need to know why, I have it in a loop so it will download after a few tries but I need to know why. here is the code. #main telnet class import telnetlib #import telnet lib class supertelnet: # super tenet class def __init__(self): # def construct """""" def telNetCall(self, Host, User, Pass, LocalFile): print "start lens dump" host = Host user = User password = Pass file = LocalFile telnet = telnetlib.Telnet(host) # connect to telnet client #telnet.set_debuglevel(1) telnet.read_until('Enter User Name', 3) # read session data untill match or timeout. telnet.write(user + '\r') # send username telnet.write(password + '\r') #send password # send command to dump len files # start print "lens dump in progress" telnet.write('table ibnlines' + '\r') telnet.write('format pack' + '\r') telnet.write('list all' + '\r') telnet.write('logout' + '\r') #end of commands lens = telnet.read_all() # get session data and store data print "file write strated" x = open(file,'wd') # open file x.write(lens) # write data to file print "file done" -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Aug 19 13:48:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 07:48:01 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> Message-ID: <1c2a2c590908190448r18f09959j67c1a6f828fe27bb@mail.gmail.com> On Tue, Aug 18, 2009 at 9:21 PM, Douglas Philips wrote: > I think you have five-ish general options: One more - put required packages and modules into the same directory as the executable, usually the current directory is on the Python search path. Kent From kent37 at tds.net Wed Aug 19 13:53:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 07:53:16 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> Message-ID: <1c2a2c590908190453o2cb7acbfoec300696b6ce56e4@mail.gmail.com> On Tue, Aug 18, 2009 at 7:57 PM, Jramak wrote: > Hello > We have developed three custom applications in Python. Each one of > these applications needs a different PYTHONPATH, in addition to > different environment variables to work. Instead of manually setting > the environment variables for each application, what would be the best > way to set PYTHONPATH and other environment variables for a specific > application? We only run one application at a time, not all of them. > We are running Python 2.5.2 and Python 2.4.1 on Win2K. Is a bash > script that sets the environment variables on the application start-up > ?way to go? > > Any ideas? I was not aware of site.py until a co-worker bandied it > about - he says site.py is better than PYTHONPATH. Don't edit site.py, it is part of the std lib. If you do want to customize it, add a site-customize.py in your site-packages folder and put your customizations there. Kent From kent37 at tds.net Wed Aug 19 13:55:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 07:55:17 -0400 Subject: [Tutor] Question if my reasoning is right In-Reply-To: References: Message-ID: <1c2a2c590908190455l503e92a6ofd9c658e1a126af3@mail.gmail.com> On Wed, Aug 19, 2009 at 1:52 AM, Darth Kaboda wrote: > I'm questioning my reason for why the follwoing code doesn't behave as I > thought it would upon first coding a project. > > m = 8 > n = 10 > cb = [[[0, None]] * (n + 1)] * (m + 1) > cb[3][2][0] = 10 > > This last statement causes the?every?first element?in the list to update. Is > this becuase this method of initializing a list is just a copy of the same > list in memory? Not literally a copy, but pointing to the same list. The correct term is that each element of the list is a reference, or alias, to the same list. Kent From kent37 at tds.net Wed Aug 19 13:57:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 07:57:30 -0400 Subject: [Tutor] handling a textfile In-Reply-To: References: <17042c3d0908190013y4b9d6ee8m7b1950a56004e903@mail.gmail.com> Message-ID: <1c2a2c590908190457p22c8d3efm752b0a4ecaeaa06a@mail.gmail.com> On Wed, Aug 19, 2009 at 5:54 AM, Alan Gauld wrote: > Lots of ways to do it. The simplest is to read the variables line by line, > so, in pseudo code: > > while infile not empty > ? ?a = f.readline() > ? ?b = f.readline() > ? ?c = f.readline() > ? ?outfile.write("%s,%s,%s" % (a,b,c) ) You will need to strip newlines from a and b. Kent From davea at ieee.org Wed Aug 19 14:03:56 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 19 Aug 2009 08:03:56 -0400 Subject: [Tutor] handling a textfile In-Reply-To: References: <17042c3d0908190013y4b9d6ee8m7b1950a56004e903@mail.gmail.com> Message-ID: <4A8BEA2C.2010204@ieee.org> Alan Gauld wrote: >
> "Olli Virta" wrote > >> I have a textfile (job.txt) that needs modifying. The structure of >> this file >> is like this: >> >> AAA1... >> BBB1... >> CCC1... >> AAA2... >> BBB2... >> CCC2... >> etc... >> Question is how can I turn this all to a textfile (done.txt) that is >> suppose >> to look like this: >> >> AAA1...BBB1...CCC1... >> AAA2...BBB2...CCC2... > > Lots of ways to do it. The simplest is to read the variables line by > line, > so, in pseudo code: > > while infile not empty > a = f.readline() > b = f.readline() > c = f.readline() > outfile.write("%s,%s,%s" % (a,b,c) ) > > If the data is manageable you could read it all into a list then use list > slicing to achieve the same > > data = infile.readlines() > for start in range(len(data))[::3]: # get every third index > outfile.write("%s\t%s\t%s" % tuple(data[start :start+3]) ) > > I suspect you can do even clever things with itertools using groupby > and such, but I'm no itertools expert - its on my list of things to > learn... :-) > > HTH, > Between ellipses and etc., you've managed to confuse everyone with the actual format of your file. But Alan's response is the closest so far to what I think you might have had in mind. The thing he seems to be missing is the treatment of newlines. Basically your output file is just like your input file except that some newlines have been removed. So the only question is what's the pattern of removal. You might have a constant number of input lines per group (e.g. three for your present example). If that's the case, you want to strip off all newlines except those in front of a multiple of (3). So loop through the data array, using rstrip() on all the lines except 2, 5, 8, ... You can use the modulo operator (%) to decide whether an index has the right form. Alternatively, you might be saying you want a newline whenever the prefix of the line changes. So loop through the lines, doing the rstrip() unless the next line begins the same as the present one. DaveA From rabidpoobear at gmail.com Wed Aug 19 15:01:41 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 19 Aug 2009 08:01:41 -0500 Subject: [Tutor] python telnet In-Reply-To: References: Message-ID: How are you running it?This usually happens when you have an error in your connection, and then you try to re-run it, and the previous connection attempt has not released the port yet. Are you having an error between subsequent runs, or do you have an error the first time you run it after a fresh reboot? On Wed, Aug 19, 2009 at 6:32 AM, Rayon wrote: > using python telnet lib to connect to a Nortel switch, and dump some > tables. > My problem is that every now and then the connection is reset by peer . > Telnet Error : (10054, Connection reset by peer) > I need to know why, I have it in a loop so it will download after a few > tries but I need to know why. > here is the code. > > > #main telnet class > import telnetlib > #import telnet lib > > class supertelnet: # super tenet class > > > def __init__(self): # def construct > """""" > > def telNetCall(self, Host, User, Pass, LocalFile): > print "start lens dump" > host = Host > user = User > password = Pass > file = LocalFile > telnet = telnetlib.Telnet(host) # connect to telnet client > #telnet.set_debuglevel(1) > telnet.read_until('Enter User Name', 3) # read session data untill > match or timeout. > telnet.write(user + '\r') # send username > telnet.write(password + '\r') #send password > # send command to dump len files > # start > print "lens dump in progress" > telnet.write('table ibnlines' + '\r') > telnet.write('format pack' + '\r') > telnet.write('list all' + '\r') > telnet.write('logout' + '\r') > #end of commands > lens = telnet.read_all() # get session data and store data > print "file write strated" > x = open(file,'wd') # open file > x.write(lens) # write data to file > print "file done" > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jramak345 at gmail.com Wed Aug 19 22:00:49 2009 From: jramak345 at gmail.com (Jramak) Date: Wed, 19 Aug 2009 13:00:49 -0700 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <1c2a2c590908190448r18f09959j67c1a6f828fe27bb@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> <1c2a2c590908190448r18f09959j67c1a6f828fe27bb@mail.gmail.com> Message-ID: <6191dd070908191300v7ba97b05p63b3470f0276cbf5@mail.gmail.com> > > > One more - put required packages and modules into the same directory > as the executable, usually the current directory is on the Python > search path. > > Kent > Hi Kent, there is no executable. It is just a collection of python scripts. I assume you refer to the Python search path as PYTHONPATH or sys.path. Do correct me if I am wrong. Jramak -------------- next part -------------- An HTML attachment was scrubbed... URL: From jramak345 at gmail.com Wed Aug 19 22:05:33 2009 From: jramak345 at gmail.com (Jramak) Date: Wed, 19 Aug 2009 13:05:33 -0700 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <1c2a2c590908190453o2cb7acbfoec300696b6ce56e4@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <1c2a2c590908190453o2cb7acbfoec300696b6ce56e4@mail.gmail.com> Message-ID: <6191dd070908191305n366c4f35lc778fb1747c5f6ed@mail.gmail.com> > > > > > Don't edit site.py, it is part of the std lib. If you do want to > customize it, add a site-customize.py in your site-packages folder and > put your customizations there. > > Kent > There is no site-customize.py in Python25, how does Python know that site-customize.py needs to be loaded on start-up? Or did you mean sitecustomize.py ? Jramak -------------- next part -------------- An HTML attachment was scrubbed... URL: From jramak345 at gmail.com Wed Aug 19 21:59:55 2009 From: jramak345 at gmail.com (Jramak) Date: Wed, 19 Aug 2009 12:59:55 -0700 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908191256n7cf973cx474ad1f727beccbb@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <1c2a2c590908190453o2cb7acbfoec300696b6ce56e4@mail.gmail.com> <6191dd070908191256n7cf973cx474ad1f727beccbb@mail.gmail.com> Message-ID: <6191dd070908191259r53cea372wa51df720efe5483a@mail.gmail.com> > > >> >> Don't edit site.py, it is part of the std lib. If you do want to >> customize it, add a site-customize.py in your site-packages folder and >> put your customizations there. > > > >> There is no site-customize.py in Python25, how does Python know that > site-customize.py needs to be loaded on start-up? Or did you mean > sitecustomize.py ? > > Jramak > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Aug 19 22:17:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 16:17:58 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908191256n7cf973cx474ad1f727beccbb@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <1c2a2c590908190453o2cb7acbfoec300696b6ce56e4@mail.gmail.com> <6191dd070908191256n7cf973cx474ad1f727beccbb@mail.gmail.com> Message-ID: <1c2a2c590908191317l6251641le46e5b8ccb23c3d0@mail.gmail.com> On Wed, Aug 19, 2009 at 3:56 PM, Jramak wrote: >> >> >> Don't edit site.py, it is part of the std lib. If you do want to >> customize it, add a site-customize.py in your site-packages folder and >> put your customizations there. > > There is no site-customize.py in Python25, how does Python know that > site-customize.py needs to be loaded on start-up? Or did you mean > sitecustomize.py ? Yes, sitecustomize.py. Kent From kent37 at tds.net Wed Aug 19 22:35:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 16:35:19 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908191300v7ba97b05p63b3470f0276cbf5@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> <1c2a2c590908190448r18f09959j67c1a6f828fe27bb@mail.gmail.com> <6191dd070908191300v7ba97b05p63b3470f0276cbf5@mail.gmail.com> Message-ID: <1c2a2c590908191335l6b18789q35800c490b3e7831@mail.gmail.com> On Wed, Aug 19, 2009 at 4:00 PM, Jramak wrote: >> One more - put required packages and modules into the same directory >> as the executable, usually the current directory is on the Python >> search path. >> >> Kent > > > Hi Kent, there is no executable. It is just a collection of python scripts. > I assume you refer to the Python search path as PYTHONPATH or sys.path. Do > correct me if I am wrong. Sorry, I mean put the packages in the same directory as the python script that needs them. The search path is sys.path which is affected by PYTHONPATH among other things... Kent From jramak345 at gmail.com Wed Aug 19 22:37:39 2009 From: jramak345 at gmail.com (Jramak) Date: Wed, 19 Aug 2009 13:37:39 -0700 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> Message-ID: <6191dd070908191337p66dd75bal1b94202ce160f9d1@mail.gmail.com> Thanks for all the insight, everyone. I was originally thinking of writing a bash or bat script that would set the PYTHONPATH and other environment variables before running the specific application code. It seemed to be the most simplest solution. There are no other applications that rely on the PYTHONPATH. As Alan said this might result in surprises So a combo solution where in the env vars would be in an .ini file and the path is set in sys.path would be, IMHO a good way to go.. it's simple. I also looked at virtualenv http://pypi.python.org/pypi/virtualenv . Each virtual env takes up 2.3 MB. To me this seems a bit of overkill, but this will enable you to run Python24, Python25, Python26 etc specific code on one computer. Jramak -------------- next part -------------- An HTML attachment was scrubbed... URL: From jramak345 at gmail.com Wed Aug 19 22:41:55 2009 From: jramak345 at gmail.com (Jramak) Date: Wed, 19 Aug 2009 13:41:55 -0700 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <1c2a2c590908191335l6b18789q35800c490b3e7831@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> <1c2a2c590908190448r18f09959j67c1a6f828fe27bb@mail.gmail.com> <6191dd070908191300v7ba97b05p63b3470f0276cbf5@mail.gmail.com> <1c2a2c590908191335l6b18789q35800c490b3e7831@mail.gmail.com> Message-ID: <6191dd070908191341xd7bdd65y3bd9f2493304b599@mail.gmail.com> > > > Sorry, I mean put the packages in the same directory as the python > script that needs them. The search path is sys.path which is affected > by PYTHONPATH among other things... > > > sys.path is affected by PYTHONPATH ? how could it be affected by the PYTHONPATH ? Could you pls enlighten me ? Jramak -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Aug 19 23:17:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 17:17:56 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908191341xd7bdd65y3bd9f2493304b599@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <4C0F03F9-D5BA-4CC6-90FA-A9714CFAC76E@mac.com> <1c2a2c590908190448r18f09959j67c1a6f828fe27bb@mail.gmail.com> <6191dd070908191300v7ba97b05p63b3470f0276cbf5@mail.gmail.com> <1c2a2c590908191335l6b18789q35800c490b3e7831@mail.gmail.com> <6191dd070908191341xd7bdd65y3bd9f2493304b599@mail.gmail.com> Message-ID: <1c2a2c590908191417v4e8d23dfn396ce2cee0c8dfe0@mail.gmail.com> On Wed, Aug 19, 2009 at 4:41 PM, Jramak wrote: >> >> Sorry, I mean put the packages in the same directory as the python >> script that needs them. The search path is sys.path which is affected >> by PYTHONPATH among other things... >> >> > > > sys.path is affected by PYTHONPATH ? how could it be affected by the > PYTHONPATH ? sys.path is the actual, runtime module search path. When Python is started, it initialized sys.path from a variety of sources including predefined locations, the contents of PYTHONPATH, and any .pth files found. http://docs.python.org/tutorial/modules.html#the-module-search-path Kent From kent37 at tds.net Wed Aug 19 23:26:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 17:26:21 -0400 Subject: [Tutor] Setting PYTHONPATH and other env vars dynamically In-Reply-To: <6191dd070908191337p66dd75bal1b94202ce160f9d1@mail.gmail.com> References: <6191dd070908181657g4b06204dg427b48c7d17e1a87@mail.gmail.com> <6191dd070908191337p66dd75bal1b94202ce160f9d1@mail.gmail.com> Message-ID: <1c2a2c590908191426r64dd91bayf61aaa43a651fc20@mail.gmail.com> On Wed, Aug 19, 2009 at 4:37 PM, Jramak wrote: > I > also looked at virtualenv http://pypi.python.org/pypi/virtualenv?. Each > virtual env takes up 2.3 MB. To me this seems a bit of overkill, but this > will enable you to run Python24, Python25, Python26 etc specific code on one > computer. You don't need virtualenv to run different versions of Python on one computer, just specify which interpreter you want to use to run a script. By default virtualenv copies your site-packages directory to each virtual environment, that is probably the bulk of the 2.3 MB. Disable the copy with the --no-site-packages option. Of course you will then have to install any needed modules yourself. http://pypi.python.org/pypi/virtualenv#the-no-site-packages-option Kent From digitalman66 at gmail.com Thu Aug 20 00:13:11 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Wed, 19 Aug 2009 17:13:11 -0500 Subject: [Tutor] Possible bug in django models when assigning model attribute Message-ID: <24a9d1f30908191513i3529a880yad4b8071d2df1143@mail.gmail.com> I ran into something weird in Django and i'm completely stumped. I got it to work but i'm trying to understand the logic behind it. *I have the following data model:* from django.db import models class Setting(models.Model): name = models.CharField(max_length=200) value = models.TextField() class Meta: db_table = "t_settings" def __unicode__(self): return self.name *I have the following form model:* from django import forms class GlobalSettingsForm(forms.Form): # specify all the variables here site_name = forms.CharField(required=True, max_length=200, label="Site Name", help_text="What you want your site to be called company name, personal name, etc." ) site_tagline = forms.CharField(required=False, max_length=200, label="Site Tagline", help_text="A quick tag line on what your site is about") site_url = forms.URLField(required=True, label="Site URL", max_length=200, help_text="All links that reference your site will use this url. I would not change this unless you are super sure." ) >From the shell I have the following code to create the form: form = GlobalSettingsForm(data={'site_name':'test','site_url':' http://localhost/','site_tagline':'test'}) Running a type on form i get: , perfect so far... next I call form.is_valid() to get the cleaned_data attribute and all is good. form.cleaned_data returns {'site_name': u'test', 'site_tagline': u'test', 'site_url': u'http://localhost/'} as expected now i want to change the information in the database so I loop through cleaned_data, grab the object, and save: for item in form.cleaned_data: *setting = Setting.objects.filter(name=item)* setting[0].value = form.cleaned_data[item] setting[0].save() but it *does not work*. setting[0].value = form.cleaned_data[item] fails to assign the data if i run it like this it works: for item in form.cleaned_data: *setting = Setting.objects.get(name__exact=item)* setting.value = form.cleaned_data[item] setting.save() all i did was change the method used from filter to get, why does one work and not the other?? if i create the objects individually and equate them they are the same: setting = Setting.objects.get(name__exact=item) setting2 = Setting.objects.filter(name=item) setting2[0] == setting it equals True type(setting2[0]) == setting it equals True Also I am using, Django 1.1 with MySql Python... Stumped. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dshunick at comcast.net Thu Aug 20 01:14:09 2009 From: dshunick at comcast.net (David Shunick) Date: Wed, 19 Aug 2009 16:14:09 -0700 Subject: [Tutor] Help on input error Message-ID: <413E6724722046D483E660D7C2C12283@ASUS> I'm trying to learn Python, but keep running into the erroor message ImportError: no module named area. I created a file area.py in IDLE. I'm using Python 3.1 and Window XP. After saving the file in c:/Python31/Lib/Python Modules/area.py I can run the program using F5. But when I start a new shell, and enter import area, that's when I get the error message. And it's not just this program.I have the same problem with all that I try to import. I hope someone can help! Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Aug 20 03:02:42 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 19 Aug 2009 20:02:42 -0500 Subject: [Tutor] Help on input error In-Reply-To: <413E6724722046D483E660D7C2C12283@ASUS> References: <413E6724722046D483E660D7C2C12283@ASUS> Message-ID: Can you import other (Standard library) modules? or can you not import anything? On Wed, Aug 19, 2009 at 6:14 PM, David Shunick wrote: > I'm trying to learn Python, but keep running into the erroor message > ImportError: no module named area. > > I created a file area.py in IDLE. I'm using Python 3.1 and Window XP. After > saving the file in c:/Python31/Lib/Python Modules/area.py > > I can run the program using F5. But when I start a new shell, and enter *import > area, *that's when I get the error message. And it's not just this > program.I have the same problem with all that I try to import. > > I hope someone can help! > > Dave > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Aug 20 03:26:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Aug 2009 21:26:19 -0400 Subject: [Tutor] Help on input error In-Reply-To: <413E6724722046D483E660D7C2C12283@ASUS> References: <413E6724722046D483E660D7C2C12283@ASUS> Message-ID: <1c2a2c590908191826v250e7fdbya8507736061f4fd2@mail.gmail.com> On Wed, Aug 19, 2009 at 7:14 PM, David Shunick wrote: > I'm trying to learn Python, but keep running into the erroor message > ImportError: no module named area. > > I created a file area.py in IDLE. I'm using Python 3.1 and Window XP. After > saving the file in c:/Python31/Lib/Python? Modules/area.py > > I can run the program using F5. But when I start a new shell, and enter > import area, that's when I get the error message. And it's not just this > program.I have the same problem with all that I try to import. "Python Modules" is not a folder recognized by Python. Try putting the file in Python31/Lib/site-packages/area.py Kent From rabidpoobear at gmail.com Thu Aug 20 04:28:34 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 19 Aug 2009 21:28:34 -0500 Subject: [Tutor] Help on input error In-Reply-To: <708416299.1598221250734921558.JavaMail.root@sz0110a.emeryville.ca.mail.comcast.net> References: <708416299.1598221250734921558.JavaMail.root@sz0110a.emeryville.ca.mail.comcast.net> Message-ID: Please reply to the whole list, using Reply All, rather than directly to me or anyone else, unless you want the conversation to take place off-list (unless you have a good reason to do so, we discourage this, because then future people cannot benefit from our advice.) Kent has already indicated the issue, you are not putting your modules in the proper location. On Wed, Aug 19, 2009 at 9:22 PM, wrote: > Yes, I can import standard library modules. > > ----- Original Message ----- > From: "Luke Paireepinart" > To: "David Shunick" > Cc: tutor at python.org > Sent: Wednesday, August 19, 2009 6:02:42 PM GMT -08:00 US/Canada Pacific > Subject: Re: [Tutor] Help on input error > > Can you import other (Standard library) modules? or can you not import > anything? > > On Wed, Aug 19, 2009 at 6:14 PM, David Shunick wrote: > >> I'm trying to learn Python, but keep running into the erroor message >> ImportError: no module named area. >> >> I created a file area.py in IDLE. I'm using Python 3.1 and Window XP. >> After saving the file in c:/Python31/Lib/Python Modules/area.py >> >> I can run the program using F5. But when I start a new shell, and enter *import >> area, *that's when I get the error message. And it's not just this >> program.I have the same problem with all that I try to import. >> >> I hope someone can help! >> >> Dave >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From llvirta at gmail.com Thu Aug 20 08:06:23 2009 From: llvirta at gmail.com (Olli Virta) Date: Thu, 20 Aug 2009 09:06:23 +0300 Subject: [Tutor] handling a textfile continued Message-ID: <17042c3d0908192306l1cf39119vb03b6cf6e755e738@mail.gmail.com> Hi! Sorry. OK I admit I might have been confusing. Although I got some good ideas from the messages. Thanks. Let me try again: So I got this big textfile. It's full of data from a database. About 200 or more rows or lines in a textfile. There's three first rows that belong to the same subject. And then next three rows belong to another subject and so on, to the end of the file. What I need to do, is put the three rows that goes together and belong to certain subject, on a one single line in the output textfile. And that goes with the rest of the data to the end of the new file. Thanks. OV -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Aug 20 09:05:10 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Aug 2009 02:05:10 -0500 Subject: [Tutor] handling a textfile continued In-Reply-To: <17042c3d0908192306l1cf39119vb03b6cf6e755e738@mail.gmail.com> References: <17042c3d0908192306l1cf39119vb03b6cf6e755e738@mail.gmail.com> Message-ID: What have you tried so far and why hasn't it worked? We prefer not to just give solutions. On Thu, Aug 20, 2009 at 1:06 AM, Olli Virta wrote: > Hi! > > Sorry. OK I admit I might have been confusing. Although I got some good > ideas from the messages. Thanks. > > Let me try again: > > So I got this big textfile. It's full of data from a database. About 200 or > more rows or lines in a textfile. > There's three first rows that belong to the same subject. And then next > three rows belong to another subject and so on, to the end of the file. > > What I need to do, is put the three rows that goes together and belong to > certain subject, on a one single line in the output textfile. > And that goes with the rest of the data to the end of the new file. > > Thanks. OV > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dgou at mac.com Thu Aug 20 09:19:19 2009 From: dgou at mac.com (Douglas Philips) Date: Thu, 20 Aug 2009 03:19:19 -0400 Subject: [Tutor] handling a textfile continued In-Reply-To: <17042c3d0908192306l1cf39119vb03b6cf6e755e738@mail.gmail.com> References: <17042c3d0908192306l1cf39119vb03b6cf6e755e738@mail.gmail.com> Message-ID: > Hi! Hi! > There's three first rows that belong to the same subject. And then > next three rows belong to another subject and so on, to the end of > the file. Thanks for clarifying, you're input comes in lines, and the lines are grouped in threes. > What I need to do, is put the three rows that goes together and > belong to certain subject, on a one single line in the output > textfile. > And that goes with the rest of the data to the end of the new file. A few suggestions have already been posted under those general assumptions, and you should find at least one of them is practically your solution. One thing that wasn't addressed is what happens if your file isn't an exact multiple of three lines long? What if it is 700 lines, or 802 lines? What kind of error handling/recovery do you need? Assuming perfect input, a not too bad solution would be: parts_so_far = [] for line in open("my-file-name-here", "rU"): # "rU" means open the file to read Universal new-lines. parts_so_far.append(line.rstrip()) if len(parts_so_far) == 3: print "".join(parts_so_far) parts_so_far = [] There are lots of other ways, some better, but this should work (I tested it on some of my own local files). If you need some text separating the lines (a space/tab/comma, whatever), you can put it in the quotes of the "".join line. --Doug From david.jamieson at gmail.com Thu Aug 20 14:30:17 2009 From: david.jamieson at gmail.com (David Jamieson) Date: Thu, 20 Aug 2009 13:30:17 +0100 Subject: [Tutor] help cvs module writerow issue Message-ID: <4f5a5a4b0908200530i1f8fa7f2m921585d96f5a112e@mail.gmail.com> Hi All, I am looking to make an append to csv file function more dynamic by allowing it to receive a variable number of arguments to write out to a single a csv file row. The funtion is an append to file function that writes out test date to a csv file. Reason for trying to make it dynamic is to allow for future expansion of data capture during a test run. I have an issue when trying to format the output to the csv.write(file).writerow() call to accept the variable number of arguments as individual cell values when written to the csv file. I have tried a few ways to escape the variable values but to no avail. When I check the csv file it has the timestamp in one cell on the row and the data in the second cell '1','2','3','4','5' Has this issue to do with the output_str being a str type and the writerow not interpreting it correctly. I added a number 2 to the writerow line to prove that I can write to an individual cell My code is below, sorry if the formatting goes awry. function call ========= append_to_file(output_file_name,'1','2','3','4','5') file == output_file_name = 'C:\\rubbish.csv' function def ======== def append_to_file(append_file_name,*values): ??? #Open the test results file and append test data. ??? output_str =' ' ??? file_out = open(append_file_name,'ab') ??? #Creating a timestamp for the test results ??? time = datetime.datetime.now() ??? time_stamp = time.ctime() ??? #Building a output str to follow the syntax required for writerow 'x','x','x' ??? for x in values: ??????? output_str = output_str+"'"+x+"'"+"," ??? str_length = len(output_str) ??? #removing the last , from the output_str variable ??? output_str = output_str[0:(str_length-1)] ??? print "The final output string is ",output_str ??? print "The output string is of type ",type(output_str) ??? #list(output_str) ??? csv.writer(file_out).writerow([time_stamp, output_str]+['2']) ??? #Close the file ??? file_out.close() -- Cheers David and thanks in advance of any help given. -- Cheers David. From srilyk at gmail.com Thu Aug 20 18:26:31 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 20 Aug 2009 11:26:31 -0500 Subject: [Tutor] Packaging for distribution Message-ID: <333efb450908200926g1cc1009al671a16f60a00d3e8@mail.gmail.com> Hi, I have a program written in python + pygtk and I'm trying to figure out what would be the best way to distribute my program. I've googled all over and I find lots of build scripts, the py2exe utility... It just seems that they're either extremely complicated for what I need (which means I could write my own installer in the time it would take me to learn these), or produce massive files (in the case of py2exe). Does anyone know of any guides/resources, or are these my best bet? Thanks, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Aug 20 22:28:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Aug 2009 16:28:53 -0400 Subject: [Tutor] help cvs module writerow issue In-Reply-To: <4f5a5a4b0908200530i1f8fa7f2m921585d96f5a112e@mail.gmail.com> References: <4f5a5a4b0908200530i1f8fa7f2m921585d96f5a112e@mail.gmail.com> Message-ID: <1c2a2c590908201328t581a1ab2s748ef7bb7b9799cc@mail.gmail.com> On Thu, Aug 20, 2009 at 8:30 AM, David Jamieson wrote: > Hi All, > > I am looking to make an append to csv file function more dynamic by > allowing it to receive a variable number of arguments to write out to > a single a csv file row. The funtion is an append to file function > that writes out test date to a csv file. Reason for trying to make it > dynamic is to allow for future expansion of data capture during a test > run. > I have an issue when trying to format the output to the > csv.write(file).writerow() call to accept the variable number of > arguments as individual cell values when written to the csv file. I > have tried a few ways to escape the variable values but to no avail. > When I check the csv file it has the timestamp in one cell on the row > and the data in the second cell '1','2','3','4','5' Has this issue to > do with the output_str being a str type and the writerow not > interpreting it correctly. I added a number 2 to the writerow line to > prove that I can write to an individual cell You seem to misunderstand writerow(). You don't have to escape the values yourself, the csv module will do that. > function call > ========= > append_to_file(output_file_name,'1','2','3','4','5') > > file > == > output_file_name = 'C:\\rubbish.csv' > > function def > ======== > def append_to_file(append_file_name,*values): > ??? #Open the test results file and append test data. > ??? output_str =' ' > ??? file_out = open(append_file_name,'ab') > ??? #Creating a timestamp for the test results > ??? time = datetime.datetime.now() > ??? time_stamp = time.ctime() > ??? #Building a output str to follow the syntax required for writerow > 'x','x','x' > ??? for x in values: > ??????? output_str = output_str+"'"+x+"'"+"," > ??? str_length = len(output_str) > ??? #removing the last , from the output_str variable > ??? output_str = output_str[0:(str_length-1)] You could write this more simply as output_str = ','.join("'"+x+"'" for x in values) but see below for what you really want. > ??? print "The final output string is ",output_str > ??? print "The output string is of type ",type(output_str) > ??? #list(output_str) > ??? csv.writer(file_out).writerow([time_stamp, output_str]+['2']) Here you are saying that you want to write a row with three elements - the time stamp, the string you constructed in output_str, and the string '2'. That's not really what you want - you want each value in a separate cell. Skip all the output_str stuff and just csv.writer(file_out).wrinerow([time_stamp] + list(values) + ['2']) Kent From kent37 at tds.net Thu Aug 20 22:54:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Aug 2009 16:54:36 -0400 Subject: [Tutor] Possible bug in django models when assigning model attribute In-Reply-To: <24a9d1f30908191513i3529a880yad4b8071d2df1143@mail.gmail.com> References: <24a9d1f30908191513i3529a880yad4b8071d2df1143@mail.gmail.com> Message-ID: <1c2a2c590908201354i38609801jdd9a2b81adf774d2@mail.gmail.com> On Wed, Aug 19, 2009 at 6:13 PM, Glen Zangirolami wrote: > I ran into something weird in Django and i'm completely stumped. I got it to > work but i'm trying to understand the logic behind it. You might have better luck asking this on django-users. Kent From quasipedia at gmail.com Fri Aug 21 00:24:21 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 21 Aug 2009 00:24:21 +0200 Subject: [Tutor] Packaging for distribution In-Reply-To: <333efb450908200926g1cc1009al671a16f60a00d3e8@mail.gmail.com> References: <333efb450908200926g1cc1009al671a16f60a00d3e8@mail.gmail.com> Message-ID: <1250807061.21016.45.camel@jabbar> On Thu, 2009-08-20 at 11:26 -0500, Wayne wrote: > Hi, > > > I have a program written in python + pygtk and I'm trying to figure > out what would be the best way to distribute my program. I've googled > all over and I find lots of build scripts, the py2exe utility... > > > It just seems that they're either extremely complicated for what I > need (which means I could write my own installer in the time it would > take me to learn these), or produce massive files (in the case of > py2exe). > > > Does anyone know of any guides/resources, or are these my best bet? I am a fellow learner here, and will follow this thread with very much interest. Just in case you don't know this already: I am considering bytecode instead of executable with PyInstaller (http://www.pyinstaller.org/). I have not tinkered with it yet, though, so I do not have "first hand impressions" to share. From a review of the features: Main Pro's: - Compact resulting files. - Cross-platform. - Flexible licensing scheme. Main Con: - Support for 2.6 is not yet fully functional. Best luck! Mac. From juhasecke at googlemail.com Fri Aug 21 07:36:38 2009 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Fri, 21 Aug 2009 07:36:38 +0200 Subject: [Tutor] Packaging for distribution In-Reply-To: <333efb450908200926g1cc1009al671a16f60a00d3e8@mail.gmail.com> References: <333efb450908200926g1cc1009al671a16f60a00d3e8@mail.gmail.com> Message-ID: Am 20.08.2009 um 18:26 schrieb Wayne: > > Does anyone know of any guides/resources, or are these my best bet? Have you considered to distribute it as an egg on http://pypi.python.org/pypi I think that the canonical way. juh -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3709 bytes Desc: not available URL: From qbits143 at gmail.com Fri Aug 21 11:45:20 2009 From: qbits143 at gmail.com (Ajith Gopinath) Date: Fri, 21 Aug 2009 15:15:20 +0530 Subject: [Tutor] how do we represent left arrow key in python programming. Message-ID: Hi Folks, how do we represent left arrow key in a python program? Can anybody help? || a j i t || -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Fri Aug 21 11:58:20 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 21 Aug 2009 04:58:20 -0500 Subject: [Tutor] how do we represent left arrow key in python programming. In-Reply-To: References: Message-ID: you're gonna have to be a lot more specific than that if you want a decent answer. On Fri, Aug 21, 2009 at 4:45 AM, Ajith Gopinath wrote: > Hi Folks, > how do we represent left arrow key in a python program? > Can anybody help? > || a j i t || > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From qbits143 at gmail.com Fri Aug 21 12:05:30 2009 From: qbits143 at gmail.com (Ajith Gopinath) Date: Fri, 21 Aug 2009 15:35:30 +0530 Subject: [Tutor] how do we represent left arrow key in python programming. In-Reply-To: References: Message-ID: Hi, I just want to travese a text based menu.My prog. will login to a text based app. and traverse its menu and clicks where i want to be. rit now i find it sifficult to traverse the menu.I am but able to click on the very first item.Will this info help? || a j i t || On Fri, Aug 21, 2009 at 3:28 PM, Luke Paireepinart wrote: > you're gonna have to be a lot more specific than that if you want a decent > answer. > > On Fri, Aug 21, 2009 at 4:45 AM, Ajith Gopinath wrote: > >> Hi Folks, >> how do we represent left arrow key in a python program? >> Can anybody help? >> || a j i t || >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Aug 21 14:11:33 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 21 Aug 2009 08:11:33 -0400 Subject: [Tutor] how do we represent left arrow key in python programming. In-Reply-To: References: Message-ID: <4A8E8EF5.8020807@ieee.org> Ajith Gopinath wrote: > Hi Folks, > how do we represent left arrow key in a python program? > Can anybody help? > || a j i t || > > Be more specific. Are you writing your gui in wxpython, in gtk, in tkinter? Or are you writing a console program? In what Python version? Are you looking to see how an arrow key shows up in a getch() call? In raw_input()? Or in some event in a gui program? Are you running on a single platform (eg. Windows)? Or must the approach work several places? DaveA From dshunick at comcast.net Fri Aug 21 02:11:21 2009 From: dshunick at comcast.net (dshunick at comcast.net) Date: Fri, 21 Aug 2009 00:11:21 +0000 (UTC) Subject: [Tutor] Help on input error In-Reply-To: <1c2a2c590908191826v250e7fdbya8507736061f4fd2@mail.gmail.com> Message-ID: <1334264045.1995251250813481857.JavaMail.root@sz0110a.emeryville.ca.mail.comcast.net> Changing the folder to site-packages did the trick. Thanks David Shunick ----- Original Message ----- From: "Kent Johnson" To: "David Shunick" Cc: tutor at python.org Sent: Wednesday, August 19, 2009 6:26:19 PM GMT -08:00 US/Canada Pacific Subject: Re: [Tutor] Help on input error On Wed, Aug 19, 2009 at 7:14 PM, David Shunick wrote: > I'm trying to learn Python, but keep running into the erroor message > ImportError: no module named area. > > I created a file area.py in IDLE. I'm using Python 3.1 and Window XP. After > saving the file in c:/Python31/Lib/Python Modules/area.py > > I can run the program using F5. But when I start a new shell, and enter > import area, that's when I get the error message. And it's not just this > program.I have the same problem with all that I try to import. "Python Modules" is not a folder recognized by Python. Try putting the file in Python31/Lib/site-packages/area.py Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.jamieson at gmail.com Fri Aug 21 14:53:39 2009 From: david.jamieson at gmail.com (David Jamieson) Date: Fri, 21 Aug 2009 13:53:39 +0100 Subject: [Tutor] help cvs module writerow issue (Now Fixed) Message-ID: <4f5a5a4b0908210553j224b6674g223bf4209a24626@mail.gmail.com> > Hi All, > > I am looking to make an append to csv file function more dynamic by > allowing it to receive a variable number of arguments to write out to > a single a csv file row. The funtion is an append to file function > that writes out test date to a csv file. Reason for trying to make it > dynamic is to allow for future expansion of data capture during a test > run. > I have an issue when trying to format the output to the > csv.write(file).writerow() call to accept the variable number of > arguments as individual cell values when written to the csv file. I > have tried a few ways to escape the variable values but to no avail. > When I check the csv file it has the timestamp in one cell on the row > and the data in the second cell '1','2','3','4','5' Has this issue to > do with the output_str being a str type and the writerow not > interpreting it correctly. I added a number 2 to the writerow line to > prove that I can write to an individual cell >You seem to misunderstand writerow(). You don't have to escape the >values yourself, the csv module will do that. > function call > ========= > append_to_file(output_file_name,'1','2','3','4','5') > > file > == > output_file_name = 'C:\\rubbish.csv' > > function def > ======== > def append_to_file(append_file_name,*values): > #Open the test results file and append test data. > output_str =' ' > file_out = open(append_file_name,'ab') > #Creating a timestamp for the test results > time = datetime.datetime.now() > time_stamp = time.ctime() > #Building a output str to follow the syntax required for writerow > 'x','x','x' > for x in values: > output_str = output_str+"'"+x+"'"+"," > str_length = len(output_str) > #removing the last , from the output_str variable > output_str = output_str[0:(str_length-1)] >You could write this more simply as >output_str = ','.join("'"+x+"'" for x in values) >but see below for what you really want. > print "The final output string is ",output_str > print "The output string is of type ",type(output_str) > #list(output_str) > csv.writer(file_out).writerow([time_stamp, output_str]+['2']) >Here you are saying that you want to write a row with three elements - >the time stamp, the string you constructed in output_str, and the >string '2'. That's not really what you want - you want each value in a >separate cell. Skip all the output_str stuff and just >csv.writer(file_out).wrinerow([time_stamp] + list(values) + ['2']) >Kent Hi Kent, thank you for your help in sorting out my writerow issue and for the better way to join strings. I have the code applied to my project. Cheers David. From alan.gauld at btinternet.com Fri Aug 21 18:44:12 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Aug 2009 17:44:12 +0100 Subject: [Tutor] Help on input error References: <1c2a2c590908191826v250e7fdbya8507736061f4fd2@mail.gmail.com> <1334264045.1995251250813481857.JavaMail.root@sz0110a.emeryville.ca.mail.comcast.net> Message-ID: wrote > "Python Modules" is not a folder recognized by Python. Try putting the > file in Python31/Lib/site-packages/area.py Although that solved your problem I tend to use sire-packages for third party modules I've downloaded - and can download again. For my own code I keep a separate Projects area outside my python installation and reference it via PYTHONPATH., That means if I delete a Python installation, including site-packages-oops! - or install a second one I can still access my modules or share thjem across both without copying. Just a thought, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 21 18:48:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Aug 2009 17:48:32 +0100 Subject: [Tutor] how do we represent left arrow key in python programming. References: Message-ID: "Ajith Gopinath" wrote > how do we represent left arrow key in a python program? > Can anybody help? That depends entirely on your terminal/environment. If you are using a Unix terminal it will be diffeent to using a Mac or a PC. You can write a program to display the key code of any key using curses on *nix or msvcrt on Windows. Here is an example from my web tutor under the Event Driven Programming topic... import msvcrt def doKeyEvent(key): if key == '\x00' or key == '\xe0': # non ASCII key = msvcrt.getch() # fetch second character print ord(key), def doQuitEvent(key): raise SystemExit # First, clear the screen of clutter then warn the user # of what to do to quit lines = 25 # set to number of lines in console for line in range(lines): print print "Hit space to end..." print # Now mainloop runs "forever" while True: ky = msvcrt.getch() length = len(ky) if length != 0: # send events to event handling functions if ky == " ": # check for quit event doQuitEvent(ky) else: doKeyEvent(ky) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Fri Aug 21 19:53:37 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 21 Aug 2009 13:53:37 -0400 Subject: [Tutor] get name of calling class at runtime Message-ID: Hi everyone, I'm trying to create a data-retriever class that executes certain SQL statements based on the name of a calling class (I'm doing this so I can group a bunch of SQL statements in one place; they're currently scattered all over the program and it's getting unwieldy). Currently, I'm forced to pass in the name of the "caller" from the calling class: class DataSources(object): def getdata(self, caller): if caller == 'CallerA': # execute sql for callerA elif caller == 'CallerB': #execute sql for callerB class CallerA(object): def getdata(self): caller = self.__class__.__name__ dao = DataSources() dao.getdata(caller) class CallerB(object): def getdata(self): caller = self.__class__.__name__ dao = DataSources() dao.getdata(caller) So I'm wondering, is there any way to have the DataSources class access the name of the calling class at runtime, and avoid having to pass in the "caller" variable? Perhaps there's some other standard approach to this kind of problem? From kent37 at tds.net Fri Aug 21 20:40:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Aug 2009 14:40:25 -0400 Subject: [Tutor] get name of calling class at runtime In-Reply-To: References: Message-ID: <1c2a2c590908211140yd21bbf1gd797cf6e907f97c3@mail.gmail.com> On Fri, Aug 21, 2009 at 1:53 PM, Serdar Tumgoren wrote: > Hi everyone, > I'm trying to create a data-retriever class that executes certain SQL > statements based on the name of a calling class (I'm doing this so I > can group a bunch of SQL statements in one place; they're currently > scattered all over the program and it's getting unwieldy). > > Currently, I'm forced to pass in the name of the "caller" from the > calling class: > > class DataSources(object): > ? ?def getdata(self, caller): > ? ? ? ?if caller == 'CallerA': > ? ? ? ? ?# execute sql for callerA > ? ? ? ?elif caller == 'CallerB': > ? ? ? ? ?#execute sql for callerB > > class CallerA(object): > ? ?def getdata(self): > ? ? ? ?caller = self.__class__.__name__ > ? ? ? ?dao = DataSources() > ? ? ? ?dao.getdata(caller) > > class CallerB(object): > ? ?def getdata(self): > ? ? ? ?caller = self.__class__.__name__ > ? ? ? ?dao = DataSources() > ? ? ? ?dao.getdata(caller) > > So I'm wondering, is there any way to have the DataSources class > access the name of the calling class at runtime, and avoid having to > pass in the "caller" variable? Perhaps there's some other standard > approach to this kind of problem? You could simplify the code above by passing self to DataSources(). Or make CallerX inherit from DataSources and use the class attribute trick we talked about before. Or perhaps you should look into SQLObject or SQLAlchemy? Kent From eike.welk at gmx.net Fri Aug 21 20:57:17 2009 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 21 Aug 2009 20:57:17 +0200 Subject: [Tutor] how do we represent left arrow key in python programming. In-Reply-To: References: Message-ID: <200908212057.17787.eike.welk@gmx.net> On Friday 21 August 2009, Ajith Gopinath wrote: > Hi, > I just want to travese a text based menu.My prog. will login to a > text based app. and traverse its menu and clicks where i want to > be. rit now i find it sifficult to traverse the menu.I am but able > to click on the very first item.Will this info help? You should look at the curses library for complex, but text based interfaces. I don't know if it exists on Windows though: http://docs.python.org/library/curses.html HTH, Eike. From zstumgoren at gmail.com Fri Aug 21 21:52:29 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 21 Aug 2009 15:52:29 -0400 Subject: [Tutor] get name of calling class at runtime In-Reply-To: <1c2a2c590908211140yd21bbf1gd797cf6e907f97c3@mail.gmail.com> References: <1c2a2c590908211140yd21bbf1gd797cf6e907f97c3@mail.gmail.com> Message-ID: > You could simplify the code above by passing self to DataSources(). Or > make CallerX inherit from DataSources and use the class attribute > trick we talked about before. Or perhaps you should look into > SQLObject or SQLAlchemy? > The class attribute trick worked nicely. I'll think about how to apply that here. Meantime, how do I pass "self" to DataSources? Do I literally just pass in the word "self" from inside the calling object? Apologies for the confusion -- I've never used that technique before and it's bending my brain a little:) From alan.gauld at btinternet.com Sat Aug 22 00:58:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Aug 2009 23:58:08 +0100 Subject: [Tutor] get name of calling class at runtime References: Message-ID: "Serdar Tumgoren" wrote > I'm trying to create a data-retriever class that executes certain SQL > statements based on the name of a calling class This is a really bad "smell" from an OO design point of view. > can group a bunch of SQL statements in one place; they're currently > scattered all over the program and it's getting unwieldy). Normally in an OO program the SQL for each class is in the methods for that class. That way any changes to the class canbe easily reflected in the related SQL. > class DataSources(object): > def getdata(self, caller): > if caller == 'CallerA': > # execute sql for callerA > elif caller == 'CallerB': > #execute sql for callerB This is exactly the kind of code that OO and polymorphism tries to avoid. It is one of the most error prone and non performant code patterns you can write. Why not put the SQL for classA in classA? > class CallerA(object): > def getdata(self): > caller = self.__class__.__name__ > dao = DataSources() > dao.getdata(caller) Just put the SQL for A here. Then if you add new classes you don't need to go and change your DataSources class as well. Thats what polymorphism is for. > So I'm wondering, is there any way to have the DataSources class > access the name of the calling class at runtime, and avoid having to > pass in the "caller" variable? Perhaps there's some other standard > approach to this kind of problem? There are ways of doing what you want, but the "standard" way is to keep the code for class A in class A. Thats why its called Object Oriented programming. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Aug 22 01:02:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Aug 2009 00:02:13 +0100 Subject: [Tutor] get name of calling class at runtime References: <1c2a2c590908211140yd21bbf1gd797cf6e907f97c3@mail.gmail.com> Message-ID: "Serdar Tumgoren" wrote > Meantime, how do I pass "self" to DataSources? > > Do I literally just pass in the word "self" from inside the calling > object? Apologies for the confusion -- I've never used that technique > before and it's bending my brain a little:) self is just a reference to the current object. Thus when you write: class C: def f(self): pass and call it with c = C() c.f() you are effectively calling C.f(c) ie self takers on the value of the current instance. Thus inside f() if you hasd a line DataSources.getData(self) you would pass the instance of C to DataSources. (and you can use isInstance() to check its type). But unless you have a really good reason its still better to get the class to do its own SQL. IMHO. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From questions.anon at gmail.com Sat Aug 22 02:34:39 2009 From: questions.anon at gmail.com (questions anon) Date: Fri, 21 Aug 2009 17:34:39 -0700 Subject: [Tutor] simple plots Message-ID: I would like to make some simple plots using matplotlib (or any python plotting modules) and I can find lots of examples that generate random data and then plot those, but I cannot find any that read in data from excel or a text file, manipulate the data and then plot the data. Does anyone have any examples for this or webpages I could go to? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Aug 22 03:25:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Aug 2009 21:25:21 -0400 Subject: [Tutor] get name of calling class at runtime In-Reply-To: References: Message-ID: <1c2a2c590908211825w6e2c5e19pc8a77b921a0ddad3@mail.gmail.com> On Fri, Aug 21, 2009 at 6:58 PM, Alan Gauld wrote: > "Serdar Tumgoren" wrote > >> I'm trying to create a data-retriever class that executes certain SQL >> statements based on the name of a calling class > > This is a really bad "smell" from an OO design point of view. > >> can group a bunch of SQL statements in one place; they're currently >> scattered all over the program and it's getting unwieldy). > > Normally in an OO program the SQL for each class is in the methods for that > class. That way any changes to the class canbe easily reflected in the > related SQL. But if all the classes need nearly the same SQL, it may make sense to abstract that out to a common location.That is what Serdar is trying to do. Duplication is also a bad smell. Kent From kent37 at tds.net Sat Aug 22 03:27:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Aug 2009 21:27:41 -0400 Subject: [Tutor] simple plots In-Reply-To: References: Message-ID: <1c2a2c590908211827s48a9b263re222ed36ccc81bad@mail.gmail.com> On Fri, Aug 21, 2009 at 8:34 PM, questions anon wrote: > I would like to make some simple plots using matplotlib (or any python > plotting modules) and I can find lots of examples that generate random data > and then plot those, but I cannot find any that read in data from excel or a > text file, manipulate the data and then plot the data. Does anyone have any > examples for this or webpages I could go to? What form is the data? You can use the csv module to read comma- or tab-separated values. You can use the third-party xlrd module or COM to read Excel files. What kind of data manipulation do you need? Python has many built-in facilities for that. Kent From pine508 at hotmail.com Sat Aug 22 04:00:14 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 21 Aug 2009 22:00:14 -0400 Subject: [Tutor] simple plots In-Reply-To: References: Message-ID: > I would like to make some simple plots using matplotlib (or any python plotting > modules) and I can find lots of examples that generate random data and then > plot those, but I cannot find any that read in data from excel or a text file, > manipulate the data and then plot the data. Does anyone have any examples > for this or webpages I could go to? Keep in mind, too, that in terms of matplotlib, for simple plots all you need to feed the plot() function is a list of x points and a list of y points. Sometimes the demos on their web page might seem to obscure this for beginners because of the fancy math functions that make pretty plots, but that's all you need: two lists. Getting those two lists of points is what you are really concerned about, as Kent indicated, and so this is not really a matplotlib concern. And as he said, Python has lots of good support for that. Che _________________________________________________________________ Hotmail? is up to 70% faster. Now good news travels really fast. http://windowslive.com/online/hotmail?ocid=PID23391::T:WLMTAGL:ON:WL:en-US:WM_HYGN_faster:082009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 22 09:54:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Aug 2009 08:54:22 +0100 Subject: [Tutor] get name of calling class at runtime References: <1c2a2c590908211825w6e2c5e19pc8a77b921a0ddad3@mail.gmail.com> Message-ID: "Kent Johnson" wrote >>> can group a bunch of SQL statements in one place; they're currently >>> scattered all over the program and it's getting unwieldy). >> >> Normally in an OO program the SQL for each class is in the methods for >> that >> class. That way any changes to the class canbe easily reflected in the >> related SQL. > > But if all the classes need nearly the same SQL, it may make sense to > abstract that out to a common location.That is what Serdar is trying > to do. Duplication is also a bad smell. Thats not what he said, he says he wants to collect SQL thats scattered into one location. And his pseudo code has the classic procedural case statement to select the right SQL depending on class. He is not calling a single parameterised piece of SQL... Thats the bad smell. If the SQL is common then the OO way to handle that would be to write a mixin class called, say, Storable that accessed the real instance attributes(like tablename). That could then be inherited by all Storable objects. That way you get the common code and avoid the case statement based on type. PS. I know Kent knows about mixins, the explanation was for anyone else who is intrested :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Aug 22 09:59:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Aug 2009 08:59:42 +0100 Subject: [Tutor] simple plots References: Message-ID: "questions anon" wrote >I would like to make some simple plots using matplotlib (or any python > plotting modules) and I can find lots of examples that generate random > data > and then plot those, but I cannot find any that read in data from excel > or a > text file, manipulate the data and then plot the data. Is your question about how to use matplotlib or how to acquire data. matplotlib doesn't care where the data comes from, the examples only use random data because its easy to produce. But the data can come from anywhere, that's a completely separate process to plotting it. So do you know how to get the data and maniplulate it? Is that really what you are asking? If so we need to know a bit more about what kind of data)its format) and what kind of manipulation you want to do - is it statistical, scientific calculation, parsing etc? There will almost certainly be some modules that can help but we can't tell which yet. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sat Aug 22 15:22:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Aug 2009 09:22:01 -0400 Subject: [Tutor] get name of calling class at runtime In-Reply-To: References: <1c2a2c590908211825w6e2c5e19pc8a77b921a0ddad3@mail.gmail.com> Message-ID: <1c2a2c590908220622p7424717ds8c3313495524ccee@mail.gmail.com> On Sat, Aug 22, 2009 at 3:54 AM, Alan Gauld wrote: > "Kent Johnson" wrote > >>>> can group a bunch of SQL statements in one place; they're currently >>>> scattered all over the program and it's getting unwieldy). >>> >>> Normally in an OO program the SQL for each class is in the methods for >>> that >>> class. That way any changes to the class canbe easily reflected in the >>> related SQL. >> >> But if all the classes need nearly the same SQL, it may make sense to >> abstract that out to a common location.That is what Serdar is trying >> to do. Duplication is also a bad smell. > > Thats not what he said, he says he wants to collect SQL thats scattered > into one location. And his pseudo code has the classic procedural > case statement to select the right SQL depending on class. He is not > calling a single parameterised piece of SQL... Thats the bad smell. Ah, right. I was reading more into the OP than was there. I think it does makes sense to keep SQL confined to well-defined locations. This can be per class - each class holds its own SQL - or a single class that does all database access so all SQL and database dependencies are in one place. But in this case if different clients needed different functionality I would make different methods for them. Rather than class DataSources(object): def getdata(self, caller): if caller == 'CallerA': # execute sql for callerA elif caller == 'CallerB': #execute sql for callerB it is reasonable to have class DataSources(object): def getAdata(self): # execute sql for callerA def getBdata(self): #execute sql for callerB etc. Kent From alan.gauld at btinternet.com Sat Aug 22 23:45:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Aug 2009 22:45:40 +0100 Subject: [Tutor] get name of calling class at runtime References: <1c2a2c590908211825w6e2c5e19pc8a77b921a0ddad3@mail.gmail.com> <1c2a2c590908220622p7424717ds8c3313495524ccee@mail.gmail.com> Message-ID: "Kent Johnson" wrote > I think it does makes sense to keep SQL confined to well-defined > locations. This can be per class - each class holds its own SQL - or a > single class that does all database access so all SQL and database > dependencies are in one place. My vote for the class every time. I hate having to make changes in two places when I add an attribute etc. Especially if they are in two separate files or the classes are beiong used in multiple projects. All that regression testing becomes a headache. > class DataSources(object): > def getAdata(self): > # execute sql for callerA > def getBdata(self): > #execute sql for callerB You might as well just put them as functions in a module, but you still have the double file maintenance issue. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Sun Aug 23 19:49:45 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Sun, 23 Aug 2009 13:49:45 -0400 Subject: [Tutor] get name of calling class at runtime In-Reply-To: References: <1c2a2c590908211825w6e2c5e19pc8a77b921a0ddad3@mail.gmail.com> <1c2a2c590908220622p7424717ds8c3313495524ccee@mail.gmail.com> Message-ID: >> I think it does makes sense to keep SQL confined to well-defined >> locations. This can be per class - each class holds its own SQL - or a >> single class that does all database access so all SQL and database >> dependencies are in one place. The above is precisely what I'm after, and I agree that the approach I initially proposed (type-checking the calling class) does have that bad code smell. I wasn't aware of Mixins -- (well, I'd heard of them but never really applied the technique). I'll look into that as a possible solution for logging and other functionality that cuts across numerous objects (or would decorators be a better approach?). But meantime, I think inheritance might once again solve my problem: > >> class DataSources(object): >> ?def getAdata(self): >> ? ? ? ?# execute sql for callerA >> ?def getBdata(self): >> ? ? ? ?#execute sql for callerB If I define a root DataSource class as above, and then have all my committee objects inherit from that, I should have a clean(er), unified access to my data sources. My only question with that approach -- is it generally bad policy to let objects inherit behavior that they don't need. For instance, say that I have a parent DataSources class and then I have subclasses called PresidentCommittee, HouseCommittee, LeadershipPAC. Now all of these child objects will inherit not only their own data-retrieval methods, but also the universe of DataSource methods used by their siblings. Is that generally something to avoid, or is it an insignificant issue in light of the benefits of inheritance? From kreglet at gmail.com Mon Aug 24 00:06:30 2009 From: kreglet at gmail.com (kreglet) Date: Sun, 23 Aug 2009 15:06:30 -0700 (PDT) Subject: [Tutor] Algorithm Message-ID: <25107922.post@talk.nabble.com> Hello, The problem that I am having is writing an algorithm for finding all the possible words from a given word. For example: python from "python" you can make the words pot, top, hop, not etc. There are few examples for making anagrams for a word, but only the whole word. I have tried unsuccessfully to modify some of these to suit my purpose. Also on the web there are numerous sites where you can type in a word and it will give you a list of all the words that could be made from it. How would I go about this in python? thanx, kreglet -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25107922.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Mon Aug 24 03:05:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Aug 2009 02:05:11 +0100 Subject: [Tutor] Algorithm References: <25107922.post@talk.nabble.com> Message-ID: "kreglet" wrote > The problem that I am having is writing an algorithm for finding all the > possible words from a given word. For example: python This sounds a lot like a homework. We don't give direct help on homeworks but will try to point you in the right direction. It helps if you tell/show us what you've tried and where you are stuck. How do you think it should work? Can you think of a systematic approach using pen and paper? Can you program that? Does it work? What is wrong? Hint: start with a small word that you can check for correctness. Also test for things like double letters, eg see. - is ese the same as ese? (the e's are swapped, honest!...) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kreglet at gmail.com Mon Aug 24 05:01:34 2009 From: kreglet at gmail.com (kreglet) Date: Sun, 23 Aug 2009 20:01:34 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: References: <25107922.post@talk.nabble.com> Message-ID: <25109886.post@talk.nabble.com> Alan, Thanks for the reply. This is not homework, it is a hobby. I am 44 years old. I was using Visual Basic, but recently decided to switch to Linux and have no intentions of going back to windows. Python seems like a good computer language. I read somewhere the the best way to learn it was to pick a project and start programming. Since one of my other hobbies is word games and Linux is severely lacking in this area I decided to write a game similar to Text Twist in windows for my first project. The game I am writing has a graphical front end using GTK and the code so far is long and in more than one file (to keep the gui code seperate). I will gladly email you the whole thing to you if you like. In my research, I looked at examples of permutations, lists, sets, and most recently dictionaries which I have the feeling is the solution. Permutation looked good, but I am an amateur programer and couldn't quite grasp the concepts from the examples I found. Dictionaries hold promise as it can be used to get a count of the letters in words. from operator import itemgetter def countletters(word): lettercount = {} for letter in word: lettercount[letter] =lettercount.get(letter,0) + 1 print sorted(lettercount.iteritems(), key=itemgetter(1)) countletters("batty") [('a', 1), ('y', 1), ('b', 1), ('t', 2)] countletters("bat") [('a', 1), ('b', 1), ('t', 1)] countletters("bats") [('a', 1), ('b', 1), ('s', 1), ('t', 1)] bat is in batty. bats is not. I have a list of words in wordlist.txt. I can write a loop the do the letter counts for each word, but I can't figure out how to compare them. thanx, kreglet Alan Gauld wrote: > > > "kreglet" wrote > >> The problem that I am having is writing an algorithm for finding all the >> possible words from a given word. For example: python > > This sounds a lot like a homework. > We don't give direct help on homeworks but will try to point you > in the right direction. It helps if you tell/show us what you've tried > and where you are stuck. > > How do you think it should work? > Can you think of a systematic approach using pen and paper? > Can you program that? > Does it work? What is wrong? > > Hint: start with a small word that you can check for correctness. > Also test for things like double letters, > eg see. - is ese the same as ese? (the e's are swapped, honest!...) > > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25109886.html Sent from the Python - tutor mailing list archive at Nabble.com. From srilyk at gmail.com Mon Aug 24 13:19:35 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 24 Aug 2009 06:19:35 -0500 Subject: [Tutor] Algorithm In-Reply-To: <25109886.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> Message-ID: <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> On Sun, Aug 23, 2009 at 10:01 PM, kreglet wrote: > > Alan, > > Thanks for the reply. This is not homework, it is a hobby. I am 44 years > old. I was using Visual Basic, but recently decided to switch to Linux and > have no intentions of going back to windows. Python seems like a good > computer language. I read somewhere the the best way to learn it was to > pick > a project and start programming. Since one of my other hobbies is word > games > and Linux is severely lacking in this area I decided to write a game > similar > to Text Twist in windows for my first project. > > The game I am writing has a graphical front end using GTK and the code so > far is long and in more than one file (to keep the gui code seperate). I > will gladly email you the whole thing to you if you like. > > In my research, I looked at examples of permutations, lists, sets, and > most recently dictionaries which I have the feeling is the solution. > Permutation looked good, but I am an amateur programer and couldn't quite > grasp the concepts from the examples I found. Dictionaries hold promise as > it can be used to get a count of the letters in words. > > from operator import itemgetter > > def countletters(word): > lettercount = {} > for letter in word: > lettercount[letter] =lettercount.get(letter,0) + 1 > print sorted(lettercount.iteritems(), key=itemgetter(1)) > > > countletters("batty") > [('a', 1), ('y', 1), ('b', 1), ('t', 2)] > > countletters("bat") > [('a', 1), ('b', 1), ('t', 1)] > > countletters("bats") > [('a', 1), ('b', 1), ('s', 1), ('t', 1)] > > bat is in batty. bats is not. > > I have a list of words in wordlist.txt. I can write a loop the do the > letter > counts for each word, but I can't figure out how to compare them. I would actually not bother sorting your return from countletters - keep it a dictionary. Then you can compare like this: mainword = countletters('batty') cmpword = countletters('bat') def myfunc(cmpword, mainword): for letter in cmpword: if mainword.gets(letter): if cmpword[letter] >mainword[letter]: return False else: return False I think that should work. First you're looping over each letter in cmpword. Because mainword is also a dictionary the order isn't terribly important. Then you check if the letter is in mainword. If it's not, obviously cmpword isn't in mainword, so return False. If the letter is, compare the counts. If cmpword has more letters than mainword, it's not in the word so again return False. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Mon Aug 24 15:01:15 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Mon, 24 Aug 2009 15:01:15 +0200 Subject: [Tutor] Algorithm In-Reply-To: <25107922.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> Message-ID: <1251118875.25986.8.camel@jabbar> On Sun, 2009-08-23 at 15:06 -0700, kreglet wrote: > Hello, > > The problem that I am having is writing an algorithm for finding all the > possible words from a given word. For example: python > > from "python" you can make the words pot, top, hop, not etc. There are few > examples for making anagrams for a word, but only the whole word. I have > tried unsuccessfully to modify some of these to suit my purpose. Also on the > web there are numerous sites where you can type in a word and it will give > you a list of all the words that could be made from it. How would I go about > this in python? > > thanx, > kreglet Of course doing things by yourself is more exciting and fun (and above all you have the pleasure to learn something new), but if you finally should decide to invoke an external utility (e.g.: for performance issues), then you might be interested in using "an": it's very fast and in the repositories of most linux distro. It has plenty of options. Example usage: an -m4 -w python [search only for single words in the dictionary with a minimum length of 4 letters] returns: hypo phony pony python tony typo Good luck with your project, Mac. From Rajasekhar.ReddyEtikela at qwest.com Mon Aug 24 13:28:46 2009 From: Rajasekhar.ReddyEtikela at qwest.com (Reddy Etikela, Rajasekhar) Date: Mon, 24 Aug 2009 05:28:46 -0600 Subject: [Tutor] Ptyhon GUI doubt Message-ID: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> Hi, I am new to the Python. I have installed Python 2.6.2 version in windows XP. When I try to open the IDLE(Python GUI), getting the below message. Any configuration settings required for this? [cid:675172311 at 24082009-0830] Please let me know the details. Thanks, Raj -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: attf6d24.jpg Type: image/jpeg Size: 12669 bytes Desc: attf6d24.jpg URL: From kreglet at gmail.com Mon Aug 24 17:48:23 2009 From: kreglet at gmail.com (kreglet) Date: Mon, 24 Aug 2009 08:48:23 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> Message-ID: <25118434.post@talk.nabble.com> Wayne, The reason I used print sorted is that using just print throws a syntax error: print (lettercount.iteritems(), key=itemgetter(1)) ---> error print lettercount.iteritems(), key=itemgetter(1) ---> error print sorted(lettercount.iteritems(), key=itemgetter(1)) ---> works I don't know why. Seems to me that any of the above should work. mainword = countletters('batty') cmpword = countletters('bat') myfunc(cmpword, mainword) Generates error: Traceback (most recent call last): File "/home/kreglet/bin/test.py", line 23, in myfunc(cmpword, mainword) File "/home/kreglet/bin/test.py", line 13, in myfunc for letter in cmpword: TypeError: 'NoneType' object is not iterable mainword = countletters('batty') print mainword returns None cmpword = countletters('bat') print cmpword returns None Both mainword and cmpword are passed to the function but since the values of each are None the function doesn't work. Is this correct? thanx, kreglet Wayne-68 wrote: > > On Sun, Aug 23, 2009 at 10:01 PM, kreglet wrote: > > I would actually not bother sorting your return from countletters - keep > it > a dictionary. > > Then you can compare like this: > > mainword = countletters('batty') > cmpword = countletters('bat') > > def myfunc(cmpword, mainword): > for letter in cmpword: > if mainword.gets(letter): > if cmpword[letter] >mainword[letter]: > return False > else: > return False > > I think that should work. First you're looping over each letter in > cmpword. > Because mainword is also a dictionary the order isn't terribly important. > Then you check if the letter is in mainword. If it's not, obviously > cmpword > isn't in mainword, so return False. If the letter is, compare the counts. > If > cmpword has more letters than mainword, it's not in the word so again > return > False. > > HTH, > Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25118434.html Sent from the Python - tutor mailing list archive at Nabble.com. From kreglet at gmail.com Mon Aug 24 18:30:30 2009 From: kreglet at gmail.com (kreglet) Date: Mon, 24 Aug 2009 09:30:30 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: <1251118875.25986.8.camel@jabbar> References: <25107922.post@talk.nabble.com> <1251118875.25986.8.camel@jabbar> Message-ID: <25119206.post@talk.nabble.com> Hello Mac, Thanks for the tip. I was aware of an and considered using it. I decided not to use it unless I have no other choice. Although it does exactly what I am after: a) I don't want to use any dependencies other than Python's built in modules b) You hit it right in the nose when you said: "doing things by yourself is more exciting and fun (and above all you have the pleasure to learn something new)" If I did use it I will have learned nothing. The whole purpose of starting this project was so I could learn python. I do so very much enjoy learning new things. The rest of the game is going well. So for I've figured out how to: 1. Create the gui 2. Pick a word from a list 3. Scramble the letters 4. Display them in a drawing area 5. Allow user to click the letters to make a word 6. Check the guessed word against a list of words 7. If matched guessed word is added to a treeview (list box) I am confidant that i can create functions for: 1. Scoring points 2. Advancing to next round 3. Saving the game 4. Polish the gui, etc The only thing I am having problems with (so far) is this algorithm which would let the player know how many words are left to guess. When I am finished this project, I plan to post it somewhere so that others can learn from it too. Peace, kreglet Mac Ryan wrote: > > > Of course doing things by yourself is more exciting and fun (and above > all you have the pleasure to learn something new), but if you finally > should decide to invoke an external utility (e.g.: for performance > issues), then you might be interested in using "an": it's very fast and > in the repositories of most linux distro. It has plenty of options. > Example usage: > > an -m4 -w python [search only for single words in the dictionary with a > minimum length of 4 letters] returns: > hypo > phony > pony > python > tony > typo > > Good luck with your project, > Mac. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25119206.html Sent from the Python - tutor mailing list archive at Nabble.com. From srilyk at gmail.com Mon Aug 24 19:32:56 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 24 Aug 2009 12:32:56 -0500 Subject: [Tutor] Algorithm In-Reply-To: <25118434.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> Message-ID: <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> On Mon, Aug 24, 2009 at 10:48 AM, kreglet wrote: > > Wayne, > > The reason I used print sorted is that using just print throws a syntax > error: > > print (lettercount.iteritems(), key=itemgetter(1)) ---> error > print lettercount.iteritems(), key=itemgetter(1) ---> error > print sorted(lettercount.iteritems(), key=itemgetter(1)) ---> works Ah, excuse me - I just glanced at your function and didn't notice you weren't returning any value. You should be returning lettercount from your function. > > > I don't know why. Seems to me that any of the above should work. > > mainword = countletters('batty') > cmpword = countletters('bat') > > myfunc(cmpword, mainword) > > Generates error: > > Traceback (most recent call last): > File "/home/kreglet/bin/test.py", line 23, in > myfunc(cmpword, mainword) > File "/home/kreglet/bin/test.py", line 13, in myfunc > for letter in cmpword: > TypeError: 'NoneType' object is not iterable > > mainword = countletters('batty') > print mainword returns None > > cmpword = countletters('bat') > print cmpword returns None > > Both mainword and cmpword are passed to the function but since the values > of > each are None > the function doesn't work. > > Is this correct? > That's correct - your function countletters returns None, so you're assigning cmpword to None. And since None is not an iterable type, it throws an error. Try returning a value like I mentioned above and see how that works. HTH, Wayne > > thanx, > kreglet > > > Wayne-68 wrote: > > > > On Sun, Aug 23, 2009 at 10:01 PM, kreglet wrote: > > > > I would actually not bother sorting your return from countletters - keep > > it > > a dictionary. > > > > Then you can compare like this: > > > > mainword = countletters('batty') > > cmpword = countletters('bat') > > > > def myfunc(cmpword, mainword): > > for letter in cmpword: > > if mainword.gets(letter): > > if cmpword[letter] >mainword[letter]: > > return False > > else: > > return False > > > > I think that should work. First you're looping over each letter in > > cmpword. > > Because mainword is also a dictionary the order isn't terribly important. > > Then you check if the letter is in mainword. If it's not, obviously > > cmpword > > isn't in mainword, so return False. If the letter is, compare the counts. > > If > > cmpword has more letters than mainword, it's not in the word so again > > return > > False. > > > > HTH, > > Wayne > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > View this message in context: > http://www.nabble.com/Algorithm-tp25107922p25118434.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Aug 24 20:03:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Aug 2009 19:03:35 +0100 Subject: [Tutor] Algorithm References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com><333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> Message-ID: "kreglet" wrote > The reason I used print sorted is that using just print throws a syntax > error: > > print (lettercount.iteritems(), key=itemgetter(1)) ---> error > print lettercount.iteritems(), key=itemgetter(1) ---> error > print sorted(lettercount.iteritems(), key=itemgetter(1)) ---> works > > I don't know why. Seems to me that any of the above should work. Nope, print takes a string (or something that can be converted to a string) as its argument. It does not know what key=itemgetter(1) means. That only makes sense to a sort function. You would need print lettercount.iteritems() Although I'm not sure that would actually print what you expect! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan at lsd.co.za Mon Aug 24 23:14:16 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Mon, 24 Aug 2009 23:14:16 +0200 Subject: [Tutor] Template long text substitution Message-ID: <5cb309e70908241414h4ab61f29kf911e09f1ae27d6c@mail.gmail.com> Hi Guys, I am trying to do the following, and im not sure how to deal with a blob of text. I have the following file i am using as a template %%NAME%% %%NUMBER%% %%REPORT%% and i have a corresponding file with values name="bob" number="123" report="report is long and spans multiple lines. It also is already in the exact format i want to replace the above template var %%REPORT%% with" The report part is obviously the problem. My code so far reads line by line and splits on the = and reads the values into a dict. file = open('test','r') data = {} for line in file: line = line.strip() line = line.split('=') data[line[0]] = line[1] My intention is then to replace the %%NAME%% with data['name'] etc. If it makes a difference, the report= will be generated by another program and given to me in the exact format i need to substitute it into %%REPORT%%. (or i can put it in that file). I hope this makes sense, thanks in advance - i really do appreciate it :) Stefan -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Aug 25 00:04:13 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 24 Aug 2009 18:04:13 -0400 Subject: [Tutor] Template long text substitution In-Reply-To: <5cb309e70908241414h4ab61f29kf911e09f1ae27d6c@mail.gmail.com> References: <5cb309e70908241414h4ab61f29kf911e09f1ae27d6c@mail.gmail.com> Message-ID: Stefan, Have you considered a templating engine such as Jinja or Cheetah? http://jinja.pocoo.org/2/ www.cheetahtemplate.org/ They should be able to handle a lot of the parsing and pairing of variables in a template that you're attempting. Basically, you use template syntax (as you seem to have created on your own), and then simply fill in those variables by passing in a "context", or dictionary of objects. The great thing about these templating engines is that they come pre-packaged with standard looping constructs, so you don't have to reinvent that wheel. I've been tinkering with Jinja and can't say enough about it. HTH, Serdar From quasipedia at gmail.com Tue Aug 25 00:14:06 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 25 Aug 2009 00:14:06 +0200 Subject: [Tutor] Pexpect latest version. Message-ID: <1251152046.10231.9.camel@jabbar> Hello everybody, this is more a request of info than of help. I want to play around with pexpect a bit, but I am confused on what is the latest stable version. On SF (linked from the site of the pexpect developer) http://pexpect.sourceforge.net/pexpect.html it seems the latest version (2.3), but I was able to download the 2.4 from here: http://pypi.python.org/pypi/pexpect/ which is just over one year old. On the other hand the version included in the repos of my linux distro is 2.3.1. So my questions: 1. Does anybody know if both version are compatible with python 2.6? 2. Does anybody know if 2.4 is a stable (secret) version? Of course if you have experience with pexpect and feel compelled to give some preliminary advice (like known limitations or quirks that take hours to understand, or "don't use it because is broken" kind of remarks) I will be glad to hear those as well! :) Many thanks for your time, Mac. From davea at ieee.org Tue Aug 25 01:36:26 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 19:36:26 -0400 Subject: [Tutor] Template long text substitution In-Reply-To: <5cb309e70908241414h4ab61f29kf911e09f1ae27d6c@mail.gmail.com> References: <5cb309e70908241414h4ab61f29kf911e09f1ae27d6c@mail.gmail.com> Message-ID: <4A9323FA.30606@ieee.org> Stefan Lesicnik wrote: > Hi Guys, > > I am trying to do the following, and im not sure how to deal with a blob of > text. > > I have the following file i am using as a template > > %%NAME%% > %%NUMBER%% > %%REPORT%% > > and i have a corresponding file with values > > name="bob" > number="123" > report="report is long > and spans multiple > lines. It also is already in the exact format > i want to replace the above template var %%REPORT%% with" > > The report part is obviously the problem. My code so far reads line by line > and splits on the = and reads the values into a dict. > > file = open('test','r') > data = {} > for line in file: > line = line.strip() > line = line.split('=') > data[line[0]] = line[1] > > My intention is then to replace the %%NAME%% with data['name'] etc. > If it makes a difference, the report= will be generated by another program > and given to me in the exact format i need to substitute it into %%REPORT%%. > (or i can put it in that file). > > I hope this makes sense, thanks in advance - i really do appreciate it :) > > Stefan > > There's much more left unsaid here. In order to parse that file, you have to know exactly what it will contain. I'll ask a few questions that might help you narrow it down. Currently you have three keywords "name" "number" and "report". Do you want this to be variable, and the order arbitrary? Clearly, you want to be case insensitive, since your template file has different case than the data file. Will there always be quotes around the value? Your current code doesn't check for them, nor does it remove them. But you do have to decide for the third keyword when the text ends. One way could be "till end of file" but I'm guessing you don't want that, especially if order is irrelevant. Another way could be "till another line with an '=' sign occurs". But what happens if you want an equal sign in the text someday? Or you could end when you encounter the next quote mark. But what happens if you want an embedded quote in the substituted text? If you have some choice in the file format, you could change it to specify the keywords with double-percent signs, same as in the template file. Then the rule could be that any line that starts with a percented keyword is the start of a new keyword, and any other line is appended (with newline between) to the previous value. DaveA From m.wanstall at gmail.com Tue Aug 25 02:55:15 2009 From: m.wanstall at gmail.com (Mal Wanstall) Date: Tue, 25 Aug 2009 10:55:15 +1000 Subject: [Tutor] Ptyhon GUI doubt In-Reply-To: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> References: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> Message-ID: <4fb9d14e0908241755j4c5f3e58o177ee95190391a3f@mail.gmail.com> Hi Raj, I used to get this error sometimes when I was using Windows. Killing the Python process via Task Manager and restarting IDLE was enough to get me going but if it still remains an issue, you can run Python in single process mode, the following is snipped from IDLE help: "Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. " On Mon, Aug 24, 2009 at 9:28 PM, Reddy Etikela, Rajasekhar wrote: > Hi, > > I am new to the Python. I have installed Python 2.6.2 version in windows XP. > > When I try to open the IDLE(Python GUI), getting the below message.?Any > configuration settings required for this? > > > Please let me know the details. > > Thanks, > Raj > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kreglet at gmail.com Tue Aug 25 03:58:18 2009 From: kreglet at gmail.com (kreglet) Date: Mon, 24 Aug 2009 18:58:18 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> Message-ID: <25124979.post@talk.nabble.com> Wayne, > def myfunc(cmpword, mainword): > for letter in cmpword: > if mainword.gets(letter): > if cmpword[letter] >mainword[letter]: > return False > else: > return False I tried your function and couldn't get it to work. It threw an error in the line "if mainword.gets(letter):" saying that "gets" was not an attribute of dictionary. I tried it with "if mainword.get(letter):" -- no s but that would't work either. I've been playing with this most of the day and this is what i came up with: from operator import itemgetter class letters: def __init__(self): self.lettercount={} self.inlist=False self.inword=False self.mainword="" self.cmpword="" lc=letters() def countletters(word): lc.lettercount = {} for letter in word: lc.lettercount[letter] =lc.lettercount.get(letter,0) + 1 print sorted(lc.lettercount.iteritems(), key=itemgetter(1)) lc.mainword="batty" lc.cmpword="batyy" countletters(lc.mainword) mainword = lc.lettercount countletters(lc.cmpword) cmpword = lc.lettercount lst=[] for key in cmpword.keys(): for ky in mainword.keys(): if key<>ky: pass else: lst.append(key) for key in cmpword.keys(): if key not in lst: lc.inlist=False break else: lc.inlist=True # At this point the program stops if a letter is in cmpword that is not in mainword # What I try to do next is compare the values of the dictionary keys( this is where I'm getting confused) # get keys/values from cmpword # compare the values of the keys from mainword that match the keys from cmpword # if there is a key in mainword that is not in cmpword, ignore it # if a key is the same in both compare the values #if the value of a key that is in cmpword is greater the the value of the corresponding key in mainword then cmpword would not be in mainword ---------------------------------------------------------- cmpkeys=[] cmpvals=[] if lc.inlist==True: for key, val in cmpword.items(): cmpkeys.append(key) cmpvals.append(val) for a in range(len(cmpkeys)): for ky, vl in mainword.items(): if cmpkeys[a]==ky: #????? if cmpvals[a]>vl: #???? lc.inword=False else: lc.inword=True print cmpkeys[a], cmpvals[a] , ky, vl print if lc.inword==True: print lc.cmpword + " is IN: " + lc.mainword else: print lc.cmpword + " is Not in: " + lc.mainword Lol, it aint pretty, and it almost works. If you change the letters in lc.cmpword you'll see what I mean. There's got to be another way :) cheers, kreglet Wayne-68 wrote: > > > > That's correct - your function countletters returns None, so you're > assigning cmpword to None. And since None is not an iterable type, it > throws > an error. Try returning a value like I mentioned above and see how that > works. > > HTH, > Wayne > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25124979.html Sent from the Python - tutor mailing list archive at Nabble.com. From roadierich at googlemail.com Tue Aug 25 12:45:21 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Tue, 25 Aug 2009 11:45:21 +0100 Subject: [Tutor] Ptyhon GUI doubt In-Reply-To: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> References: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> Message-ID: 2009/8/24 Reddy Etikela, Rajasekhar : > Hi, > > I am new to the Python. I have installed Python 2.6.2 version in windows XP. > > When I try to open the IDLE(Python GUI), getting the below message.?Any > configuration settings required for this? > > > Please let me know the details. > > Thanks, > Raj > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > This is usually a firewall issue. What firewall software are you using, and do you have access to modify its settings? -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From kent37 at tds.net Tue Aug 25 14:05:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Aug 2009 08:05:13 -0400 Subject: [Tutor] Algorithm In-Reply-To: <25107922.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> Message-ID: <1c2a2c590908250505x2e426984x432994aeb895c662@mail.gmail.com> On Sun, Aug 23, 2009 at 6:06 PM, kreglet wrote: > > Hello, > > ?The problem that I am having is writing an algorithm for finding all the > possible words from a given word. For example: python > > from "python" you can make the words pot, top, hop, not etc. There are few > examples for making anagrams for a word, but only the whole word. I have > tried unsuccessfully to modify some of these to suit my purpose. Also on the > web there are numerous sites where you can type in a word and it will give > you a list of all the words that could be made from it. How would I go about > this in python? Another way to do this: - sort the letters in the target word; for example 'python' becomes 'hnopty' - sort the letters in the word you want to test, for example 'pot' becomes 'opt' - walk through test letters looking for them in the target list. For each test letter, - if it matches the current target letter, go to the next letter in each list - if it is less than the current target letter, go to the next target letter - if the test letter is greater than the target letter, or you run out of target letters, there is no match - if you get to the end of the test letters, you have a match The code for this is pretty simple and doesn't require much in the way of data, just the two lists of letters. If you like I can share my implementation. Kent From Rajasekhar.ReddyEtikela at qwest.com Tue Aug 25 12:50:31 2009 From: Rajasekhar.ReddyEtikela at qwest.com (Reddy Etikela, Rajasekhar) Date: Tue, 25 Aug 2009 04:50:31 -0600 Subject: [Tutor] Ptyhon GUI doubt In-Reply-To: References: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> Message-ID: <3C84231676CF714388E1B5E8711020C20D0910AFBA@qtdenexmbm20.AD.QINTRA.COM> Hi Rich, I am using my organization machine. I am not aware of the firewall which we are using and don't have the access to it. Thanks, Raj -----Original Message----- From: Rich Lovely [mailto:roadierich at googlemail.com] Sent: Tuesday, August 25, 2009 4:15 PM To: Reddy Etikela, Rajasekhar Cc: tutor at python.org Subject: Re: [Tutor] Ptyhon GUI doubt 2009/8/24 Reddy Etikela, Rajasekhar : > Hi, > > I am new to the Python. I have installed Python 2.6.2 version in windows XP. > > When I try to open the IDLE(Python GUI), getting the below message.? > Any configuration settings required for this? > > > Please let me know the details. > > Thanks, > Raj > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > This is usually a firewall issue. What firewall software are you using, and do you have access to modify its settings? -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From srilyk at gmail.com Tue Aug 25 14:17:44 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 25 Aug 2009 07:17:44 -0500 Subject: [Tutor] Algorithm In-Reply-To: <25124979.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> <25124979.post@talk.nabble.com> Message-ID: <333efb450908250517s562c4ef3xaa0eab016bdc4885@mail.gmail.com> On Mon, Aug 24, 2009 at 8:58 PM, kreglet wrote: > > Wayne, > > > def myfunc(cmpword, mainword): > > for letter in cmpword: > > if mainword.gets(letter): > > if cmpword[letter] >mainword[letter]: > > return False > > else: > > return False > > I tried your function and couldn't get it to work. It threw an error in > the > line "if mainword.gets(letter):" saying that "gets" was not an attribute of > dictionary. I tried it with "if mainword.get(letter):" -- no s but that > would't work either. sorry, 'get' is what I meant. You also need to add "return True" on the same level as the else. In [5]: word1 = {'d':1, 'o':1, 'g':1} In [6]: word2 = {'g':1, 'o':1} In [7]: in_word(word2, word1) Out[7]: True In [24]: word2 = {'b':1, 'a':1, 'r':1} In [25]: in_word(word2, word1) Out[25]: False HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From garry.bettle at gmail.com Tue Aug 25 15:37:52 2009 From: garry.bettle at gmail.com (Garry Bettle) Date: Tue, 25 Aug 2009 15:37:52 +0200 Subject: [Tutor] Trouble with a Recipe ... Message-ID: Hi, Hope this email finds everyone well - roll on the weekend. I'm trying to run http://code.activestate.com/recipes/576824/ I'm in IDLE and I try: >>> email_it_via_gmail( {"To": "garry.bettle at gmail.com", "Subject": "Testing", "From": "garry.bettle at gmail.com"}, text="Testing") but I get the following error: Traceback (most recent call last): File "", line 1, in email_it_via_gmail( {"To": "garry.bettle at gmail.com", "Subject": "Testing", "From": "garry.bettle at gmail.com"}, text="Testing") File "C:\Documents and Settings\Garry\Desktop\recipe-576824-1.py", line 50, in email_it_via_gmail + headers.get("Bcc", []) TypeError: cannot concatenate 'str' and 'list' objects Sorry, but I according to the recipe I don't need a Bcc. Sorry, again, for such a simple question! Cheers, Garry From vceder at canterburyschool.org Tue Aug 25 15:55:35 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Tue, 25 Aug 2009 09:55:35 -0400 Subject: [Tutor] Trouble with a Recipe ... In-Reply-To: References: Message-ID: <4A93ED57.1010405@canterburyschool.org> At the top in the docstring it says, '"To", "Cc" and "Bcc" values must be *lists*'. That means instead of "To": "garry.bettle at gmail.com", you need "To": ["garry.bettle at gmail.com"] i.e. a list containing the destination address. That's so that you could send to, cc and bcc more than one address. HTH, Vern Garry Bettle wrote: > Hi, > > Hope this email finds everyone well - roll on the weekend. > > I'm trying to run http://code.activestate.com/recipes/576824/ > > I'm in IDLE and I try: > >>>> email_it_via_gmail( {"To": "garry.bettle at gmail.com", "Subject": "Testing", "From": "garry.bettle at gmail.com"}, text="Testing") > > but I get the following error: > > Traceback (most recent call last): > File "", line 1, in > email_it_via_gmail( {"To": "garry.bettle at gmail.com", "Subject": > "Testing", "From": "garry.bettle at gmail.com"}, text="Testing") > File "C:\Documents and Settings\Garry\Desktop\recipe-576824-1.py", > line 50, in email_it_via_gmail > + headers.get("Bcc", []) > TypeError: cannot concatenate 'str' and 'list' objects > > Sorry, but I according to the recipe I don't need a Bcc. > > Sorry, again, for such a simple question! > > Cheers, > > Garry > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From garry.bettle at gmail.com Tue Aug 25 16:12:34 2009 From: garry.bettle at gmail.com (Garry Bettle) Date: Tue, 25 Aug 2009 16:12:34 +0200 Subject: [Tutor] Trouble with a Recipe ... In-Reply-To: <4A93ED57.1010405@canterburyschool.org> References: <4A93ED57.1010405@canterburyschool.org> Message-ID: Many, many thanks Vern. For the life of me, I couldn't remember [] are for lists: I was trying with (). Guess I picked a bad day to stop sniffing glue! Cheers, Garry On Tue, Aug 25, 2009 at 15:55, Vern Ceder wrote: > At the top in the docstring it says, '"To", "Cc" and "Bcc" values must be > *lists*'. > > That means instead of "To": ?"garry.bettle at gmail.com", you need "To": > ["garry.bettle at gmail.com"] i.e. a list containing the destination address. > That's so that you could send to, cc and bcc more than one address. > > HTH, > > Vern > > > Garry Bettle wrote: >> >> Hi, >> >> Hope this email finds everyone well - roll on the weekend. >> >> I'm trying to run http://code.activestate.com/recipes/576824/ >> >> I'm in IDLE and I try: >> >>>>> email_it_via_gmail( {"To": "garry.bettle at gmail.com", "Subject": >>>>> "Testing", "From": "garry.bettle at gmail.com"}, text="Testing") >> >> but I get the following error: >> >> Traceback (most recent call last): >> ?File "", line 1, in >> ? ?email_it_via_gmail( {"To": "garry.bettle at gmail.com", "Subject": >> "Testing", "From": "garry.bettle at gmail.com"}, text="Testing") >> ?File "C:\Documents and Settings\Garry\Desktop\recipe-576824-1.py", >> line 50, in email_it_via_gmail >> ? ?+ headers.get("Bcc", []) >> TypeError: cannot concatenate 'str' and 'list' objects >> >> Sorry, but I according to the recipe I don't need a Bcc. >> >> Sorry, again, for such a simple question! >> >> Cheers, >> >> Garry >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > -- > This time for sure! > ? -Bullwinkle J. Moose > ----------------------------- > Vern Ceder, Director of Technology > Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 > vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 > From johnjenkinson1 at gmail.com Tue Aug 25 16:28:36 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Tue, 25 Aug 2009 07:28:36 -0700 Subject: [Tutor] Tutor Mailing List Message-ID: <58fd32380908250728u458d17c0oab519eb821ff01b7@mail.gmail.com> For the time being, I would like to be removed from the Tutor Mailing List for Python Users. Thanks, - John Jenkinson -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Aug 25 17:24:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Aug 2009 11:24:25 -0400 Subject: [Tutor] Tutor Mailing List In-Reply-To: <58fd32380908250728u458d17c0oab519eb821ff01b7@mail.gmail.com> References: <58fd32380908250728u458d17c0oab519eb821ff01b7@mail.gmail.com> Message-ID: <1c2a2c590908250824i6ba6be51g602c858574b184c1@mail.gmail.com> On Tue, Aug 25, 2009 at 10:28 AM, John Jenkinson wrote: > For the time being, I would like to be removed from the Tutor Mailing List > for Python Users. Click on the link below and follow the directions... Kent > Thanks, > - John Jenkinson > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kreglet at gmail.com Tue Aug 25 21:14:11 2009 From: kreglet at gmail.com (kreglet) Date: Tue, 25 Aug 2009 12:14:11 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: <333efb450908250517s562c4ef3xaa0eab016bdc4885@mail.gmail.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> <25124979.post@talk.nabble.com> <333efb450908250517s562c4ef3xaa0eab016bdc4885@mail.gmail.com> Message-ID: <25140474.post@talk.nabble.com> Wayne, I appreciate your patience with me. I still can't get this to work: from operator import itemgetter class testwords: def __init__(self): self.lettercount={} self.inword=False self.mainword="" self.cmpword="" def countletters(word): lc.lettercount = {} for letter in word: lc.lettercount[letter] =lc.lettercount.get(letter,0) + 1 print sorted(lc.lettercount.iteritems(), key=itemgetter(1)) def comparewords(cmpword, mainword): for letter in cmpword: if mainword.get(letter): print letter, cmpword[letter], mainword[letter] if cmpword[letter] >mainword[letter]: lc.inword=False else: if cmpword[letter] <=mainword[letter]: lc.inword=True lc=testwords() lc.mainword="batty" lc.cmpword="bat" countletters(lc.mainword) mainword = lc.lettercount countletters(lc.cmpword) cmpword = lc.lettercount comparewords(cmpword, mainword) if lc.inword==True: print lc.cmpword + " IS in: " + lc.mainword if lc.inword==False: print lc.cmpword + " IS NOT in: " + lc.mainword This is confusing me: lc.mainword="batty" lc.cmpword="bat" [('a', 1), ('y', 1), ('b', 1), ('t', 2)] [('a', 1), ('b', 1), ('t', 1)] a 1 1 b 1 1 t 1 2 bat IS in: batty lc.mainword="batty" lc.cmpword="byyt" [('a', 1), ('y', 1), ('b', 1), ('t', 2)] [('b', 1), ('t', 1), ('y', 2)] y 2 1 b 1 1 t 1 2 byyt IS in: batty if I put : if cmpword[letter] <=mainword[letter]: lc.inword=True on the same level as the else statement: lc.mainword="batty" lc.cmpword="bat" [('a', 1), ('y', 1), ('b', 1), ('t', 2)] [('a', 1), ('b', 1), ('t', 1)] a 1 1 b 1 1 t 1 2 bat IS Not in: batty Neither is: byyt Isn't what comes after the else statment to catch if a letter is in the cmpword that is not in the mainword? lc.mainword="batty" lc.cmpword="bst" KeyError: 's' Wayne-68 wrote: > > On Mon, Aug 24, 2009 at 8:58 PM, kreglet wrote: > >> >> Wayne, >> >> > def myfunc(cmpword, mainword): >> > for letter in cmpword: >> > if mainword.gets(letter): >> > if cmpword[letter] >mainword[letter]: >> > return False >> > else: >> > return False >> >> I tried your function and couldn't get it to work. It threw an error in >> the >> line "if mainword.gets(letter):" saying that "gets" was not an attribute >> of >> dictionary. I tried it with "if mainword.get(letter):" -- no s but that >> would't work either. > > > sorry, 'get' is what I meant. You also need to add "return True" on the > same > level as the else. > > In [5]: word1 = {'d':1, 'o':1, 'g':1} > > In [6]: word2 = {'g':1, 'o':1} > > In [7]: in_word(word2, word1) > Out[7]: True > > In [24]: word2 = {'b':1, 'a':1, 'r':1} > > In [25]: in_word(word2, word1) > Out[25]: False > > HTH, > Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25140474.html Sent from the Python - tutor mailing list archive at Nabble.com. From kreglet at gmail.com Tue Aug 25 23:03:54 2009 From: kreglet at gmail.com (kreglet) Date: Tue, 25 Aug 2009 14:03:54 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: <1c2a2c590908250505x2e426984x432994aeb895c662@mail.gmail.com> References: <25107922.post@talk.nabble.com> <1c2a2c590908250505x2e426984x432994aeb895c662@mail.gmail.com> Message-ID: <25142030.post@talk.nabble.com> Hello Kent, Yes I would like to see your implementation. It seems to work but I get error at the end. concat=''.join mainword="python" cmpword="pot" # sort the letters in the target word; for example 'python' becomes 'hnopty' tmplst=[] for letters in mainword: tmplst.append(letters) tmplst.sort() mainword=concat(tmplst) # sort the letters in the word you want to test, for example 'pot' becomes 'opt' tmplst=[] for letters in cmpword: tmplst.append(letters) tmplst.sort() cmpword=concat(tmplst) inword=False # walk through test letters looking for them in the target list. print cmpword, mainword for letter in range(len(cmpword)): #Test for let in range(len(mainword)):#Target print cmpword[letter], mainword[let], # if it matches the current target letter, go to the next letter in each list if cmpword[letter]==mainword[let]: print "Match: " let +=1 letter +=1 # if it is less than the current target letter, go to the next target letter if cmpword[letter]mainword[let]: print "No Match:" inword=False inword=True if inword==True: print cmpword + " is IN: " + mainword else: print cmpword + " is NOT in: " + mainrowd opt hnopty o h No Match: o n No Match: o o Match: p p Match: t t Match: Traceback (most recent call last): File "/home/kreglet/bin/knt.py", line 45, in if cmpword[letter] > > Another way to do this: > - sort the letters in the target word; for example 'python' becomes > 'hnopty' > - sort the letters in the word you want to test, for example 'pot' becomes > 'opt' > - walk through test letters looking for them in the target list. For > each test letter, > - if it matches the current target letter, go to the next letter in each > list > - if it is less than the current target letter, go to the next target > letter > - if the test letter is greater than the target letter, or you run > out of target letters, there is no match > - if you get to the end of the test letters, you have a match > > The code for this is pretty simple and doesn't require much in the way > of data, just the two lists of letters. If you like I can share my > implementation. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25142030.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Tue Aug 25 23:50:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Aug 2009 17:50:32 -0400 Subject: [Tutor] Algorithm In-Reply-To: <25142030.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> <1c2a2c590908250505x2e426984x432994aeb895c662@mail.gmail.com> <25142030.post@talk.nabble.com> Message-ID: <1c2a2c590908251450s6f86cb20i6f515c3f9e11965a@mail.gmail.com> On Tue, Aug 25, 2009 at 5:03 PM, kreglet wrote: > > Hello Kent, > > Yes I would like to see your implementation. It seems to work but I get > error at the end. > > concat=''.join > > mainword="python" > cmpword="pot" > ?# sort the letters in the target word; for example 'python' becomes > 'hnopty' > tmplst=[] > for letters in mainword: > ? ? ? ?tmplst.append(letters) This can be written as tmplst = list(mainword) > tmplst.sort() The above could be greatly simplified to tmplst = sorted(mainword) > mainword=concat(tmplst) You don't really need to convert back to a string, the list would work fine. > # sort the letters in the word you want to test, for example 'pot' becomes > 'opt' > tmplst=[] > for letters in cmpword: > ? ? ? ?tmplst.append(letters) > > tmplst.sort() > cmpword=concat(tmplst) Same as above > inword=False > # walk through test letters looking for them in the target list. > print cmpword, mainword > for letter in range(len(cmpword)): #Test > ? ? ? ?for let in range(len(mainword)):#Target You want to walk the two lists together. Nested loops is not the right structure. Here is my version: """ Find all words that can be made with the letters of a given word """ def contains(word, letters): ''' Test whether all letters of word are in letters. Letters must be a sorted list.''' letterIndex = 0; for letter in sorted(word): if letterIndex >= len(letters): # Ran out of letters return False while letter > letters[letterIndex] and letterIndex < len(letters) -1: # Skip letters that are too small letterIndex += 1 if letter == letters[letterIndex]: # A match, keep checking letterIndex += 1 continue # No match for current letter return False return True def findWordsIn(targetWord, minLen=3): letters = sorted(targetWord) for word in open('/usr/share/dict/words'): word = word.strip() if len(word) < minLen: continue if contains(word, letters): print word findWordsIn('python', 3) Prints: hop hot hoy hyp hypo not noy nth opt pho phon phony phot phyton poh pon pont pony pot poy python tho thon thy ton tony top toph toy typo yon yont yot Kent From davidwilson at Safe-mail.net Tue Aug 25 23:55:17 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Tue, 25 Aug 2009 17:55:17 -0400 Subject: [Tutor] how to remove first '/' Message-ID: Hello, I want to strip the first '/' from the following: '/path/to/file' How can I do this? Dave From vinces1979 at gmail.com Tue Aug 25 23:58:52 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 25 Aug 2009 15:58:52 -0600 Subject: [Tutor] how to remove first '/' In-Reply-To: References: Message-ID: <1e53c510908251458y1bb47f7gb62c06f70041166d@mail.gmail.com> On Tue, Aug 25, 2009 at 3:55 PM, wrote: > Hello, > I want to strip the first '/' from the following: > > '/path/to/file' > > How can I do this? > > Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > there are many ways to do this, heres a few: x = "/path/to/file" print x.partition("/")[-1] print x[1:] print "/".join(x.split("/")[1:]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Wed Aug 26 00:01:26 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Tue, 25 Aug 2009 18:01:26 -0400 Subject: [Tutor] how to remove first '/' In-Reply-To: References: Message-ID: <652641e90908251501lac2f68dob29993b9983ee7f9@mail.gmail.com> On Tue, Aug 25, 2009 at 5:55 PM, wrote: > Hello, > I want to strip the first '/' from the following: > > '/path/to/file' > > How can I do this? > > Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > If I understand correctly >>> m = '/path/to/file' >>> m[1:] 'path/to/file' >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidwilson at Safe-mail.net Wed Aug 26 00:15:27 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Tue, 25 Aug 2009 18:15:27 -0400 Subject: [Tutor] how to remove first '/' Message-ID: Thank you for the replies. -------- Original Message -------- From: Emad Nawfal (???? ????) To: davidwilson at safe-mail.net Cc: tutor at python.org Subject: Re: [Tutor] how to remove first '/' Date: Tue, 25 Aug 2009 18:01:26 -0400 > > > On Tue, Aug 25, 2009 at 5:55 PM, wrote: > > > > Hello, > > I want to strip the first '/' from the following: > > > > '/path/to/file' > > > > How can I do this? > > > > Dave > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > If I understand correctly > >>> m = '/path/to/file' > >>> m[1:] > 'path/to/file' > >>> > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Aug 26 03:55:56 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 25 Aug 2009 20:55:56 -0500 Subject: [Tutor] Algorithm In-Reply-To: <25140474.post@talk.nabble.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> <25124979.post@talk.nabble.com> <333efb450908250517s562c4ef3xaa0eab016bdc4885@mail.gmail.com> <25140474.post@talk.nabble.com> Message-ID: <333efb450908251855n35aeab27j4b1a2b1b880c800f@mail.gmail.com> On Tue, Aug 25, 2009 at 2:14 PM, kreglet wrote: > > Wayne, > I appreciate your patience with me. I still can't get this to work: > > > from operator import itemgetter > class testwords: > def __init__(self): > self.lettercount={} > self.inword=False > self.mainword="" > self.cmpword="" > > def countletters(word): > lc.lettercount = {} > for letter in word: > lc.lettercount[letter] =lc.lettercount.get(letter,0) + 1 > print sorted(lc.lettercount.iteritems(), key=itemgetter(1)) > > def comparewords(cmpword, mainword): > for letter in cmpword: > if mainword.get(letter): > print letter, cmpword[letter], mainword[letter] > if cmpword[letter] >mainword[letter]: > lc.inword=False > > else: > if cmpword[letter] <=mainword[letter]: > lc.inword=True > > > lc=testwords() > > lc.mainword="batty" > lc.cmpword="bat" > > countletters(lc.mainword) > mainword = lc.lettercount > > countletters(lc.cmpword) > cmpword = lc.lettercount > > comparewords(cmpword, mainword) > > if lc.inword==True: > print lc.cmpword + " IS in: " + lc.mainword > if lc.inword==False: > print lc.cmpword + " IS NOT in: " + lc.mainword This is a bit redundant - since lc.inword returns True or False you can simply test: if lc.inword: #do stuff else: #do other stuff That's really the proper way to do it. Also, AFAIK two "if" statements take longer than an if/else statement. Of course we're talking about ms or less, but it still reads better to have an if/else. It appears that I've not been coding enough lately - and my explanation has been a bit of a failure. I just did a quick test and this code seems to work correctly: def countletters(word): lettercount = {} for letter in word: lettercount[letter] = lettercount.get(letter, 0) + 1 return lettercount def comparewords(cmpword, mainword): for letter in cmpword: if mainword.get(letter): if cmpword[letter] > mainword[letter]: return False else: return False return True word1 = countletters('python') word2 = countletters('pyz') print comparewords(word2, word1) at least "py" was in "python", so was "pyn", but 'pyz' was not. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Aug 26 05:02:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Aug 2009 23:02:20 -0400 Subject: [Tutor] Algorithm In-Reply-To: <333efb450908251855n35aeab27j4b1a2b1b880c800f@mail.gmail.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> <25124979.post@talk.nabble.com> <333efb450908250517s562c4ef3xaa0eab016bdc4885@mail.gmail.com> <25140474.post@talk.nabble.com> <333efb450908251855n35aeab27j4b1a2b1b880c800f@mail.gmail.com> Message-ID: <1c2a2c590908252002m3a822654u31a9504b787e37ed@mail.gmail.com> On Tue, Aug 25, 2009 at 9:55 PM, Wayne wrote: > I just did a quick test and this code seems to work correctly: > def countletters(word): > ?? ?lettercount = {} > ?? ?for letter in word: > ?? ? ? ?lettercount[letter] = lettercount.get(letter, 0) + 1 > ?? ?return lettercount > def comparewords(cmpword, mainword): > ?? ?for letter in cmpword: > ?? ? ? ?if mainword.get(letter): > ?? ? ? ? ? ?if cmpword[letter] > mainword[letter]: > ?? ? ? ? ? ? ? ?return False This could be if cmpword[letter] > mainword.get(letter, 0): The whole loop could be simplified a bit using dict.items(): for letter, count in cmpword.items(): if count > mainword.get(letter, 0): return False Kent From kreglet at gmail.com Wed Aug 26 05:04:59 2009 From: kreglet at gmail.com (kreglet) Date: Tue, 25 Aug 2009 20:04:59 -0700 (PDT) Subject: [Tutor] Algorithm In-Reply-To: <333efb450908251855n35aeab27j4b1a2b1b880c800f@mail.gmail.com> References: <25107922.post@talk.nabble.com> <25109886.post@talk.nabble.com> <333efb450908240419w6cb0f8e6k914eae6e214b1d5a@mail.gmail.com> <25118434.post@talk.nabble.com> <333efb450908241032m2e706d15rea5b85a4118c6332@mail.gmail.com> <25124979.post@talk.nabble.com> <333efb450908250517s562c4ef3xaa0eab016bdc4885@mail.gmail.com> <25140474.post@talk.nabble.com> <333efb450908251855n35aeab27j4b1a2b1b880c800f@mail.gmail.com> Message-ID: <25145813.post@talk.nabble.com> Wayne, Kent, Alan, and Mac Thank you for all the help and suggestions . Wayne and Kent, Both your solutions work great. The extra comments you gave on the code that I tried will help reduce the line count and make the code more readable in the rest of the project. Apparently, I still have a lot to learn. I really appreciate the time you took to help and teach me. Thanx, kreglet -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25145813.html Sent from the Python - tutor mailing list archive at Nabble.com. From lie.1296 at gmail.com Wed Aug 26 07:13:11 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 26 Aug 2009 15:13:11 +1000 Subject: [Tutor] Ptyhon GUI doubt In-Reply-To: <3C84231676CF714388E1B5E8711020C20D0910AFBA@qtdenexmbm20.AD.QINTRA.COM> References: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> <3C84231676CF714388E1B5E8711020C20D0910AFBA@qtdenexmbm20.AD.QINTRA.COM> Message-ID: Reddy Etikela, Rajasekhar wrote: > Hi Rich, > > I am using my organization machine. I am not aware of the firewall which we are using and don't have the access to it. > You can just ignore the message if you cannot the administrator to adjust the firewall's setting. Just be aware that when IDLE is running without subprocess, the execution environment between IDLE itself and your own program is shared (although IDLE does its best to clean things up). This means your program can mess up IDLE and a previous runs of the program may affect the later runs. It may also be problematic to work with a windowing toolkit or threading as they may compete with IDLE's own GUI thread. To work around this, test your program directly from the real python interpreter (i.e. from the command line/terminal, instead of via IDLE). From alan.gauld at btinternet.com Wed Aug 26 09:38:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Aug 2009 08:38:18 +0100 Subject: [Tutor] Ptyhon GUI doubt References: <3C84231676CF714388E1B5E8711020C20D0910AE3C@qtdenexmbm20.AD.QINTRA.COM> Message-ID: "Reddy Etikela, Rajasekhar" wrote > I am new to the Python. I have installed Python 2.6.2 version in windows > XP. > When I try to open the IDLE(Python GUI), getting the below message. Others have advised what to do for IDLE but since you are on XP I'd strongly recommend using Pythonwin instead of IDLE. If you downloaded Python from the python.org web site you need to download and install the additional Windows package and inside that you will find Pythonwin. This is a more powerful IDE than IDLE with several useful Windows specific extras. Find it here: http://sourceforge.net/projects/pywin32/files/ Select the version corresponding to your version of Python.. If you got your Python from activestate.com then pythonwin is already included. In fact I'd go so far as to recommend dumping the python.org installation and getting the activestate version. It has a whole bunch of extras including all of the python documentation in Windows help format. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lupin at orcon.net.nz Wed Aug 26 08:16:29 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Wed, 26 Aug 2009 18:16:29 +1200 (NZST) Subject: [Tutor] how to remove first '/' In-Reply-To: References: Message-ID: <52868.121.73.55.101.1251267389.squirrel@mail.orcon.net.nz> I would say the best way would be to use lstrip... path='/path/to/file' stripped_path = path.lstrip('/') Cheers --Brett > Hello, > I want to strip the first '/' from the following: > > '/path/to/file' > > How can I do this? > > Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From davidwilson at Safe-mail.net Wed Aug 26 13:52:15 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Wed, 26 Aug 2009 07:52:15 -0400 Subject: [Tutor] design advise Message-ID: Hello, I would like advise on what method would be better in terms of search and retrieval. In my application I need to choose how to store data for each user, for example: /news /articles /games My difficulty now comes in how to store this data in that I will need to create views of the data depending on where in the directory the viewer is at for example file:///news/ should contain all the news submitted by all users and file:///games/ should contain all games ... Also in the file:///users/user/ the user will need access only to their own items, so for example, file:///users/user_1/news/ will list all news added by user_1 etc... Which is the more efficient option for storing this data, is it better to have all in one place and for each users' view to search by user id and return the filtered down list, or store it within each users' individual directory and then create a new list by traversing each users' directory? Thanks Dave From quasipedia at gmail.com Wed Aug 26 18:25:52 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Wed, 26 Aug 2009 18:25:52 +0200 Subject: [Tutor] Declaration order of classes... why it is important? Message-ID: <1251303952.20327.46.camel@jabbar> Hello everybody, I am using "storm" (https://storm.canonical.com/) to manage my database. In storm, relationships between tables (each table is represented by a class) are expressed like this (line #4): 1 >>> class Employee(Person): 2 ... __storm_table__ = "employee" 3 ... company_id = Int() 4 ... company = Reference(company_id, Company.id) where Company is another class. Now, what I noticed is that Company must be declared as a class before Employee, or python will throw an exception (Company is not defined). I would be interested in understanding why this is so designed. I expected that the exception would not be thrown at all, as I imagined that the interpreter simply kept track of where classes were declared and would try to evaluate the code only once an actual object would be instantiated (at that point the interpreter would know where to look for each class code). BTW, the behaviour I am describing is exactly what happens with function declaration: the following code evaluates as expected, indeed. def fone(): ftwo() def ftwo(): print "hello" fone() I would also be interested in knowing if there is a way around this or if I simply have to live with it. It is not that this impede to achieve anything, but in reading code, I normally prefer to have the big picture first [This is a house, as you see is composed of walls, roof, basement. A wall can have...] while this behaviour obliges me to write the code the other way around ["This is a brick, if you put together bricks you get a wall, if you put together walls you get..."] Thanks in advance, Mac. From alan.gauld at btinternet.com Wed Aug 26 19:23:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Aug 2009 18:23:28 +0100 Subject: [Tutor] design advise References: Message-ID: wrote > In my application I need to choose how to store data for each user, for > example: > > /news > /articles > /games > > My difficulty now comes in how to store this data in that I will need to > create views > Which is the more efficient option for storing this data, is it better to > have > all in one place and for each users' view to search by user id and return > the > filtered down list, or store it within each users' individual directory > and then > create a new list by traversing each users' directory? How about storing it in one place and creating shortcuts from the users areas to the master? That way items can be shared by users but still appear to be private. It might also be worth a look at how Apple do that stuff on MacOS... including iTunes etc Alan G From srilyk at gmail.com Wed Aug 26 19:28:28 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 26 Aug 2009 12:28:28 -0500 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251303952.20327.46.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> Message-ID: <333efb450908261028v2c0bd7b3g89042acad8f7202b@mail.gmail.com> On Wed, Aug 26, 2009 at 11:25 AM, Mac Ryan wrote: > Hello everybody, > > I am using "storm" (https://storm.canonical.com/) to manage my > database. In storm, relationships between tables (each table is > represented by a class) are expressed like this (line #4): > > 1 >>> class Employee(Person): > 2 ... __storm_table__ = "employee" > 3 ... company_id = Int() > 4 ... company = Reference(company_id, Company.id) > > where Company is another class. Now, what I noticed is that Company must > be declared as a class before Employee, or python will throw an > exception (Company is not defined). > > I would be interested in understanding why this is so designed. I > expected that the exception would not be thrown at all, as I imagined > that the interpreter simply kept track of where classes were declared > and would try to evaluate the code only once an actual object would be > instantiated (at that point the interpreter would know where to look for > each class code). > > BTW, the behaviour I am describing is exactly what happens with function > declaration: the following code evaluates as expected, indeed. > > def fone(): > ftwo() > def ftwo(): > print "hello" > fone() Try it with a class definition instead: In [1]: class One: ...: Two() ...: ...: --------------------------------------------------------------------------- NameError Traceback (most recent call last) C:\Documents and Settings\Wayne\ in () C:\Documents and Settings\Wayne\ in One() NameError: name 'Two' is not defined Yet with a function inside a class: In [2]: class One: ...: def spam(self): ...: Two() ...: ...: No problems. My guess is that it has to do with the difference between class and function definitions. AFAIK, classes are simply another namespace exactly like the global namespace. Similar to an 'import' statement which executes all the code found in that module. Further testing verifies this: In [3]: class One: ...: print "Hello" ...: ...: Hello Of course usually with a class you declare an __init__ method (function) that would eliminate your problem. The __init__ method is called on object instantiation. In [4]: class One: ...: def __init__(self): ...: Two() ...: ...: In [5]: One() --------------------------------------------------------------------------- NameError Traceback (most recent call last) C:\Documents and Settings\Wayne\ in () C:\Documents and Settings\Wayne\ in __init__(self) NameError: global name 'Two' is not defined HTH, Wayne p.s. The In[#] instead of >>> are because I'm using Ipython. > > > I would also be interested in knowing if there is a way around this or > if I simply have to live with it. > > It is not that this impede to achieve anything, but in reading code, I > normally prefer to have the big picture first [This is a house, as you > see is composed of walls, roof, basement. A wall can have...] while this > behaviour obliges me to write the code the other way around ["This is a > brick, if you put together bricks you get a wall, if you put together > walls you get..."] > > Thanks in advance, > Mac. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Aug 26 19:40:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Aug 2009 13:40:18 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251303952.20327.46.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> Message-ID: <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> On Wed, Aug 26, 2009 at 12:25 PM, Mac Ryan wrote: > Hello everybody, > > ? ? ? ?I am using "storm" (https://storm.canonical.com/) to manage my > database. In storm, relationships between tables (each table is > represented by a class) are expressed like this (line #4): > > 1 >>> class Employee(Person): > 2 ... ? ? __storm_table__ = "employee" > 3 ... ? ? company_id = Int() > 4 ... ? ? company = Reference(company_id, Company.id) > > where Company is another class. Now, what I noticed is that Company must > be declared as a class before Employee, or python will throw an > exception (Company is not defined). > > I would be interested in understanding why this is so designed. I > expected that the exception would not be thrown at all, as I imagined > that the interpreter simply kept track of where classes were declared > and would try to evaluate the code only once an actual object would be > instantiated (at that point the interpreter would know where to look for > each class code). The body of a class definition is executed when it is encountered. The result is a class object (an instance of 'type', usually). Any names defined at class scope become attributes of the class. The class name becomes a reference to the class object. > BTW, the behaviour I am describing is exactly what happens with function > declaration: the following code evaluates as expected, indeed. > > def fone(): > ?ftwo() > def ftwo(): > ?print "hello" > fone() Yes, functions are different than classes. The body of a function is not executed until it is called. Note that class methods behave like functions (well, they are functions) - they are not executed until called. But statements at class scope are executed to create the class. > > I would also be interested in knowing if there is a way around this or > if I simply have to live with it. You have to live with it unless you can put the attributes inside a method. In this case, I don't think that will work. Kent From kent37 at tds.net Wed Aug 26 19:41:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Aug 2009 13:41:54 -0400 Subject: [Tutor] design advise In-Reply-To: References: Message-ID: <1c2a2c590908261041l8d8733dxecf527710a0e3cd8@mail.gmail.com> On Wed, Aug 26, 2009 at 7:52 AM, wrote: > Hello, > I would like advise on what method would be better in terms of search and retrieval. > > In my application I need to choose how to store data for each user, for example: > > /news > /articles > /games > > My difficulty now comes in how to store this data in that I will need to create views of the data depending on where in the directory the viewer is at for example file:///news/ should contain all the news submitted by all users and file:///games/ should contain all games ... > > Also in the file:///users/user/ the user will need access only to their own items, so for example, file:///users/user_1/news/ will list all news added by user_1 etc... > > Which is the more efficient option for storing this data, is it better to have all in one place and for each users' > ?view to search by user id and return the filtered down list, or store it within each users' individual directory and then create a new list by traversing each users' directory? Maybe you should consider storing the data in a database instead of in the file system? Then it would be easy to retrieve all news, or just the news for a single user. Kent From davea at ieee.org Wed Aug 26 21:46:28 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 15:46:28 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> Message-ID: <4A959114.8010703@ieee.org> Kent Johnson wrote: > On Wed, Aug 26, 2009 at 12:25 PM, Mac Ryan wrote: > >> Hello everybody, >> >> I am using "storm" (https://storm.canonical.com/) to manage my >> database. In storm, relationships between tables (each table is >> represented by a class) are expressed like this (line #4): >> >> 1 >>> class Employee(Person): >> 2 ... __storm_table__ =employee" >> 3 ... company_id =nt() >> 4 ... company =eference(company_id, Company.id) >> >> where Company is another class. Now, what I noticed is that Company must >> be declared as a class before Employee, or python will throw an >> exception (Company is not defined). >> >> I would be interested in understanding why this is so designed. I >> expected that the exception would not be thrown at all, as I imagined >> that the interpreter simply kept track of where classes were declared >> and would try to evaluate the code only once an actual object would be >> instantiated (at that point the interpreter would know where to look for >> each class code). >> > > The body of a class definition is executed when it is encountered. The > result is a class object (an instance of 'type', usually). Any names > defined at class scope become attributes of the class. The class name > becomes a reference to the class object. > > >> BTW, the behaviour I am describing is exactly what happens with function >> declaration: the following code evaluates as expected, indeed. >> >> def fone(): >> ftwo() >> def ftwo(): >> print "hello" >> fone() >> > > Yes, functions are different than classes. The body of a function is > not executed until it is called. > > Note that class methods behave like functions (well, they are > functions) - they are not executed until called. But statements at > class scope are executed to create the class. > >> I would also be interested in knowing if there is a way around this or >> if I simply have to live with it. >> > > You have to live with it unless you can put the attributes inside a > method. In this case, I don't think that will work. > > Kent > > In Python, you don't declare classes, you define them. You can forward reference inside a definition (or method), but not elsewhere. That's because it's a one-pass system, where the lines are executed in order. In the case of a "def", execution consists of compiling the body and making a function object. That function object may forward reference all it likes, as long as it's not called until those references are available. So there are two workarounds to get what you'd like. Your problem is that you want the classes in a certain order, but that the first class has class attributes that have a forward reference. You can't do that directly. 1) As Kent suggested, you can put the attribute initialization inside a "dummy class method," one that will only be executed once, and that you promise will be executed before any other method of the class. Then when you have finished defining the dependency (the other class), you call this dummy method. Since you don't define all the other stuff, I have to simplify your case. Give a working fragment, if this is too simplified. class Employee(object): __storm_table__ = "employee" company_id = [] company = Company.id #where Company is a forward reference class Company: id = 42 This gives an error trying to define the Employee.company attribute. So define a classmethod to finish the job, and invoke it later class Employee(object): @classmethod def finish(cls): cls.__storm_table__ = "employee" cls.company_id = [] cls.company = Company.id #where Company is a forward reference del cls.finish #remove this method so it won't be called a second time class Company: id = 42 Employee.finish() #This finishes initializing the class help(Employee) print Employee.company_id 2) Simpler: Simply define the forward referencing class method later in the file, in the same place you would have invoked finish(). class Employee(object): __storm_table__ = "employee" company_id = [] #company = Company.id #Do this later class Company: id = 42 Employee.company_id = Company.id DaveA From quasipedia at gmail.com Wed Aug 26 23:52:34 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Wed, 26 Aug 2009 23:52:34 +0200 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <4A959114.8010703@ieee.org> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> Message-ID: <1251323554.23132.7.camel@jabbar> On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote: > So define a classmethod to finish the job, and invoke it later > > class Employee(object): > @classmethod > def finish(cls): > cls.__storm_table__ = "employee" > cls.company_id = [] > cls.company = Company.id #where Company is a forward > reference > del cls.finish #remove this method so it won't be called a > second time > > class Company: > id = 42 > > Employee.finish() #This finishes initializing the class > > > help(Employee) > print Employee.company_id First things first, thank you Wayne, Kent and Dave for your extensive and complementary explanations. As many things in python, what it seemed obscure at first now - with your help - seems perfectly obvious. Second thing: the example that Dave gave me and that I left quoted above makes use of decorators, but this is something that I still do not understand. I believe I got a grasp of the concept of metaclasses, to which the concept of decorator seems to be related, but the official documentation is a a bit obscure for me. I don't want to steal your time asking for an explanation that probably is already somewhere out there, but my google searches did not return anything useful (I assume I am using the wrong keywords here), so if you have a good pointer for me, I would be very grateful. :) Mac. From alan.gauld at btinternet.com Thu Aug 27 00:01:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Aug 2009 23:01:34 +0100 Subject: [Tutor] Declaration order of classes... why it is important? References: <1251303952.20327.46.camel@jabbar> Message-ID: "Mac Ryan" wrote > 1 >>> class Employee(Person): > 2 ... __storm_table__ = "employee" > 3 ... company_id = Int() > 4 ... company = Reference(company_id, Company.id) > > where Company is another class. Now, what I noticed is that Company must > be declared as a class before Employee, or python will throw an > exception (Company is not defined). Thats because you are using Comany as a class attribute rather than an instance attribute. A class is an object in Python, in the same sense that functions are objects. Python creates the class object by evaluating the class definition. Instances are created by calling the class object. > I would be interested in understanding why this is so designed. I > expected that the exception would not be thrown at all, as I imagined > that the interpreter simply kept track of where classes were declared > and would try to evaluate the code only once an actual object would be > instantiated (at that point the interpreter would know where to look for > each class code). No it interprets the class definition when it first sees it and the result is a class object. Because you refer to Company as part of the definition of a class attribute - part of the class object - Python needs to evaluate Company to create the class. > BTW, the behaviour I am describing is exactly what happens with function > declaration: the following code evaluates as expected, indeed. > > def fone(): > ftwo() > def ftwo(): > print "hello" > fone() > > I would also be interested in knowing if there is a way around this or > if I simply have to live with it. functions are objects too. But there are no variables inside the function that persist, even local variables are created then destroyed. But if you consider a default parameter you do get an error: def p(a=b): a() def b(): print 'hello' p() Will give a name error and thats as close as I can get to what you are doing with the class definition using clas variables. If you use instamnce variables the problem does not exist: >>> class C: d = M def __init__(self): pass Traceback (most recent call last): File "", line 1, in class C: File "", line 2, in C d = M NameError: name 'M' is not defined >>> class D: def __init__(self): self.d = M >>> > It is not that this impede to achieve anything, but in reading code, I > normally prefer to have the big picture first [This is a house, as you > see is composed of walls, roof, basement. A wall can have...] while this > behaviour obliges me to write the code the other way around ["This is a > brick, if you put together bricks you get a wall, if you put together > walls you get..."] You can put the top level function in a separate module and import the lower level ones, similarly you can put the class definitions in separate modules. But IMHO its better to just get used to Pythons way of working. Cut n Paste works wonders :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Thu Aug 27 02:01:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Aug 2009 20:01:46 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251323554.23132.7.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323554.23132.7.camel@jabbar> Message-ID: <1c2a2c590908261701u38643690r62f9ed4e9a4bbf25@mail.gmail.com> On Wed, Aug 26, 2009 at 5:52 PM, Mac Ryan wrote: > Second thing: the example that Dave gave me and that I left quoted above > makes use of decorators, but this is something that I still do not > understand. I believe I got a grasp of the concept of metaclasses, to > which the concept of decorator seems to be related, but the official > documentation is a a bit obscure for me. > > I don't want to steal your time asking for an explanation that probably > is already somewhere out there, but my google searches did not return > anything useful (I assume I am using the wrong keywords here), so if you > have a good pointer for me, I would be very grateful. :) http://personalpages.tds.net/~kent37/kk/00001.html Kent From jdmccla at regence.com Thu Aug 27 02:41:42 2009 From: jdmccla at regence.com (James D Mcclatchey) Date: Wed, 26 Aug 2009 17:41:42 -0700 Subject: [Tutor] AUTO: James D Mcclatchey is out of the office. (returning 08/31/2009) Message-ID: I am out of the office until 08/31/2009. I will respond to your message when I return. Note: This is an automated response to your message "Tutor Digest, Vol 66, Issue 72" sent on 8/26/09 17:01:48. This is the only notification you will receive while this person is away. *IMPORTANT NOTICE: This communication, including any attachment, contains information that may be confidential or privileged, and is intended solely for the entity or individual to whom it is addressed. If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure, copying, or distribution of this message is strictly prohibited. Nothing in this email, including any attachment, is intended to be a legally binding signature. * From davea at ieee.org Thu Aug 27 03:32:54 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 21:32:54 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251323517.23132.6.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> Message-ID: <4A95E246.7090105@ieee.org> Mac Ryan wrote: > On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote: > >> So define a classmethod to finish the job, and invoke it later >> >> class Employee(object): >> @classmethod >> def finish(cls): >> cls.__storm_table__ = "employee" >> cls.company_id = [] >> cls.company = Company.id #where Company is a forward >> reference >> del cls.finish #remove this method so it won't be called a >> second time >> >> class Company: >> id = 42 >> >> Employee.finish() #This finishes initializing the class >> >> >> help(Employee) >> print Employee.company_id >> > > First things first, thank you Wayne, Kent and Dave for your extensive > and complementary explanations. As many things in python, what it seemed > obscure at first now - with your help - seems perfectly obvious. > > Second thing: the example that Dave gave me and that I left quoted above > makes use of decorators, but this is something that I still do not > understand. I believe I got a grasp of the concept of metaclasses, to > which the concept of decorator seems to be related, but the official > documentation is a a bit obscure for me. > > I don't want to steal your time asking for an explanation that probably > is already somewhere out there, but my google searches did not return > anything useful (I assume I am using the wrong keywords here), so if you > have a good pointer for me, I would be very grateful. :) > > Mac. > > > (I see Kent posted a good link. But I had already composed this, so I'll send it along. First time, I accidentally posted to c.l.p. but I'll do better this time.) Decorators are syntactic sugar to save typing; what they accomplish can always be done another way, but generally not as readable. #somebody (eg., Python library) defines a function that takes a function as parameter, and returns a function, generally a different one related to the first def mydecorator(funct): .... return newfunct class myclass(object): @mydecorator def mymethod(self, arg1, arg2): ... Instead of the @syntax, we could also have written: class myclass(object): def mymethod(self, arg1, arg2) .... mymethod = mydecorator(mymethod) #this call happens when the class is being created Now there are a couple of decorators that are in the standard library that everyone should know about: classmethod() and staticmethod(). They wrap a method in a new one (which ends up having the same name), such that the first argument is either eaten (staticmethod), or changed to a class (classmethod). Hope that was sufficient detail. DaveA From jramak345 at gmail.com Thu Aug 27 03:47:03 2009 From: jramak345 at gmail.com (Jramak) Date: Wed, 26 Aug 2009 18:47:03 -0700 Subject: [Tutor] Callbacks in Python Message-ID: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> Hello I'm confused by callbacks. I would really appreciate any introduction or help in understanding the concept of callbacks. Thanks much Jramak -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Aug 27 03:51:31 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 26 Aug 2009 20:51:31 -0500 Subject: [Tutor] Callbacks in Python In-Reply-To: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> References: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> Message-ID: Suppose you are writing a GUI application. You don't want to write it from scratch so you want to use TKInter or WXPython. However, you also want to process the user's mouse clicks. These clicks won't occur in a consistent manner; sometimes they may occur frequently (double-clicking), sometimes infrequently (they're busy reading your interface, whatever.) So if you just poll the TKInter side of the program for events, a lot of the polls will be wasted. What you really want is that your code is run only when your event occurs.So you write a program that does what you want on each mouse click. Then you pass it to TKInter and say "hey, call this whenever you get a mouseclick event!" that function you wrote is called a "callback". Make sense? On Wed, Aug 26, 2009 at 8:47 PM, Jramak wrote: > Hello > > I'm confused by callbacks. I would really appreciate any introduction or > help in understanding the concept of callbacks. > > Thanks much > Jramak > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Aug 27 03:52:05 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 26 Aug 2009 20:52:05 -0500 Subject: [Tutor] Callbacks in Python In-Reply-To: References: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> Message-ID: On Wed, Aug 26, 2009 at 8:51 PM, Luke Paireepinart wrote: > > So you write a program that does what you want on each mouse click. > I meant "function" rather than "program". -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffpeery at yahoo.com Thu Aug 27 03:38:58 2009 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed, 26 Aug 2009 18:38:58 -0700 (PDT) Subject: [Tutor] how do I post event to thread? Message-ID: <619196.18753.qm@web43131.mail.sp1.yahoo.com> hello, I've read a bit about multi thread communication, and found that most people use a queue, which makes sense. however in my case I simply have two threads, a main thread and one other. the main thread is doing many different things and the second thread is receiving numerical data?via a serial port.. when data comes in, I want to post the data to the main thread so it can use the it. I don't want to use a queue because I don't want to lock up my main thread in a loop that is always looking at the queue waiting to get something out of it. I would prefer to do something like post an event.?The alternative would be to simply have a method in my main thread called OnResult(data), and when data comes in to the second thread I could call main_thread.OnResult(data). This would solve my problem, but I'm not sure if that is an ok thing to do... calling a main thread method from within a second thread? ? is there a way to post an event to the main thread from a second thread? ? Is it ok to pass the main thread (self) into the second thread and have the second thread call a main_thread.OnResult(data) method to pass the data into the main thread? I'm not sure how the main thread handles this, my guess is that it can only do one thing at a time so it might be exactly that same as 'posting an event'. ? any thoughts would be much appreciated. thanks! ? Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 27 05:16:35 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 23:16:35 -0400 Subject: [Tutor] how do I post event to thread? In-Reply-To: <619196.18753.qm@web43131.mail.sp1.yahoo.com> References: <619196.18753.qm@web43131.mail.sp1.yahoo.com> Message-ID: <4A95FA93.9040605@ieee.org> Jeff Peery wrote: > hello, > I've read a bit about multi thread communication, and found that most people use a queue, which makes sense. however in my case I simply have two threads, a main thread and one other. the main thread is doing many different things and the second thread is receiving numerical data via a serial port.. when data comes in, I want to post the data to the main thread so it can use the it. I don't want to use a queue because I don't want to lock up my main thread in a loop that is always looking at the queue waiting to get something out of it. I would prefer to do something like post an event. The alternative would be to simply have a method in my main thread called OnResult(data), and when data comes in to the second thread I could call main_thread.OnResult(data). This would solve my problem, but I'm not sure if that is an ok thing to do... calling a main thread method from within a second thread? > > is there a way to post an event to the main thread from a second thread? > > Is it ok to pass the main thread (self) into the second thread and have the second thread > call a main_thread.OnResult(data) method to pass the data into the main thread? I'm not sure how the main thread handles this, my guess is that it can only do one thing at a time so it might be exactly that same as 'posting an event'. > > any thoughts would be much appreciated. thanks! > > Jeff > > > You have some confusion here. A function doesn't belong to a thread, it's just code. When that code is called from the main thread, it's a function in the main thread. When the same function is called from a second thread, it's a function in that one. The trick to communicating between threads is *not* calling, it's a queue. You can use standard ones, or you can write your own. And you can call it lots of things. But basically the main thread will need to poll the "queue" somehow, to decide whether there's anything there to do. What is your main thread doing? Is yours a GUI program? If so, the main thread already has a polling loop, and you can just post an event on the event queue. Something like "callafter" or whatever it's called in your particular GUI. A queue of length 1 might be just a flag that's set by the secondary thread whenever there's data available. And it gets cleared by the main thread whenever it's noticed and acted upon. When the OS creates a thread, it basically creates a second stack frame, and creates another instance of the static space called "thread local storage (TLS)." Python presumably puts the thread object into the thread local storage. And the OS switches threads by restoring the stack pointer to point to a different stack frame, as well as the threadpointer to point to whichever TLS corresponds to it. Most things are totally shared between the threads. There are various OS things that affect the scheduling, so for example if you make a blocking call to an OS function, a thread switch will let other threads run in the meantime. Presumably an example of that is the call to read the serial port. Another way a thread can voluntarily give up control is with a sleep() call. Hopefully a GUI mainloop does one of those whenever there are no events waiting. There's more subtlety to threads. But this should get you started, and help point the way to questions more specific to your program design. Tell us python version, OS, and what GUI library you may be using. DaveA From lie.1296 at gmail.com Thu Aug 27 09:21:14 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 27 Aug 2009 17:21:14 +1000 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251323554.23132.7.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323554.23132.7.camel@jabbar> Message-ID: Mac Ryan wrote: > Second thing: the example that Dave gave me and that I left quoted above > makes use of decorators, but this is something that I still do not > understand. I believe I got a grasp of the concept of metaclasses, to > which the concept of decorator seems to be related, but the official > documentation is a a bit obscure for me. Think in black box. Consider the decorator syntax for staticmethod and classmethod as a special syntax to create functions that doesn't require the instance and function that requires class object. Forget about the fact that it uses metaclasses stuff to do its bidding, just know that decorator is simply a syntax sugar for function call and staticmethod() and classmethod() as a magical function that "eats self" and "turns self to class". Don't bother about the implementation details. From lie.1296 at gmail.com Thu Aug 27 09:47:49 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 27 Aug 2009 17:47:49 +1000 Subject: [Tutor] Callbacks in Python In-Reply-To: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> References: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> Message-ID: Jramak wrote: > Hello > > I'm confused by callbacks. I would really appreciate any introduction or > help in understanding the concept of callbacks. By example: def callback(nums): """ The callback function """ return sum(nums) * 2 def another_callback(nums): """ Yet another callback function """ return sum(nums) * 3 def strange_sum(nums, cb): """ Returns the sum, if less than 10 else returns the result of calling the callback function cb(), which must accepts one list argument """ if sum(nums) > 10: return sum(nums) else: return cb(nums) print strange_sum([1, 3, 4, 2, 4], callback) print strange_sum([3, 5, 4, 2], another_callback) So basically, a callback is a function that you passes as an argument (to another function) that may be called when a certain condition happens. In GUI-related stuff, callbacks are called when a certain events happens (e.g. a button is clicked). For the note, there are two main reasons why you want to pass a function to another function: 1. For callbacks, as explained and reasoned above. 2. To modify the passed functions, this case is known as decorator. From alan.gauld at btinternet.com Thu Aug 27 10:07:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Aug 2009 09:07:41 +0100 Subject: [Tutor] Callbacks in Python References: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> Message-ID: "Jramak" wrote > I'm confused by callbacks. I would really appreciate any introduction or > help in understanding the concept of callbacks. Callbacks are used in all sorts of different ways in programming so it might help to undertand what exactly confuses you. Is it the whole concept of a callback? Is it the idea of a function as an object? Is it the use of callbacks? In a GUI? In a networking framework like Twisted? Do you want to use someone elses callback mechanism or do you want to create your own? The basic name comnes from the concept of calling someone, asking them to do someting then call you back when they are done. So you leave your number with them. The number you leave is what they "call back". In programming you call a function and at some critical point that function calls you back on the function that you passed in. def someFunction(value, callback) result = pow(value,2) callback(result) def myFunction() v = 42 someFunction(v, myFunction_continue) def myFunction_contiinue(result) print result myFunction() This was very useful before threading environments became common as a way of simulating multi threading. Then when GUIs came along it bacame a common way of associating functions with widgets. And in networking we can associate network events with functions in a similar way. In fact any kind of event driven program is likely to use callbacks as a way of distributing control depending on event type. The typical implementation will see the event framework storing the callbacks in some kind of dictionary keyed by event type. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Thu Aug 27 13:00:59 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Aug 2009 07:00:59 -0400 Subject: [Tutor] how do I post event to thread? In-Reply-To: <619196.18753.qm@web43131.mail.sp1.yahoo.com> References: <619196.18753.qm@web43131.mail.sp1.yahoo.com> Message-ID: <1c2a2c590908270400m7c63b834i4458bc45628f7796@mail.gmail.com> On Wed, Aug 26, 2009 at 9:38 PM, Jeff Peery wrote: > hello, > I've read a bit about multi thread communication, and found that most people > use a queue, which makes sense. however in my case I simply have two > threads, a main thread and one other. the main thread is doing many > different things and the second thread is receiving numerical data?via a > serial port. when data comes in, I want to post the data to the main thread > so it can use the it. I don't want to use a queue because I don't want to > lock up my main thread in a loop that is always looking at the queue waiting > to get something out of it. I would prefer to do something like post an > event.?The alternative would be to simply have a method in my main thread > called OnResult(data), and when data comes in to the second thread I could > call main_thread.OnResult(data). This would solve my problem, but I'm not > sure if that is an ok thing to do... calling a main thread method from > within a second thread? As Dave explained, this will run OnResult() in the data thread. > is there a way to post an event to the main thread from a second thread? There is no way I know of to just force a function to run in another thread. The main thread needs to poll in some way for a notification from the data thread. If the main thread is running a GUI toolkit, there is probably a way for the data thread to post an event to the main thread. Most GUI toolkits also have idle loop callbacks so you could schedule an idle task to look for data from the data thread. Does your current main thread have an idle loop where you could poll the queue for data? Kent From davidwilson at Safe-mail.net Thu Aug 27 13:26:26 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Thu, 27 Aug 2009 07:26:26 -0400 Subject: [Tutor] design advise Message-ID: Thanks for the reply, but reading from my initial post I don't seem to have made my question clear ;( I was thinking more in terms of how python would find it more efficient in retrieving the information, this being: 1) Storing all the user files in one place and then selecting only the files with the correct permissions for the user views 2) Storing the files in the user's folder and then building a list of this files on the main views, such as /news/index.html I guess in the first instance the code will only has to traverse one directory and build the dictionary of all the files for that specific user when the user wants their files. i.e /users/user/news/list_of_news_items.html Whereas on the second method the code will have to travererse each user's directory and build a dictionary for all the published documents to display for the main view i.e /news/index.html The thing that bothers me is that I ma have 10 users or 100,000 users and really wanted to get an opinion as to which option would scale better, leaving aside the relational DB approach. Dave -------- Original Message -------- From: Kent Johnson Apparently from: kent3737 at gmail.com To: davidwilson at safe-mail.net Cc: tutor at python.org Subject: Re: [Tutor] design advise Date: Wed, 26 Aug 2009 13:41:54 -0400 > On Wed, Aug 26, 2009 at 7:52 AM, wrote: > > Hello, > > I would like advise on what method would be better in terms of search and retrieval. > > > > In my application I need to choose how to store data for each user, for example: > > > > /news > > /articles > > /games > > > > My difficulty now comes in how to store this data in that I will need to create views of the data depending on where in the directory the viewer is at for example file:///news/ should contain all the news submitted by all users and file:///games/ should contain all games ... > > > > Also in the file:///users/user/ the user will need access only to their own items, so for example, file:///users/user_1/news/ will list all news added by user_1 etc... > > > > Which is the more efficient option for storing this data, is it better to have all in one place and for each users' > > ?view to search by user id and return the filtered down list, or store it within each users' individual directory and then create a new list by traversing each users' directory? > > Maybe you should consider storing the data in a database instead of in > the file system? Then it would be easy to retrieve all news, or just > the news for a single user. > > Kent From kent37 at tds.net Thu Aug 27 16:28:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Aug 2009 10:28:06 -0400 Subject: [Tutor] design advise In-Reply-To: References: Message-ID: <1c2a2c590908270728v40c1a1c5hcb1ce14e7ca7a201@mail.gmail.com> On Thu, Aug 27, 2009 at 7:26 AM, wrote: > I was thinking more in terms of how python would find it more efficient in retrieving the information, this being: > 1) Storing all the user files in one place and then selecting only the files with the correct permissions for the user views > ?2) Storing the files in the user's folder and then building a list of this files on the main views, such as /news/index.html > > I guess in the first instance the code will only has to traverse one directory and build the dictionary of all the files for that specific user when the user wants their files. i.e /users/user/news/list_of_news_items.html > > Whereas on the second method the code will have to travererse each user's directory and build a dictionary for all the published documents to display for the main view i.e /news/index.html There is no right answer to your question the way you have asked it. Organizing per user will be faster for the per-user search. All files together will be faster for locating all files. Which one do you want to prefer? > The thing that bothers me is that I ma have 10 users or 100,000 users and really wanted to get an opinion as to which option would scale better, leaving aside the relational DB approach. I'm no expert on scaling but I can't imagine that any approach based purely on scanning a filesystem is going to scale to 100,000 users. Perhaps you should use a database to make an index of the files? Kent From jeffpeery at yahoo.com Thu Aug 27 17:07:16 2009 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 27 Aug 2009 08:07:16 -0700 (PDT) Subject: [Tutor] how do I post event to thread? In-Reply-To: <1c2a2c590908270400m7c63b834i4458bc45628f7796@mail.gmail.com> Message-ID: <384470.64923.qm@web43135.mail.sp1.yahoo.com> Hi, thanks for all the good responses. I appreciate your thoughts. I was sightly confused about how these threads work together. ? I am using python 2.6,?no GUI at the moment, so I can't use the wxEvent class or the equivalent.? ? The program basically pulls data from a serial port and then calculates some stats and writes data to a file. eventually I will put a GUI on it. ? I think you are correct that since my logic is in its own thread I can put a portion of code that watches the queue. ? Thanks for the advice! ? Jeff --- On Thu, 8/27/09, Kent Johnson wrote: From: Kent Johnson Subject: Re: [Tutor] how do I post event to thread? To: "Jeff Peery" Cc: tutor at python.org Date: Thursday, August 27, 2009, 4:00 AM On Wed, Aug 26, 2009 at 9:38 PM, Jeff Peery wrote: > hello, > I've read a bit about multi thread communication, and found that most people > use a queue, which makes sense. however in my case I simply have two > threads, a main thread and one other. the main thread is doing many > different things and the second thread is receiving numerical data?via a > serial port. when data comes in, I want to post the data to the main thread > so it can use the it. I don't want to use a queue because I don't want to > lock up my main thread in a loop that is always looking at the queue waiting > to get something out of it. I would prefer to do something like post an > event.?The alternative would be to simply have a method in my main thread > called OnResult(data), and when data comes in to the second thread I could > call main_thread.OnResult(data). This would solve my problem, but I'm not > sure if that is an ok thing to do... calling a main thread method from > within a second thread? As Dave explained, this will run OnResult() in the data thread. > is there a way to post an event to the main thread from a second thread? There is no way I know of to just force a function to run in another thread. The main thread needs to poll in some way for a notification from the data thread. If the main thread is running a GUI toolkit, there is probably a way for the data thread to post an event to the main thread. Most GUI toolkits also have idle loop callbacks so you could schedule an idle task to look for data from the data thread. Does your current main thread have an idle loop where you could poll the queue for data? Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Aug 27 17:54:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Aug 2009 16:54:31 +0100 Subject: [Tutor] design advise References: Message-ID: wrote > The thing that bothers me is that I ma have 10 users or 100,000 users > and really wanted to get an opinion as to which option would scale > better, leaving aside the relational DB approach. If you have to cater for 100,000 users all with different views on a common set of resources I don;t think you can afford to leave aside the database approach! Almost anything else will run like a dog with a broken leg... 10 users with 100,000 resources would be fine but 100,000 users will be a problem if you try to use the filesystem as an organising tool. The trick to using the database is to build the relationships in the database but keep the resources in the filesystem. You can then query the database for which resources to display then access the resources directly from disk using their filenames etc HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Thu Aug 27 18:28:47 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 12:28:47 -0400 Subject: [Tutor] design advise In-Reply-To: References: Message-ID: <4A96B43F.1050804@ieee.org> Alan Gauld wrote: >
> wrote > >> The thing that bothers me is that I ma have 10 users or 100,000 users >> and really wanted to get an opinion as to which option would scale >> better, leaving aside the relational DB approach. > > If you have to cater for 100,000 users all with different views on a > common set of resources I don;t think you can afford to leave aside > the database approach! Almost anything else will run like a dog with a > broken leg... > > 10 users with 100,000 resources would be fine but 100,000 users > will be a problem if you try to use the filesystem as an organising tool. > > The trick to using the database is to build the relationships in the > database but keep the resources in the filesystem. You can then query > the database for which resources to display then access the resources > directly from disk using their filenames etc > > HTH, > > +1 you need a database to keep track of 100,000 users. Scaling is what databases do best. That doesn't mean you necessarily need a "real database" yet. But if you start with a database-compatible approach, then you'll be able to scale it into a database when the users grows enough. However, whether or not you use a database, you still have to design the interactions. If these filenames have to be unique, then it'd be quite difficult to check that if they were all in separate directories. So adding a new file would require that you check in all the directories to make sure the selected name is unique. So updating a single file would be very slow. Cure for that is either to put them all centrally, or make the name arbitrary. This is equivalent in database terms to using an ID (integer) abstraction to identify people, since their name field might not be unique. If you're trying to use the file system as your database, you have to consider three tradeoffs: 1) how to make sure things are self-consistent, according to whatever the business rules are. 2) how to minimize access time for more than one kind of query 3) how to reconstruct things when something goes wrong (which it will). And of course you have to decide which problems are to be recoverable and which ones are catastrophic. DaveA From cburgmer at ira.uka.de Thu Aug 27 17:15:56 2009 From: cburgmer at ira.uka.de (Christoph Burgmer) Date: Thu, 27 Aug 2009 17:15:56 +0200 Subject: [Tutor] string.title(): correct? Message-ID: <200908271715.56200.cburgmer@ira.uka.de> > Allen Fowler wrote: > > Hello, > > > > "He's a great guy".title() > > > > Gives me: > > > > "He'S A Great Guy" > > > > > > I expected: > > > > "He's A Great Guy" > > > > Did i miss something here? > > The docs state: > > "title( ) - Return a titlecased version of the string: words start with > uppercase characters, all remaining cased characters are lowercase." > > It depends on the definition of "word". Yes, but in this case Python is wrong. Titlecase should, at least for Unicode strings, follow the Unicode "Default Case Algorithms", see bug http://bugs.python.org/issue6412. http://www.unicode.org/Public/5.2.0/ucd/DerivedCoreProperties-5.2.0d15.txt lists: 0027 ; Case_Ignorable # Po APOSTROPHE An as such the following would be correct: >>> "He's a great guy".title() "He's A Great Guy" I'm not subsribed to the list, CC me for answer. -Christoph Burgmer From jramak345 at gmail.com Thu Aug 27 20:48:07 2009 From: jramak345 at gmail.com (Jramak) Date: Thu, 27 Aug 2009 11:48:07 -0700 Subject: [Tutor] Callbacks in Python In-Reply-To: References: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> Message-ID: <6191dd070908271148nb575ccen3041de311cade085@mail.gmail.com> Thanks everyone for your excellent insights. I think I understand the callback concept better. So, it is like passing a function as an argument to another function. I am interested in learning more about how callbacks can be applied in GUIs, using wxPython as an example. Would appreciate any insight. Thanks much Jramak On 8/27/09, Alan Gauld wrote: > > "Jramak" wrote > >> I'm confused by callbacks. I would really appreciate any introduction or >> help in understanding the concept of callbacks. > > Callbacks are used in all sorts of different ways in programming > so it might help to undertand what exactly confuses you. > > Is it the whole concept of a callback? > Is it the idea of a function as an object? > Is it the use of callbacks? > In a GUI? In a networking framework like Twisted? > > Do you want to use someone elses callback mechanism > or do you want to create your own? > > The basic name comnes from the concept of calling > someone, asking them to do someting then call you back > when they are done. So you leave your number with them. > The number you leave is what they "call back". > In programming you call a function and at some critical > point that function calls you back on the function that > you passed in. > > def someFunction(value, callback) > result = pow(value,2) > callback(result) > > def myFunction() > v = 42 > someFunction(v, myFunction_continue) > > def myFunction_contiinue(result) > print result > > myFunction() > > This was very useful before threading environments became > common as a way of simulating multi threading. Then when GUIs > came along it bacame a common way of associating functions > with widgets. And in networking we can associate network events > with functions in a similar way. In fact any kind of event driven > program is likely to use callbacks as a way of distributing control > depending on event type. The typical implementation will see the > event framework storing the callbacks in some kind of dictionary > keyed by event type. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From daneicher99 at hotmail.com Fri Aug 28 02:08:52 2009 From: daneicher99 at hotmail.com (Dan Eicher) Date: Fri, 28 Aug 2009 00:08:52 +0000 Subject: [Tutor] FW: Kerberos Validation Message-ID: Hi,I have Heimdal Kerberos server running under Solaris. It is working and my pam stack is correct as I can kinit on a client and validate on the unix command line. Under Linux (ubuntu 9.04 in this case) - I'd like to write a python program that will validate a user name and password against the kerberos server. I've found one module python-kerberos, but not a lot (any?) of examples. Does anyone on the list have any experience with kerberos validation that they can share? Thanks, Dan _________________________________________________________________ Windows Live: Keep your friends up to date with what you do online. http://windowslive.com/Campaign/SocialNetworking?ocid=PID23285::T:WLMTAGL:ON:WL:en-US:SI_SB_online:082009 From ballerz4ishi at sbcglobal.net Fri Aug 28 09:14:08 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Fri, 28 Aug 2009 00:14:08 -0700 (PDT) Subject: [Tutor] NLTK Message-ID: <260156.69098.qm@web83308.mail.sp1.yahoo.com> Hello, I have successfully downloaded NLTK and the toy grammars. I want to run a few of the packages that come with NLTK on corpora that I have. How do I do this? What commands would I use? The corpora are text files; should I put them in the Python25 folder (is that the so called same directory)? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Fri Aug 28 13:47:09 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 28 Aug 2009 13:47:09 +0200 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <4A95E246.7090105@ieee.org> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> Message-ID: <1251460029.11653.59.camel@jabbar> On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > Now there are a couple of decorators that are in the standard library > that everyone should know about: classmethod() and staticmethod(). > They wrap a method in a new one (which ends up having the same name), > such that the first argument is either eaten (staticmethod), or changed > to a class (classmethod). > > Hope that was sufficient detail. > > DaveA Thank you all for your answer, I read the link posted by Kent end the explanations given by others, and now almost all the pieces of the puzzle are falling to their place. The (last?) thing still escaping my understanding is the difference between classmethod() and staticmethod(). I understand that both of them are to make sure a method will be associated with the class rather than with an instance of it (a bit like variables declared in a class but outside a method), so I assume I should use them like: class myClass(object): @staticmethod / @classmethod def method_of_class(self): pass def method_of_instances(self): pass I am not sure I understood the difference between staticmethod end classmethod, though, even if I can guess it has to do with subclassing, (given classmethod go fish for the class name)... am I on the right track? Any hint (or full-fledged explanation!)? :) [The official documentation is a bit obscure for me as it refers to C# and Java, languages that I do not know.] Also, what is the advantage of using a method at class level rather than using it at object instance (I can imagine you can save some memory by not duplicating X times the same code, maybe... but what kind of designs require/call for use of statc/classmethods?) Thank you in advance for your help, Mac. From kent37 at tds.net Fri Aug 28 13:49:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 07:49:40 -0400 Subject: [Tutor] NLTK In-Reply-To: <260156.69098.qm@web83308.mail.sp1.yahoo.com> References: <260156.69098.qm@web83308.mail.sp1.yahoo.com> Message-ID: <1c2a2c590908280449m6e27e28bxae99402cff5a0d4e@mail.gmail.com> On Fri, Aug 28, 2009 at 3:14 AM, Ishan Puri wrote: > Hello, > ??? I have successfully downloaded NLTK and the toy grammars. I want to run > a few of the packages that come with NLTK on corpora that I have. How do I > do this? What commands would I use? The corpora are text files; should I put > them in the Python25 folder (is that the so called same directory)? The section Loading your own Corpus in the book seems to show what you want: http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html Kent From davea at ieee.org Fri Aug 28 14:55:06 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 08:55:06 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251460029.11653.59.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> Message-ID: <4A97D3AA.5060109@ieee.org> Mac Ryan wrote: > On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > > >> Now there are a couple of decorators that are in the standard library >> that everyone should know about: classmethod() and staticmethod(). >> They wrap a method in a new one (which ends up having the same name), >> such that the first argument is either eaten (staticmethod), or changed >> to a class (classmethod). >> >> Hope that was sufficient detail. >> >> DaveA >> > > Thank you all for your answer, I read the link posted by Kent end the > explanations given by others, and now almost all the pieces of the > puzzle are falling to their place. > > The (last?) thing still escaping my understanding is the difference > between classmethod() and staticmethod(). I understand that both of them > are to make sure a method will be associated with the class rather than > with an instance of it (a bit like variables declared in a class but > outside a method), so I assume I should use them like: > > class myClass(object): > > @staticmethod / @classmethod > def method_of_class(self): > pass > > def method_of_instances(self): > pass > > I am not sure I understood the difference between staticmethod end > classmethod, though, even if I can guess it has to do with subclassing, > (given classmethod go fish for the class name)... am I on the right > track? Any hint (or full-fledged explanation!)? :) > > [The official documentation is a bit obscure for me as it refers to C# > and Java, languages that I do not know.] > > Also, what is the advantage of using a method at class level rather than > using it at object instance (I can imagine you can save some memory by > not duplicating X times the same code, maybe... but what kind of designs > require/call for use of statc/classmethods?) > > Thank you in advance for your help, > Mac. > > > I thought someone (me) had already posted examples. The method itself looks different in the three cases: class MyClass(object): def my_method1(self, arg): ... do something with this particular object @classmethod def my_class_method(cls, arg) .... do something that may requires use of class, but that doesn't need to know the particular object @staticmethod def my_static_method(arg): .... do something which isn't affected at all by what class it's in self and cls parameters are named that merely by convention. Unlike the "this" of C++, C#, and Java, these names have no specific meaning to the compiler. But convention is a very good thing, especially in this case. So the first difference between static and class is that the method signature must be different. There's an extra parameter on the latter that must be included. The second difference is that a classmethod may call other methods of the same class, and gets the appropriate methods even if the class was subclassed. The hint to play with is that any of these 3 may be called with an object (obj.my_class_method()), and the last two may be called with a classname. DaveA From krissy.ambert at gmail.com Fri Aug 28 16:17:09 2009 From: krissy.ambert at gmail.com (Kristina Ambert) Date: Fri, 28 Aug 2009 10:17:09 -0400 Subject: [Tutor] What does it mean to create separate applications? Message-ID: Hi, I'm new to python and frankly new to programming. This is my first question post, so I hope everyone could bear with me. I'm working on a small database application which basically handles a store inventory, it's my internship project for the semester. My boss asked me to break down each form (e.g. product information entry, store inventory list) into separate small applications. I'm having a hard time understanding what she means by this. Does it mean each form is it's separate python file? If that's the case, the things I have already is that way. I guess my question basically is, what does it mean for something to be called an application or a standalone application? I've searched the internet for some answers but I just keep getting more confused. Thanks for any pointers anyone can give me! Best, Krissy -------------- next part -------------- An HTML attachment was scrubbed... URL: From kp8 at me.com Fri Aug 28 16:05:44 2009 From: kp8 at me.com (kevin parks) Date: Fri, 28 Aug 2009 23:05:44 +0900 Subject: [Tutor] packing a list of lists Message-ID: Back to python after a long long layoff. So i am running into some beginner's confusion... I am trying to plot a list of numbers in gnuplot.py. To do that I am trying to pack the list with an index by iterating over the list so i can get something like: foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] So that i have x, y pairs to plot. When i print in my func i get the right thing, for each item (note scaffolding) yet when i reurn the whole list i just get the last pair repeated over and over. I am not sure why this is. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list # function declarations would go here def test(): """test function - say what this does here and skip a line Keyword arguments: none """ print foo = minus(200) plot_me = pack(foo) #print foo print print plot_me if __name__ == "__main__": test() From quasipedia at gmail.com Fri Aug 28 17:06:07 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 28 Aug 2009 17:06:07 +0200 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <4A97D3AA.5060109@ieee.org> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> <4A97D3AA.5060109@ieee.org> Message-ID: <1251471967.5472.29.camel@jabbar> On Fri, 2009-08-28 at 08:55 -0400, Dave Angel wrote: > Mac Ryan wrote: > > On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > > > > > >> Now there are a couple of decorators that are in the standard library > >> that everyone should know about: classmethod() and staticmethod(). > >> They wrap a method in a new one (which ends up having the same name), > >> such that the first argument is either eaten (staticmethod), or changed > >> to a class (classmethod). > >> > >> Hope that was sufficient detail. > >> > >> DaveA > >> > > > > Thank you all for your answer, I read the link posted by Kent end the > > explanations given by others, and now almost all the pieces of the > > puzzle are falling to their place. > > > > The (last?) thing still escaping my understanding is the difference > > between classmethod() and staticmethod(). I understand that both of them > > are to make sure a method will be associated with the class rather than > > with an instance of it (a bit like variables declared in a class but > > outside a method), so I assume I should use them like: > > > > class myClass(object): > > > > @staticmethod / @classmethod > > def method_of_class(self): > > pass > > > > def method_of_instances(self): > > pass > > > > I am not sure I understood the difference between staticmethod end > > classmethod, though, even if I can guess it has to do with subclassing, > > (given classmethod go fish for the class name)... am I on the right > > track? Any hint (or full-fledged explanation!)? :) > > > > [The official documentation is a bit obscure for me as it refers to C# > > and Java, languages that I do not know.] > > > > Also, what is the advantage of using a method at class level rather than > > using it at object instance (I can imagine you can save some memory by > > not duplicating X times the same code, maybe... but what kind of designs > > require/call for use of statc/classmethods?) > > > > Thank you in advance for your help, > > Mac. > > > > > > > I thought someone (me) had already posted examples. The method itself > looks different in the three cases: > > class MyClass(object): > > def my_method1(self, arg): > ... do something with this particular object > > @classmethod > def my_class_method(cls, arg) > .... do something that may requires use of class, but > that doesn't need to know the particular object > > @staticmethod > def my_static_method(arg): > .... do something which isn't affected at all by what > class it's in > > self and cls parameters are named that merely by convention. Unlike the > "this" of C++, C#, and Java, these names have no specific meaning to the > compiler. But convention is a very good thing, especially in this case. > > So the first difference between static and class is that the method > signature must be different. There's an extra parameter on the latter > that must be included. The second difference is that a classmethod may > call other methods of the same class, and gets the appropriate methods > even if the class was subclassed. > > The hint to play with is that any of these 3 may be called with an > object (obj.my_class_method()), and the last two may be called with a > classname. > > DaveA Thank you Dave, very helpful as ever. I made a few tests and experiments to understand better, and I feel I am understanding how it works. Although the mechanic of this is increasingly clear, the logic behind is still a bit obscure: here comes a silly test on which results I have questions about ====================================================== class A(object): variable = 0 @classmethod def cm(cls): cls.variable += 3 class B(A): pass class C(B): pass a = A() b = B() c = C() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' b.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' c.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.variable = 7 A.variable = 4 print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' B.variable = 'x' print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable ====================================================== Now, the output of this test is as follows (I manually added the numbers on the right for reference in the remaining of the post): 0 0 # 1 0 0 0 0 --- 3 3 # 2 3 3 3 3 --- 3 3 # 3 6 6 6 6 --- 3 3 # 4 6 6 9 9 --- 4 7 # 5 6 6 9 9 --- 4 7 # 6 x x 9 9 #1 is plain obvious. #2 came as a bit of surprise: "Ah-ah!... so the class variable is the same for all the hierarchy of classes! I would have guessed each class had its own variable..." #3 and #4 are bigger surprises: "Uh? let me understand better, so... it must be like branches... as soon as I say that B.variable is different than its ancestors, all the descendants of B get updated... Yet, it's strange: this very thread on the mailing list has started with me asking about the order of declaration for classes, and I have been told that class variables are processed as soon as the interpreter hits the class definition... so I would have expected that C.variable would have been initialised already and would not dynamically change when B.variable does..." #5 confused me: it seems that a.variable can refer to both the class variable or a newly created object property... that sounds like a never-ending source of bugs to me: it is me who has then to remember if a given syntax refers to a class variable or to an object method? #6 really make no sense to me: it seems that the class variable of C has not been changed this time (as it did in #3)... The points above confuse me even more about the "design purposes" of classmethods and staticmethods... Any help/feedback, very much appreciated. mac. From vinces1979 at gmail.com Fri Aug 28 17:18:08 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 28 Aug 2009 09:18:08 -0600 Subject: [Tutor] packing a list of lists In-Reply-To: References: Message-ID: <1e53c510908280818j1dd180bfj3297ee62aba5158@mail.gmail.com> On Fri, Aug 28, 2009 at 8:05 AM, kevin parks wrote: > Back to python after a long long layoff. So i am running into some > beginner's confusion... > > I am trying to plot a list of numbers in gnuplot.py. To do that I am trying > to pack the list with an index by iterating over the list so i can get > something like: > > foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] > > [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] > > So that i have x, y pairs to plot. When i print in my func i get the right > thing, for each item (note scaffolding) yet when i reurn the whole list i > just get the last pair repeated over and over. > > I am not sure why this is. > > > def pack(in_seq): > out_list=[] > x = 1 > ll=[1, 1] > for each in in_seq: > ll[0] = x > ll[1] = each > out_list.append(ll) > #print ll > x = x + 1 > print out_list > > > # function declarations would go here > def test(): > """test function - say what this does here and skip a line > > Keyword arguments: > none > """ > > print > foo = minus(200) > plot_me = pack(foo) > #print foo > print > print plot_me > > > if __name__ == "__main__": > test() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Although I didn't test your code, I think what you are trying to accomplish can be done using enumerate cleaner def pack(foo): out = [] for x,y in enumerate(foo, 1): out.append((x,y)) return out -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Fri Aug 28 17:20:30 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 28 Aug 2009 09:20:30 -0600 Subject: [Tutor] packing a list of lists In-Reply-To: <1e53c510908280818j1dd180bfj3297ee62aba5158@mail.gmail.com> References: <1e53c510908280818j1dd180bfj3297ee62aba5158@mail.gmail.com> Message-ID: <1e53c510908280820n1d89bba1k2c743016f60b1524@mail.gmail.com> On Fri, Aug 28, 2009 at 9:18 AM, vince spicer wrote: > > > On Fri, Aug 28, 2009 at 8:05 AM, kevin parks wrote: > >> Back to python after a long long layoff. So i am running into some >> beginner's confusion... >> >> I am trying to plot a list of numbers in gnuplot.py. To do that I am >> trying to pack the list with an index by iterating over the list so i can >> get something like: >> >> foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] >> >> [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] >> >> So that i have x, y pairs to plot. When i print in my func i get the right >> thing, for each item (note scaffolding) yet when i reurn the whole list i >> just get the last pair repeated over and over. >> >> I am not sure why this is. >> >> >> def pack(in_seq): >> out_list=[] >> x = 1 >> ll=[1, 1] >> for each in in_seq: >> ll[0] = x >> ll[1] = each >> out_list.append(ll) >> #print ll >> x = x + 1 >> print out_list >> >> >> # function declarations would go here >> def test(): >> """test function - say what this does here and skip a line >> >> Keyword arguments: >> none >> """ >> >> print >> foo = minus(200) >> plot_me = pack(foo) >> #print foo >> print >> print plot_me >> >> >> if __name__ == "__main__": >> test() >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > Although I didn't test your code, I think what you are trying to accomplish > can be done using enumerate cleaner > > > def pack(foo): > out = [] > for x,y in enumerate(foo, 1): > out.append((x,y)) > return out > > > > Or even cleaner with list comprehension def pack(foo): return [x for x in enumerate(foo, 1)] -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at shamirlens.co.uk Fri Aug 28 17:23:48 2009 From: michael at shamirlens.co.uk (Michael M Mason) Date: Fri, 28 Aug 2009 16:23:48 +0100 Subject: [Tutor] packing a list of lists In-Reply-To: References: Message-ID: <2B7AA81C577B0942A14C2B388867E2C77EDB@harry.shamirlens.co.uk> Kevin Parks wrote: > def pack(in_seq): > out_list=[] > x = 1 > ll=[1, 1] > for each in in_seq: > ll[0] = x > ll[1] = each > out_list.append(ll) > #print ll > x = x + 1 > print out_list Variable out_list consists of list ll repeated however many times. Each time you change ll you're changing it everywhere it appears in out_list. That is, what's being appended to out_list isn't a copy of ll, it's a pointer to ll. You need something like:- out_list.append([ll[0],ll[1]]) And you need to add a return at the end of the function, otherwise it returns None: return out_list -- Michael From zstumgoren at gmail.com Fri Aug 28 18:01:31 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 28 Aug 2009 12:01:31 -0400 Subject: [Tutor] flyweight pattern using Mixin vs. Inheritance Message-ID: Hi everyone, Based on some earlier list advice, I went back to the drawing board and started testing various approaches to adding the "flyweight" pattern to my classes. To recap, I have a bunch of campaign finance-related classes and subclasses (Committee, HouseCommittee, PresidentialCommittee, Candidate, CampaignReport, etc.), and I'm trying to add in the ability for a class to check for a unique instance of itself before creating a new instance. So if I have a committee named "Pac1", I want to check if that committee has previously been created. If it does exist, I want to return the "Pac1" instance; otherwise, I want to create the "Pac1" instance. The closest description I could find to this pattern was the "flyweight" (described here: http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#behavioural-patterns), though it appears that this pattern relates as much (or more?) to efficient memory usage than to the notion of only creating a new instance if an identical one does not already exist. (If there's a name for the latter piece of this pattern, please let me know so I can avoid typing that phrase over and over again!) I pasted my test code for two approaches to solving this problem, one using a Mixin class and another using Inheritance. http://pastebin.com/m3252c407 I'm not certain I'll need this functionality on all occasions, and not all of my classes/subclasses require this behavior. Given those requirements, is the Mixin approach the way to go? Either way, have I implemented these correctly? Also, for purposes of the test, please note that I commented out the weakref usages (which kind of defeats the purpose of the flyweight pattern, right?). It was easier to wrap my brain around this when the instance ids remained the same. I found that when using weakref, the ids changed (even for what should have been the same instance). Is that due to the nature of how garbage collection works with weakref? Or perhaps I'm not implementing this pattern correctly? Hence my asking you all! As always, any and all advice is appreciated. Serdar From davea at ieee.org Fri Aug 28 18:24:22 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 12:24:22 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251471967.5472.29.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> <4A97D3AA.5060109@ieee.org> <1251471967.5472.29.camel@jabbar> Message-ID: <4A9804B6.2000206@ieee.org> Mac Ryan wrote: > On Fri, 2009-08-28 at 08:55 -0400, Dave Angel wrote: > >> Mac Ryan wrote: >> >>> On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: >>> >>> >>> >>>> Now there are a couple of decorators that are in the standard library >>>> that everyone should know about: classmethod() and staticmethod(). >>>> They wrap a method in a new one (which ends up having the same name), >>>> such that the first argument is either eaten (staticmethod), or changed >>>> to a class (classmethod). >>>> >>>> Hope that was sufficient detail. >>>> >>>> DaveA >>>> >>>> >>> Thank you all for your answer, I read the link posted by Kent end the >>> explanations given by others, and now almost all the pieces of the >>> puzzle are falling to their place. >>> >>> The (last?) thing still escaping my understanding is the difference >>> between classmethod() and staticmethod(). I understand that both of them >>> are to make sure a method will be associated with the class rather than >>> with an instance of it (a bit like variables declared in a class but >>> outside a method), so I assume I should use them like: >>> >>> class myClass(object): >>> >>> @staticmethod / @classmethod >>> def method_of_class(self): >>> pass >>> >>> def method_of_instances(self): >>> pass >>> >>> I am not sure I understood the difference between staticmethod end >>> classmethod, though, even if I can guess it has to do with subclassing, >>> (given classmethod go fish for the class name)... am I on the right >>> track? Any hint (or full-fledged explanation!)? :) >>> >>> [The official documentation is a bit obscure for me as it refers to C# >>> and Java, languages that I do not know.] >>> >>> Also, what is the advantage of using a method at class level rather than >>> using it at object instance (I can imagine you can save some memory by >>> not duplicating X times the same code, maybe... but what kind of designs >>> require/call for use of statc/classmethods?) >>> >>> Thank you in advance for your help, >>> Mac. >>> >>> >>> >>> >> I thought someone (me) had already posted examples. The method itself >> looks different in the three cases: >> >> class MyClass(object): >> >> def my_method1(self, arg): >> ... do something with this particular object >> >> @classmethod >> def my_class_method(cls, arg) >> .... do something that may requires use of class, but >> that doesn't need to know the particular object >> >> @staticmethod >> def my_static_method(arg): >> .... do something which isn't affected at all by what >> class it's in >> >> self and cls parameters are named that merely by convention. Unlike the >> "this" of C++, C#, and Java, these names have no specific meaning to the >> compiler. But convention is a very good thing, especially in this case. >> >> So the first difference between static and class is that the method >> signature must be different. There's an extra parameter on the latter >> that must be included. The second difference is that a classmethod may >> call other methods of the same class, and gets the appropriate methods >> even if the class was subclassed. >> >> The hint to play with is that any of these 3 may be called with an >> object (obj.my_class_method()), and the last two may be called with a >> classname. >> >> DaveA >> > > Thank you Dave, very helpful as ever. I made a few tests and experiments > to understand better, and I feel I am understanding how it works. > Although the mechanic of this is increasingly clear, the logic behind is > still a bit obscure: here comes a silly test on which results I have > questions about > > ====================================================== > > class A(object): > variable = 0 > @classmethod > def cm(cls): > cls.variable += 3 > > class B(A): > pass > > class C(B): > pass > > a = A() > b = B() > c = C() > print A.variable, a.variable > print B.variable, b.variable > print C.variable, c.variable > print '---' > a.cm() > print A.variable, a.variable > print B.variable, b.variable > print C.variable, c.variable > print '---' > b.cm() > print A.variable, a.variable > print B.variable, b.variable > print C.variable, c.variable > print '---' > c.cm() > print A.variable, a.variable > print B.variable, b.variable > print C.variable, c.variable > print '---' > a.variable = 7 > A.variable = 4 > print A.variable, a.variable > print B.variable, b.variable > print C.variable, c.variable > print '---' > B.variable = 'x' > print A.variable, a.variable > print B.variable, b.variable > print C.variable, c.variable > > ====================================================== > > Now, the output of this test is as follows (I manually added the numbers > on the right for reference in the remaining of the post): > > 0 0 # 1 > 0 0 > 0 0 > --- > 3 3 # 2 > 3 3 > 3 3 > --- > 3 3 # 3 > 6 6 > 6 6 > --- > 3 3 # 4 > 6 6 > 9 9 > --- > 4 7 # 5 > 6 6 > 9 9 > --- > 4 7 # 6 > x x > 9 9 > > #1 is plain obvious. > > #2 came as a bit of surprise: "Ah-ah!... so the class variable is the > same for all the hierarchy of classes! I would have guessed each class > had its own variable..." > > #3 and #4 are bigger surprises: "Uh? let me understand better, so... it > must be like branches... as soon as I say that B.variable is different > than its ancestors, all the descendants of B get updated... Yet, it's > strange: this very thread on the mailing list has started with me asking > about the order of declaration for classes, and I have been told that > class variables are processed as soon as the interpreter hits the class > definition... so I would have expected that C.variable would have been > initialised already and would not dynamically change when B.variable > does..." > > #5 confused me: it seems that a.variable can refer to both the class > variable or a newly created object property... that sounds like a > never-ending source of bugs to me: it is me who has then to remember if > a given syntax refers to a class variable or to an object method? > > #6 really make no sense to me: it seems that the class variable of C has > not been changed this time (as it did in #3)... > > The points above confuse me even more about the "design purposes" of > classmethods and staticmethods... > > Any help/feedback, very much appreciated. > > mac. > > > Great questions. I love a person who is organized as you are. And as willing to learn. #3 and #4 - First let me point out that these are not class variables, but class attributes. It's unfortunate that you called the attributes with the label 'variable'. I frequently make the same mistake (call it sloppy mistake), but it might matter somewhere in the following discussion. A class variable is simply a "variable" which references the class. Think of it as an alias for the class. Just like a list variable is a variable which references a list. If you do: newclass = A then you can use newclass in exactly the same way as A. a = newclass(), print newclass.variable, etc. A class attribute, on the other hand, is what other languages would call a field of the class. And it definitely does get initialized when the class is executed. That's important in the earlier discussion because the *right-hand-side* has to be valid at that time, which is why you had the forward referencing problem. So in the following code: n = 12 class A(object): attr = n n = 42 the attribute A.attr is a reference to 12, not 42. The confusion in this #3 and #4 case is that when some later expression tries to use a particular class attribute there are some rules for lookup. I don't know the correct terminology, but I think of this as the "." operator. When I say C.variable, the first search is in the classes dictionary. If it's not found there, then it searches in the parent class' dictionary, and so on. The attribute is not copied, there's just a search order when it's accessed. #5 - It's search order again (on what I call the dot operator). When you reference c.variable, it looks first in the dictionary for the instance object c, and then if it doesn't find it, it looks in the parent, which is the class. And if it doesn't find it there, it again looks in the parent, and so on. #6 - by this time, there is a class attribute C.variable, so changing B.variable has no effect Probably the key thing that misleads people is that the += operator may actually create a new attribute. That happened when you called b.cm() and c.cm(). You might be helped by using help(B) before and after the call to b.cm(). It says a lot that you might not care about, but it makes clear what attribute are "defined here" versus "inherited from..." HTH DaveA From davea at ieee.org Fri Aug 28 18:48:29 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 12:48:29 -0400 Subject: [Tutor] Callbacks in Python In-Reply-To: <6191dd070908271148nb575ccen3041de311cade085@mail.gmail.com> References: <6191dd070908261847w869a3d9s2e7c86434902749a@mail.gmail.com> <6191dd070908271148nb575ccen3041de311cade085@mail.gmail.com> Message-ID: <4A980A5D.2060306@ieee.org> Jramak wrote: > Thanks everyone for your excellent insights. I think I understand the > callback concept better. > So, it is like passing a function as an argument to another function. > I am interested in learning more about how callbacks can be applied in > GUIs, using wxPython as an example. Would appreciate any insight. > > Thanks much > Jramak > > On 8/27/09, Alan Gauld wrote: > >> "Jramak" wrote >> >> >>> I'm confused by callbacks. I would really appreciate any introduction or >>> help in understanding the concept of callbacks. >>> >> Callbacks are used in all sorts of different ways in programming >> so it might help to undertand what exactly confuses you. >> >> Is it the whole concept of a callback? >> Is it the idea of a function as an object? >> Is it the use of callbacks? >> In a GUI? In a networking framework like Twisted? >> >> Do you want to use someone elses callback mechanism >> or do you want to create your own? >> >> The basic name comnes from the concept of calling >> someone, asking them to do someting then call you back >> when they are done. So you leave your number with them. >> The number you leave is what they "call back". >> In programming you call a function and at some critical >> point that function calls you back on the function that >> you passed in. >> >> def someFunction(value, callback) >> result = pow(value,2) >> callback(result) >> >> def myFunction() >> v = 42 >> someFunction(v, myFunction_continue) >> >> def myFunction_contiinue(result) >> print result >> >> myFunction() >> >> This was very useful before threading environments became >> common as a way of simulating multi threading. Then when GUIs >> came along it bacame a common way of associating functions >> with widgets. And in networking we can associate network events >> with functions in a similar way. In fact any kind of event driven >> program is likely to use callbacks as a way of distributing control >> depending on event type. The typical implementation will see the >> event framework storing the callbacks in some kind of dictionary >> keyed by event type. >> >> HTH, >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > If you have any sample code for wxPython, look for the Bind method. Generally used within widget code, it passes a reference to a method that should be called when some specific event happens to that widget. In the following line, if the widget gets resized (by the user dragging the edges of the window), my method OnSize() will be called. self.Bind(wx.EVT_SIZE, self.OnSize) DaveA From kp8 at me.com Fri Aug 28 18:49:40 2009 From: kp8 at me.com (kevin parks) Date: Sat, 29 Aug 2009 01:49:40 +0900 Subject: [Tutor] packing a list of lists In-Reply-To: <1e53c510908280820n1d89bba1k2c743016f60b1524@mail.gmail.com> References: <1e53c510908280818j1dd180bfj3297ee62aba5158@mail.gmail.com> <1e53c510908280820n1d89bba1k2c743016f60b1524@mail.gmail.com> Message-ID: <9B134454-F286-437E-AABE-70BB8194A3D6@me.com> Thanks for the replies. Though the list comprehension does not work: TypeError: enumerate() takes exactly 1 argument (2 given) On Aug 29, 2009, at 12:20 AM, vince spicer wrote: > > > #print foohough I didn't test your code, I think what you are > trying to accomplish can be done using enumerate cleaner > > > def pack(foo): > out = [] > for x,y in enumerate(foo, 1): > out.append((x,y)) > return out > > > > > Or even cleaner with list comprehension > > def pack(foo): > return [x for x in enumerate(foo, 1)] > > From vinces1979 at gmail.com Fri Aug 28 18:57:33 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 28 Aug 2009 10:57:33 -0600 Subject: [Tutor] packing a list of lists In-Reply-To: <9B134454-F286-437E-AABE-70BB8194A3D6@me.com> References: <1e53c510908280818j1dd180bfj3297ee62aba5158@mail.gmail.com> <1e53c510908280820n1d89bba1k2c743016f60b1524@mail.gmail.com> <9B134454-F286-437E-AABE-70BB8194A3D6@me.com> Message-ID: <1e53c510908280957n11a8768eh86686804af307ddc@mail.gmail.com> On Fri, Aug 28, 2009 at 10:49 AM, kevin parks wrote: > > Thanks for the replies. Though the list comprehension does not work: > > TypeError: enumerate() takes exactly 1 argument (2 given) > > > On Aug 29, 2009, at 12:20 AM, vince spicer wrote: > > >> >> #print foohough I didn't test your code, I think what you are trying >> to accomplish can be done using enumerate cleaner >> >> >> def pack(foo): >> out = [] >> for x,y in enumerate(foo, 1): >> out.append((x,y)) >> return out >> >> >> >> >> Or even cleaner with list comprehension >> >> def pack(foo): >> return [x for x in enumerate(foo, 1)] >> >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > What version of python are using, python 2.6+ have a "start" parameter http://docs.python.org/library/functions.html#enumerate -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 28 19:03:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Aug 2009 18:03:39 +0100 Subject: [Tutor] Declaration order of classes... why it is important? References: <1251303952.20327.46.camel@jabbar><1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com><4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar><4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> Message-ID: "Mac Ryan" wrote > I am not sure I understood the difference between staticmethod end > classmethod, though, even if I can guess it has to do with subclassing, I think it is mainly historical. staticmethod came first (I think) and classmethod was an improvement a couple of versions later. I think classmethod is the preferred choice nowadays. > Also, what is the advantage of using a method at class level rather than > using it at object instance There are two common cases: 1) You want to do something at the class level rather than instance level - such as find all instances, or keep a count of all instances. Or you may have a method or variable that affects all instances simultaneously - perhaps activates or disables all network connections say. 2) You want somethig that can be done without creating an instance, or at least does not depend on whether any instances exist yet. This is very common in Java which doesn't support standalone functions but is not needed so much in Python because a module function is usually a better option. You can also use it to provide meta-class programming features and other tricks, but frankly thats usually being too clever for your own good! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Fri Aug 28 19:05:35 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 13:05:35 -0400 Subject: [Tutor] What does it mean to create separate applications? In-Reply-To: References: Message-ID: <4A980E5F.5050509@ieee.org> Kristina Ambert wrote: > Hi, > > I'm new to python and frankly new to programming. This is my first question > post, so I hope everyone could bear with me. > I'm working on a small database application which basically handles a store > inventory, it's my internship project for the semester. My boss asked me to > break down each form (e.g. product information entry, store inventory list) > into separate small applications. I'm having a hard time understanding what > she means by this. Does it mean each form is it's separate python file? If > that's the case, the things I have already is that way. > I guess my question basically is, what does it mean for something to be > called an application or a standalone application? I've searched the > internet for some answers but I just keep getting more confused. > > Thanks for any pointers anyone can give me! > > Best, > Krissy > > An application is something the end-user can run by itself. Typically, a python application is a script dedicated to one purpose, that may import other python modules that are more general purpose, and those may be shared between applications. At its simplest, such a script parses the command line arguments (sys.argv) does some initialization, and invokes some features in the shared code of those imports. A standalone application is one that's ready to install and use on an arbitrary machine, without having much in the way of external dependencies. But that's very dependent on the customer base you're aiming at. For example, python.exe (and all its libraries ) is a dependency, but a particular company may already assume every machine has a particular version of Python installed and ready to go. Now, different levels of management may have different notions of what an application is. For example, to some people, maybe an application is something that can be run from a Windows Desktop shortcut, with all other interactions being prompted by the program itself. So they want to see separate shortcuts for "product entry", "store inventory" etc. Now if I were doing these, they might all invoke the same Python script, but pass parameters choosing what subset of features are needed. As long as "installation" includes initializing these shortcuts, the manager is happy. DaveA From alan.gauld at btinternet.com Fri Aug 28 19:15:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Aug 2009 18:15:34 +0100 Subject: [Tutor] What does it mean to create separate applications? References: Message-ID: "Kristina Ambert" wrote > inventory, it's my internship project for the semester. My boss asked me > to > break down each form (e.g. product information entry, store inventory > list) > into separate small applications. I'm having a hard time understanding > what > she means by this. Does it mean each form is it's separate python file? Pretty much. > I guess my question basically is, what does it mean for something to be > called an application or a standalone application? I've searched the > internet for some answers but I just keep getting more confused. An "application" is a pseudonym for most users for a "program". But to a programmer a "program" can also mean the complete source code for an application. So to distinguish between program (source code) and program(executable) the term application is often used. So I suspect your boss wants a separate exercutable python script for each main form. By using modules you should be able to reuse a lot of your database code between the different applications. You will find more on this topic in the "What is Programming" topic in my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kp8 at me.com Fri Aug 28 19:23:50 2009 From: kp8 at me.com (kevin parks) Date: Sat, 29 Aug 2009 02:23:50 +0900 Subject: [Tutor] packing a list of lists In-Reply-To: <1760583206-1251480078-cardhu_decombobulator_blackberry.rim.net-161485977-@bxe1158.bisx.prod.on.blackberry> References: <1760583206-1251480078-cardhu_decombobulator_blackberry.rim.net-161485977-@bxe1158.bisx.prod.on.blackberry> Message-ID: I think this is b/c I am running 2.5. I also have 2.6 but i am using 2.5 for gnupoly and an older audio lib i have. I ran the listcom below on 2.6 and it worked, so i just have to figure out how that can be written for 2.5. I guess 2.6 has an update to enumerate. -k On Aug 29, 2009, at 2:21 AM, afith13 at gmail.com wrote: > Enumerate() is returning a tuple, I haven't tested this code but try: > [[x[0],x[1]] for x in enumerate(blah,1)] > ------Original Message------ > Sender: tutor-bounces+afith13+python=gmail.com at python.org > To: tutor at python.org > Subject: Re: [Tutor] packing a list of lists > Sent: Aug 28, 2009 9:49 AM > > > Thanks for the replies. Though the list comprehension does not work: > > TypeError: enumerate() takes exactly 1 argument (2 given) > > > On Aug 29, 2009, at 12:20 AM, vince spicer wrote: > >> >> >> #print foohough I didn't test your code, I think what you are >> trying to accomplish can be done using enumerate cleaner >> >> >> def pack(foo): >> out = [] >> for x,y in enumerate(foo, 1): >> out.append((x,y)) >> return out >> >> >> >> >> Or even cleaner with list comprehension >> >> def pack(foo): >> return [x for x in enumerate(foo, 1)] >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Aug 28 19:29:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Aug 2009 18:29:15 +0100 Subject: [Tutor] flyweight pattern using Mixin vs. Inheritance References: Message-ID: "Serdar Tumgoren" wrote > Given those requirements, is the Mixin approach the way to go? Either > way, have I implemented these correctly? I haven't looked at your code but you could use a mixin here however I find using mixins for insantiation can bend your brain. I tend to use them for instance behavioural type things . Instead I would actually use a dictionary class attribute (see the thread on class attributes/methods) The way I'd do it would be to store a dictionary of object instances (using some kind of unique name/id as key). In the constructor of each class (ie __new__() not __init__() check to see if the ID exists in the dictionary and return the object if it does. Otherwise continue as usual. Something like this(untested pseudo code): class A instances = {} def __new__(self, ID, *args, **kwargs): if ID in instances: return ID def __init__(self, *args, **kwargs): if ID in self.instances: return else: # init as usual. def __del__(self): del( self.instances[self.ID] ) The __del__ can probably be implemented in the top level class and inherited. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Fri Aug 28 19:29:47 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 13:29:47 -0400 Subject: [Tutor] packing a list of lists In-Reply-To: References: Message-ID: <4A98140B.1030405@ieee.org> kevin parks wrote: >
Back to > python after a long long layoff. So i am running into some beginner's > confusion... > > I am trying to plot a list of numbers in gnuplot.py. To do that I am > trying to pack the list with an index by iterating over the list so i > can get something like: > > foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] > > [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] > > So that i have x, y pairs to plot. When i print in my func i get the > right thing, for each item (note scaffolding) yet when i reurn the > whole list i just get the last pair repeated over and over. > > I am not sure why this is. > > > def pack(in_seq): > out_list=[] > x = 1 > ll=[1, 1] > for each in in_seq: > ll[0] = x > ll[1] = each > out_list.append(ll) > #print ll > x = x + 1 > print out_list > > > # function declarations would go here > def test(): > """test function - say what this does here and skip a line > > Keyword arguments: > none > """ > > print > foo = minus(200) > plot_me = pack(foo) > #print foo > print > print plot_me > > > if __name__ == "__main__": > test() > > > >
> Your specific problem is that you're not building new lists, you're just reusing the same one each time through the loop. The most brute-force fix for the problem is to use the slice operator to make a copy of the list before appending it to the outer list. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll[:]) #make a copy of ll, and append that copy #print ll x = x + 1 print out_list pack(in_seq) #But that's not efficient. Better would be to construct a new list each time (and I'm going to avoid using variables that look like numbers): def pack(in_seq): out_list=[] x = 1 for each in in_seq: item = [x, each] out_list.append(item) #print ll x = x + 1 print out_list pack(in_seq) #or even: def pack(in_seq): out_list=[] x = 1 for each in in_seq: out_list.append( [x, each] ) #print ll x = x + 1 print out_list pack(in_seq) #Note that there's a useful function enumerate which could help here: def pack(in_seq): out_list=[] for x, each in enumerate(in_seq): item = [x+1, each] #(too bad you want your integers to start at 1; Python likes zero-based out_list.append(item) #print ll print out_list pack(in_seq) #and that could be simplified further def pack(in_seq): out_list=[] for item in enumerate(in_seq): item = list(item) #turn the tuple into a list item[0] += 1 #because you're 1-based instead of zero-based out_list.append(item) #print ll print out_list pack(in_seq) #and one more step, using zip() to combine two lists def pack(in_seq): out_list = zip(xrange(1, 1+len(in_seq)), in_seq) print out_list pack(in_seq) HTH DaveA From jeffpeery at yahoo.com Fri Aug 28 17:21:55 2009 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri, 28 Aug 2009 08:21:55 -0700 (PDT) Subject: [Tutor] thread causes idle to crash In-Reply-To: <1c2a2c590908270400m7c63b834i4458bc45628f7796@mail.gmail.com> Message-ID: <979424.60936.qm@web43143.mail.sp1.yahoo.com> hello, I've been working on threads and queues and I think I have it working well. The problem seems to be that when I run a thread via the IDLE it crashes. if I simply double click the file it appears to run ok. I'm not sure if I'm doing something incorrectly or not. it seems pretty straight forward. my sample code is listed below. I'm using Python 2.6.2, and I'm running on Microsoft Vista. Any thoughts would be much appreciated. thanks! Jeff ? import threading import Queue import time, random WORKERS = 2 ? class Worker(threading.Thread): ??? def __init__(self, queue): ??????? self.__queue = queue ??????? threading.Thread.__init__(self) ??? def run(self): ??????? while 1: ??????????? item = self.__queue.get() ??????????? if item is None: ??????????????? break # reached end of queue ??????????? # pretend we're doing something that takes 10-100 ms ??????????? time.sleep(random.randint(10, 100) / 100.0) ??????????? print "task", item, "finished" # # try it queue = Queue.Queue(0) for i in range(WORKERS): ??? print 'starting' ??? Worker(queue).start() # start a worker for i in range(10): ??? print 'putting' ??? queue.put(i) for i in range(WORKERS): ??? print 'putting None' ??? queue.put(None) # add end-of-queue markers ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kp8 at mac.com Fri Aug 28 16:28:57 2009 From: kp8 at mac.com (kevin parks) Date: Fri, 28 Aug 2009 23:28:57 +0900 Subject: [Tutor] packing a list of lists In-Reply-To: References: Message-ID: <802EDE81-BE3C-4D48-AF94-394F0575F423@mac.com> Interestingly changing: out_list.append(ll) to out_list.append(list(ll)) seems to work. The part of my brain that understood why that is must have sleeping. -k On Aug 28, 2009, at 11:05 PM, i wrote: > Back to python after a long long layoff. So i am running into some > beginner's confusion... > > I am trying to plot a list of numbers in gnuplot.py. To do that I am > trying to pack the list with an index by iterating over the list so > i can get something like: > > foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] > > [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, > 8] ... ] > > So that i have x, y pairs to plot. When i print in my func i get the > right thing, for each item (note scaffolding) yet when i reurn the > whole list i just get the last pair repeated over and over. > > I am not sure why this is. > > > def pack(in_seq): > out_list=[] > x = 1 > ll=[1, 1] > for each in in_seq: > ll[0] = x > ll[1] = each > out_list.append(ll) > #print ll > x = x + 1 > print out_list > > > # function declarations would go here > def test(): > """test function - say what this does here and skip a line > > Keyword arguments: > none > """ > > print > foo = minus(200) > plot_me = pack(foo) > #print foo > print > print plot_me > > > if __name__ == "__main__": > test() > > From kp8 at mac.com Fri Aug 28 18:53:25 2009 From: kp8 at mac.com (kevin parks) Date: Sat, 29 Aug 2009 01:53:25 +0900 Subject: [Tutor] packing a list of lists In-Reply-To: <2B7AA81C577B0942A14C2B388867E2C77EDB@harry.shamirlens.co.uk> References: <2B7AA81C577B0942A14C2B388867E2C77EDB@harry.shamirlens.co.uk> Message-ID: <2E6A1BD5-CEB8-47E8-9843-B543F1C33C3F@mac.com> On Aug 29, 2009, at 12:23 AM, Michael M Mason wrote: > i wrote: >> def pack(in_seq): >> out_list=[] >> x = 1 >> ll=[1, 1] >> for each in in_seq: >> ll[0] = x >> ll[1] = each >> out_list.append(ll) >> #print ll >> x = x + 1 >> print out_list > > Variable out_list consists of list ll repeated however many times. > Each > time you change ll you're changing it everywhere it appears in > out_list. > That is, what's being appended to out_list isn't a copy of ll, it's a > pointer to ll. > > You need something like:- > > out_list.append([ll[0],ll[1]]) Right... ugh.. Totally forgot about that. Python 101. I don't know why my brain resists that idea. Every time i let python alone a while and come back to it i get bit by this. > > And you need to add a return at the end of the function, otherwise it > returns None: > > return out_list > That, of course, i know... I was messing around debugging of course. Thanks for the response. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Aug 28 19:57:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 13:57:57 -0400 Subject: [Tutor] packing a list of lists In-Reply-To: <1e53c510908280820n1d89bba1k2c743016f60b1524@mail.gmail.com> References: <1e53c510908280818j1dd180bfj3297ee62aba5158@mail.gmail.com> <1e53c510908280820n1d89bba1k2c743016f60b1524@mail.gmail.com> Message-ID: <1c2a2c590908281057t3508ef65wf9a408c2b6ec5869@mail.gmail.com> On Fri, Aug 28, 2009 at 11:20 AM, vince spicer wrote: > Or even cleaner with list comprehension > > def pack(foo): > ??? return [x for x in enumerate(foo, 1)] Or just list(enumerate(foo, 1)) For Python 2.5 use [ [i+1, x] for i, x in enumerate(foo) ] Kent From kent37 at tds.net Fri Aug 28 20:39:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 14:39:37 -0400 Subject: [Tutor] packing a list of lists In-Reply-To: <802EDE81-BE3C-4D48-AF94-394F0575F423@mac.com> References: <802EDE81-BE3C-4D48-AF94-394F0575F423@mac.com> Message-ID: <1c2a2c590908281139q3d22d7feud8c4497917f3c792@mail.gmail.com> On Fri, Aug 28, 2009 at 10:28 AM, kevin parks wrote: > Interestingly changing: > ? ? ? ? ? ? ? ?out_list.append(ll) > > to > > ? ? ? ? ? ? ? ?out_list.append(list(ll)) > > > seems to work. The part of my brain that understood why that is must have > sleeping. Because it makes a new list instead of appending many references to the same list. Kent From zstumgoren at gmail.com Fri Aug 28 21:20:26 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 28 Aug 2009 15:20:26 -0400 Subject: [Tutor] flyweight pattern using Mixin vs. Inheritance In-Reply-To: References: Message-ID: I was able to resolve the error by explicitly naming the class in the dictionary lookup inside __new__: if candid in CandidateAuto.instances: return candid I'm curious why this is necessary though. From our earlier dicussions (and from other reading), I thought that by declaring a static class attribute, that it would automatically become available to an instances of that class. My impression was that that a method searches for the variables/attributes in it's local scope, and failing to find it there, would bubble up to the class level and find the static variable there. Is that not correct? From eduardo.susan at gmail.com Fri Aug 28 21:37:37 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 28 Aug 2009 13:37:37 -0600 Subject: [Tutor] Making sense of "'python' is not recognized as an internal or external command... Message-ID: <9356b9f30908281237s666f899bs3199a7ddb310ff80@mail.gmail.com> Hello, list. Sorry, for this basic question. But why in Windows (XP) command prompt I get this message if, for example I type "python myscript.py"? But it works if I simply type myscript.py? Maybe by getting an answer for this question I could know how to make commands "grep, diff" work from any folder, and not have to type the full path for them or start in their folder...-- I have GnuWin32 utilities installed in my c:\Program Files. Thanks, Eduardo From dirk at pensiun.com Fri Aug 28 22:30:40 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Fri, 28 Aug 2009 22:30:40 +0200 Subject: [Tutor] Running two applications at once Message-ID: <4A983E70.9080505@pensiun.com> hi, I'm new to python, and I'm starting with Python 3.1 directly. I have been learning python for about 2 weeks now. And I have few questions. Is it possible if I run two applications at once? For example, if I make a clock/timer application with alarm etc, then I want exercise with my python, creating other codes, and running it. Is it possible? If I can make the application as stand-alone application (executeable EXE file - I'm using Windows XP), then there should be no problem. But as far that I know, py2exe doesnt support python version 3 yet. Does anyone know anyway to convert python to exe for python 3.1? Thank you. Dirk From damontimm at gmail.com Fri Aug 28 23:10:16 2009 From: damontimm at gmail.com (Damon Timm) Date: Fri, 28 Aug 2009 17:10:16 -0400 Subject: [Tutor] Store Class in Tuple Before Defining it ... Message-ID: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> Hi - I would like to have a tuple that holds information, as such: VIDEO_TYPES = ( (SyncYoutube, re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), ) From damontimm at gmail.com Fri Aug 28 23:21:00 2009 From: damontimm at gmail.com (Damon Timm) Date: Fri, 28 Aug 2009 17:21:00 -0400 Subject: [Tutor] Store Class in Tuple Before Defining it ... In-Reply-To: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> References: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> Message-ID: <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> Sorry for the double post! Went off by mistake before I was done ... Anyhow, I would like to have a tuple defined at the beginning of my code that includes classes *before* they are defined ... as such (this is on-the-fly-hack-code just for demonstrating my question): VIDEO_TYPES = ( (SyncYoutube, re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), (SyncVimeo, re.compile(#more regex here#),), (SyncBlip, re.compile(#more regex here#),), ) class Video(object): url = "http://youtube.com/xxxx" #variables ... def sync(self): for videotype in VIDEO_TYPES: #check the url against the regex, # if it matches then initiate the appropriate class and pass it the current "self" object sync = videotype[0](self).sync() class SyncYoutube(object): def __init__(self,video): self.video = video def sync(self): #do some custom Youtube syncing here class SyncBlip(object): #etc This way, I can get any video object and simply run Video.sync() and it will figure out which "sync" to run. However, I am finding (of course) that I can't reference a class that hasn't been defined! I know this is a rush-job question, but I am hoping someone seems my quandary and maybe has a way around it. I am learning python as we speak! Thanks! And sorry for the double post. Damon On Fri, Aug 28, 2009 at 5:10 PM, Damon Timm wrote: > Hi - > > I would like to have a tuple that holds information, as such: > > VIDEO_TYPES = ( > ? ?(SyncYoutube, > re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), > > ) > From dirk at pensiun.com Fri Aug 28 18:30:20 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Fri, 28 Aug 2009 18:30:20 +0200 Subject: [Tutor] Running two applications at once Message-ID: <4A98061C.2080402@pensiun.com> hi, I'm new to python, and I'm starting with Python 3.1 directly. I have been learning python for about 2 weeks now. And I have few questions. Is it possible if I run two applications at once? For example, if I make a clock/timer application with alarm etc, then I want exercise with my python, creating other codes, and running it. Is it possible? If I can make the application as stand-alone application (executeable EXE file - I'm using Windows XP), then there should be no problem. But as far that I know, py2exe doesnt support python version 3 yet. Does anyone know anyway to convert python to exe for python 3.1? Thank you. Dirk From marc at marcd.org Fri Aug 28 21:00:17 2009 From: marc at marcd.org (Marc) Date: Fri, 28 Aug 2009 15:00:17 -0400 Subject: [Tutor] Sending an email alert Message-ID: <000001ca2811$cb320b10$61962130$@org> Hello, I am trying to code an email alert and am running into the following error: Connecting to server Traceback (most recent call last): File "C:\Users\Marc1\Documents\Python\email test\email.py", line 1, in import smtplib File "C:\Python26\lib\smtplib.py", line 46, in import email.utils File "C:\Users\Marc1\Documents\Python\email test\email.py", line 12, in s = smtplib.SMTP('smtp.marcd.org') AttributeError: 'module' object has no attribute 'SMTP' The code I am trying to use is: import smtplib import time >From ="me at mydomain.org" To = ["me at mydomain.org"] Date = time.ctime(time.time()) Subject = "Email Python Test" Text = "It Works!!" mMessage = ('From %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To, Date, Subject, Text)) print 'Connecting to server' s = smtplib.SMTP('smtp.mydomain.org') rCode = s.sendmail(From, To, mMessage) s.quit() if rCode: print 'Error sending message' else: print 'message sent' Of course, I am substituting me at mydoamin.org with my email address and 'smtp.mydomain.org' with my domain email server. The error seems to say that the method or function SMTP does not exist within smtplib, but if I run the lines import smtplib s = smtplib.SMTP('smtp.mydomain.org') in IDLE, it connects and then times out, as I would expect. I tried this on Windows and Linux with the same result. Thanks, Marc What am I missing here? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 29 00:32:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Aug 2009 23:32:47 +0100 Subject: [Tutor] Running two applications at once References: <4A98061C.2080402@pensiun.com> Message-ID: "Dirk Wangsadirdja" wrote > Is it possible if I run two applications at once? Yes, you just run two instances of the python interpreter. They will happuily run independantly of one another or communicate with each other as you wish. Its exactly the same as with Java or Visual Basic or any other interpreter. > If I can make the application as stand-alone application (executeable > EXE file - I'm using Windows XP), then there should be no problem. But > as far that I know, py2exe doesnt support python version 3 yet. You don;t nered py2exe just run the two scripts, windows XP will start two copies of python based on the .py extension. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From alan.gauld at btinternet.com Sat Aug 29 00:40:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Aug 2009 23:40:09 +0100 Subject: [Tutor] Making sense of "'python' is not recognized as an internalor external command... References: <9356b9f30908281237s666f899bs3199a7ddb310ff80@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote > Hello, list. Sorry, for this basic question. But why in Windows (XP) > command prompt I get this message if, for example I type "python > myscript.py"? But it works if I simply type myscript.py? In the latter case Windows usees a registry setting to pick up what program to use. In the first case it looks for python in its PATH. (Notice this is different to PYTHONPATH!) Unfortunately the Windows installer no longer automatically adds Python to your PATH you have to do this yourself. To check that this works you can do it from a command window by typing SET PATH %PATH%;C:\Program Files\Python26 Or whatever the actual path to your python is. After typing that you should find you can type Python from anywhere on your PC and it will work. If that solves the problem you now need to add it to the envirtonment variables so that it is set every time. This is done via MyComputer->Properties->Advanced->Environment Variables Select Path and click Edit Be very careful not to accidentally delete the existing path! add your Python folder to the end of the existing path separating it with a semi-colon. That should work! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ballerz4ishi at sbcglobal.net Sat Aug 29 01:02:36 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Fri, 28 Aug 2009 16:02:36 -0700 (PDT) Subject: [Tutor] Using my own corpus with NLTK Message-ID: <708972.77013.qm@web83307.mail.sp1.yahoo.com> Hi, Thanks for your response. I tried this and got to the 3rd line. However, when I type in the fourth: >>> wordlists.fileids() a blank comes as a result. When I try the len() function it only counts the letters in title of the text document IM50re.txt. How do I get it to open and analyze the text, as they have done with the Gutenberg texts at the beginning of the chapter? Or more generally, how does one import a .txt document to analyze in Python? I have downloaded the packages to analyze my data with in Python. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Sat Aug 29 01:13:01 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 28 Aug 2009 19:13:01 -0400 Subject: [Tutor] flyweight pattern using Mixin vs. Inheritance In-Reply-To: <755528.88118.qm@web86704.mail.ird.yahoo.com> References: <755528.88118.qm@web86704.mail.ird.yahoo.com> Message-ID: >>>> class A: > instances = {} > def __new__(self,ID): > if ID in self.instances: > return self.instances[ID] > else: > self.instances[ID] = self > return self > def __init__(self, ID): > if ID not in self.instances: > print("unregistered instance!") > def __del__(self): > del(self.instances[self.ID]) > Aha! I should have done some tweaking. Many thanks as always! From kent37 at tds.net Sat Aug 29 01:24:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 19:24:19 -0400 Subject: [Tutor] NLTK In-Reply-To: <495894.92452.qm@web83308.mail.sp1.yahoo.com> References: <260156.69098.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908280449m6e27e28bxae99402cff5a0d4e@mail.gmail.com> <495894.92452.qm@web83308.mail.sp1.yahoo.com> Message-ID: <1c2a2c590908281624k2695269budf03950a7d5766c9@mail.gmail.com> On Fri, Aug 28, 2009 at 6:09 PM, Ishan Puri wrote: > Hi, > ??? Thanks for your response. I tried this and got to the 3rd line. However, > when I type in the fourth: > >>>> wordlists.fileids() > > a blank comes as a result. When I try the len() function it only counts the > letters in title of the > text document IM50re.txt. How do I get it to open and analyze the text, as > they have done > with the Gutenberg texts at the beginning of the chapter? Did you give the correct path to your files? How did you use len()? It helps if you show what you tried and what result you got. Please Reply All to reply to the list. Kent > ??? ??? Thank you. > > > > ________________________________ > From: Kent Johnson > To: Ishan Puri > Cc: Python Tutor > Sent: Friday, August 28, 2009 4:49:40 AM > Subject: Re: [Tutor] NLTK > > On Fri, Aug 28, 2009 at 3:14 AM, Ishan Puri > wrote: >> Hello, >> ??? I have successfully downloaded NLTK and the toy grammars. I want to >> run >> a few of the packages that come with NLTK on corpora that I have. How do I >> do this? What commands would I use? The corpora are text files; should I >> put >> them in the Python25 folder (is that the so called same directory)? > > The section Loading your own Corpus in the book seems to show what you want: > http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html > > Kent > From ballerz4ishi at sbcglobal.net Sat Aug 29 01:29:27 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Fri, 28 Aug 2009 16:29:27 -0700 (PDT) Subject: [Tutor] NLTK In-Reply-To: <1c2a2c590908281624k2695269budf03950a7d5766c9@mail.gmail.com> References: <260156.69098.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908280449m6e27e28bxae99402cff5a0d4e@mail.gmail.com> <495894.92452.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908281624k2695269budf03950a7d5766c9@mail.gmail.com> Message-ID: <593907.56413.qm@web83305.mail.sp1.yahoo.com> Hi, >>> from nltk.corpus import PlaintextCorpusReader >>> corpus_root='C:\Users\Ishan\Documents' >>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>> wordlists.fileids() ['IM50re.txt'] This is the result I get. I was wondering how I can use the packages on IM50re.txt? I followed successfully the steps detailed under Using Your Own Corpus. What do I do next, say, if I wanted to use the lemmatizer on this .txt document? Thank you. ________________________________ From: Kent Johnson To: Ishan Puri Cc: *tutor python Sent: Friday, August 28, 2009 4:24:19 PM Subject: Re: [Tutor] NLTK On Fri, Aug 28, 2009 at 6:09 PM, Ishan Puri wrote: > Hi, > Thanks for your response. I tried this and got to the 3rd line. However, > when I type in the fourth: > >>>> wordlists.fileids() > > a blank comes as a result. When I try the len() function it only counts the > letters in title of the > text document IM50re.txt. How do I get it to open and analyze the text, as > they have done > with the Gutenberg texts at the beginning of the chapter? Did you give the correct path to your files? How did you use len()? It helps if you show what you tried and what result you got. Please Reply All to reply to the list. Kent > Thank you. > > > > ________________________________ > From: Kent Johnson > To: Ishan Puri > Cc: Python Tutor > Sent: Friday, August 28, 2009 4:49:40 AM > Subject: Re: [Tutor] NLTK > > On Fri, Aug 28, 2009 at 3:14 AM, Ishan Puri > wrote: >> Hello, >> I have successfully downloaded NLTK and the toy grammars. I want to >> run >> a few of the packages that come with NLTK on corpora that I have. How do I >> do this? What commands would I use? The corpora are text files; should I >> put >> them in the Python25 folder (is that the so called same directory)? > > The section Loading your own Corpus in the book seems to show what you want: > http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Aug 29 01:31:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 19:31:03 -0400 Subject: [Tutor] Store Class in Tuple Before Defining it ... In-Reply-To: <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> References: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> Message-ID: <1c2a2c590908281631m25879b47hfe68a26753662eac@mail.gmail.com> On Fri, Aug 28, 2009 at 5:21 PM, Damon Timm wrote: > Sorry for the double post! ?Went off by mistake before I was done ... > > Anyhow, I would like to have a tuple defined at the beginning of my > code that includes classes *before* they are defined ... as such (this > is on-the-fly-hack-code just for demonstrating my question): > > VIDEO_TYPES = ( > ? ?(SyncYoutube, > re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), > ? ?(SyncVimeo, re.compile(#more regex here#),), > ? ?(SyncBlip, re.compile(#more regex here#),), > ) > > class Video(object): > ? url = "http://youtube.com/xxxx" > ? #variables ... > > ? def sync(self): > ? ? ? for videotype in VIDEO_TYPES: > ? ? ? ? ? #check the url against the regex, > ? ? ? ? ? # if it matches then initiate the appropriate class and > pass it the current "self" object > ? ? ? ? ? sync = videotype[0](self).sync() > > class SyncYoutube(object): > ? ?def __init__(self,video): > ? ? ? self.video = video > > ? ?def sync(self): > ? ? ? ? #do some custom Youtube syncing here > > class SyncBlip(object): > ? ? #etc > > > This way, I can get any video object and simply run Video.sync() and > it will figure out which "sync" to run. ?However, I am finding (of > course) that I can't reference a class that hasn't been defined! Just move the definition of VIDEO_TYPES after the def'n of the classes it uses. Video.sync() will compile just fine, it doesn't need VIDEO_TYPES to be defined until it is executed. Kent From alan.gauld at btinternet.com Sat Aug 29 01:32:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Aug 2009 00:32:53 +0100 Subject: [Tutor] Store Class in Tuple Before Defining it ... References: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> Message-ID: "Damon Timm" wrote > Anyhow, I would like to have a tuple defined at the beginning of my > code that includes classes *before* they are defined ... as such (this > is on-the-fly-hack-code just for demonstrating my question): See another recent thread - you can't do it. What you could do is put your classes in another module and then import that module. Or you could put the tuple initialisation into a function. But its probably easiest to just move the definition to the bottom of the file... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sat Aug 29 01:36:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 19:36:23 -0400 Subject: [Tutor] Sending an email alert In-Reply-To: <000001ca2811$cb320b10$61962130$@org> References: <000001ca2811$cb320b10$61962130$@org> Message-ID: <1c2a2c590908281636q61b1d51fp2272e296f8a294b1@mail.gmail.com> On Fri, Aug 28, 2009 at 3:00 PM, Marc wrote: > Hello, > > > > I am trying to code an email alert and am running into the following error: > > Connecting to server > > Traceback (most recent call last): > > ? File "C:\Users\Marc1\Documents\Python\email test\email.py", line 1, in > > > ??? import smtplib > > ? File "C:\Python26\lib\smtplib.py", line 46, in > > ??? import email.utils > > ? File "C:\Users\Marc1\Documents\Python\email test\email.py", line 12, in > > > ??? s = smtplib.SMTP('smtp.marcd.org') > > AttributeError: 'module' object has no attribute 'SMTP' Your file 'email.py' is hiding the std lib 'email' module and this is creating a circular import and basically a mess :-) Try calling your program something else. Kent From kent37 at tds.net Sat Aug 29 04:03:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Aug 2009 22:03:15 -0400 Subject: [Tutor] NLTK In-Reply-To: <593907.56413.qm@web83305.mail.sp1.yahoo.com> References: <260156.69098.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908280449m6e27e28bxae99402cff5a0d4e@mail.gmail.com> <495894.92452.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908281624k2695269budf03950a7d5766c9@mail.gmail.com> <593907.56413.qm@web83305.mail.sp1.yahoo.com> Message-ID: <1c2a2c590908281903p6ef0836dwbcb1e22521ec3486@mail.gmail.com> On Fri, Aug 28, 2009 at 7:29 PM, Ishan Puri wrote: > Hi, >>>> from nltk.corpus import PlaintextCorpusReader >>>> corpus_root='C:\Users\Ishan\Documents' >>>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>>> wordlists.fileids() > ['IM50re.txt'] > > This is the result I get. That seems to be working then. You should be able to get a list of words with wordlists.words('IM50re.txt') > I was wondering how I can use the packages on > IM50re.txt? I followed successfully the steps detailed under Using Your Own > Corpus. What do I do next, say, if I wanted to use the lemmatizer on this > .txt document? I have no idea. Is IM50re.txt a plain text corpus? What is a package? What is a lemmatizer? I don't know anything about NLTK, I'm just good at reading manuals. You have to give me more help than that. What have you tried? Can you find an example that is similar to what you want to do? Don't assume I know what you are talking about :-) Kent From ballerz4ishi at sbcglobal.net Sat Aug 29 04:16:53 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Fri, 28 Aug 2009 19:16:53 -0700 (PDT) Subject: [Tutor] NLTK In-Reply-To: <1c2a2c590908281903p6ef0836dwbcb1e22521ec3486@mail.gmail.com> References: <260156.69098.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908280449m6e27e28bxae99402cff5a0d4e@mail.gmail.com> <495894.92452.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908281624k2695269budf03950a7d5766c9@mail.gmail.com> <593907.56413.qm@web83305.mail.sp1.yahoo.com> <1c2a2c590908281903p6ef0836dwbcb1e22521ec3486@mail.gmail.com> Message-ID: <582007.43563.qm@web83306.mail.sp1.yahoo.com> Hi, Thanks for the confirmation. IM50re.txt is a plain text corpus. Let us say that we want to count the words in this corpus. In the NLTK book, there is an example. >>> import nltk >>> nltk.corpus.gutenberg.fileids() ['austen-emma.txt', 'austen-persuasion.txt', 'austen-sense.txt', 'bible-kjv.txt', 'blake-poems.txt', 'bryant-stories.txt', 'burgess-busterbrown.txt', 'carroll-alice.txt', 'chesterton-ball.txt', 'chesterton-brown.txt', 'chesterton-thursday.txt', 'edgeworth-parents.txt', 'melville-moby_dick.txt', 'milton-paradise.txt', 'shakespeare-caesar.txt', 'shakespeare-hamlet.txt', 'shakespeare-macbeth.txt', 'whitman-leaves.txt'] These are the texts that come with NLTK. >>> emma = nltk.corpus.gutenberg.words('austen-emma.txt') >>> len(emma) 192427 So this is the number of words in a particular 'austen-emma.txt'. How would I do this with my IM50re.txt? It seems the code "nltk.corpus.gutenberg.words" is specific to some Gutenberg corpus installed with NLTK. Like this many examples are given for different analyses that can be done with NLTK. However they all seem to be specific to one of the texts above or another one already installed with NLTK. I am not sure how to apply these examples to my own corpus. Thank you. You are my own source of help right now; I have been trying to figure this out all day now. ________________________________ From: Kent Johnson To: Ishan Puri Cc: *tutor python Sent: Friday, August 28, 2009 7:03:15 PM Subject: Re: [Tutor] NLTK On Fri, Aug 28, 2009 at 7:29 PM, Ishan Puri wrote: > Hi, >>>> from nltk.corpus import PlaintextCorpusReader >>>> corpus_root='C:\Users\Ishan\Documents' >>>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>>> wordlists.fileids() > ['IM50re.txt'] > > This is the result I get. That seems to be working then. You should be able to get a list of words with wordlists.words('IM50re.txt') > I was wondering how I can use the packages on > IM50re.txt? I followed successfully the steps detailed under Using Your Own > Corpus. What do I do next, say, if I wanted to use the lemmatizer on this > .txt document? I have no idea. Is IM50re.txt a plain text corpus? What is a package? What is a lemmatizer? I don't know anything about NLTK, I'm just good at reading manuals. You have to give me more help than that. What have you tried? Can you find an example that is similar to what you want to do? Don't assume I know what you are talking about :-) Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc at marcd.org Sat Aug 29 02:37:31 2009 From: marc at marcd.org (Marc) Date: Fri, 28 Aug 2009 20:37:31 -0400 Subject: [Tutor] Sending an email alert In-Reply-To: <1c2a2c590908281636q61b1d51fp2272e296f8a294b1@mail.gmail.com> References: <000001ca2811$cb320b10$61962130$@org> <1c2a2c590908281636q61b1d51fp2272e296f8a294b1@mail.gmail.com> Message-ID: <006901ca2840$e613b670$b23b2350$@org> > On Fri, Aug 28, 2009 at 3:00 PM, Marc wrote: > > Hello, > > > > > > > > I am trying to code an email alert and am running into the following > error: > > > > ??? s = smtplib.SMTP('smtp.marcd.org') > > > > AttributeError: 'module' object has no attribute 'SMTP' > > Your file 'email.py' is hiding the std lib 'email' module and this is > creating a circular import and basically a mess :-) > > Try calling your program something else. > > Kent That did it - Thanks!! From fidellira.6 at gmail.com Sat Aug 29 04:34:03 2009 From: fidellira.6 at gmail.com (Fidel Sanchez-Bueno) Date: Fri, 28 Aug 2009 22:34:03 -0400 Subject: [Tutor] general import VS importing inside a function Message-ID: <4A98939B.5000008@gmail.com> What is the best aproach when it comes to import??, is allways better to make all the import calls in the global scope, making the overall runtime of the program better because the program is not going to import something everytime a function is called, or is better to make specific import's inside a function making the function completely portable?? here's a example: case 1: # importing in the global scope import foo variable = "somethin here" def bar(value1, value2): return value1, value2 = foo.foo Case 2: # importing inside a function variable = "somethin here" def bar(value1, value2): import foo return value1, value2 = foo.foo and another thing, making specific import, makes the program less, how you said this "RAM eater" (sorry my native language is spanish and i dont now how to translate "cosume menos recursos" google says "cosumes less resources", but anyway i hope you get it) I say this because, for example when i'm in the interactive shell and import big things like Scipy, and NumPy, python takes 3 to 5 seconds to respond, and if am only going to use like 4 or 5 function inside NumPy i think is better to say just "from Numpy import foo, bar, qux etc" but i would actually like to read this from someone that knows about programming and not just me making asumptions... salu2! From alan.gauld at btinternet.com Sat Aug 29 10:36:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Aug 2009 09:36:09 +0100 Subject: [Tutor] general import VS importing inside a function References: <4A98939B.5000008@gmail.com> Message-ID: "Fidel Sanchez-Bueno" wrote > What is the best aproach when it comes to import??, is allways better to > make all the import calls in the global scope, making the overall runtime > of the program better because the program is not going to import > something everytime a function is called, or is better to make specific > import's inside a function making the function completely portable?? The general concensus is to keep all imports together at the top of the module. I do occasionally put an import inside a function but only if a) its in an exceptioon block that I don;t expect to be used AND b) the module takes significant time to load and I care about performance Those two things don't happen very often so 99% of the time all imports go at the top. > and another thing, making specific import, makes the program less, how > you said this "RAM eater" (sorry my native language is spanish and i dont > now how to translate "cosume menos recursos" google says "cosumes less > resources", but anyway i hope you get it) Unless the module has huge data structures populated within it thats unlikely to be a significant issue. Usually the memory consumption comes from the main execution code where the data is defined not the module code. On a huge project that might be an issue but not on the average Python project. > I say this because, for example when i'm in the interactive shell and > import big things like Scipy, and NumPy, python takes 3 to 5 seconds to > respond, and if am only going to use like 4 or 5 function inside NumPy i > think is better to say just "from Numpy import foo, bar, qux etc" Thats a different question. :-) If you are only using a few names from the module the "from x imporrt y " style is good. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sat Aug 29 12:34:09 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Aug 2009 06:34:09 -0400 Subject: [Tutor] NLTK In-Reply-To: <582007.43563.qm@web83306.mail.sp1.yahoo.com> References: <260156.69098.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908280449m6e27e28bxae99402cff5a0d4e@mail.gmail.com> <495894.92452.qm@web83308.mail.sp1.yahoo.com> <1c2a2c590908281624k2695269budf03950a7d5766c9@mail.gmail.com> <593907.56413.qm@web83305.mail.sp1.yahoo.com> <1c2a2c590908281903p6ef0836dwbcb1e22521ec3486@mail.gmail.com> <582007.43563.qm@web83306.mail.sp1.yahoo.com> Message-ID: <1c2a2c590908290334r2c064978w689fc85c6d8e65d7@mail.gmail.com> On Fri, Aug 28, 2009 at 10:16 PM, Ishan Puri wrote: >>>> emma = nltk.corpus.gutenberg.words('austen-emma.txt') >>>> len(emma) > 192427 > > So this is the number of words in a particular 'austen-emma.txt'. How would > I do this > with my IM50re.txt? It > seems the code "nltk.corpus.gutenberg.words" is specific to some Gutenberg > corpus installed with NLTK. > Like this many examples are given for different analyses that can be done > with NLTK. However they all seem to be specific > to one of the texts above or another one already installed with NLTK. I am > not sure how to apply these examples to my own corpus. This is pretty much the next line in the "Loading your own Corpus" example. After >>> from nltk.corpus import PlaintextCorpusReader >>> corpus_root='C:\Users\Ishan\Documents' >>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>> wordlists.fileids() ['IM50re.txt'] you should be able to do my_words = wordlists.words('IM50re.txt') len(my_words) Kent From kent37 at tds.net Sat Aug 29 12:38:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Aug 2009 06:38:26 -0400 Subject: [Tutor] general import VS importing inside a function In-Reply-To: <4A98939B.5000008@gmail.com> References: <4A98939B.5000008@gmail.com> Message-ID: <1c2a2c590908290338h6e49b6fcy217096f824083719@mail.gmail.com> On Fri, Aug 28, 2009 at 10:34 PM, Fidel Sanchez-Bueno wrote: > What is the best aproach when it comes to import??, is allways better to > make all the import calls in the global scope, making the overall runtime of > the program better because the program is not going to import something > everytime a function is called, or is better to make specific import's > inside a function making the function completely portable?? Imports are conventionally put at the start of a module. Generally the unit of reuse in Python is a module, not a function, so you don't limit portability by putting the imports at the top of a module. > ?and another thing, making specific import, makes the program less, how you > said this "RAM eater" (sorry my native language is spanish and i dont now > how to translate "cosume menos recursos" google says "cosumes less > resources", but anyway i hope you get it) Modules are only loaded once, at the first import. The loaded modules are cached in sys.modules. So subsequent imports are fast (just a dictionary lookup) and don't consume any resources. > I say this because, for example when i'm in the interactive shell and import > big things like Scipy, and NumPy, python takes 3 to 5 seconds to respond, > and if am only going to use like 4 or 5 function inside NumPy i think is > better to say just "from Numpy import foo, bar, qux etc" but i would > actually like to read this from someone that knows about programming and not > just me making asumptions... It will take the same amount of time for the import with either style of import. It is the initial load of the module that takes time and memory. Kent From quasipedia at gmail.com Sat Aug 29 12:34:44 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 29 Aug 2009 12:34:44 +0200 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <4A9804B6.2000206@ieee.org> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> <4A97D3AA.5060109@ieee.org> <1251471967.5472.29.camel@jabbar> <4A9804B6.2000206@ieee.org> Message-ID: <1251542084.19477.2.camel@jabbar> On Fri, 2009-08-28 at 12:24 -0400, Dave Angel wrote: > > Thank you Dave, very helpful as ever. I made a few tests and experiments > > to understand better, and I feel I am understanding how it works. > > Although the mechanic of this is increasingly clear, the logic behind is > > still a bit obscure: here comes a silly test on which results I have > > questions about > > > > ====================================================== > > > > class A(object): > > variable = 0 > > @classmethod > > def cm(cls): > > cls.variable += 3 > > > > class B(A): > > pass > > > > class C(B): > > pass > > > > a = A() > > b = B() > > c = C() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > a.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > b.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > c.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > a.variable = 7 > > A.variable = 4 > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > B.variable = 'x' > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > > > ====================================================== > > > > Now, the output of this test is as follows (I manually added the numbers > > on the right for reference in the remaining of the post): > > > > 0 0 # 1 > > 0 0 > > 0 0 > > --- > > 3 3 # 2 > > 3 3 > > 3 3 > > --- > > 3 3 # 3 > > 6 6 > > 6 6 > > --- > > 3 3 # 4 > > 6 6 > > 9 9 > > --- > > 4 7 # 5 > > 6 6 > > 9 9 > > --- > > 4 7 # 6 > > x x > > 9 9 > > > > #1 is plain obvious. > > > > #2 came as a bit of surprise: "Ah-ah!... so the class variable is the > > same for all the hierarchy of classes! I would have guessed each class > > had its own variable..." > > > > #3 and #4 are bigger surprises: "Uh? let me understand better, so... it > > must be like branches... as soon as I say that B.variable is different > > than its ancestors, all the descendants of B get updated... Yet, it's > > strange: this very thread on the mailing list has started with me asking > > about the order of declaration for classes, and I have been told that > > class variables are processed as soon as the interpreter hits the class > > definition... so I would have expected that C.variable would have been > > initialised already and would not dynamically change when B.variable > > does..." > > > > #5 confused me: it seems that a.variable can refer to both the class > > variable or a newly created object property... that sounds like a > > never-ending source of bugs to me: it is me who has then to remember if > > a given syntax refers to a class variable or to an object method? > > > > #6 really make no sense to me: it seems that the class variable of C has > > not been changed this time (as it did in #3)... > > > > The points above confuse me even more about the "design purposes" of > > classmethods and staticmethods... > > > > Any help/feedback, very much appreciated. > > > > mac. > > > > > > > Great questions. I love a person who is organized as you are. And as > willing to learn. > > #3 and #4 - First let me point out that these are not class variables, > but class attributes. It's unfortunate that you called the attributes > with the label 'variable'. I frequently make the same mistake (call it > sloppy mistake), but it might matter somewhere in the following > discussion. A class variable is simply a "variable" which references > the class. Think of it as an alias for the class. Just like a list > variable is a variable which references a list. If you do: > newclass = A > > then you can use newclass in exactly the same way as A. a = > newclass(), print newclass.variable, etc. > > A class attribute, on the other hand, is what other languages would call > a field of the class. And it definitely does get initialized when the > class is executed. That's important in the earlier discussion because > the *right-hand-side* has to be valid at that time, which is why you had > the forward referencing problem. So in the following code: > > n = 12 > class A(object): > attr = n > > n = 42 > > > the attribute A.attr is a reference to 12, not 42. The confusion in > this #3 and #4 case is that when some later expression tries to use a > particular class attribute there are some rules for lookup. I don't > know the correct terminology, but I think of this as the "." operator. > When I say C.variable, the first search is in the classes dictionary. > If it's not found there, then it searches in the parent class' > dictionary, and so on. The attribute is not copied, there's just a > search order when it's accessed. > > #5 - It's search order again (on what I call the dot operator). When > you reference c.variable, it looks first in the dictionary for the > instance object c, and then if it doesn't find it, it looks in the > parent, which is the class. And if it doesn't find it there, it again > looks in the parent, and so on. > > #6 - by this time, there is a class attribute C.variable, so changing > B.variable has no effect Probably the key thing that misleads people > is that the += operator may actually create a new attribute. That > happened when you called b.cm() and c.cm(). > > You might be helped by using help(B) before and after the call to > b.cm(). It says a lot that you might not care about, but it makes clear > what attribute are "defined here" versus "inherited from..." > > > HTH > DaveA Well, thank you a lot for the explanation. Now it makes perfectly sense and I am an happy man. :) BTW, your appreciation for good learners is totally matched by my appreciation for good teachers... thank you again! :) Mac. From quasipedia at gmail.com Sat Aug 29 12:58:05 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 29 Aug 2009 12:58:05 +0200 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> Message-ID: <1251543485.19477.25.camel@jabbar> On Fri, 2009-08-28 at 18:03 +0100, Alan Gauld wrote: > "Mac Ryan" wrote > > > I am not sure I understood the difference between staticmethod end > > classmethod, though, even if I can guess it has to do with subclassing, > > I think it is mainly historical. staticmethod came first (I think) and > classmethod > was an improvement a couple of versions later. I think classmethod is the > preferred choice nowadays. > > > Also, what is the advantage of using a method at class level rather than > > using it at object instance > > There are two common cases: > > 1) You want to do something at the class level rather than instance > level - such as find all instances, or keep a count of all instances. > Or you may have a method or variable that affects all instances > simultaneously - perhaps activates or disables all network connections > say. > > 2) You want somethig that can be done without creating an instance, > or at least does not depend on whether any instances exist yet. This > is very common in Java which doesn't support standalone functions > but is not needed so much in Python because a module function is > usually a better option. > > You can also use it to provide meta-class programming features > and other tricks, but frankly thats usually being too clever for your > own good! :-) > > HTH, Thank you Alan, that totally answer my question about classmethods. :) What is still unclear to me, is what the staticmethods are for, though: since the reference to the object instance or to the class object are stripped away from the call, I wonder why not to use a module function instead. The only difference I can think of between the two (static method and module function) is that the namespaces they "live in" are different (mymodule.function vs. mymodule.myclass.function)... but I suspect there must be a better and more important design reason to have them implemented in the core... Many thanks in advance for your help, Mac. From alan.gauld at btinternet.com Sat Aug 29 13:44:02 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 29 Aug 2009 11:44:02 +0000 (GMT) Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251543485.19477.25.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> <1251543485.19477.25.camel@jabbar> Message-ID: <399066.83253.qm@web86702.mail.ird.yahoo.com> > What is still unclear to me, is what the staticmethods are for, though: > since the reference to the object instance or to the class object are > stripped away from the call, I wonder why not to use a module function > instead. First recall that xsstatic methods were historically the first attempt at giving Python class methods. (They were called staticmethods because C++ and Java define their class methods using the label 'static' ) The static method is still inside the class so it provides namespace protection. Thus if we want to create a search class method in each of three classes within the same module we can do so, whereas a module function would need to take the class as an input parameter and probably then do a if/else type switch statement to manipulate/access the class attributes etc. Or you write 3 functions, one per class. Neither is very OO in approach. But a classmethod would be equally suitable, if not better. > The only difference I can think of between the two (static method and > module function) is that the namespaces they "live in" are different And that is significant. Alan G From lie.1296 at gmail.com Sat Aug 29 14:05:39 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 29 Aug 2009 22:05:39 +1000 Subject: [Tutor] Store Class in Tuple Before Defining it ... In-Reply-To: <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> References: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> Message-ID: Damon Timm wrote: > Sorry for the double post! Went off by mistake before I was done ... > > Anyhow, I would like to have a tuple defined at the beginning of my > code that includes classes *before* they are defined ... as such (this > is on-the-fly-hack-code just for demonstrating my question): > What you want to do can be done with a helper function (e.g. Sync.find_sync() below), but I smelled a bad class design. Anyway, here is how you would do it... class Video(object): url = '...' def sync(self): sync = Sync.find_sync(self.url) class Sync(object): class NoSuitableSync(Exception): pass @staticmethod def find_sync(url): for S in Sync.__subclasses__(): if S.RE.match(url): return S(url) raise Sync.NoSuitableSync() class SyncYoutube(Sync): RE = re.compile(r'some regex here') class SyncBlip(Sync): RE = re.compile(r'other regex here') what I suggest you could do: class Video(object): # Video is a mixin class def __init__(self, url): self.url = url def sync(self): # source agnostic sync-ing or just undefined pass @staticmethod def find_video(url): for sc in Video.__subclasses__(): if sc.RE.match(url) return sc(url) class Youtube(Video): RE = re.compile('... some regex here ...') def sync(self): # costum sync-ing pass class Blip(Video): RE = re.compile('... other regex here ...') def sync(self): # costum sync-ing pass a = Video.find_video('http://www.youtube.com/xxxx') that way, url detection will only happen on class initialization instead of every time sync is called. From fidellira.6 at gmail.com Sat Aug 29 13:38:57 2009 From: fidellira.6 at gmail.com (Fidel Sanchez-Bueno) Date: Sat, 29 Aug 2009 07:38:57 -0400 Subject: [Tutor] general import VS importing inside a function In-Reply-To: <1c2a2c590908290338h6e49b6fcy217096f824083719@mail.gmail.com> References: <4A98939B.5000008@gmail.com> <1c2a2c590908290338h6e49b6fcy217096f824083719@mail.gmail.com> Message-ID: <4A991351.2080309@gmail.com> thanks both (Alan and Kent)! now am clear about the right way of making import.. salu2.. From quasipedia at gmail.com Sat Aug 29 15:00:18 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 29 Aug 2009 15:00:18 +0200 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <399066.83253.qm@web86702.mail.ird.yahoo.com> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> <4A95E246.7090105@ieee.org> <1251460029.11653.59.camel@jabbar> <1251543485.19477.25.camel@jabbar> <399066.83253.qm@web86702.mail.ird.yahoo.com> Message-ID: <1251550818.31433.2.camel@jabbar> On Sat, 2009-08-29 at 11:44 +0000, ALAN GAULD wrote: > First recall that xsstatic methods were historically the first attempt at > giving Python class methods. (They were called staticmethods because > C++ and Java define their class methods using the label 'static' ) > ... > > The only difference I can think of between the two (static method and > > module function) is that the namespaces they "live in" are different > > And that is significant. > > Alan G Ok, now I am an happy man. :) Thank you for your time! Mac. From prasadaraon50 at gmail.com Sat Aug 29 15:02:14 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 29 Aug 2009 18:32:14 +0530 Subject: [Tutor] How to convert binary files back to text files? Message-ID: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> Hello! I want to convert compiled files to text files. I believe compiled files are binary files. I am able to convert a given string to binary and back to text. But when it comes to a file it is proving to be impossible. def p(a): s=open(a,'rb') for x in s: d=map(lambda y:chr(int(y,2)),x) print d s.close() >>> p("C:/pp.txt") Traceback (most recent call last): File "", line 1, in p("C:/pp.txt") File "", line 5, in p d=map(lambda y:chr(int(y,2)),x) File "", line 5, in d=map(lambda y:chr(int(y,2)),x) ValueError: invalid literal for int() with base 2: 'f' Please some one point where the problem is. -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Sat Aug 29 15:12:54 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 29 Aug 2009 18:42:54 +0530 Subject: [Tutor] How to convert binary files back to text files? In-Reply-To: <200908291302.n7TD2UbF005698@tlgmlp01.teamlog.com> References: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> <200908291302.n7TD2UbF005698@tlgmlp01.teamlog.com> Message-ID: <9e3fac840908290612o75998ee4gab46c1e93f6464c6@mail.gmail.com> >On 8/29/09, Genevi?ve DIAGORN wrote: > > >Bonjour, > >Je suis absente jusqu'au 02/09 inclus. > >En cas d'urgence Soprane, contacter notre adresse g?n?rique > >projet.soprane at teamlog.com. > >Cordialement. > > >Genevi?ve I dont know your language.Please communicate in English. I am using the code below to conver string to bin and back. def tobin(astr): z=map(lambda x: bin(ord(x)),astr) return z def tostring(blist): z=map(lambda x: chr(int(x,2)),l) return ''.join(z) I dont believe it is impossible on files. -------------- next part -------------- An HTML attachment was scrubbed... URL: From damontimm at gmail.com Sat Aug 29 15:14:18 2009 From: damontimm at gmail.com (Damon Timm) Date: Sat, 29 Aug 2009 09:14:18 -0400 Subject: [Tutor] Store Class in Tuple Before Defining it ... In-Reply-To: References: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> Message-ID: <262679b50908290614w9f17a56t4172773bf2a86149@mail.gmail.com> Hi Everyone - thanks for your responses. Answered my direct questions: [1] can't be done at the top and [2] would have to move the tuple somewhere else as well as gave me some new ideas about completely rethinking the design ... I love keeping the RE definitions with the child classes ... makes it easy just to add a child anywhere without having to fool with the original code. One of my issues has been fixed using the @staticmethod decorator (which I did not know about). Here is what I have now, and my final question (perhaps) follows. #### #this is a django app, by the way class Video(models.Model): url = models.URLField('Video URL') # more fields and functions here def sync(self): 'Update videos external data - for children only' pass @staticmethod def add_video(url): 'add a video only if it matches correct regex -- need ExceptionHandler' for sc in Video.__subclasses__(): if sc.RE.match(url): return sc(url=url) class YoutubeVideo(Video): RE = re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*') def sync(self): # do custom syncing here print "am syncing a YOUTUBE video" class ViemoVideo(Video): RE = re.compile(r'([^(]|^)http://(www.|)vimeo\.com/(?P\d+)\S*') def sync(self): # do custom syncing here print "am syncing a VIMEO video" ############## So, this is *great* because now I can "add_video" without knowing the video url type at all. >>> v = Video.add_video(url="http://www.youtube.com/watch?v=UtEg3EQwN9A") >>> v >>> Perfect! The last part is figuring out the syncing -- what I would like to do would be either: >>> Video.sync_all_videos() #create another static method Or, if I had to, create another function that did a: >>> for video in Video.objects.all(): # object.all() is a django function that returns everything ... video.sync() However, I am not sure how to determine the "actual" class of a video when I am dealing only with the parent. That is, how do I call a child's sync() function when I am dealing the parent object? As suggested (in email below) I could re-run the regex for each parent video for each sync, but that seems like it could be an expensive operation (supposing one day I had thousands of videos to deal with). Is there another easy way to find the "real" class of an object when dealing with the parent? I know so little, I have to think there might be something (like the @staticmethod decorator!). Thanks again! Damon On Sat, Aug 29, 2009 at 8:05 AM, Lie Ryan wrote: > what I suggest you could do: > > class Video(object): > ? ?# Video is a mixin class > ? ?def __init__(self, url): > ? ? ? ?self.url = url > ? ?def sync(self): > ? ? ? ?# source agnostic sync-ing or just undefined > ? ? ? ?pass > ? ?@staticmethod > ? ?def find_video(url): > ? ? ? ?for sc in Video.__subclasses__(): > ? ? ? ? ? ?if sc.RE.match(url) > ? ? ? ? ? ? ? ?return sc(url) > class Youtube(Video): > ? ?RE = re.compile('... some regex here ...') > ? ?def sync(self): > ? ? ? ?# costum sync-ing > ? ? ? ?pass > class Blip(Video): > ? ?RE = re.compile('... other regex here ...') > ? ?def sync(self): > ? ? ? ?# costum sync-ing > ? ? ? ?pass > a = Video.find_video('http://www.youtube.com/xxxx') > > that way, url detection will only happen on class initialization instead of > every time sync is called. From quasipedia at gmail.com Sat Aug 29 17:49:34 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 29 Aug 2009 17:49:34 +0200 Subject: [Tutor] How to convert binary files back to text files? In-Reply-To: <9e3fac840908290612o75998ee4gab46c1e93f6464c6@mail.gmail.com> References: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> <200908291302.n7TD2UbF005698@tlgmlp01.teamlog.com> <9e3fac840908290612o75998ee4gab46c1e93f6464c6@mail.gmail.com> Message-ID: <1251560974.32270.26.camel@jabbar> On Sat, 2009-08-29 at 18:42 +0530, prasad rao wrote: > >On 8/29/09, Genevi?ve DIAGORN wrote: > >Bonjour, > >Je suis absente jusqu'au 02/09 inclus. > >En cas d'urgence Soprane, contacter notre adresse g?n?rique > >projet.soprane at teamlog.com. > >Cordialement. > > >Genevi?ve > > I dont know your language.Please communicate in English. The message just says the person is out of office until the second of september. Unluckily her company (which is an IT company!!!) seems to be unable to properly configure an autoresponder... Mac. From ballerz4ishi at sbcglobal.net Sat Aug 29 20:08:48 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Sat, 29 Aug 2009 11:08:48 -0700 (PDT) Subject: [Tutor] NLTK Message-ID: <912635.86063.qm@web83303.mail.sp1.yahoo.com> Hi, Yes! It works! I guess I am asking how did you know to use wordlists.words('IM50re.txt')? Is this a specific command, as I believe it was not in the book? Thanks. ________________________________ From: Kent Johnson To: Ishan Puri Cc: *tutor python Sent: Saturday, August 29, 2009 3:34:09 AM Subject: Re: [Tutor] NLTK On Fri, Aug 28, 2009 at 10:16 PM, Ishan Puri wrote: >>>> emma = nltk.corpus.gutenberg.words('austen-emma.txt') >>>> len(emma) > 192427 > > So this is the number of words in a particular 'austen-emma.txt'. How would > I do this > with my IM50re.txt? It > seems the code "nltk.corpus.gutenberg.words" is specific to some Gutenberg > corpus installed with NLTK. > Like this many examples are given for different analyses that can be done > with NLTK. However they all seem to be specific > to one of the texts above or another one already installed with NLTK. I am > not sure how to apply these examples to my own corpus. This is pretty much the next line in the "Loading your own Corpus" example. After >>> from nltk.corpus import PlaintextCorpusReader >>> corpus_root='C:\Users\Ishan\Documents' >>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>> wordlists.fileids() ['IM50re.txt'] you should be able to do my_words = wordlists.words('IM50re.txt') len(my_words) Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sat Aug 29 21:11:32 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 30 Aug 2009 05:11:32 +1000 Subject: [Tutor] Store Class in Tuple Before Defining it ... In-Reply-To: <262679b50908290614w9f17a56t4172773bf2a86149@mail.gmail.com> References: <262679b50908281410tfcc801eve465263a8580b446@mail.gmail.com> <262679b50908281421i28f124bex75ba2f00ded543e@mail.gmail.com> <262679b50908290614w9f17a56t4172773bf2a86149@mail.gmail.com> Message-ID: Damon Timm wrote: > Hi Everyone - thanks for your responses. Answered my direct questions: > > [1] can't be done at the top and actually you can, but it's opening a can of worms that I wouldn't dare to go near: VIDEO_RE = { re.compile(r'regex here'): 'Youtube', re.compile(r'regex there'): 'Vimeo', re.compile(r'regex over here'): 'Blip', ) or VIDEO_TYPES = { 'Youtube': re.compile(r'regex here'), 'Vimeo': re.compile(r'regex here'), 'Blip': re.compile(r'regex here'), } > [2] would have to move the tuple somewhere else > > as well as gave me some new ideas about completely rethinking the > design ... I love keeping the RE definitions with the child classes > ... makes it easy just to add a child anywhere without having to fool > with the original code. > > One of my issues has been fixed using the @staticmethod decorator > (which I did not know about). Here is what I have now, and my final > question (perhaps) follows. > > #### > #this is a django app, by the way > > class Video(models.Model): > url = models.URLField('Video URL') > # more fields and functions here > > def sync(self): > 'Update videos external data - for children only' > pass You may want to raise an exception or `assert False` here since Video.sync() should never be called (because children class must always override it). Alternatively, you can just not define sync so it raises AttributeError. > @staticmethod > def add_video(url): > 'add a video only if it matches correct regex -- need ExceptionHandler' > for sc in Video.__subclasses__(): > if sc.RE.match(url): > return sc(url=url) > > class YoutubeVideo(Video): > RE = re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*') > > def sync(self): > # do custom syncing here > print "am syncing a YOUTUBE video" > > class ViemoVideo(Video): > RE = re.compile(r'([^(]|^)http://(www.|)vimeo\.com/(?P\d+)\S*') > > def sync(self): > # do custom syncing here > print "am syncing a VIMEO video" > ############## > > So, this is *great* because now I can "add_video" without knowing the > video url type at all. > >>>> v = Video.add_video(url="http://www.youtube.com/watch?v=UtEg3EQwN9A") >>>> v > > > Perfect! The last part is figuring out the syncing -- what I would > like to do would be either: > >>>> Video.sync_all_videos() #create another static method > > Or, if I had to, create another function that did a: > >>>> for video in Video.objects.all(): # object.all() is a django function that returns everything > ... video.sync() > > However, I am not sure how to determine the "actual" class of a video > when I am dealing only with the parent. That is, how do I call a > child's sync() function when I am dealing the parent object? Just run v.sync(); python's object model will determine the correct .sync() to call (i.e. v.sync() will call YoutubeVideo.sync(v) if isinstance(v, YoutubeVideo); OR ViemoVideo.sync(v) if isinstance(v, ViemoVideo); etc). This is known as `polymorphism`, in OOP terms. > As > suggested (in email below) I could re-run the regex for each parent > video for each sync, but that seems like it could be an expensive > operation (supposing one day I had thousands of videos to deal with). You're on the right mindset. It's not just an expensive operation, rechecking the url type on every function calls defeats the whole purpose of OOP. Check the url type only once when you instantiate the video container class, and use polymorphism for the rest of the day. From damontimm at gmail.com Sat Aug 29 22:31:57 2009 From: damontimm at gmail.com (Damon Timm) Date: Sat, 29 Aug 2009 16:31:57 -0400 Subject: [Tutor] Initialize Class Variables by Dictionary ... Message-ID: <262679b50908291331v2be4183fu7ce602838a31f480@mail.gmail.com> Hi again - thanks for your help with my question early today (and last night). Tried searching google for this next question but can't get an answer ... here is what I would like to do (but it is not working) ... >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} >>> class Test(): ... def __init__(self): ... for key in dict: ... self.key = dict[key] ... >>> t = Test() >>> t.test1 Traceback (most recent call last): File "", line 1, in AttributeError: Test instance has no attribute 'test1' >>> t.key 'value3' Can I do what I am dreaming of ? Thanks, Damon From quasipedia at gmail.com Sat Aug 29 22:59:20 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 29 Aug 2009 22:59:20 +0200 Subject: [Tutor] Initialize Class Variables by Dictionary ... In-Reply-To: <262679b50908291331v2be4183fu7ce602838a31f480@mail.gmail.com> References: <262679b50908291331v2be4183fu7ce602838a31f480@mail.gmail.com> Message-ID: <1251579560.19679.54.camel@jabbar> On Sat, 2009-08-29 at 16:31 -0400, Damon Timm wrote: > Hi again - thanks for your help with my question early today (and last > night). Tried searching google for this next question but can't get > an answer ... here is what I would like to do (but it is not working) > ... > > >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} > >>> class Test(): > ... def __init__(self): > ... for key in dict: > ... self.key = dict[key] > ... > >>> t = Test() > >>> t.test1 > Traceback (most recent call last): > File "", line 1, in > AttributeError: Test instance has no attribute 'test1' > >>> t.key > 'value3' > > Can I do what I am dreaming of ? Yes you can, but not that way. Here is how I did on my console: >>> class A(object): ... pass ... >>> dir(A) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> setattr(A, 'test1', 'mytest') >>> dir(A) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'test1'] >>> A.test1 'mytest' So, the key here is to use the setattr() builtin function. However keep in mind that I am a python beginner, so you would probably like to hear from some real tutors before implementing this solution all over your code... Mac. From pedrooconnell at gmail.com Sat Aug 29 23:21:41 2009 From: pedrooconnell at gmail.com (pedro) Date: Sat, 29 Aug 2009 17:21:41 -0400 Subject: [Tutor] update html pages using python Message-ID: Hi, I was wondering if anyone could point me in the right direction as far as the best way to use python to update html. Specifically, I have a python script which coordinates the rendering of image sequences to disk (rendered from Nuke, the compositing program) and also automates the creation of Quicktime movies based on these sequences. Added on to the end of this program, I would like to have a function which updates a cell in a table on a webpage to change the status of the shot from "in progress" to "new version ready for review". I have a reasonable understanding of text file reading, writing and parsing, but I was wondering if there is a module or some such thing that handles this kind of thing well. Ultimately I want to set up a page with a table of thumbnail images corresponding to sequences each with their own colour coding indicating status. Thanks for any help Pete From kent37 at tds.net Sat Aug 29 23:43:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Aug 2009 17:43:00 -0400 Subject: [Tutor] NLTK In-Reply-To: <912635.86063.qm@web83303.mail.sp1.yahoo.com> References: <912635.86063.qm@web83303.mail.sp1.yahoo.com> Message-ID: <1c2a2c590908291443o15ea2696w1333de1eeab46ced@mail.gmail.com> On Sat, Aug 29, 2009 at 2:08 PM, Ishan Puri wrote: > Hi, > ??? Yes! It works! I guess I am asking how did you know to use > wordlists.words('IM50re.txt')? Is this a specific command, as I believe it > was not in the book? It is taken directly from the example in the book: >>> wordlists.fileids() ['README', 'connectives', 'propernames', 'web2', 'web2a', 'words'] >>> wordlists.words('connectives') Kent From kent37 at tds.net Sun Aug 30 00:23:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Aug 2009 18:23:47 -0400 Subject: [Tutor] How to convert binary files back to text files? In-Reply-To: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> References: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> Message-ID: <1c2a2c590908291523r6c4869f8g4d8aca149fbe6df3@mail.gmail.com> On Sat, Aug 29, 2009 at 9:02 AM, prasad rao wrote: > Hello! > ?I want to convert compiled files to text files. > > I believe compiled files are binary files. I don't understand what you are trying to do. Do you mean compiled Python files, e.g. .pyc files? Kent From damontimm at gmail.com Sun Aug 30 00:30:15 2009 From: damontimm at gmail.com (Damon Timm) Date: Sat, 29 Aug 2009 18:30:15 -0400 Subject: [Tutor] Initialize Class Variables by Dictionary ... In-Reply-To: <1251579560.19679.54.camel@jabbar> References: <262679b50908291331v2be4183fu7ce602838a31f480@mail.gmail.com> <1251579560.19679.54.camel@jabbar> Message-ID: <262679b50908291530l2c1405bdyf076b48efa940d2d@mail.gmail.com> Hey! I am a newbie too but it works for me: >>> class Test(object): ... def __init__(self,dict): ... for key in dict: ... self.__setattr__(key,dict[key]) ... >>> t = Test() >>> t.test1 'hi there' >>> t.test2 'not so much' >>> t.test3 'etc' Thanks! On Sat, Aug 29, 2009 at 4:59 PM, Mac Ryan wrote: > On Sat, 2009-08-29 at 16:31 -0400, Damon Timm wrote: >> Hi again - thanks for your help with my question early today (and last >> night). ?Tried searching google for this next question but can't get >> an answer ... here is what I would like to do (but it is not working) >> ... >> >> >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} >> >>> class Test(): >> ... ? def __init__(self): >> ... ? ? for key in dict: >> ... ? ? ? self.key = dict[key] >> ... >> >>> t = Test() >> >>> t.test1 >> Traceback (most recent call last): >> ? File "", line 1, in >> AttributeError: Test instance has no attribute 'test1' >> >>> t.key >> 'value3' >> >> Can I do what I am dreaming of ? > > Yes you can, but not that way. Here is how I did on my console: > >>>> class A(object): > ... ? pass > ... >>>> dir(A) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', > '__str__', '__subclasshook__', '__weakref__'] >>>> setattr(A, 'test1', 'mytest') >>>> dir(A) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', > '__str__', '__subclasshook__', '__weakref__', 'test1'] >>>> A.test1 > 'mytest' > > So, the key here is to use the setattr() builtin function. > > However keep in mind that I am a python beginner, so you would probably > like to hear from some real tutors before implementing this solution all > over your code... > > Mac. > > > From alan.gauld at btinternet.com Sun Aug 30 01:29:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Aug 2009 00:29:02 +0100 Subject: [Tutor] How to convert binary files back to text files? References: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> Message-ID: "prasad rao" wrote > I want to convert compiled files to text files. > I believe compiled files are binary files. If you are talking about compiled executables made from C++ for example yes. But... > I am able to convert a given string to binary and back to text. They are not just binary representations of the source code thay are translations of the C++ instruictions into the native binary codes of the target computer plus a whole bunch of housekeeping binary code that sets up the runtime environment. Decompiling a binary back to source code is incredibly difficult and even when done right the resulting code is barely recognisable compared to the original - for example a for loop may come out as a while loop - especially in C++ - and all variable names may be totally changed because the bninary doesn't need them (it uses memory addresses not names) So if thats what you are aiming for it won;t ever work. And a lot of software companies will be very happy that it won;t or lots of people would be stealing their proprietary and copyright code! > But when it comes to a file it is proving to be impossible. Yes, see above... > def p(a): > s=open(a,'rb') > for x in s: I doubt this will work for a binary file, you usually have to use read() and provide a buffer size. > d=map(lambda y:chr(int(y,2)),x) This is assuming that the binary digits are all stored in individual lines, which is not the case, they are stored consecutively with no breaks, thats wgy you need to use read() and tell it how many bytes you want to read. What you appear to be doing is the equivalent to od -a in Unix - ie dump a file in its ascii representation. It would be instructive for you to try that command if you have access to a Unix box... Try it on a text file then try it on an executable file then try it on a compiled Pyhthon module. Finally try using the dis module in Python to look at the disassembled pcode - or just read the documentation for dis... >>>> p("C:/pp.txt") OK, Now you appear to be examining a tet file as if it were binary, thats different again - and slightly more doable. Could you explain what exacvtly you are trying to do - and why? Maybe we can help? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Aug 30 01:34:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Aug 2009 00:34:15 +0100 Subject: [Tutor] update html pages using python References: Message-ID: "pedro" wrote > Hi, I was wondering if anyone could point me in the right direction as > far as the best way to use python to update html. There are a number of modules in the standard library that can help but the best known module for this is BeautifulSoup which you have to download - try Google. There are a couple of others and all of them are better than trying to do it using normal text manipulation or regex... > kind of thing well. Ultimately I want to set up a page with a table of > thumbnail images corresponding to sequences each with their own colour > coding indicating status. That should be fairly straightforward with any of the html parser modules available HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sun Aug 30 03:29:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Aug 2009 21:29:07 -0400 Subject: [Tutor] Initialize Class Variables by Dictionary ... In-Reply-To: <262679b50908291530l2c1405bdyf076b48efa940d2d@mail.gmail.com> References: <262679b50908291331v2be4183fu7ce602838a31f480@mail.gmail.com> <1251579560.19679.54.camel@jabbar> <262679b50908291530l2c1405bdyf076b48efa940d2d@mail.gmail.com> Message-ID: <1c2a2c590908291829o73ea7f35yd44e7399edd40d5b@mail.gmail.com> On Sat, Aug 29, 2009 at 6:30 PM, Damon Timm wrote: > Hey! ?I am a newbie too but it works for me: > >>>> class Test(object): > ... ? def __init__(self,dict): > ... ? ? for key in dict: > ... ? ? ? self.__setattr__(key,dict[key]) Use the setattr() builtin: setattr(self, key, dict[key]} or just def __init__(self, d): self.__dict__.update(d) BTW don't use dict as the name of a variable, it shadows the built-in of the same name. Kent From pedrooconnell at gmail.com Sun Aug 30 07:01:42 2009 From: pedrooconnell at gmail.com (pedro) Date: Sun, 30 Aug 2009 01:01:42 -0400 Subject: [Tutor] update html pages using python References: Message-ID: On 2009-08-29 19:34:15 -0400, "Alan Gauld" said: > > "pedro" wrote > >> Hi, I was wondering if anyone could point me in the right direction as >> far as the best way to use python to update html. > > There are a number of modules in the standard library that can help > but the best known module for this is BeautifulSoup which you have > to download - try Google. > > There are a couple of others and all of them are better than trying > to do it using normal text manipulation or regex... > >> kind of thing well. Ultimately I want to set up a page with a table of >> thumbnail images corresponding to sequences each with their own colour >> coding indicating status. > > That should be fairly straightforward with any of the html parser modules > available > > HTH, Hi Alan, yes it looks like BeautifulSoup should do the trick. Thanks Pete From prasadaraon50 at gmail.com Sun Aug 30 12:32:56 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sun, 30 Aug 2009 16:02:56 +0530 Subject: [Tutor] How to convert binary files back to text files? In-Reply-To: <1c2a2c590908291523r6c4869f8g4d8aca149fbe6df3@mail.gmail.com> References: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> <1c2a2c590908291523r6c4869f8g4d8aca149fbe6df3@mail.gmail.com> Message-ID: <9e3fac840908300332o253e6522p97932061ccd072fa@mail.gmail.com> > . > > >I don't understand what you are trying to do. Do you mean compiled > >Python files, e.g. .pyc files? > > ?Kent > Yes I want to examine pyc files.(ex:itertools). itertools.py is not available inPython26. pyc files are binaryfiles.Isn't it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Aug 30 14:58:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Aug 2009 08:58:24 -0400 Subject: [Tutor] How to convert binary files back to text files? In-Reply-To: <9e3fac840908300332o253e6522p97932061ccd072fa@mail.gmail.com> References: <9e3fac840908290602ya5251eet900a039cd67f9801@mail.gmail.com> <1c2a2c590908291523r6c4869f8g4d8aca149fbe6df3@mail.gmail.com> <9e3fac840908300332o253e6522p97932061ccd072fa@mail.gmail.com> Message-ID: <1c2a2c590908300558s23d14703lb23f214e79a2c1d7@mail.gmail.com> On Sun, Aug 30, 2009 at 6:32 AM, prasad rao wrote: > I want to examine pyc files.(ex:itertools). > itertools.py is not available inPython26. > pyc files are binaryfiles.Isn't it. itertools is written in C. All the Python source code is freely available for you to read. Download the entire source here: http://python.org/download/ or browse it online. The itertools source is here: http://svn.python.org/view/python/branches/release26-maint/Modules/itertoolsmodule.c?view=markup Kent From jsseabold at gmail.com Sun Aug 30 17:59:06 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Sun, 30 Aug 2009 11:59:06 -0400 Subject: [Tutor] Dealing with bitfields in Python Message-ID: Hello all, Fair warning, I didn't know what a bitfield was a few hours ago. I am working with a program via the dbus module and I am wondering if there is built-in support to deal with bitfields in Python. I query my application and it returns a bitfield 119. The bitfield "key" is NONE = 0, CAN_GO_NEXT = 1 << 0, CAN_GO_PREV = 1 << 1, CAN_PAUSE = 1 << 2, CAN_PLAY = 1 << 3, CAN_SEEK = 1 << 4, CAN_PROVIDE_METADATA = 1 << 5, CAN_HAS_TRACKLIST = 1 << 6 And a call to the method returns 119. I have gotten far enough to understand that 119 is >>> (1<<0)+(1<<1)+(1<<2)+(0<<3)+(1<<4)+(1<<5)+(1<<6) 119 119 is 01110111 as a binary byte (I'm reaching back to high school computer science here...) So I guess I understand the basics of what it's telling me, but I'd like to unpack 119 into binary, so I can read it and use the information in my program. I've adapted a code snippet that I found online to do this, but I'm wondering if there is a better way in python maybe using binascii or struct? Here is the helper function I've adapated def int_2_binary(int): const = 0x80000000 output = "" ## for each bit for i in range(1,33): ## if the bit is set, print 1 if( int & const ): output = output + "1" else: output = output + "0" ## shift the constant using right shift const = const >> 1 output = list(output) output = "".join(output[-8:]) return output As you can see const is the smallest signed 32-bit integer, and it would return a length 32 string. But I know that my bitfield will be 8-bit, I just don't know what this is in hexadecimal (?) to define const. Any pointers to do this in a better way would be appreciated. Thanks, Skipper From jsseabold at gmail.com Sun Aug 30 19:35:42 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Sun, 30 Aug 2009 13:35:42 -0400 Subject: [Tutor] Dealing with bitfields in Python In-Reply-To: References: Message-ID: On Sun, Aug 30, 2009 at 1:25 PM, Luke Paireepinart wrote: > You can just do a binary AND with your consts and your bitfield value to get > each bit. ?The values will be the actual value (2, 4, 8, etc.) but if you > use these as a boolean it won't matter. > I.E. >>>> bitfield = 119 >>>> seek = bitfield & CAN_SEEK >>>> seek > 16 >>>> if seek: > print "Hello" > Hello >>>> > if you have to have these constants defined. > The way I'd actually do it is probably without defining constants. > #unpack bitfield values > go_next, go_prev, pause, play, seek, meta, tracklist = [(1< for i in range(7)] > If you need them as booleans for some reason, > go_next, go_prev, pause, play, seek, meta, tracklist = [((1< > 0) for i in range(7)] > If this isn't what you're asking, just clarify what you meant and I'll try > to help. > HTH, > -Luke No that's perfect. It looks like I need to read up a bit more (pun not intended) on the binary AND, but I think I see what it does and I understand your example. Thanks, Skipper > On Sun, Aug 30, 2009 at 5:59 PM, Skipper Seabold > wrote: >> >> Hello all, >> >> Fair warning, I didn't know what a bitfield was a few hours ago. >> >> I am working with a program via the dbus module and I am wondering if >> there is built-in support to deal with bitfields in Python. ?I query >> my application and it returns a bitfield 119. ?The bitfield "key" is >> >> NONE ? ? ? ? ? ? ? ? ?= 0, >> CAN_GO_NEXT ? ? ? ? ? = 1 << 0, >> CAN_GO_PREV ? ? ? ? ? = 1 << 1, >> CAN_PAUSE ? ? ? ? ? ? = 1 << 2, >> CAN_PLAY ? ? ? ? ? ? ?= 1 << 3, >> CAN_SEEK ? ? ? ? ? ? ?= 1 << 4, >> CAN_PROVIDE_METADATA ?= 1 << 5, >> CAN_HAS_TRACKLIST ? ? = 1 << 6 >> >> And a call to the method returns 119. ?I have gotten far enough to >> understand that 119 is >> >> >>> (1<<0)+(1<<1)+(1<<2)+(0<<3)+(1<<4)+(1<<5)+(1<<6) >> 119 >> >> 119 is 01110111 as a binary byte (I'm reaching back to high school >> computer science here...) >> >> So I guess I understand the basics of what it's telling me, but I'd >> like to unpack 119 into binary, so I can read it and use the >> information in my program. ?I've adapted a code snippet that I found >> online to do this, but I'm wondering if there is a better way in >> python maybe using binascii or struct? >> >> Here is the helper function I've adapated >> >> def int_2_binary(int): >> ? ?const = 0x80000000 >> ? ?output = "" >> ? ?## for each bit >> ? ?for i in range(1,33): >> ? ? ? ?## if the bit is set, print 1 >> ? ? ? ?if( int & const ): >> ? ? ? ? ? ?output = output + "1" >> ? ? ? ?else: >> ? ? ? ? ? ?output = output + "0" >> ? ? ? ?## shift the constant using right shift >> ? ? ? ?const = const >> 1 >> ? ?output = list(output) >> ? ?output = "".join(output[-8:]) >> ? ?return output >> >> As you can see const is the smallest signed 32-bit integer, and it >> would return a length 32 string. ?But I know that my bitfield will be >> 8-bit, I just don't know what this is in hexadecimal (?) to define >> const. ?Any pointers to do this in a better way would be appreciated. >> >> Thanks, >> >> Skipper >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From rabidpoobear at gmail.com Sun Aug 30 19:25:18 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 30 Aug 2009 19:25:18 +0200 Subject: [Tutor] Dealing with bitfields in Python In-Reply-To: References: Message-ID: You can just do a binary AND with your consts and your bitfield value to get each bit. The values will be the actual value (2, 4, 8, etc.) but if you use these as a boolean it won't matter.I.E. >>> bitfield = 119 >>> seek = bitfield & CAN_SEEK >>> seek 16 >>> if seek: print "Hello" Hello >>> if you have to have these constants defined. The way I'd actually do it is probably without defining constants. #unpack bitfield values go_next, go_prev, pause, play, seek, meta, tracklist = [(1< 0) for i in range(7)] If this isn't what you're asking, just clarify what you meant and I'll try to help. HTH, -Luke On Sun, Aug 30, 2009 at 5:59 PM, Skipper Seabold wrote: > Hello all, > > Fair warning, I didn't know what a bitfield was a few hours ago. > > I am working with a program via the dbus module and I am wondering if > there is built-in support to deal with bitfields in Python. I query > my application and it returns a bitfield 119. The bitfield "key" is > > NONE = 0, > CAN_GO_NEXT = 1 << 0, > CAN_GO_PREV = 1 << 1, > CAN_PAUSE = 1 << 2, > CAN_PLAY = 1 << 3, > CAN_SEEK = 1 << 4, > CAN_PROVIDE_METADATA = 1 << 5, > CAN_HAS_TRACKLIST = 1 << 6 > > And a call to the method returns 119. I have gotten far enough to > understand that 119 is > > >>> (1<<0)+(1<<1)+(1<<2)+(0<<3)+(1<<4)+(1<<5)+(1<<6) > 119 > > 119 is 01110111 as a binary byte (I'm reaching back to high school > computer science here...) > > So I guess I understand the basics of what it's telling me, but I'd > like to unpack 119 into binary, so I can read it and use the > information in my program. I've adapted a code snippet that I found > online to do this, but I'm wondering if there is a better way in > python maybe using binascii or struct? > > Here is the helper function I've adapated > > def int_2_binary(int): > const = 0x80000000 > output = "" > ## for each bit > for i in range(1,33): > ## if the bit is set, print 1 > if( int & const ): > output = output + "1" > else: > output = output + "0" > ## shift the constant using right shift > const = const >> 1 > output = list(output) > output = "".join(output[-8:]) > return output > > As you can see const is the smallest signed 32-bit integer, and it > would return a length 32 string. But I know that my bitfield will be > 8-bit, I just don't know what this is in hexadecimal (?) to define > const. Any pointers to do this in a better way would be appreciated. > > Thanks, > > Skipper > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sun Aug 30 19:50:37 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 30 Aug 2009 19:50:37 +0200 Subject: [Tutor] update html pages using python In-Reply-To: References: Message-ID: Alan Gauld wrote: > "pedro" wrote >> Hi, I was wondering if anyone could point me in the right direction as >> far as the best way to use python to update html. > > There are a number of modules in the standard library that can help but > the best known module for this is BeautifulSoup I would call that statement highly exaggerated. http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ Stefan From alan.gauld at btinternet.com Sun Aug 30 19:58:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Aug 2009 18:58:09 +0100 Subject: [Tutor] Dealing with bitfields in Python References: Message-ID: "Skipper Seabold" wrote > You can just do a binary AND with your consts and your bitfield value to > get > > each bit. The values will be the actual value (2, 4, 8, etc.) but if > > you > > use these as a boolean it won't matter. > No that's perfect. It looks like I need to read up a bit more (pun > not intended) on the binary AND, but I think I see what it does and I > understand your example. You can go to the Using the OS topic in my tutorial for a quick tutoerial on how to extracts bits from a bitfield. There is a "sidebar" box entitled "Bitwise Operations and Flags" which explains the idea HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jsseabold at gmail.com Sun Aug 30 20:17:06 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Sun, 30 Aug 2009 14:17:06 -0400 Subject: [Tutor] Dealing with bitfields in Python In-Reply-To: References: Message-ID: On Sun, Aug 30, 2009 at 1:58 PM, Alan Gauld wrote: > > "Skipper Seabold" wrote > >> You can just do a binary AND with your consts and your bitfield value to >> get >> > each bit. The values will be the actual value (2, 4, 8, etc.) but if > >> > you >> > use these as a boolean it won't matter. >> No that's perfect. ?It looks like I need to read up a bit more (pun >> not intended) on the binary AND, but I think I see what it does and I >> understand your example. > > You can go to the Using the OS topic in my tutorial for a quick tutoerial > on how to extracts bits from a bitfield. There is a "sidebar" box entitled > "Bitwise Operations and Flags" which explains the idea > Thanks. Your description is (of course) as clear as day. Cheers, Skipper From kent37 at tds.net Sun Aug 30 20:29:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Aug 2009 14:29:30 -0400 Subject: [Tutor] Dealing with bitfields in Python In-Reply-To: References: Message-ID: <1c2a2c590908301129i6194d232ld049cc4a667c2bf@mail.gmail.com> On Sun, Aug 30, 2009 at 11:59 AM, Skipper Seabold wrote: > Hello all, > > Fair warning, I didn't know what a bitfield was a few hours ago. > > I am working with a program via the dbus module and I am wondering if > there is built-in support to deal with bitfields in Python. ?I query > my application and it returns a bitfield 119. ?The bitfield "key" is > > NONE ? ? ? ? ? ? ? ? ?= 0, > CAN_GO_NEXT ? ? ? ? ? = 1 << 0, > CAN_GO_PREV ? ? ? ? ? = 1 << 1, > CAN_PAUSE ? ? ? ? ? ? = 1 << 2, > CAN_PLAY ? ? ? ? ? ? ?= 1 << 3, > CAN_SEEK ? ? ? ? ? ? ?= 1 << 4, > CAN_PROVIDE_METADATA ?= 1 << 5, > CAN_HAS_TRACKLIST ? ? = 1 << 6 If you have many such fields you might be interested in Construct: http://construct.wikispaces.com/ See for example http://construct.wikispaces.com/tut-bitwise Disclaimer - I've never used Construct myself. It looks handy though... Kent From j8ooth at gmail.com Mon Aug 31 00:12:03 2009 From: j8ooth at gmail.com (j booth) Date: Sun, 30 Aug 2009 18:12:03 -0400 Subject: [Tutor] word replace Message-ID: <1afd95d30908301512y5128ab26i87b0ee481dc7bbd1@mail.gmail.com> Hello, I have been experiencing such difficulty with something that should be easy-- pretty new to programming.. Need to: (1) open a text file (2) iterate through it word by word (3) replace each word with an alternative word and close the file. **I don't know what the alternative word will be before running the script... this looks sloppy, but for brevity I'll ignore the rest of the code that is working and post the area I'm having trouble with; def exchange(): > > original = old() # 'old()' parses the txt file and iterates through > each of the words > new = syn() # the processed alternative that I want to replace the > original with > > try: > > for line in fileinput.input("test.txt",inplace=1): > line = line.replace(original, new, 1) > print line, > > > finally: > fileinput.close() > So, I'm aware that the in the definition 'exchange()' I don't actually parse the file test again.. the result is that it seems to loop the entire file everytime it replaces a word; consequently, if there is a word at in the last paragraph of the file it is also replaced anywhere proceeding that point. For example: this is a test for testing sake will give the result: this is a trial for testing sake but... this is a test for testing sake > test will give the result: this is a trial for trialing sake > trial > Any help will be greatly appreciated! I've been quite slow in figuring out this problem.. which is funny as I've been able to solve several other problems that seem as if they should be much more complicated.. thanks for the time.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Aug 31 00:58:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Aug 2009 23:58:57 +0100 Subject: [Tutor] update html pages using python References: Message-ID: "Stefan Behnel" wrote >> "pedro" wrote >>> Hi, I was wondering if anyone could point me in the right direction as >>> far as the best way to use python to update html. >> >> There are a number of modules in the standard library that can help but >> the best known module for this is BeautifulSoup > > I would call that statement highly exaggerated. > > http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ There may be a language thing at work here but by "best known module" I do not mean Beautiful Soup is the best of all known modules, rather it is the module which is most widely known of the non standard HTML packages. I stand by that. It is also, arguably, one of the easiest to use and well behaved with non compliant html - ie most web pages - and it has reasonable documentation and support. Ian B's article considers parser performance and Beautiful Soup has never claimed to be the fastest! I hope that clarifies any confusion. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Aug 31 01:07:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Aug 2009 00:07:01 +0100 Subject: [Tutor] word replace References: <1afd95d30908301512y5128ab26i87b0ee481dc7bbd1@mail.gmail.com> Message-ID: "j booth" wrote > I have been experiencing such difficulty with something that should be > easy-- pretty new to programming.. > > Need to: > (1) open a text file > (2) iterate through it word by word And here lies the first problem. Programming languages in general don't know much about words(*) (or paragraphs for that matter). They know about lines and letters(or characters). So you as programmer will have to teach OPython what you mean by a word and how to manipulate them (*)The exception is regular expressions which do have a comcept of a word. Whethjer that concept matches yours is another matter entirely! :-) > (3) replace each word with an alternative word and close the file. > > **I don't know what the alternative word will be before running the > script... We had a somewhat similar thread a few weeks ago it might be worth searching the archives. > this is a test for testing sake >> test > > will give the result: > > this is a trial for trialing sake >> trial Again Python just replaces a sequence of characters, it has no concept of a word. You might be better working with regular expressions where you can define the pattern to be replaced as a whole word only. Caveat: Regex are much harder to work with than simple strings. Be prepared for a lot of trial and error to get the patterns just right. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dirk at pensiun.com Mon Aug 31 12:40:04 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Mon, 31 Aug 2009 12:40:04 +0200 Subject: [Tutor] Displaying .jpg in Tkinter (Python 3.1) Message-ID: <4A9BA884.8060708@pensiun.com> hi, is there anyway to display a .jpg (or other type) images in Tkinter with Python 3.1? From what I read here in the forum, for Python 2.6 I could use the PIL package. But the PIL packages doesnt support Pyton 3.1 yet (from what I read on the PIL website). Are there perhaps other packages or other way to do it without using PIL? Thanks. From alan.gauld at btinternet.com Mon Aug 31 14:46:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Aug 2009 13:46:47 +0100 Subject: [Tutor] Displaying .jpg in Tkinter (Python 3.1) References: <4A9BA884.8060708@pensiun.com> Message-ID: "Dirk Wangsadirdja" wrote > is there anyway to display a .jpg (or other type) images in Tkinter with > Python 3.1? You can display a limited set of image types, including GIF and JPG in Tkinter without PIL. Several Widgets take an image including the Canvas and Text widgets. I think a label can be an image too, but am not certain. The trick is to crate an PhotoImage object from your file and insert that into the widget. To change the widget you modify the image object not the widget. See here for more info: http://effbot.org/tkinterbook/photoimage.htm HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dirk at pensiun.com Mon Aug 31 15:55:23 2009 From: dirk at pensiun.com (Dirk Wangsadirdja) Date: Mon, 31 Aug 2009 15:55:23 +0200 Subject: [Tutor] Displaying .jpg in Tkinter (Python 3.1) In-Reply-To: References: <4A9BA884.8060708@pensiun.com> Message-ID: <4A9BD64B.7020300@pensiun.com> Hi, with Tkinter, you can only display GIF and PGM/PPM images. when you try to create an PhotoImage object from another file format (JPG for example), it will give you an error. Alan Gauld wrote: > > "Dirk Wangsadirdja" wrote > >> is there anyway to display a .jpg (or other type) images in Tkinter >> with Python 3.1? > > You can display a limited set of image types, including GIF and > JPG in Tkinter without PIL. Several Widgets take an image including > the Canvas and Text widgets. I think a label can be an image too, > but am not certain. > > The trick is to crate an PhotoImage object from your file and insert that > into the widget. To change the widget you modify the image object > not the widget. > > See here for more info: > > http://effbot.org/tkinterbook/photoimage.htm > > > HTH, > >