[Tutor] i++
Hi, is there any way in Python to simply add or subtract one from a variable like i++ or i--? I don't mind doing a i = i + 1, but would prefer something more simple and faster. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i++
Danny Yoo wrote: is there any way in Python to simply add or subtract one from a variable like i++ or i--? I don't mind doing a i = i + 1, but would prefer something more simple and faster. Out of curiosity, why are you incrementing variables? Actually, it is mostly just my curiosity :) I'm designing my first major Python program (It will run a EnGarde PBEM for me). I had to make a loop to loop around 5 times and was going to use the i += 1 when I remembered range :) I did the following instead and it worked perfectly. for l in range(1,6): print l I will, eventually, be needing the i+= 1 as in the game many times I will needing to take away or add to attributes. I have attached what I got so far if you feel like taking a look, but it is probably nasty by your standards :) Thanks everyone for your answers. I'll probably have a few more questions before I finish this project. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) #!/usr/bin/env python '''This is a program to manage a PBEM EnGarde game using we=custom rules''' def mfile_read(): '''This will open the master file and load all the variables''' i = 0 try: mfile = open("./Master/mfile", "r") except: mfile = open("./Master/mfile", "w") print "File could not be opened, so I created one" i = 1 if i == 1: year = 1631 month = 8 else: year = cPickle.load(mfile) month = cPickle.load(mfile) mfile.close() return [year, month] def mfile_save(year, month): '''This will save the main variables into the master file''' mfile = open("./Master/mfile", "w") cPickle.dump(year, mfile) cPickle.dump(month, mfile) mfile.close() return def char_sheet(player, title, character, password, year, month, influence, cur_influence, sp, sl, income, funds, mid, mistress_name, mistress_sl, club, house, horses, regiment, rank, ma, appointment, strength, con, max_endurance, cur_endurance, rapier, dagger, sabre, cutlass, two_hand): """Create the text based character sheet""" path = "./character_sheets/" + character path.rstrip() cfile = open(path, "w") cfile.write("Engarde! Death with Honour\n--\n") cfile.write(player) cfile.write("\n") if title: s = title + " " + character else: s = character cfile.write(s) cfile.write("\nPassword: ") cfile.write(password) if month == 1: month = "January" elif month == 2: month = "February" elif month == 3: month = "March" elif month == 4: month = "April" elif month == 5: month = "May" elif month == 6: month = "June" elif month == 7: month = "July" elif month == 8: month = "August" elif month == 9: month = "September" elif month == 10: month = "October" elif month == 11: month = "November" elif month == 12: month = "December" s = "\n" + month + " " + str(year) cfile.write(s) s = "\n\nTotal Influence: " + str(influence) cfile.write(s) s = "\nCurrent Influence: " + str(cur_influence) cfile.write(s) s = "\nSocial Points: " + str(sp) cfile.write(s) s = "\nSocial Level: " + str(sl) cfile.write(s) s = "\n\nAllowance/Income: " + str(income) cfile.write(s) s = "\nMonth End Funds: " + str(funds) cfile.write(s) s = "\n\nMistress Name: " + mistress_name cfile.write(s) s = "\nMistress SL: " + str(mistress_sl) cfile.write(s) s = "\n\nClub: " + club cfile.write(s) s = "\nHouse: " + house cfile.write(s) s = "\nHorses: " + str(horses) cfile.write(s) s = "\n\nRegiment: " + regiment cfile.write(s) s = "\nRank: " + rank cfile.write(s) s = "\nMilitary Ability: " + str(ma) cfile.write(s) s = "\nMID: " + str(mid) cfile.write(s) s = "\nAppointment: " + appointment cfile.write(s) s = "\n\nStrength: " + str(strength) cfile.write(s) s = "\nConstitution: " + str(con) cfile.write(s) s = "\nMax Endurance: " + str(max_endurance) cfile.write(s) s = "\nCurrent Endurance: " + str(cur_endurance) cfile.write(s) s = "\nRapier: " + str(rapier) cfile.wr
Re: [Tutor] i++
Danny Yoo wrote: > > >> I have attached what I got so far if you feel like taking a look, but >> it is probably nasty by your standards :) > > Good, this is exactly what I want. Yes, there are a few things here > that you will want to learn how to fix. Let me point out one or two, > and I'm sure others here on the list can chime in too. > > # > ## within definition of char_sheet(): > > if month == 1: > month = "January" > elif month == 2: > month = "February" > elif month == 3: > month = "March" > ... > # > > Make this a separate function: the essence of this block of code is > pretty self-contained as a number-to-month-string converter. I never thought about that, I will put it into its own function. That makes sense because I may actually need to use that number-month converter in another part of the program. > There is also a much nicer way to express the code: rather than make it > conditional logic, just build a data structure that naturally expresses > the mapping from a number to a string. There are two data structures > that fit the above nicely: a "list" and a "hashtable". For the above, a > list naturally works out. > > ## > ## pseudocode > months = ["January", "February", ...] > monthName = months[monthNumeral - 1] > ## > > Do this, and that block of code reduces from twenty-four lines to about > three. Thanks, that is a great idea. Also, this will be a good exercise for me to learn about list. > I'm looking at the number of attributes you're storing as a Player. Yea, both Pychecker and pylint complained about that. > All these values "belong" together. Rather than pass them separately, > glue them together as a "structure". In Python, can we use a class to > glue things together... Okay, that makes good sense :) This should be a good exercise for OOP Programming :) > There are a few other things to discuss about in the code, but I should > let you take a look again and respond before going on. If you have more > questions, please feel free to ask the list. Thanks, I never even expected you to go through the code :) I will work at your suggestions and will get back to you if I have any problems. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Engarde program was: i++
Danny Yoo wrote: I will work at your suggestions and will get back to you if I have any problems. Good! Keep the folks on Python-Tutor up to date with your progress. Here is the code changes I made based on your suggestions: I put all the values together into a class ### class Character_stats: def __init__(self, player, title, name, password, family, sl_inf, mistress_inf, mistress2_inf, appt_inf, appt2_inf, spec_inf, sl, allowance, funds, mid, mistress_name, mistress_sl, club, house, horses, regiment, rank, ma, appointment, strength, con, cur_endurance, rapier, dagger, sabre, cutlass, two_hand): self.player = player self.title = title self.name = name self.password = password self.family = family self.sl_inf = sl_inf self.mistress_inf = mistress_inf self.mistress2_inf = mistress2_inf self.appt_inf = appt_inf self.appt2_inf = appt2_inf self.spec_inf = spec_inf self.sl = sl self.allowance = allowance self.funds = funds self.mid = mid self.mistress_name = mistress_name self.mistress_sl = mistress_sl self.club = club self.house = house self.horses = horses self.regiment = regiment self.rank = rank self.ma = ma self.appointment = appointment self.strength = strength self.con = con self.cur_endurance = cur_endurance self.rapier = rapier self.dagger = dagger self.sabre = sabre self.cutlass = cutlass self.two_hand = two_hand # There where some values I did not want saved to the character file. A couple where values that are for all characters, so I put them into their own class. ### class Master_stats: def __init__(self, year, month): self.year = year self.month = month ### There are only two values now, but that will most likely increase as I get further into the program. Lastly, I put the temporary values that I did not want saved on the sheet into their own class. # class Character_temp: def __init__(self, max_endurance): self.sp = 0 self.income = 0 self.max_endurance = max_endurance self.bribe_inf = 0 ## As you mentioned, my character save file is only a few lines long now :) ## def char_save(character): '''This saves the character to the harddrive''' path = "./characters/" + character.player cfile = open(path, "w") cPickle.dump(character, cfile) return ## With the months, I used both your suggestions. I used the list and then put it into a function. ### def month_name(monthNumeral): """Returns the month name as a string""" months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] return months[monthNumeral - 1] ### and I was able to call then function nicely by using: s = "\n" + month_name(master.month) + " " + str(master.year) cfile.write(s) -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) #!/usr/bin/env python '''This is a program to manage a PBEM EnGarde game using we=custom rules''' class Character_stats: def __init__(self, player, title, name, password, family, sl_inf, mistress_inf, mistress2_inf, appt_inf, appt2_inf, spec_inf, sl, allowance, funds, mid, mistress_name, mistress_sl, club, house, horses, regiment, rank, ma, appointment, strength, con, cur_endurance, rapier, dagger, sabre, cutlass, two_hand): self.player = player self.title = title self.name = name self.password = password self.family = family self.sl_inf = sl_inf self.mistress_inf = mistress_inf self.mistress2_inf = mistress2_inf self.appt_inf = appt_inf self.appt2_inf = appt2_inf self.spec_inf = spec_inf self.sl = sl self.allowance = allowance self.funds = funds self.mid = mid self.mistress_name = mistress_name self.mistress_sl = mistress_sl self.club = club self.house = house self.horses = horses self.regiment = regiment self.rank = rank self.ma = ma self.appointment = appointment self.strength = strength self.con = con self.cur_
Re: [Tutor] Engarde program was: i++
Danny Yoo wrote: In the context of the new Master_stats class, it makes more sense for mfile_read() to return a Master_stats object now rather than a two-tuple list. I was able to change the [year, month] to just master and it worked fine. I was also able to do master = mfile_read() and it worked fine as well. To make the code a little safer, explicitely close the file here. Oh, I forgot to add in the close; I intended to have one put in. I also noticed I forgot to put a close in for the char_sheet as well, so I added one in. I assume that it is good programming practise to close all open files when they are not needed anymore? Ok, looking at create_char() since it's one of the larger functions. The value of 's' in create_char() is mixed: at one point, it's an integer, at other instances, a string. There's a possible flow of control that doesn't make sense to me... I wrote the is_yes as follows and it seems to work fine. ### def is_yes(question): i = 0 while i == 0: s = raw_input(question) if s == 'y' or s == 'yes': return True elif s == 'n' or s == 'no': return False else: print '\nplease select y, n, yes, or no\n' ### I was also able to shrink the code down to: ### if not is_yes('Is ' + name + ' a sufficient character name?'): if is_yes('Is ' + alt_name + ' a sufficient character name?'): name = alt_name else: return ### You will probably notice a new unused class. I am starting to do the main part of the program and the first thing I need to do is read a very large text file generated from a web form. What I was thinking about doing was creating a function that reads the text form and then place all the values into variables "glued" together in a class. I can then pass that class back and use the variables when I need them. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) #!/usr/bin/env python '''This is a program to manage a PBEM EnGarde game using we=custom rules''' class Character_stats: """Character atributes""" def __init__(self, player, title, name, password, family, sl_inf, mistress_inf, mistress2_inf, appt_inf, appt2_inf, spec_inf, sl, allowance, funds, mid, mistress_name, mistress_sl, club, house, horses, regiment, rank, ma, appointment, strength, con, cur_endurance, rapier, dagger, sabre, cutlass, two_hand): self.player = player self.title = title self.name = name self.password = password self.family = family self.sl_inf = sl_inf self.mistress_inf = mistress_inf self.mistress2_inf = mistress2_inf self.appt_inf = appt_inf self.appt2_inf = appt2_inf self.spec_inf = spec_inf self.sl = sl self.allowance = allowance self.funds = funds self.mid = mid self.mistress_name = mistress_name self.mistress_sl = mistress_sl self.club = club self.house = house self.horses = horses self.regiment = regiment self.rank = rank self.ma = ma self.appointment = appointment self.strength = strength self.con = con self.cur_endurance = cur_endurance self.rapier = rapier self.dagger = dagger self.sabre = sabre self.cutlass = cutlass self.two_hand = two_hand class Master_stats: """Master variables used by all characters""" def __init__(self, year, month): self.year = year self.month = month class Character_temp: """Temperary variables used by characters""" def __init__(self, max_endurance): self.sp = 0 self.income = 0 self.max_endurance = max_endurance self.bribe_inf = 0 class turn_sheet: """Variables read from the turn sheet""" def __init__(self, character, password, lending, lend_id, shylock, appt, appt1, appt2, npc_step, npc_step1, npc_step2, join, join_inf1, join_inf2, gen_inf1, gen_inf2, concon, gen_opt1, gen_opt2, gen_opt3, week1, w1toady, w1court_extra, w1bring, w1gamble, w1bets, w1gamble_cut, w1carouse, w1bring_mistress, w1party, w1guest, week2, w2toady, w2court_extra, w2bring, w2gamble, w2bets, w2gamble_cut, w2carouse, w2bring_mistress, w2party, w2guest, week3, w3toady, w3court_extra, w3bring, w3gamble, w3bets, w3gamble_cut, w3carouse, w3bring_mistress, w3party, w3guest, week4, w4toady, w4court_extra, w4br
Re: [Tutor] Engarde program was: i++
Alan Gauld wrote: > You never change i so this is always true. > Therefore you can express that better with... Thanks for your suggestions, I put together the following based on them: ## def is_yes(question): while True: s = raw_input(question).lower() if s == 'y' or s == 'yes': return True elif s == 'n' or s == 'no': return False else: print '\nplease select y, n, yes, or no\n' #### It seems to work perfectly :) -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Engarde program was: i++
Danny Yoo wrote: > Double check the definition of mfile_read(). It has a possible type > error in terms of the values it returns back to the user. Oh, I see. I forgot to change the "if file does not exist part" when i changed the other half. I have changed it and is seems to work when there is no file. # def mfile_read(): '''This will open the master file and load all the variables''' try: mfile = open("./Master/mfile", "r") except: mfile = open("./Master/mfile", "w") mfile.close() print "File could not be opened, so I created one" master = Master_stats(1631, 8) return master master = cPickle.load(mfile) mfile.close() return master ## -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python IDE
Hi, I have been using Kdevelop so far to develop and a few bugs it inherits from Kate/Kwrite are really annoying me. It does not collapse quotes properly and there are other graphical glitches as well. Could someone suggest a few good IDE's for me to look at. I would need a IDE that haves syntax highlighting and I also really like type completion where the IDE gives you suggestions as you type. Extras like a good built in dictionary and anything else that makes coding faster or easier would be great. I also prefer a IDE that is for multiple languages, but I am willing to use a IDE that is only Python for now until those bugs get fixed in Kdevelop. Lastly, I am a Linux user, so the IDE would need to run natively on Linux. Thanks. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python IDE
Preecha Bundrikwong wrote: > Hi, > > I'm supporting John's opinion. WingIDE rocks!! I use Linux at work, > Windows & Mac at home, I notice the Python editor on Windows also hints > you the syntax as you type. Thank you everyone for your help. I'm going to try out eclipse because I have a newer computer that should not have any problem running it and many people seem to suggest it. -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Which GUI?
Hi, now that I have a very basic understanding of Python I would like to take a look at programming in a GUI. Which GUI is generally the easiest to learn? -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Bulk] Re: Which GUI?
Eric Brunson wrote: > Easiest depends on your background. I was a Mac developer back in the day, > so WXPython was easy for me. If you're a KDE programmer, then PyQT is > probably your cup of tee. Similarly, GTK programmers will probably like > PyGTK. I cannot make any statements about Tkinter, since I eschew everything > TCL related. I have not done any GUI programming at all using any GUI language. So, I'm not anything, not yet anyway :) I know I don't want to program using PyQT because of the licencing issues; I prefer something that is completely open source. I know I will eventually poke around a couple different GUI languages, but, would prefer to start with what is easiest to learn for a new programmer. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
Hi, I have been doing some research on the GUI's and noticed it is a very difficult choice to make which one to write with. It seems to be even more difficult than choosing which programming language to use. If you don't mind I have a few questions to ask about selecting the right GUI to program with. 1: I know many people suggest learning more than one programming language when writing programs and use each programming language like a tool on a toolbox. Should one also learn more than one GUI and select the correct one for each individual program? 2: How have you come to select your favourite GUI(s)? 3: Is there a GUI that is better for developing for Linux? 4: I have read that WxPython is difficult to install on Linux from a couple different sources. I have personally never found that a problem. Is this true? Is WxPython a poor choice for a Linux developer? Thank you for any help you can give me :) -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
Terry Carroll wrote: > I think it's rigged. I answered it honestly, and it suggested wxPython, > which is no surprise; I came to the same conclusion myself based on my > needs and preferences. I thought the same, it always came up with WxPython for me. This is what I meant by it being difficult to decide :) I am thinking about starting with Tkinter then trying WxPython because WxPython seems to be the most highly suggested and seems to have the best documentation and selection of software/RADs. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
Kent Johnson wrote: > BTW you eliminated PyQt because you want an open source solution but Qt > 4 and PyQt 4 are available under GPL for all supported platforms. I know that most likely everything I develop will be released under the GPL, but, I like the freedom to choose. I don't like how Qt is only open source if you release under the GPL. Unless Qt 4 will be released only under LGPL and/or GPL, no matter how you decide to release your product. I actually moved from Kubuntu using KDE to Ubuntu using Gnome when I found out about the Qt licence. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
Terry Carroll wrote: >> I think that is a good plan, Tkinter is pretty easy to learn but harder >> to use to create polished, high-function interfaces. wxPython comes with >> a lot more in the box. > > I've heard "Tkinter is easier to learn" before, and I think I would once > have agreed. But now that there's a good book on wxPython, I think > wxPython's pretty easy to learn, and is now even better documented than > Tkinter. > > As I was learning wxPython, most of my learning gotchas were noting > differences from the Tkinter approach (including terminology). I think if > I were approaching wxPython with no prior GUI knowledge, it would be > approximately as easy to learn as Tkinter. > > All this is assuming access to a copy of "wxPython in Action"; without the > book, you're back to a dearth of tutorials, and yes, Tkinter would be > easier to learn. I was thinking about finding a copy of that book, so maybe starting WxPython would be easier then and not worry about Tkinter. Is "WxPython in Action" a very good book? -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Bulk] Re: Which GUI?
Eric Brunson wrote: > Thanks for the review, I hope > it helps the original poster. Yes, defiantly. Everyone haves been a great help in choosing which GUI. My mind is much clearer now and I know what I want to do. I'm going to try and get a copy of the WxPython book and then go through some of the tutorials after to re-enforce my knowledge. I did something similar when I was first Learning Python and it worked out well. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which GUI?
Terry Carroll wrote: > I'm an avid user of my local public library, and if you're not sure you > want to shell out the bucks for it (and assuming you're in the US), I'd > suggest you do what I did: try to borrow a copy through your library. My > library did not have it, but could get it for me on inter-library loan > from another local library. http://www.worldcat.org/ shows that there are > 121 library copies in the U.S., so give it a shot. I'm a Canadian and I don't Live in a City; I live in a town. My local library is not bad for most subjects, but its programming section is fairly nasty. Not many books and most of the few books they have are worthless. We do have a inter-library exchange here as well, but I have never used it and don't know much about it. I'll take a trip to the library sometime to ask. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie
Toby Holland wrote: > I was wondering if any of you had any advice as to where I should start > in regards to learning using and programing with Python. I have wanted > to learn a program language for some time and just felt that now was > good and I have heard some great things about Python so any suggestions > would be great. I myself am a newbie and I found starting with "How to Think Like a Computer Scientist Learning with Python" as a great starter. You can find it at http://ibiblio.org/obp/thinkCS/python.php. It was very easy to read, the writer is great, I believe a high school teacher. The writer does not expect you to know any prior programming. also, best of all, it is completely free. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] aBSOLUTE BEGINNER
>> Hello all, >> I am an absolute beginner for python.currently i am working under >> mainframe technologybut getting kinda bored from it and want to >> learn a good scripting language...so chose python...please give me link >> to a pdf which is suitable for beginners. This is my favourite all time beginner book http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html. IT is in html, I don't know if you can get it in pdf. > > I don't know about pdf but many beginner resources here: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Kent > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Your friend, Scott Sent to you from a Linux computer using Kubuntu Version 7.04 (Feisty Fawn) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sorting and editing large data files
m. When I look at the dataset from which these two outputs are created the exons are not present in all transcripts. When I look at the first gene listed in the first output file the first exon ENSE1054700.1 is present in both the transcripts listed in Z:\datasets\h35GroupedDec15b.txt however the second exon in that list (ENSE1054696.4) is only found in the first of the two transcripts. as below: NEW GENE ENSG0160818.4 ENST0292338.3 ENSE1363386.1 ENSE1054698.3 ***ENSE1054700.1*** ENSE1054701.1 ENSE1054703.1 ENSE1377097.1 ENSE1376166.1 ***ENSE1054696.4 NEW TRANSCRIPT ENSG0160818.4 ENST0334588.2 ENSE1434292.1 ENSE1054698.3 ***ENSE1054700.1*** ENSE1054701.1 ENSE1054703.1 ENSE1336475.3 end of gene group Any suggestions on where I am going wrong? Scott ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Ajax classes at Foothill College
I would like to take your python class @ middlefield foothill campus. Can I sign up for the next class? When will it start? Thanks much, Scott ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Ajax classes at Foothill College
Oh, sorry about that. Rich Lovely wrote: I think you've got the wrong mailing list. This is an online "helpline" for anybody who is learning python, not a list for a specific class. On 29 January 2010 17:49, Scott Pritchard wrote: I would like to take your python class @ middlefield foothill campus. Can I sign up for the next class? When will it start? Thanks much, Scott ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Plugin system - how to manage plugin files?
On Wed, Jul 28, 2010 at 10:07 AM, Mac Ryan wrote: > Hi everybody, > > Mac, I don't know if this is exactly what you are after, but I created a poor-man's plugin system by simply putting .py files into the same directory as my app and naming them like _plugin.py Each of these .py "plugins", had to define a class named "Plugin" that had some set of expected methods and properties (ex: initialize(), run(), etc.). Then, when my app started up, it simply got a list of all the "*_plugin.py" files in the current directory, dynamically imported the files using "my_module = __import__(name)" and then I could do whatever I wanted with that module using "my_module", such as instantiate an object for each module's "Plugin" class, etc. Actually, here's a snippet of code I had lying around that I slapped together a few years ago to remind myself of how I did this. I can't promise this is 100% tested, but it should give you an idea. http://pastebin.com/UtVp6J9j Also, you might want to look at this discussion: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba8d361516403fdf/ Best of luck! -Scott ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding all IP addresses associated with a host
I'm very new to python, and my google-fu has failed to locate an answer to the following: How can I find all of the (ipv4) addresses that are currently up on a host? I realize I can call ifconfig and then munge the output with awk, but that seems messy, and before I tried that I though I would ask around. To give a bit more information, I'm writing a script that will use the ip address assigned to the wifi interface to determine location (this is on a Mac) and then mount network drives appropriate to the location. If anyone has a better idea how to do this, I'd be happy to hear them. Thanks in advance! Scott Newton ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding all IP addresses associated with a host
Thanks, not sure how I missed that one. -Scott On Thu, Apr 9, 2009 at 7:25 PM, Emile van Sebille wrote: > Scott Newton wrote: > >> I'm very new to python, and my google-fu has failed to locate an answer to >> the following: >> >> How can I find all of the (ipv4) addresses that are currently up on a >> host? >> > > > In google I searched for "python what's my ip" and about the fourth entry > down found a link that led me to http://pypi.python.org/pypi/netifaces/0.3 > > How far does that get you? > > HTH, > > Emile > > > > >> I realize I can call ifconfig and then munge the output with awk, but that >> seems messy, and before I tried that I though I would ask around. >> >> To give a bit more information, I'm writing a script that will use the ip >> address assigned to the wifi interface to determine location (this is on a >> Mac) and then mount network drives appropriate to the location. If anyone >> has a better idea how to do this, I'd be happy to hear them. >> >> Thanks in advance! >> >> Scott Newton >> >> >> >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python logging
Hi, For some reason, I'm having a bit of trouble figuring this one out. I know it has to be relatively easy but it just isn't "working" for me at the moment. I want to re-direct the logs from python's logging library and while using a config file rather than instantiating all of the logging within my actual code. So, lets say I have a file log.conf that contains the various directives for the logging module. Amongst all of the other settings a handler might look like this: [handler_warn_logfile] class=handlers.RotatingFileHandler level=WARNING formatter=DatetimeLevelMessage args=('test_warn.log', 'a', 125829120, 5) filename=test_warn.log mode=a then loaded like this logging.config.fileConfig(log_config_path) logging.debug('Logging enabled') ... which basically says append WARNING messages to the rotating file handler in DatetimeLevelMessage format to a log-file named test_warn.log splitting the log-file when it exceeds 125829120 bytes. Because I don't have any full paths listed, the logger uses the current working directory i.e. "/home/user/workspace/logged_app/ test_warn.log" I could change the name to "logs/test_warn.log" for a sub-directory but I'd like to put a data on some of the logs and not necessarily in the root of the scripts but maybe elsewhere on the system i.e. /home/ user/logs/someapp/200904_logs/ I've done a bunch of inspection of dictionaries, methods and attributes but nothing seems to be surfacing that would allow me to re- direct the paths in a dynamic way -- other than using os.cwd('some_path') before instantiating the logging... which is quite hack-ish IMO. The only thing that comes to mind, after reviewing the logging via help(logging...), is that I may need to dynamically re-write the .conf file using ConfigParser. Any ideas on what I'm missing within the logging for redirecting the files? Or, should I bump this up to the main python list? Thanks in advance, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Webpy vs Django
On Apr 19, 2009, at 4:52 AM, vishwajeet singh wrote: This is not to flame any war; I just wanted to know the key features to consider among the two web frame works. What advantage and disadvantages you have when you decide using any one of them. I can't speak with any authority on Webpy (webpy.org), as I have not actually used it though I did read up on its features about a year ago and now just a quick glance again. I do have some experience with a different 'light-weight' framework called Quixote (www.quixote.ca) and have a production project using it... that I'm migrating to Django. I also have a couple of projects using Zope... also being migrated to Django. I don't mention all of this as any indication of prowess, in fact much of the code on these projects has been written by other developers I've contracted to, but that I have some similar experience. The main point I wish to make of all this is that these different frameworks kind of coalesce into sub-groups. They sort-of form into three groups: light-weight framework, full-featured framework and heavy CMS (lots of inseparable overhead). Furthermore, like a series of balls or coins in a simple Pachinko machine (http://en.wikipedia.org/wiki/Pachinko ) where each one takes a different route, the application you are developing will have a huge influence on requirements. Personally, I've been working with Django on and off for about 2-1/2 years and find it a joy to work with. It does not have the overhead and hidden 'magic' of Zope and I don't have to re-invent almost everything like Quixote. For _my_ needs, it has been a great blend of capabilities without the oppressing overhead of the CMS. I can add or remove the modules needed on a project-by-project basis. "Out of the box", the automated admin interface is a huge time-saver and its object-relational model is quite good at wrapping relational databases into a python-friendly framework. Also it's user-admin and authentication takes care of the core of most sites I work on. It has a good blend for my requirements of granular framework access and functional tools to save me time. And now, there is quite a nice selection of add-on applications that extend Django in a very modular fashion, though there are still growing pains. Like "Goldie Locks and the three bears", this one is "just right" for my needs. Just as Zope is overkill for projects that don't need CMS, Django would be overkill for a project that didn't need much for database access and admin interface. The authors of Django, try pretty hard to not hide anything that is going on in the background but there is still a lot being done for the developer. For example in creating db schemas, wrapping queries and result-sets into object calls, rendering content through templates and much more. All have ways of being modified but not necessarily by novice python developers. So the short answer to your question is that Webpy and Django are quite different in their tool-sets and are therefore tough to compare. As with all lightweight frameworks, they are _shorter_ on pre-defined features. That's not a negative, that _is_ the point of them. Django has tried to bridge, and in my opinion done a good job of it, a lighter-weight core with a well documented and developer-friendly interface for extension. It is a framework that has allowed me to gradually dig deeper and deeper into its workings to extract more advanced features while not bogging me down with redundant and tedious things like forms and user authentication. I chose Django because it had the most to offer for what I need and it seems to have the "legs" to cover a lot of ground. That said, I don't that anyone could say you were wrong by choosing either of the projects you mentioned given appropriate circumstances (though personally, I can't find _any_ circumstances where I'd recommend Zope today -- but that's probably a personal bias and I won't digress). I know this doesn't answer your question directly but I hope it helps broaden the perspective a little, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python logging
Hi Stephan & Kent, On Apr 19, 2009, at 6:12 AM, Stefan Behnel wrote: just commenting on this part: ... which basically says append WARNING messages to the rotating file handler in DatetimeLevelMessage format to a log-file named test_warn.log splitting the log-file when it exceeds 125829120 bytes. You may have a reason to cut these at "125829120" bytes, but it's usually a bad idea to cut log files by size. It's much more natural to have time sliced log files (one per day or per hour), so that you directly know which file you have to look at to analyse that stuff that went so terribly wrong yesterday evening (especially once they get archived somewhere). I didn't set-up this portion of the file config. file and have not found much documentation for the conf-file formating (much of the rest is very well documented). I guess I should really find the actual code and read what it is doing... as Kent very gently prodded me with. I did go through a few PEPs too, and I don't recall seeing anything about time-based rotation ... but then maybe it was there and it didn't register with me. Thanks for the heads-up, I'll go back and re- read the material. Looking at the code for the logging module, I think it will work to create the RotatingFileHandler with the parameter delay=True, then in your code get the handler and change its baseFilename attribute to be the path you want, e.g. "/home/user/workspace/logged_app/test_warn.log". That's an interesting feature, I'll have to go look and see what other jewels are lurking in various modules. So far I've not spent a lot of time going through the code for modules like this, but obviously I should (I often learn more than just how a bit of code works by reading how others have solved problems). Thank you both! Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading from files problem
Students, with a file-import method using the CSV lib which then did the work of putting all the data into a database, bypassing a Student class (until there was a valid reason for one). Once the data is loaded in, it can be referenced without re- interpreting the CSV file, again through methods in a Students class. I hope this helps, Scott PS. My email is acting up, did my prev. message actually make it to the list? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shebang (#!) in the first line of a python script
On Tue, Oct 13, 2009 at 1:54 PM, Dave Angel wrote: > Katt wrote: > >> >> You were right. I did not have .PY/.PYW in my PATHEXT. I have put it in >> as >> suggested. I do have python.exe in my path so that should take care of >> things. >> >> Messing around with the windows registry isn't something I want to tackle >> just yet so I will save that for later. >> >> Thank you for your help, >> >> Katt >> > You don't have to directly mess with the registry. But if you just enter > the script name, you are causing the registry lookups just the same. As I > said, the install took care of it for you, and you shouldn't have to change > till you have two installs. > > But to re-iterate: When you run a script this way, the PATH is *not* used > to look up the Python.exe, but only to search for the script. > > DaveA > > You can do it strictly through the explorer. Right click on any .py or .pyw file and select 'properties.' Where it says 'open with' click 'change.' In the dialog select 'other' and browse to python.exe. Make sure it's the python.exe from the version you want to use. I just installed python 2.6 and had to do that and set the paths manually as for some reason the installer didn't do it for me. (oops hit "reply" the first time instead of "reply all." New to this mailing list thing.) > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- This just goes to show that there's nothing an agnostic can't do if he really doesn't know if he believes in anything or not. ~Monty Python ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyWin32 - Library of functions to interact with windows?
If I may chime in... As Alan said, pywin is basically a thin wrapper around the Win32 API. The Win32 API is very complex. Thus pywin is, by necessity, also very complex. There is documentation for pywin, but it is very minimal as you've probably noticed. If you are a *very* bold beginner with lots of patience, the best documentation for pywin is actually the documentation for the Win32 API itself found on Microsoft's "MSDN Library" website [1]. Navigating and using this documentation requires a knowledge of the Windows architecture and C programming. Once you find what you want in the MSDN documentation, you can usually find the same function in pywin. Again, this is not going to be easy if you are a beginner (it is difficult even for more experienced programmers), but I wanted to let you know the info is out there. If you want to dive into Win32 programming and learn the basics, the books Alan mentioned are good. But again, Win32 programming is pretty low-level and complex. There is usually an easier way to do most things you need to do. Especially if you want to create GUI's in Python, don't start with pywin and Win32. Use EasyGUI, Tkinter, or wxPython (in order of easiest to most powerful) Now, back to your specific task. To clarify, I'm assuming you want to color the text that shows up in Window's console when you do "print" from Python, correct? It *is* possible to color console text with Python and pywin. But, it is tricky and not obvious. I've been wondering how to do this myself and I recently found some C code on the web [2] that does this and I translated that into to Python and pywin. It can be done in about 4 lines of Python. To get you started, here is the link [3] to the MSDN documentation that tells you what you need to know about coloring text in a Windows console window (what Python's print command uses). Then, it is up to you to translate this into Python and pywin. The link [2] could also help. If you are up for a challenge, give it a shot. If you get stuck or it takes too long, write back and I/we can nudge you in the right direction with a code snippet. (While writing this email, I also discovered that you can control the cursor position in a win32 console with pywin! Fun!) Best of luck, and feel free to ask for more help! -Scott [1] - http://msdn.microsoft.com/en-us/library/default.aspx [2] - http://www.dreamincode.net/forums/showtopic23272.htm [3] - http://msdn.microsoft.com/en-us/library/ms682088(VS.85).aspx ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyWin32 - Library of functions to interact with windows?
Scott Nelson wrote: > > It *is* possible to color console text with Python and pywin. But, it is > tricky and not obvious. I've been wondering how to do this myself and I > recently found some C code on the web [2] that does this and I translated > that into to Python and pywin. It can be done in about 4 lines of Python. > For the sake of posterity (and the archives), I figured I'd list the "4 lines of Python" I mentioned above: import win32console handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) print 'blue text' Beginning with this snippet, there are a number of other things you can do, such as set the cursor position (handle.SetConsoleCursorPosition) and get the properties of the console itself (handle.GetConsoleScreenBufferInfo). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is URL to online Python interpreter?
> > On Thu, Dec 17, 2009 at 09:32:44PM -0800, Benjamin Castillo wrote: > > What is URL to online Python interpreter? > There is also http://codepad.org/ which also supports lots of languages (Python, Ruby, Perl, PHP, C/C++...). Pretty slick. You can also use it as a public pastebin (this link will expire eventually) http://codepad.org/YCrMADrc. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] Hi I made a mistake
You *have* signed up to get help, it's just that you see all the mail to the mailing list. The requests for help go to all subscribers, not just a select group of 'tutors' - obviously you won't be offering solutions just yet, but maybe one day you will! This behaviour is the whole point of a mailing list, and you will find reading selected questions and answers very helpful if you are serious about learning Python. However if you want to suspend mail delivery, visit the list info page, and sign in at the bottom of the screen with the password you were given. Once signed in you can change all sorts of settings: stopping list mail, receiving it as a daily digest, unsubscribing, etc. You could for example stop mail delivery and just look for answers to your questions in the archive. (Again, see list info page: http://mail.python.org/mailman/listinfo/tutor). > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > Behalf Of Julius > Sent: 21 December 2004 15:01 > To: [EMAIL PROTECTED] > Subject: [Tutor] Hi I made a mistake > > > I am a beginner with Python, I originally tried to sign up to "GET" > help, not to become a tutor, now i have alot of email everyday of > people asking me questions, please take my name off the > list, i won't > be able to help, and please let me know how to sign up to > get help :) > -- > Julius > ___ > Tutor maillist - [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] replacement for constants from other languages in Python?
Hey all, I've done the usual googling, checked the Learning Python book and did some list searches, to no avail as of yet. I'm _very_ used to using C style constants (preprocessor #define directives) or C++ const keyword style, for a variety of reasons. I've yet to see anything covering 'how to work around the lack of constants in Python'...can anyone point me in the right direction here? A few examples/reasons for use: The 'need' to define a global constant in an imported module, for example- (I know about sys.version_info, but it doesn't exist in 1.5.2...don't ask ;-) I also know this could be handled via a class, but what is the equivalent of the following snippets? Not so interested in style comments (I am, but not on these/this thread ;-) as much as other ways to do this.. 1. ourversion.py: import sys MINVERSION = 1.5 def checkVersion(): """ used as an evil hack because 1.5.2 doesn't have sys.version_info """ # Not sure why, but declaring MINVERSION as repr(foo) in the # first place doesn't work, something about python type handling # I'm sure.. return repr(MINVERSION) >= repr(getVersion()) def getVersion(): return sys.version[0:3] if repr(getVersion() < 2.0) # boo, we have no builtin bool global True global False True = 1 False = 0 funkyScopeAndConstants.py: import ourversion.py import sys import os import ... ... if someOtherModule.property = True # do something You get the point. The other oddity is without being able to define a 'real' constant, as in #DEFINE MINVERSION 1.5, the scope of MINVERSION (and True/False) even using the global keyword still uses the ocal file's namespace. I don't want to debate the merits of using globals...most people that claim they never use any in other languages _still_ use constants in header files, which is the purpose I'd like to be able to do generallynot to mention the fact that I really am _not_ thrilled with the use of string literals typed in each time in code (yes, quick and dirty code but still) I see seems to be 'OK' in python for the use of comparisons...opposed to something like if(strncmp(strVal, CONSTANT_STRING_VAL_LIKE_HTTP_ACCEPT_ENCODING_HEADER, strlen(strVal) { do_something(); } or if(floatVal > PI) { do_something() } ok, hopefully that's explaining some of why I'd like a 'constant equivalent' as well as a question on global scoping/python namespaces. A last question would also be if the equivalent of __FILE__ and __LINE__ macros exist? Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
Kent Johnson wrote: Scott W wrote: The 'need' to define a global constant in an imported module, for example- (I know about sys.version_info, but it doesn't exist in 1.5.2...don't ask ;-) I also know this could be handled via a class, but what is the equivalent of the following snippets? Not so interested in style comments (I am, but not on these/this thread ;-) as much as other ways to do this.. 1. ourversion.py: import sys MINVERSION = 1.5 This is the usual Python way. Python's approach generally is 'treat your users like adults', i.e. give them the information needed to make sensible decisions, but don't try to keep them from doing something you think is stupid. Putting the name in upper case gives the information that this is intended to be a constant. Sure, if I can't make it a true constant value, might as well make it 'obvious' ;-) def checkVersion(): """ used as an evil hack because 1.5.2 doesn't have sys.version_info """ # Not sure why, but declaring MINVERSION as repr(foo) in the # first place doesn't work, something about python type handling # I'm sure.. MINVERSION = repr(1.5) should work just fine. It will give the same result as the more readable MINVERSION = '1.5' Ok, this would make a bit more sense RE: repr()- in one of the resources I found, it seemed to state that repr(x) was converting x into a numeric representation, ala atoi() and friends. Obviously, this is the opposite of what I'd actually wanted. The sample snippets I put in had a duplicated repr() if not more than one, which wasn't doing what I expected anyways (although at which point I was essentially comparing strings of similar length, getting 'a' result, just not the intended one ;-) I'm not sure why you are using repr() so much. return repr(MINVERSION) >= repr(getVersion()) def getVersion(): return sys.version[0:3] if repr(getVersion() < 2.0) This will certainly not do what you want for two reasons. - getVersion() returns a string, you are comparing it to a float which will not give a meaningful result. - In Python < 2.3 the result of the comparison will be an integer 0 or 1. repr() converts this to a *string* '0' or '1' which will *always* evaluate as True!! Yep, see above...wish I knew where I saw that 'explanation' of repr() and str() # boo, we have no builtin bool global True [snip] Rather than testing the version, you can test directly to see whether True and False are defined. If not, you can add them to the __builtin__ module and they will be globally available. Here is one way: import __builtin__ if not __builtin__.hasattr('True'): __builtin__.True = 1 if not __builtin__.hasattr('False'): __builtin__.False = 0 OK, that's helpful. I can see the advantages of several of python's mechanisms, such as dir() as well as treating everything like an 'interactive object to determine existing methods and attributes (dir() and your example of hasattr(). Pretty cool...now to go from libc/POSIX to an entirely new and (mostly) different set of core libs and functionality.. ;-) Actually, that IS pretty nice, can perhaps take the place of some(most?) of features.h, unistd.h and friendswhich is really what I want, regardless of the example...or having to 'roll my own'. Very cool. This suggestion is taken from this thread on comp.lang.python: http://tinyurl.com/46me3 Note that adding names to __builtin__ is NOT recommended in general! Don't use this to create your own global constants! It is OK in this case because to duplicate Python 2.3 behaviour you need a true global. The other oddity is without being able to define a 'real' constant, as in #DEFINE MINVERSION 1.5, the scope of MINVERSION (and True/False) even using the global keyword still uses the ocal file's namespace. I don't want to debate the merits of using globals...most people that claim they never use any in other languages _still_ use constants in header files, which is the purpose I'd like to be able to do generally The usual Python solution is to make a module containing constant definitions and import it where you need them. [snip] or, if you want to import all the constants directly, # Client2.py from Constants import * There was my catch/issue I was having. I expected the global keyword being used in my previous bool/True/False definition to put it into a global namespace, but I still had a namespace issue as you explained here- simply doing an 'import ' will allow access to variables created as globals in that module, but not without scope resolution, ie module.True, module.MINVERSION, etc...what I expected was anything declared as global to simply be in the global namespace of any other module importing t
[Tutor] class instance with identity crisis
This is probably a very easy question, and one that I was shocked to find I was stuck on, having thought I understood classes! I was wondering how you can get an instance of a class to change itself into something else (given certain circumstances), but doing so from within a method. So: class Damson: def __str__(self): return 'damson' def dry(self): self = Prune() class Prune: def __str__(self): return 'prune' weapon = Damson() weapon.dry() print weapon All the old hands will of course know this will produce the output damson but something in me suggests it should produce prune After all, 'self' refers to the instance 'weapon'. Obviously one could reassign weapon to a Prune outside the class definition, but I was hoping to write something in which, given certain circustances arising, the instance would change itself into something else. Time to go back to school! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] class instance with identity crisis
Thanks to all who responded. I see my biggest mistake was not spotting the assignment of 'self' being local to the method - very dumb indeed, especially as I have seen this many times before. However I am glad I was not necessarily dumb to want to do what I was thinking of. I am learning lots! Thanks > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > Behalf Of Alan Gauld > Sent: 12 January 2005 20:13 > To: Alan Gauld; Barnaby Scott; 'Tutor' > Subject: Re: [Tutor] class instance with identity crisis > > > Whoops, I forgot to do an assignment... > > > So try > > > > def dry(self): return Prune() > > > > > class Prune: > > > def __str__(self): > > > return 'prune' > > > > > > weapon = Damson() > > > weapon.dry() > > weapon = weapon.dry() > > > > print weapon > > > > Should work as expected... > > Alan G > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to create a key-value pairs with alternative elements in a list ... please help.
> I have a simple list:> ['a', 'apple', 'b', 'boy', 'c', 'cat']> I want to create a dictionary:> dict = {'a':'apple', 'b':'boy', 'c':'cat'} From the Quick and Dirty Department: If you have Python version 2.3 or later, you can use 'itertools' to unflatten the list in a very concise manner. Here is an interpreter session using your example data above. >>> l = ['a', 'apple', 'b', 'boy', 'c', 'cat']>>> d = {}>>> import itertools>>> slice0 = itertools.islice(l,0,None,2)>>> slice1 = itertools.islice(l,1,None,2)>>> while True:... try:... d[slice0.next()] = slice1.next()... except: StopIteration... break... >>> d{'a': 'apple', 'c': 'cat', 'b': 'boy'} This should be fairly space-efficient. As another approach, you could use extended slicing to break the list apart (creating two new lists could be expensive) and then patch it back together again: >>> slice0 = l[::2]>>> slice1 = l[1::2]>>> slice0['a', 'b', 'c']>>> slice1['apple', 'boy', 'cat']>>> d = dict(zip(slice0,slice1))>>> d{'a': 'apple', 'c': 'cat', 'b': 'boy'}>>> In both cases, we get slice0 by starting at position 0 in the list and taking every other item and we get get slice1 by starting at position 1 in the list and again taking every other item. Hope this helps! Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] Re: glob or filter help
For anyone who doesn't like lambda, how about import os def get_fles(exts, upd_dir): return [i for i in os.listdir(upd_dir) if i.split('.')[-1] in exts] > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > Behalf Of Javier > Ruere > Sent: 22 January 2005 16:25 > To: tutor@python.org > Subject: [Tutor] Re: glob or filter help > > > Jay Loden wrote: > > Thanks! That's exactly the kind of feedback I was looking for. If > it's not > > too much trouble, do you think you could explain how > lambda works, or > just > > point me towards a lambda explanation/tutorial that a new > programmer can > > understand? It seems to give you some great power but I > really don't > > understand how it works. > >Lambda defines anonymous functions. It has some > restrictions like that > the function must be expressed in one line and there can be no > assigments. The syntax can be found in [1]. >Though I personaly like this keyword, I must say that it > can make code > less readable so I tend to use it for only for extremely simple > snippets. The example given in the previous mail is almost > too big. But > then again, one must try things out to learn so use it and > find your own > balance. >Also the BDFL has said he is unhappy with lambda (and > filter, reduce > and map) so he may remove this keyword in the future (but not before > Python3000)[2]. > > Javier > > [1] http://www.python.org/doc/2.4/ref/lambdas.html > [2] Look in the user list if you want to learn more about > this topics. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Changing (Unix) environment for python shell/popen() commands
Hey all. I'm unfortunately stuck using python 1.5.2, primarily on Linux currently, and have done the usual searching (on list, active state, google), without luck. I've got to shell out from my python code to execute a command, but _must_ set the environment at the same time (or prior to execution). I say must, because in this case the obvious answer of modifying the command to be called or wrapping it with a shell script to set the environment won't work/isn't going to happen. I saw some comments about setting os.environ[], but didn't seem to be seeing this work in subsequent calls using popen2(). Does anyone have a working piece of code setting some env variable successfully prior to(or along with) calling popen2() (or friends). Also, is there any way to get the called programs return code via popen() (again, under python 1.5.2)? I know this has been asked often enough, but once again, it seems I'm left wanting for _good_ documentation under python (ie compared to man pages, DevStudio Win32 docs, Linux info, Java docs, etc), including the half dozen python books I own (great for some things, but no reference whatsoever to other things that I'd think would warrant some coverage).. Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sorting a 2 gb file
Hello! I am wondering about the best way to handle sorting some data from some of my results. I have an file in the form shown at the end (please forgive any wrapparounds due to the width of the screen here- the lines starting with ENS end with the e-12 or what have you on same line.) What I would like is to generate an output file of any other ENSE000...e-4 (or whathaveyou) lines that appear in more than one place and for each of those the queries they appear related to. So if the first line ENSE1098330.2|ENSG0013573.6|ENST0350437.2 assembly=N... etc appears as a result in any other query I would like it and the queries it appears as a result to (including the score if possible). My data set the below is taken from is over 2.4 gb so speed and memory considerations come into play. Are sets more effective than lists for this? To save space in the new file I really only need the name of the result up to the | and the score at the end for each. to simplify things, the score could be dropped, and I could check it out as needed later. As always all feedback is very appreciated. Thanks, Scott FILE: This is the number 1 query tested. Results for scoring against Query= hg17_chainMm5_chr17 range=chr1:2040-3330 5'pad=0 3'pad=0 are: ENSE1098330.2|ENSG0013573.6|ENST0350437.2 assembly=N...72 1e-12 ENSE1160046.1|ENSG0013573.6|ENST0251758.3 assembly=N...72 1e-12 ENSE1404464.1|ENSG0013573.6|ENST0228264.4 assembly=N...72 1e-12 ENSE1160046.1|ENSG0013573.6|ENST0290818.3 assembly=N...72 1e-12 ENSE1343865.2|ENSG0013573.6|ENST0350437.2 assembly=N...46 8e-05 ENSE1160049.1|ENSG0013573.6|ENST0251758.3 assembly=N...46 8e-05 ENSE1343865.2|ENSG0013573.6|ENST0228264.4 assembly=N...46 8e-05 ENSE1160049.1|ENSG0013573.6|ENST0290818.3 assembly=N...46 8e-05 This is the number 2 query tested. Results for scoring against Query= hg17_chainMm5_chr1 range=chr1:82719-95929 5'pad=0 3'pad=0 are: ENSE1373792.1|ENSG0175182.4|ENST0310585.3 assembly=N...80 6e-14 ENSE1134144.2|ENSG0160013.2|ENST0307155.2 assembly=N...78 2e-13 ENSE1433065.1|ENSG0185480.2|ENST0358383.1 assembly=N...78 2e-13 ENSE1422761.1|ENSG0183160.2|ENST0360503.1 assembly=N...74 4e-12 ENSE1431410.1|ENSG0139631.6|ENST0308926.3 assembly=N...74 4e-12 ENSE1433065.1|ENSG0185480.2|ENST0358383.1 assembly=N...72 1e-11 ENSE1411753.1|ENSG0126882.4|ENST0358329.1 assembly=N...72 1e-11 ENSE1428167.1|ENSG0110497.4|ENST0314823.4 assembly=N...72 1e-11 ENSE1401130.1|ENSG0160828.5|ENST0359898.1 assembly=N...72 1e-11 ENSE1414900.1|ENSG0176920.4|ENST0356650.1 assembly=N...72 1e-11 ENSE1428167.1|ENSG0110497.4|ENST0314823.4 assembly=N...72 1e-11 ENSE1400942.1|ENSG0138670.5|ENST0356373.1 assembly=N...72 1e-11 ENSE1400116.1|ENSG0120907.6|ENST0356368.1 assembly=N...70 6e-11 ENSE1413546.1|ENSG0184209.6|ENST0344033.2 assembly=N...70 6e-11 ENSE1433572.1|ENSG0124243.5|ENST0355583.1 assembly=N...70 6e-11 ENSE1423154.1|ENSG0125875.4|ENST0354200.1 assembly=N...70 6e-11 ENSE1400109.1|ENSG0183785.3|ENST0339190.2 assembly=N...70 6e-11 ENSE1268950.4|ENSG0084112.4|ENST0303438.2 assembly=N...68 2e-10 ENSE1057279.1|ENSG0161270.6|ENST0292886.2 assembly=N...68 2e-10 ENSE1434317.1|ENSG0171453.2|ENST0304004.2 assembly=N...68 2e-10 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Code review
If anyone has the time to look through an entire script, I would would be very grateful for any comments, tips or suggestions on a wiki-engine script I am working on. http://www.waywood.co.uk/cgi-bin/monkeywiki.py (this will download rather than execute) It does work, but I have not been using Python very long, and am entirely self-taught in computer programming of any sort, so I have huge doubts about my 'style'. I am also aware that I probably don't 'think like a programmer' (being, in fact a furniture maker!) I did post a previous version of this about a year(?) ago, and received some very welcome suggestions, but I have changed it quite a lot since then. Also, please ignore the licensing stuff - I do intend to make the thing available like this when I am more confident about it, and I am just getting a bit ahead of myself: you guys are the first people who know it's there. Many thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] sorting a 2 gb file- i shrunk it and turned it around
Thanks for the thoughts so far. After posting I have been thinking about how to pare down the file (much of the info in the big file was not relevant to this question at hand). After the first couple of responses I was even more motivated to shrink the file so not have to set up a db. This test will be run only now and later to verify with another test set so the db set up seemed liked more work than might be worth it. I was able to reduce my file down about 160 mb in size by paring out every line not directly related to what I want by some simple regular expressions and a couple tests for inclusion. The format and what info is compared against what is different from my original examples as I believe this is more clear. my queries are named by the lines such as: ENSE1387275.1|ENSG0187908.1|ENST0339871.1 ENSE is an exon ENSG is the gene ENST is a transcript They all have the above format, they differ in in numbers above following ENS[E,G orT]. Each query is for a different exon. For background each gene has many exons and there are different versions of which exons are in each gene in this dataset. These different collections are the transcripts ie ENST0339871.1 in short a transcript is a version of a gene here transcript 1 may be formed of exons a,b and c transcript 2 may contain exons a,b,d the other lines (results) are of the format hg17_chainMm5_chr7_random range=chr10:124355404-124355687 5'pad=...44 0.001 hg17_chainMm5_chr14 range=chr10:124355392-124355530 5'pad=0 3'pa...44 0.001 "hg17_chainMm5_chr7_random range=chr10:124355404-124355687" is the important part here from "5'pad" on is not important at this point What I am trying to do is now make a list of any of the results that appear in more than one transcript ## FILE SAMPLE: This is the number 1 query tested. Results for scoring against Query= ENSE1387275.1|ENSG0187908.1|ENST0339871.1 are: hg17_chainMm5_chr7_random range=chr10:124355404-124355687 5'pad=...44 0.001 hg17_chainMm5_chr14 range=chr10:124355392-124355530 5'pad=0 3'pa...44 0.001 hg17_chainMm5_chr7 range=chr10:124355391-124355690 5'pad=0 3'pad...44 0.001 hg17_chainMm5_chr6 range=chr10:124355389-124355690 5'pad=0 3'pad...44 0.001 hg17_chainMm5_chr7 range=chr10:124355388-124355687 5'pad=0 3'pad...44 0.001 hg17_chainMm5_chr7_random range=chr10:124355388-124355719 5'pad=...44 0.001 This is the number 3 query tested. Results for scoring against Query= ENSE1365999.1|ENSG0187908.1|ENST0339871.1 are: hg17_chainMm5_chr14 range=chr10:124355392-124355530 5'pad=0 3'pa...60 2e-08 hg17_chainMm5_chr7 range=chr10:124355391-124355690 5'pad=0 3'pad...60 2e-08 hg17_chainMm5_chr6 range=chr10:124355389-124355690 5'pad=0 3'pad...60 2e-08 hg17_chainMm5_chr7 range=chr10:124355388-124355687 5'pad=0 3'pad...60 2e-08 ## I would like to generate a file that looks for any results (the hg17_etc line) that occur in more than transcript (from the query line ENSE1365999.1|ENSG0187908.1|ENST0339871.1) so if hg17_chainMm5_chr7_random range=chr10:124355404-124355687 shows up again later in the file I want to know and want to record where it is used more than once, otherwise I will ignore it. I am think another reg expression to capture the transcript id followed by something that captures each of the results, and writes to another file anytime a result appears more than once, and ties the transcript ids to them somehow. Any suggestions? I agree if I had more time and was going to be doing more of this the DB is the way to go. -As an aside I have not looked into sqlite, I am hoping to avoid the db right now, I'd have to get the sys admin to give me permission to install something again etc etc. Where as I am hoping to get this together in a reasonably short script. However I will look at it later (it could be helpful for other things for me. Thanks again to all, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: sorting a 2 gb file- i shrunk it and turned it around
Hello again! Thank you everyone for all the help. The most important step in dealing with Blast results is getting rid of all the extraneous information. The standard result file gives you everything you could ask for when comparing DNA sequences, however at this step I am looking for specific data. Once I have my relevant matches I can go back and pull out the info for just those matches from the file. Following Kent's advice I came up with the following (I should set up defs and a modular system for renewability, that will be next) import sys #my system complained when I had them on 1 line as sys, sets, re import sets #not sure why but that's another issue (2.4 on win XP) import re result=re.compile('^(hg17.+)5\'.+') #the import part of the line is in the ( ) query=re.compile('^.+(ENST\d+\.\d)+') #matches the line up to the important transcriptID #and groups the ID info TFILE = open(sys.argv[1], 'r' ) #file to read from WFILE=open(sys.argv[2], 'w') # file to write to results={} for line in TFILE: isQueryLine= query.match(line) isResultLine= result.match(line) if isQueryLine: current_query = isQueryLine.group(1) if isResultLine: key = isResultLine.group(1) results.setdefault(key, []).append(current_query) # see explanation below # Now go through results looking for entries with more than one query for key, queries in results.iteritems(): if len(queries) > 1: print >> WFILE print >> WFILE, key for query in queries: print >> WFILE, query I am almost there the program seemed to run well will minimal swapping and finished in 5 minutes. My output file is only 45 mb. A sample of the output file is: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST0339563.1 ENST0342196.1 ENST0339563.1 ENST0344055.1 hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST0279800.3 ENST0309556.3 hg17_chainMm5_chr6 range=chr1:155548627-155549517 ENST0321157.3 ENST0256324.4 hg17_chainMm5_chr13 range=chr1:81386270-81386967 ENST0011649.3 ENST0348636.1 hg17_chainMm5_chr19 range=chr11:56050656-56051559 ENST0341231.1 ENST0341231.1 ENST0331792.1 ENST0341231.1 ENST0341231.1 ENST0331792.1 hg17_chainMm5_chr9 range=chr11:123561223-123562097 ENST0341493.1 ENST0318666.4 ENST0341493.1 I can see where any of the chains appear more than once, which is good and I am looking for situations like first example where ENST0339563.1 is the first and third on the list or the fifth example. Next step is to cut out the ENST lines that only show up once and wind up with just the places where there are matches at least twice to a given transcript (using the ENST0...) ids. Like in the final example I only want the first and third so I know it is twice in that transcript. Back to it and other things. Thanks for all the help so far, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with regexps/filename parsing
Hey all. I've got an issue that's been driving me a bit nuts. I'm sure it _can_ be done with a regexp, although I'm missing a piece needed to tie it together to work for all cases. I need to parse out a list of RPMs in this case, but it seems the RPM naming convention has changed, as there are files I'll need to parse that are NOT in the normal name-version-release.arch.rpm format. I need to be able to grab the 'basename' for each file, as well as the version and arch, although these can be done seperately. The problem can be shown by the following list of filenames: XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm (Note the EL embedded in name) xfig-3.2.3d-12.i386.rpm (standard naming) rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm perl-DateManip-5.42a-0.rhel3.noarch.rpm openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm Those should represent the set of variations now possible. I can handle most, but not all of the cases...any suggestions that would cover all of the above allowing the extraction of: basename- in this case: XFree86-ISO8859-15-75dpi-fonts, xfig, rhel-ig-ppc-multi-zh_tw, perl-DateManip, openoffice.org-style-gnome version: 4.3.0-78.EL (yes, including the .EL unfortunately, although I'd be OK without it and munging it on end if needed) 3.2.3d-12 3-4 5.42a-0 1.1.0-16.9.EL arches: i386, i386, noarch, noarch, i386 respectively. Any help greatly appreciated, as I've been beating myself up on this one for a bit. Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with regexps/filename parsing
Slight correction which I realized after sending, see below for version/release seperation, which I should have seen but blame lack of sleep ;-) Scott W wrote: Hey all. I've got an issue that's been driving me a bit nuts. I'm sure it _can_ be done with a regexp, although I'm missing a piece needed to tie it together to work for all cases. I need to parse out a list of RPMs in this case, but it seems the RPM naming convention has changed, as there are files I'll need to parse that are NOT in the normal name-version-release.arch.rpm format. I need to be able to grab the 'basename' for each file, as well as the version and arch, although these can be done seperately. The problem can be shown by the following list of filenames: XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm(Note the EL embedded in name) xfig-3.2.3d-12.i386.rpm(standard naming) rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm perl-DateManip-5.42a-0.rhel3.noarch.rpm openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm Those should represent the set of variations now possible. I can handle most, but not all of the cases...any suggestions that would cover all of the above allowing the extraction of: basename- in this case: XFree86-ISO8859-15-75dpi-fonts, xfig, rhel-ig-ppc-multi-zh_tw, perl-DateManip, openoffice.org-style-gnome version: 4.3.0-78.EL(yes, including the .EL unfortunately, although I'd be OK without it and munging it on end if needed) 3.2.3d-12 3-4 5.42a-0 1.1.0-16.9.EL corrected versions: 4.3.0 3.2.3d 3 5.42a 1.10 (new) releases: 78.EL 12 4 0 16.9.EL arches: i386, i386, noarch, noarch, i386 respectively. Any help greatly appreciated, as I've been beating myself up on this one for a bit. Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] variation of Unique items question
Hello once more. I am stuck on how best to tie the finding Unique Items in Lists ideas to my file I am stuck at level below: What I have here taken from the unique items thread does not work as I need to separate each grouping to the hg chain it is in (see below for examples) import sys WFILE=open(sys.argv[1], 'w') def get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2): a_list=open(fname, 'r') #print "beginning get_list_dup" items_dict, dup_dict = {}, {} for i in a_list: items_dict[i] = items_dict.get(i, 0) + 1 for k, v in items_dict.iteritems(): if v==threshold: dup_dict[k] = v return dup_dict def print_list_dup_report(fname='Z:/datasets/fooyoo.txt', threshold=2): #print "Beginning report generation" dup_dict = get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2) for k, v in sorted(dup_dict.iteritems()): print WFILE,'%s occurred %s times' %(k, v) if __name__ == '__main__': print_list_dup_report() My issue is that my file is as follows: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST0339563.1 ENST0342196.1 ENST0339563.1 ENST0344055.1 hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST0279800.3 ENST0309556.3 hg17_chainMm5_chr6 range=chr1:155548627-155549517 ENST0321157.3 ENST0256324.4 I need a print out that would give the line hg17 and then any instances of the ENST that occur more than once only for that chain section. Even better it only prints the hg17 line if it is followed by an instance of ENST that occurs more than once I am hoping for something that gives me an out file roughly like: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST0339563.1 occurs 2 times hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST0279800.3 occurs 2 times All help and ideas appreciated, I am trying to get this finished as soon as possible, the output file will be used to go back to my 2 gb file and pull out the rest of the data I need. Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: variation of Unique items question
Hello. Kent once again you have responded incredibly quickly in a most helpful manor. I sometimes wonder if the old reference to a "Kent-bot" has some truth to it. Thanks again, I will play with it and keep on going. Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Is self.__init__() call bad style?
I am working on a script at the moment, in which I seem to need to re-initialise a class instance from within some of its methods. Before I go too much further down this route - could anyone comment on whether the call self.__init__() is in itself considered bad style or 'unpythonic'? For instance, is it better to create a 'reset' method, which is called both by __init__ and by the methods which are wanting to force a re-initialisation? I would be happy to post some of the code, but perhaps there is a general consensus about this anyway? Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] database applications with Python - where to start
Hi, this is one of those difficult questions about where to start! I want to create a book-keeping/accounting application for my own use 1. because I can't find any that suits me, and 2. because I want to improve and extend my knowledge of Python. Clearly this is going to be a database application - the trouble is, that despite reading loads of stuff (including previous posts here on the topic), I get a Catch-22 feeling that I need to be an expert with 'the big picture' before I can even take my first stumbling steps towards becoming that expert! Also the trouble with reading stuff on the web is that you don't know who is an out-on-a-limb lunatic, and who is talking sense backed up with concrete experience. And of course, quite understandably, everyone wants you to use *their* module/driver/database/whatever. Here's where I am: I have a reasonable grasp of Python (but realise that I have a lot still to learn). I have written database applications before, but only using MS Access (both with its own Jet database and with MSDE/SQL-Server) - no major boasts here, let's just say they *worked*! The thing is, Access rather pampers you with visual tools for doing many aspects of the work, and even a neat little environment to manage your code. Now I want to move on, and use Python, probably with a RDBMS. I haven't chosen the database - difficult again, because although this will be a small application, it is accounting data, so its integrity is paramount, and certain inviolable constraints must be built in at a very fundamental level (the data needs protection from my code!!). I will also obviously need a UI, probably a GUI (but it would be nice to keep my options open to do a web UI version at some point). So here's the thing. Even though I have quite a clear idea of what the database schema will look like, and what the UI will *do* (even though I don't know what it will look like), I'm having real trouble understanding how/where to start. I'm tempted to try to put together a 'kit' of tools (as visual as possible) to emulate what I'm used to - but is this a good idea? and if so, which tools? What on earth is my application's model going to look like? should I get involved with object-relational mapping? how much work should I delegate to the RDBMS, and how much logic should I code in Python? Should I even be thinking radically and ditch the RDBMS in favour of something like a 'Prevalence Layer' that I have read about? what should inform these decisions? I just don't know where to start! A book perhaps, but then, which one? Or maybe an example app for me to pick apart and learn from? Sorry it is such a vague question, but any pointers gratefully received. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "#!/usr/bin/env python" vs "#!/usr/local/bin/python"
[EMAIL PROTECTED] wrote: > hi list, > > how to choose between "#!/usr/bin/env python" and > "#!/usr/local/bin/python" in the beginning of the script ? > e. > > > > - > > SCENA - Ĺäčíńňâĺíîňî ÁĹÇĎËŔŇÍÎ ńďčńŕíčĺ çŕ ěîáčëíč ęîěóíčęŕöčč č ňĺőíîëîăčč. > http://www.bgscena.com/ > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > One of the main dis-advantages to using '/usr/bin/env python' is that you have to either A) make sure the environment is initialized, or B) initialize the environment manually before executing the script. If you, for example, want to use a python script at boot time, before the environment is initialized, i strongly recommend using an absolute path. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A replacement for a "for" loop
John Fouhy wrote: > On 29/08/07, Trey Keown <[EMAIL PROTECTED]> wrote: > >> attrs={u'title': u'example window title', u'name': u'SELF', u'icon': >> u'e.ico'} >> keys = ['name','title','icon'] >> for (tag, val) in attrs.iteritems(): >> for key in keys: >> print val >> >> the first "for" tag causes the dictionary (attrs) to have its keys called >> "tag" and its value called "val". The second "for" loop causes the >> dictionary keys to be read in a certain order. How could I take away the >> first "for" loop and replace it with something else to do the same general >> function? >> > > for key in keys: > print 'Attribute %s has value %s' % (key, attrs[key]) > > Why even have the keys variable at all.. for key in attrs: print 'Attribute %s has value %s' % (key, attrs[key]) -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A replacement for a "for" loop
Terry Carroll wrote: > On Wed, 29 Aug 2007, Scott Oertel wrote: > > >> Why even have the keys variable at all.. >> >> for key in attrs: >> print 'Attribute %s has value %s' % (key, attrs[key]) >> > > In a prior email thread, the OP indicated that he needed to process the > keys in that particular order; and it's not really amenable to any sort. > > Yup, I didn't see that the first time, sorry. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Formatting output into columns
Someone asked me this question the other day, and I couldn't think of any easy way of printing the output besides what I came up with pasted below. So what you have is a file with words in it as such: apple john bean joke ample python nice and you want to sort and output the text into columns as such: a p j b n apple python john bean nice ample joke and this is what works, but I would also like to know how to wrap the columns, plus any ideas on a better way to accomplish this. #!/usr/bin/env python data = {} lrgColumn = 0 for line in open("test.txt","r").read().splitlines(): char = line[0].lower() if not char in data: data[char] = [line] else: data[char].append(line) for item in data: print item.ljust(10), if len(data[item]) > lrgColumn: lrgColumn = len(data[item]) print for item in range(lrgColumn): for i in data.iteritems(): try: print i[1][item].ljust(10), except IndexError: print "".ljust(10), print ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting output into columns
Alan Gauld wrote: > "Scott Oertel" <[EMAIL PROTECTED]> wrote > > >> and you want to sort and output the text into columns as such: >> >> a p j b n >> apple python john bean nice >> ample joke >> >> and this is what works, but I would also like to know how to wrap >> the >> columns, plus any ideas on a better way to accomplish this. >> > > Use format strings. You can calculate the column widths by analyzing > the data then create a format string for the required number of > columns. > Finally insert the data on each row from a tuple. > > > HTH, > > > Do you have any good documentation that could shed some more light on exactly how to use format strings in such a way? -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting output into columns
Luke Paireepinart wrote: > Scott Oertel wrote: >> Someone asked me this question the other day, and I couldn't think of >> any easy way of printing the output besides what I came up with pasted >> below. >> >> So what you have is a file with words in it as such: >> >> apple >> john >> bean >> joke >> ample >> python >> nice >> >> and you want to sort and output the text into columns as such: >> >> a p j b n >> apple python john bean nice >> ample joke >> >> and this is what works, but I would also like to know how to wrap the >> columns, plus any ideas on a better way to accomplish this. >> >> #!/usr/bin/env python >> >> data = {} >> lrgColumn = 0 >> >> for line in open("test.txt","r").read().splitlines(): >> > you can just directly do > for line in open('test.txt'): > > depending on your Python version. I believe it's 2.3+. > I have 2.4 and it works there, at least. > If using an older version of Python, you can use .readlines() instead > of .read().splitlines() > > I believe Kent and Alan already helped you with your original question. > -Luke The reason I use read().splitlines, is because if you do .readlines() it adds the carriage return to the end of each line where in i have to .rstrip() to remove it. If you use .read() it doesn't split the lines in the file into a tuple, there for you it is not an iteration. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] visualizing code structure / flow charting
On 11/6/07, Wesley Brooks ([EMAIL PROTECTED]) wrote: >Taking both one step further if you can extract all the __doc__ >strings for all the objects listed from the dir of an object: > >a = 'a random string' >for i in dir(a): >command = "print str." + i + ".__doc__" >exec(command) > >This will print out all the __doc__ strings for functions you can call >on your string object a. This is particually helpful when you know >what you want to do to something (for instance capitalise the first >letter each word in a string) but don't know what function to call. While not as educational from one perspective, I've found the epydoc package quite useful. It extracts all of the doc strings and formats them in a nice, easy to read, layout. <http://epydoc.sourceforge.net/> Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Obtaining image date of creation
#x27;EXIF MaxApertureValue', 'EXIF MeteringMode', 'EXIF SceneType', 'EXIF ShutterSpeedValue', 'EXIF SubSecTime', 'Image DateTime', 'Image ImageDescription', 'Image Make', 'Image Model', 'Image Orientation', 'Image XResolution', 'Image YResolution', 'ImageType', 'ImageNumber', 'OwnerName', 'SerialNumber', 'FirmwareVersion', 'InternalSerialNumber'] try: image_file = open(strPath,'rb') image_tags = EXIF.process_file(image_file, details=False) image_file.close() image_keys = image_tags.keys() for key_name in exif_keys: if key_name in image_keys: return_exif_dict[key_name] = image_tags[key_name] ... You should be aware that it _is_ possible for a DC to take more than one image per second - though with a consumer P&S it is unlikely. The solution I used was to capture the camera's original sequential number - had the added benefit of letting the photogs I was working with reference to their own libraries later. There are lots of pages to be found discussing file renaming and date conversions, so that should not be a problem... just be sure to use file-system compatible characters (sorry, I don't know your python exp. - just covering a couple of bases). HTH Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] repeat
On 11/17/07, Michael ([EMAIL PROTECTED]) wrote: >This has probably been asked before but can I get some clarification on >why Python does not have a repeat...until statement, and does that mean >repeat...until is bad practice? I was trying to get Python on the >standard langauge list for my state secondary school system but they say >a langauge must have a test last structure in it to be considered. While you may feel your assertion to be true, it will persist until discovered false... <http://docs.python.org/ref/while.html> ... to date has satisfied my needs for the task. 8^) Like many things in Python there are alternates, even to this (I expect to be learning more of them myself for a good long time 8^) More examples and detail can be found at: <http://www.diveintopython.org/> <http://www.pasteur.fr/formation/infobio/python/ch10s03.html> <http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm> Simply put: while [test]: do something or while True: do something if [test]: break x = 0 while x < 100: x += 1 print x 100 Still, the links can elaborate more than I can. HTH Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CMS advice wanted
On 11/27/07, jim stockford ([EMAIL PROTECTED]) wrote: >IMO: >my experience with cms systems is that there's a big >learning curve. you might have more fun (and be more >productive and maybe more creative) if you use the >available appropriate python modules and cobble >together your own site. Woah, I whole-heartedly disagree with this. Sorry! >maintenance, especially by some one else, would >be an area to worry about: each cms system has its >own community of experts, a few of which are always >available to help. your custom code would present >new people a learning curve. This is why I disagree: maintenance. Oh yeah, how about: security! Along with expediency, quality and a bunch of other things like maybe the OP would like a life too (i.e. not be a slave to supporting his own code). Frankly, the OP (Richard) does not really need the 'full-meal' of a CMS. He's looking for a templating system (cheetah, myghty, kid) and a mechanism to organize code into a web application of sorts. While there are some behemouth CMS options (Zope/Plone) there are some lighter ones (turbogears) and even ones that are not as much CMS but frameworks (django, pylons, even quixote). Yes, some of the frameworks/CMS have small communities (quixote) but others (django, tubogears) are quite active. Still, each _do_ have a community and if th OP chooses one that has a critical mass (all of the above), he will find ample help to get over the humps & bumps. I'm presently working with Django and am thoroughly enjoying it. While it isn't perfect, nothing is, it is very well documented and has a vigorous community. I have worked with Zope and Quixote (ridiculous to the sublime), Django is a nice blend of features with an intelligent API for my needs. Your mileage may vary. >expansion and extensibility would probably be as >problematic regardless of your choice: you can >expand/extend your code depending on available >modules and your imagination/skill. you can expand/ >extend a packaged cms system depending on how >it presents an API and/or other means and limited >by what the people coding, managing, and releasing >the cms package choose to add (there'll sooner or >later be bloat in everything, you want your bloat or >some one else's?). Do you think a person with emerging skills is going to create clean, elegant code that optimizes Python's strengths? No aspersions toward's Richard's skills, just going by his own remark: "I have a rudimentary knowledge of Python" If the OP had stated some really specific and very unique requirements, there may be justification but telling someone to 'roll their own'. It is like saying there are side-effects to the latest Flu shot so you better go create your own. I don't mean to be critical of you; taking the time to express your constructive opinion is a valuable act. However, in this case I don't believe it serves in the best interest in the OP's requirements. There are some truths to what I believe you were trying to say. Some CMS/Frameworks like Zope are to be avoided, IMHO, unless they satisfy some specific requirements (the Zope sites I have are a bear to extend for reasons outside the scope of this thread). They are bloated or just non-starters, but thankfully they are not the only options. To close, I strongly suggest the original poster Richard check out Django, TurboGears and Pylons. I don't have much exp. with the latter two, but there is a reason they are generally popular. While those reasons don't meet with my req. they may meet with his. It is _always_ easier to engineer/re-engineer from a _good_ base of knowledge than it is to start fresh... though an open mind is equally important. I hope this helps, Scott >On Nov 27, 2007, at 6:52 AM, Richard Querin wrote: > >> Hi, >> >> I've got a site that is currently a static site. While not >> unmanageable at the moment (it's still pretty young), we've been >> entertaining thoughts of converting it to a CMS system. I'm looking >> for some good suggestions based on some simple criteria: >> >> >> I'm a complete newbie when it comes to CMS systems so I'm not sure >> whether or not it might be better just to go with something like an >> install of Wordpress instead. >> >> Just looking for some suggestions. The current site btw is >> http://screencasters.heathenx.org >> >> RQ >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CMS advice wanted
the above), he will find ample help to get over the humps & bumps. >evaluating the community around a framework/cms product >is an important part of evaluation. ... and everybody's measuring sticks are different. >> Do you think a person with emerging skills is going to create clean, >> elegant code that optimizes Python's strengths? No aspersions toward's >> Richard's skills, just going by his own remark: "I have a rudimentary >> knowledge of Python" >certainly not: experienced coders generally code much better >than in their pre-experienced state. Note the key issues are >* does he want to take on coding >* does his project reasonably permit his doing so (time to market) >* is there some special customization he has in mind Valid as a learning exercise, sure, or to maintain propriety, another reason. All good points but not necessarily a good _starting_ point. It helps knowing what you don't want as much as it helps knowing what you want. The evaluation of existing tools available can assist in both and only after that can one trully make an informed decision as to wether to build or buy, as you put it. >> I don't mean to be critical of you; taking the time to express your >> constructive opinion is a valuable act. However, in this case I don't >> believe it serves in the best interest in the OP's requirements. >your comments are very informative. this is a build-or-buy issue, and >i hope what we're writing provides some helpful insights to those who >are considering python projects, including richard. Absolutely. If the least we've obtaind is the ability to ask better questions, then it is a net gain. >> There are some truths to what I believe you were trying to say. Some >> CMS/Frameworks like Zope are to be avoided, IMHO, unless they satisfy >> some specific requirements (the Zope sites I have are a bear to extend >> for reasons outside the scope of this thread). They are bloated or >> just non-starters, but thankfully they are not the only options. >it would be nice to have some comparative information >on these products: does anyone know of a web site or >other source that compares CMS/frameworks? Ahh, now this is _where_ roll-your-own comes into play. Rough comparrisions i.e. "does it have xyz feature" are helpful in narrowing the range but a person really does have to take the leap and play with the tools. A really good starting point, IMO, is to scan the tutorials and documentation. Maybe watch a few videos and see which 'feels' the best. Then choose one that seems to fit the needs and dive into it with the tutorial or a small project. Rinse and repeat as necessary. Before I chose my current framework, I looked for comparative information. Since this is a moving target, it can only be a rough guide. I had to research more into the features available and see how they fit. Some of the things I considered were how it interfaced with a DB. I'm an object-oriented guy so the ORM (object-relational model) was a consideration. The cost of that is performance as a site becomes more complex. If your db requirements are minimal then this may not be an issue or it may make the db interface so transparent you don't have to think about it anymore. Another consideration was portability of code from one project to another - something I do frequently. How is that handled. If you don't move code, it doesn't matter as much. Templating syntax and the separation of code from presentation was yet another consideration. Is it intelligently done and easy to work with? There are more things to think about, but I have run out of time for now. HTH Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CMS advice wanted
On 11/27/07, Richard Querin ([EMAIL PROTECTED]) wrote: >After reading it all I'm wondering if maybe a templating system like >Cheetah might be the way to go for us. I'll have to do a lot more >reading and exploring. Sure. Be wary of any system that allows the template to freely call python i.e. one system I've seen: ... 'nuf said. >I'd love to learn something like Django but >like it has been said, that's really a framework you'd use to build a >CMS. And this site is really a labour of love and not a business >venture so the time we invest into it at the moment is kind of in >short supply. There are a couple of 'screencasts' on 'showmedo.com', one of them is here: <http://showmedo.com/videos/video?name=110&fromSeriesID=110> ... it's the typical "Build a wiki in 20 minutes" dog 'n pony show, but you do get a feel for some of the key features. There is a pretty direct line between the request and rendering a response. Everything arrives in a dictionary and is returned in a dictionary, usually with a template spec'd but can be direct too (this isn't totally unique to django, I'm just illustrating the concept). URLs are parsed using regular expressions, a portable skill so it's not a framework-specific element and IMO doesn't count in the 'learning curve'. A big difference between templating systems is how 'active content' is described. Some templating structures use embedded python within custom tags. This is not the case with django and for some that is a deal-breaker, others it is a deal-maker. It's pretty feature-rich, but _does_ have its own (well documented) syntax using curly-braces ie. {{ dict.item }} or {% ifequal %}. The db interface is straightforward and much of it is managed for the developer, including the table creation; a single command-line call. There are a few gotcha's when you want to do some complex queries, but for most things it is straightforward and capable. There is the ability to use raw SQL, so the developer isn't 'trapped'. Each table is defined as a python class with field-names as class-attributes and the class-name typically as the app & table-name i.e. 'thisap_apptable'. The developer can then define methods within each of the classes to do most table-related things i.e. custom type-chekcing, agregation of fields and so on. Quite pythonic indeed. (you could check out SQLObject for similar functionality in an independent library)[EMAIL PROTECTED] Again, much of the required skills are very portable and not framework specific. This was a selling point _for_me_, it feels natural to work with. It's automatic admin forms were another bonus, allowing the developer to focus on more important things. Did I mention the automatic forms??? It has a built-in server as well, typically for development and dead-simple to start/config. From the main project directory the call is: python manage.py runserver ... an optional port number can be added. "manage.py" is a set of utility and maintenance scripts for creating the databases, seeing what SQL is generated and so on. Still, as much as _I_ like this framework, I fully recognize there are good reasons why others exist and respect their capabilities. I don't want you or anyone else to use this because I said so, but because after review it is what meets your needs. All the best, Scott PS. In fact, I fully intend on exploring Pylons (and now Webpy) in the new year - nothing is perfect for all circumstances. >While we have less than 50 entries at the moment, adding each one is >still quite a hack. I've written a small wxpython app to take away >some of the pain of it, but it's still prone to corruption and still >too much work. > >I think I'll have to watch some demo's to get a feel for how some of >these systems work before going down any specific path, because a lot >of it is still Greek to me. > >Again sincere thanks for all the great info, and I'll try to check >back in on this thread once we get going on a solution. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python CMS advice wanted
On 11/27/07, jim stockford ([EMAIL PROTECTED]) wrote: >I'd love to know scott's definition of "framework", especially >contrasting with full-blown CMS. Yes, when one compares something like Quixote to Zope, there is a _lot_ of middle-ground. They are all frameorks, just with incrementally larger feature-sets (a.k.a. bloat and learning curve). I just anecdotally draw anline in the sand when workflows and content start being managed extensively. With the two names above, I classify the first is a framework, the latter is hel^h^h^h a CMS. <http://en.wikipedia.org/wiki/Web_framework> >Frameworks for Python: >CherryPy · Django · Karrigell · Nevow · Porcupine · Pylons · Spyce · >TurboGears · TwistedWeb · Webware · Zope I just found a new-to-me rather lite framework: <http://webpy.org/> There is also more related info here: <http://wiki.python.org/moin/WebProgramming> A few years old, but still somewhat informative: <http://colorstudy.com/docs/shootout.html> <http://www.boddie.org.uk/python/web_frameworks.html> >Richard, i think from the (very) little investigation i did >following scott's last post, that you should investigate >Django. to me it looks like a pretty streamlined "framework" >that marries a database (your choice of a few) to a web >server (apache seems their choice) via mod_python. FastCGI and WSGI are also supported, the latter looks promising. Has an integrated server as well. >If you take a look on the top-level page for django >http://www.djangoproject.com/ >you should see a link for "DRY principle". Click it and >read and follow the links in the subsequent pages: >you'll find an easy-to-read, to-the-point set of links to >coders' wisdom (Don't Repeat Yourself, >OnceAndOnlyOnce, YouAren'tGonnaNeedIt, and more). > >http://www.djangoproject.com/ If nothing else, some of the documentation from the project does cover good general material, as you've pointed out. (I wish I could get my teen-aged kid to figure out the DRY principal... but I digress ;-) Thanks for the good discussion, Jim. For my part, I think it's about time for me to stick a fork in it 'cause it's done ;-) Happy trails! Scott >On Nov 27, 2007, at 6:49 PM, Richard Querin wrote: > >> Whoa!. Lots of very good advice here. Thanks to all. >> >> After reading it all I'm wondering if maybe a templating system like >> Cheetah might be the way to go for us. I'll have to do a lot more >> reading and exploring. I'd love to learn something like Django but >> like it has been said, that's really a framework you'd use to build a >> CMS. And this site is really a labour of love and not a business >> venture so the time we invest into it at the moment is kind of in >> short supply. >> >> While we have less than 50 entries at the moment, adding each one is >> still quite a hack. I've written a small wxpython app to take away >> some of the pain of it, but it's still prone to corruption and still >> too much work. >> >> I think I'll have to watch some demo's to get a feel for how some of >> these systems work before going down any specific path, because a lot >> of it is still Greek to me. >> >> Again sincere thanks for all the great info, and I'll try to check >> back in on this thread once we get going on a solution. >> >> RQ >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Silly question: Modifying code while the script is running
Okay, I've got this ircbot that i wrote in python, and while we were all making Terminator jokes, it occurred to me that it would actually be reletively easy to have redqueen (that's the bot) write code into another file. Then you just have to specify the file and import the code and run it. It sounds possible, but there are a couple of things i'm not sure how to do. The biggest problem is I'm not sure how to run the external code. Does anyone know of good way to do this, or can someone just point me in the right direction? -Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help beginner in python.
i need to write an algorithm for computing square roots. so far I have import math def main (): print " This program computes approximate square roots using Newton's method: " print input = (" Enter whose square root you wish to compute (a) : ") input = (" Enter the number of iterations :" ) discRoot = math.sqrt print print "The solutions of the square roots" I need to have it print out iterations and math.sqrt what am i doing wrong? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Counting help
I have extracted a list of names, i.e. "Joe Smith" "Joe Smith" "Jack Smith" "Sam Love" "Joe Smith" I need to be able to count the occurances of these names and I really don't have any idea where to begin. Any ideas? excuse me this is my first post to this list, I hope I included enough information. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Counting help
Byron wrote: Luis N wrote: Ideally, you would put your names into a list or dictionary to make working with them easier. If all you're trying to do is count them (and your list of names is long), you might consider a dictionary which you would use like so: #This is just the first thing I considered. l = ['a list of names'] d = {} for name in namelist: if d.has_key(name): x = d.get(name) d[name] = x + 1 else: d[name] = 1 100% agreed. I have used this approach before and it works great... Byron Thanks for the snipplet, it's perfect for what I'm doing, I wasn't aware of the has_key() or get(), this is very usefull. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Counting help
Scott Oertel wrote: Byron wrote: Luis N wrote: Ideally, you would put your names into a list or dictionary to make working with them easier. If all you're trying to do is count them (and your list of names is long), you might consider a dictionary which you would use like so: #This is just the first thing I considered. l = ['a list of names'] d = {} for name in namelist: if d.has_key(name): x = d.get(name) d[name] = x + 1 else: d[name] = 1 100% agreed. I have used this approach before and it works great... Byron Thanks for the snipplet, it's perfect for what I'm doing, I wasn't aware of the has_key() or get(), this is very usefull. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor The next problem I have though is creating the dict, i have a loop, but i can't figure out how to compile the dict, it is returning this: ('Joey Gale', ('Scott Joe', ('This is lame' ))) listofnames = [] while (cnt < number[1][0]): if (date[2] == today[2]): test = regex.findall(M.fetch(int(number[1][0]) - cnt, '(BODY[HEADER.FIELDS (FROM)])')[1][0][1].rstrip()) cnt += 1 if (nameofsender != []): print nameofsender[0] listofnames = nameofsender[0], listofnames else: no_name += 1 else: break ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Counting help
Scott Oertel wrote: Byron wrote: Luis N wrote: Ideally, you would put your names into a list or dictionary to make working with them easier. If all you're trying to do is count them (and your list of names is long), you might consider a dictionary which you would use like so: #This is just the first thing I considered. l = ['a list of names'] d = {} for name in namelist: if d.has_key(name): x = d.get(name) d[name] = x + 1 else: d[name] = 1 100% agreed. I have used this approach before and it works great... Byron Thanks for the snipplet, it's perfect for what I'm doing, I wasn't aware of the has_key() or get(), this is very usefull. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor The next problem I have though is creating the dict, i have a loop, but i can't figure out how to compile the dict, it is returning this: ('Joey Gale', ('Scott Joe', 'This is lame' ))) listofnames = [] while (cnt < number[1][0]): if (date[2] == today[2]): test = regex.findall(M.fetch(int(number[1][0]) - cnt, '(BODY[HEADER.FIELDS (FROM)])')[1][0][1].rstrip()) cnt += 1 if (nameofsender != []): print nameofsender[0] listofnames = nameofsender[0], listofnames else: no_name += 1 else: break ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Counting help
Kent Johnson wrote: Scott Oertel wrote: The next problem I have though is creating the dict, i have a loop, but i can't figure out how to compile the dict, it is returning this: ('Joey Gale', ('Scott Joe', 'This is lame' ))) listofnames = [] while (cnt < number[1][0]): if (date[2] == today[2]): test = regex.findall(M.fetch(int(number[1][0]) - cnt, '(BODY[HEADER.FIELDS (FROM)])')[1][0][1].rstrip()) cnt += 1 if (nameofsender != []): print nameofsender[0] listofnames = nameofsender[0], listofnames I think you want listofnames.append(nameofsender[0]) which will add nameofsender[0] to the list. What you have - listofnames = nameofsender[0], listofnames is making a tuple (a pair) out of the new name and the old list, and assigning it to listofnames. Kind of like CONS in LISP - but Python lists are more like arrays than like LISP lists. Kent else: no_name += 1 else: break ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Thank you everyone, this is exactly it, I'm going to take that link from byron and read up on dicts/lists. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Working with files
How do I use the built in file objects to insert text into a file at a certain location? i.e. something, 2, chance, weee nothing, happened, crap, nice need to search for "something" and insert, "what," before it thanks for the feedback you guys are great :) -Scott Oertel -Py2.4 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with files
Byron wrote: Bob Gailer wrote: read the file into a string variable (assuming the file is not humungus) find the location of "something" in the string assemble a new string consisting of: the original string up to the location (index) of "something" "what" the rest of the original string write the new string to the file Hi Scott, Bob gave you the basic instructions that you need to complete the task that you are asking for. If you don't know how to do this, I would suggest that you start with the following Python tutorial: http://www.greenteapress.com They provide an excellent tutorial for learning the basics of Python -- and best of all, it's free and written for absolute beginners. Take care, Byron --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Thanks again, I figured it out with the index function of the file objects, I didn't know that you could search for a word and find the exact pos of it, that was the tiny bit of information I was looking for. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with files
Bob Gailer wrote: > At 02:55 PM 8/24/2005, Scott Oertel wrote: > >> How do I use the built in file objects to insert text into a file at a >> certain location? >> >> i.e. >> >> something, 2, chance, weee >> nothing, happened, crap, nice >> >> need to search for "something" and insert, "what," before it > > > Here's the algorithm. If you know enough Python you will be able to > code it. So put together a program, give it a try and come back with > questions. > > read the file into a string variable (assuming the file is not humungus) > find the location of "something" in the string > assemble a new string consisting of: > the original string up to the location (index) of "something" > "what" > the rest of the original string > write the new string to the file > > Bob Gailer > 303 442 2625 home > 720 938 2625 cell basically I took the idea and the code example given and wrote this little function, i stuck vars in this html page like #email# and just used it like this, " insertdata('#email#','[EMAIL PROTECTED]') works perfect! def insertdata(name, data): file = open('template.html', 'r+') contents = file.read() pos = contents.index(name) file.seek(pos) file.write(data) file.write(contents[pos + len(name):]) file.close() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] mod_python.publisher
I'm having an issue with mod_python.publisher, supposedly i should be able to just place this code def index(): return "This is only a test." into test.py and when placed into my browser it should run the index function by default, but instead i get a 404 error. i'm running Apache/1.3.33 (Unix) mod_python/2.7.11 Python/2.2.3 -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mod_python.publisher
Scott Oertel wrote: I'm having an issue with mod_python.publisher, supposedly i should be able to just place this code def index(): return "This is only a test." into test.py and when placed into my browser it should run the index function by default, but instead i get a 404 error. i'm running Apache/1.3.33 (Unix) mod_python/2.7.11 Python/2.2.3 -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Just for fun i decided to upgrade the python version to 2.4.1 Apache/1.3.33 (Unix) mod_python/2.7.11 Python/2.4.1 mod_gzip/1.3.26.1a mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635 mod_ssl/2.8.22 OpenSSL/0.9.7a PHP-CGI/0.1b still no luck =( ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CREATING A PR.EXE FROM A PR.PY
Jack Anema wrote: Can you or someone give me very specific instructions as to how to create an _.EXE file from a _.PY file. I have spent a lot of time looking through all 7 sections of FAQ's at http://www.python.org/doc/faq/ and many other sights. I have also gone to http://starship.python.net/crew/theller/py2exe/ and tried to use the general comments there. I did download and install *win-py2.4.exe . This installed successfully as far as I can see. There were no error messages and REMOVEPY2EXE.EXE was created in my PYTHON24 folder. The machine I am running, is running XP professional, 2002. It has a Pentiuum(R) 4, 1.8 Ghz CPU. The drive has 37 GB free. I am by no means a computer expert but I am not illiterate either. I have used MS Quick Basic for many years. In the past I have also used APL and Fortran on various machines over the years. I just am not familiar enough with Python and have not been able to find the detailed data I need to do what I want. Up to a month ago I had never heard of Python and I badly need the ability to make *.PY programs files run as *.EXE files. Can you or someone supply the very specific instructions to do this? I would also be perfectly willing to arrange with someone to call them at their convenience and do it over the phone and compensate the person for their effort and time. I sincerely and very much appreciate anyone's response and help! Thank you! Jack Anema. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Try using py2exe it works pretty well for compiling .py into a portable .exe distribution. http://starship.python.net/crew/theller/py2exe/ -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Opening files, finding their location
I have a small problem with one of my scripts currently, I'm using the config parser to open a config.ini file, but this program is going to be designed to be used as a cron job, currently i made a work around.. ./program.py config.ini is how you run it from the command line I'm looking for an easy way to find the current directory location of my program so I can include the config.ini file correctly without having to pass command line args. here is my work around, try: config.readfp(open(argv[1])) except (IndexError, IOError): print "Config.ini file not found." exit() thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Opening files, finding their location
Christopher Arndt wrote: Scott Oertel schrieb: I'm looking for an easy way to find the current directory location of my program so I can include the config.ini file correctly without having to pass command line args. So, do you want to find out, where your script is living, or the directory from which it was called (the "working directory")? The former can be found out like this: Assuming cron calls your script with the full path name (which should be the case because it uses the shell to execute your script): import os, sys mydir = os.path.dirname(sys.argv[0]) When you want the current working directory: import os mydir = os.getcwd() Then to get the path to your config file, either: config_path = os.path.join(mydir, 'config.ini') HTH, Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor It was this one: mydir = os.path.dirname(sys.argv[0]) thanks man, it was starting to drive me nuts :) -Scott Oertel -Gawr.com! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] code improvement for beginner ?
lmac wrote: > --- > >The problem with downloading the images is this: > >- >http://images.nfl.com/images/globalnav-shadow-gray.gif >Traceback (most recent call last): > File "/home/internet/bin/nflgrab.py", line 167, in ? >urllib.urlretrieve(img,img[f:]) > File "/usr/lib/python2.3/urllib.py", line 83, in urlretrieve >return _urlopener.retrieve(url, filename, reporthook, data) > File "/usr/lib/python2.3/urllib.py", line 216, in retrieve >tfp = open(filename, 'wb') >IOError: [Errno 13] Permission denied: '/globalnav-shadow-gray.gif' >- > >Is there any solution to know if i can download the image ? > >Thanks. > > > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > > I used this in my previous program while having problems writing files. from sys import argv from os.path import dirname, join try: tfp = open(join(dirname(argv[0]), filename), 'wb') except IOError: print "Unable to write file, pick another directory" this will save it into the directory that your program resides in. you might want to check out this current lib doc, http://www.python.org/doc/current/lib/os-file-dir.html it has a bunch of objects of the os module that are good for testing if a directory is writable ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone teach me...?
luke p wrote: nathan, there are a few GUI options available to you. the one that is bundled with the python installation is TKInter. that's an "i" not an "L". you can also use the python interface for WxWindows, I forget what it's called. anyway, TKInter looks fairly nice, some say it doesn't have the windows "feel" to it as much as WxWindows but who really cares because it's pretty easy to learn etc. There's a tutorial somewher eon the web written by some New Mexico thing I'm not sure but I have to run to class so I can't look it up. anyway, Give google a workout and learn as much as you can on your own. I don't think you should ask any questions that you could solve yourself, or you may aggravate the list. so try as much as you can and then if you get stuck ask someone. Go for TKInter I think you'll like it. Alan Gauld might have a tutorial for TKInter, you could check that out too. good luck. On 10/12/05, Nathan Pinno <[EMAIL PROTECTED]> wrote: Hey all, When I said that I might go to Visual Basic in an earlier message, someone replied by saying that I should ask here how to do it in Python. Well, I'm asking now: Can anyone teach me how to make a simple program that uses a GUI? Thanks, Nathan Pinno Crew, McDonalds Restaurant and fan extraordinare of the Oilers. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor I've tried ALL the available options for creating GUI's with python, or so I believe I have :) right now I am finding that using PythonCard is the best solution for me, it's still a little bit rough around the edges but it make working with wxPython really simple, and things I cannot accomplish with PythonCard I can go back to using wxPython instead. Boa constructor always crashes on me in linux, on windows it's nice, but I make one small change in the code and boaconstructor will freak out and not be able to read anything. that's just my experience. -- scott oertel gawr.com :) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Newbie Question - Python vs Perl
As a newbie to Python I'd like to know if someone can tell me some strengths and weaknesses of this language. The reason I'm asking is a friend told me I should learn Perl over Python as it's more prevalent. I'm going to be using it on a Mac. I'd appreciate hearing any views on this topic. My own view is that it's always good to learn new things as you then have more tools to use in your daily programming. Thanks in advance. Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request For Suggestions
You could include the Pygame module. If this CD is for beginners, nothing like writing a game to provide a little bit of motivation! Plus, Pygame provides a lot of multimedia features all in one place (graphics, sound, keyboard, mouse, joystick, CD, mixer) http://www.pygame.org/ I'm sure everyone could suggest their favorite module be included, but Pygame might be the kind of thing that would catch some beginner's fancy. How many of us wrote a game as one of our first programs? :) -Scott -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Basem Narmok Sent: Friday, December 02, 2005 3:54 PM To: tutor@python.org Subject: [Tutor] Request For Suggestions Hi all, I am planning to make a Python CD for advocating Python, and I need your suggestions about this, the objective is to build a CD that contains the basic material for Python beginner (e.g. Python 2.4.2 for different platforms) with some advocating material (e.g. videos), and here is what comes to my mind to present on the CD: Software: - Python 2.4.2 for different platforms. - ironPython 0.9.5 - wxPython 2.6 - SPE 0.7.5 Media: - Introducing Python (video) - TurboGears (videos) - ironPython (videos) - maybe some video from URU and CIV IV games The CD is intended to be given to Python beginners in a free course, any comments or suggestions are welcome. Thanks Basem ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception repeated in a loop
An unhandled exception immediately stops the execution of your code. A handled exception (try/except) does not stop code execution (unless you explicitly tell it to). This shows how a handled exception does not stop code execution: try: raise Exception except: print 'caught exception' print 'fell through' Hope this helps... -Scott -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Jan Eden Sent: Tuesday, December 06, 2005 10:24 AM To: Pawel Kraszewski; tutor@python.org Subject: Re: [Tutor] Exception repeated in a loop Hi Pawel, Pawel Kraszewski wrote on 06.12.2005: >Dnia wtorek, 6 grudnia 2005 16:29, Jan Eden napisa?: >> Hi, >> >> I use the following loop to parse some HTML code: >> >> for record in data: >> try: >> parser.feed(record['content']) >> except HTMLParseError, (msg): >> print "!!!Parsing error in", record['page_id'], ": ", msg >> >> Now after HTMLParser encounters a parse error in one record, it repeats to >> execute the except statement for all following records - why is that? > >Short answer: because you told Python to do so... > >Long answer: > >My hint for students having such problems is to execute their code with a >pencil on a hardcopy. They read aloud what the program currently does - >usually they spot the error during the first "reading". > >Your code being "read loud" > >1. begin loop >2. attempt to execute parser.feed >3. abort attempt if it fails, showing the error >4. take next loop > >So - you take next loop regardless of the failure or not. There are two ways >out of here. I wrote them "aloud", to transcribe into python as an excersize: > >(Notice the difference between this and your original) > >I) > >1. attempt to >2. begin loop >3. abort attempt if it fails, showing the error >4. take next loop > >II) >1. begin loop >2. attempt to execute parser.feed >3. abort attempt if it fails, showing the error AND breaking the loop >4. take next loop > Thanks, I tested your suggestion, which works fine. But I don't understand the problem with my original code. If the parser raises an exception for a certain record, it should print the error message and move on to the next record in the loop. Why would I need the break statement? What's more - if the break statement is executed, all following records will never be parsed. I still don't understand why failure of a single record affects the other records. Thanks, Jan -- There's no place like ~/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Auto package install?
The Zen of Python (http://www.python.org/doc/Humor.html#zen) states: "There should be one-- and preferably only one --obvious way to do it." I'm searching for the obvious Pythonic way to achieve automated package installation (I believe Perl's CPAN can be used to accomplish this in Perl?). I'd like to have a way where a Python script can automatically download/install/update the versions of packages it needs to run. I'm looking to avoid requiring the users of my scripts to manually download and install a pile of packages (with potential for user error) just to run my scripts. I use mostly common packages such as wxPython. My scripts may eventually get out to > 100 people over 3 states so I want to minimize administration and potential for user error. I'm aware of the very handy CheeseShop (http://www.python.org/pypi), but this doesn't automate the installation process. I've done some googling and found ciphon (http://sourceforge.net/projects/pythonsiphon) and pypan (http://starship.python.net/crew/theller/pypan/), but both seem somewhat abandoned and incomplete. EasyInstall (http://peak.telecommunity.com/DevCenter/EasyInstall) seems new and I'm willing to hear any experiences with it. I also glanced thru c.l.p and most of the discussions seem a few years old and bordered on holy wars with no real obvious resolution... So, what is the obvious way to accomplish this? If no such solution exists currently, what do people consider "best practices" when releasing scripts dependent on other packages to a number of users? Thanks for the help. I'm relatively new to the group and it has been great so far! -Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pyton and Webpages
WRT creating the Excel file... The previously mentioned techniques work great. But, if you want to start off even simpler, just create a .csv (comma separated value) file with python's file i/o (there is even a python module to help you with this if you want). It is just a simple text file that looks something like this: Name, Age, Hair Adam, 23, brown Don, 19, gray Biff, 42, blond Cathy, 35, red Gary, 99, none Excel handles these files just fine. You don't get all the fancy formatting, but this is a good first step. Good luck -Scott -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Kent Johnson Sent: Monday, May 01, 2006 10:38 AM Cc: Tutor@python.org Subject: Re: [Tutor] Pyton and Webpages Jon Whitehouse wrote: > Greetings All, > > I'm a newbie to python and am curious if I can do the following in python. I'm > not asking HOW to do this, just if it is possible before I spend the time to > learn python and do it myself. > > I want to write a program to go to a webpage, pull the data, and then place it > into an excel spreadsheet and then write it to an html file and allow me to > also click on the link to the excel spreadsheet. > > Is this possible to do with python? Yes. Some of the pieces you might use are urllib2 and BeautifulSoup to get the data from the web page win32com or pyexcelerator to write the Excel file http://docs.python.org/lib/module-urllib2.html http://www.crummy.com/software/BeautifulSoup/index.html http://starship.python.net/crew/mhammond/win32/ http://sourceforge.net/projects/pyexcelerator Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Getting current class method name
Ok, I’m looking to create a quick debug function that prints out the current function that is running (to help in debugging what functions are being run). I know that I can use a debugger to get a stack trace (and I do), but I’m still curious about this problem. Here’s what I’ve got so far: def Foo(): PrintCurFunc() class cBase: def Run(self): PrintCurFunc(self) class cChild(cBase): pass import traceback def PrintCurFunc(obj = None): stack = traceback.extract_stack() scriptName, lineNum, funcName, lineOfCode = stack[-2] if obj: print '%s.%s()' % (obj.__class__.__name__, funcName) else: print '%s()' % funcName def main(): Foo() b = cBase() c = cChild() b.Run() c.Run() x = cTwo() x.Run() if __name__ == '__main__': main() The output I get is: Foo() cBase.Run() cChild.Run() cTwo.Run() cTwo.Run() Now, PrintCurFunc() above gets me the output I want in the fist two cases (Foo() and cBase.Run()). But, in the case of c.Run(), I would still like to see it output cBase.Run(), since that is the method that is being run. Yes, cChild being derived from cBase does have an inherited Run method, but I would like my output to display “where the code physically lives” so that for debugging I can basically get a stack trace to see what is executed when. It might be more clear in this example: class cOne: def Run(self): PrintCurFunc(self) class cTwo(cOne): def Run(self): PrintCurFunc(self) cOne.Run(self) x = cTwo() x.Run() gets me the output of: cTwo.Run() cTwo.Run() when I would prefer it output: cTwo.Run() cOne.Run() …which reflects the call stack more clearly. Now, I’ve looked into the traceback module but was only able to find the name of the function. Passing self into PrintCurFunc was my attempt at getting at the class name. But, as you see, it obviously returns the object’s class name and not the class name the function was defined on. I also looked at this recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 but it only gives me a function name and not the class name as well. Any thoughts? I’m a bit new to Python’s reflection features… Thanks tons! -Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Communicating with Win2000 runas.exe
I have a problem which I was hoping that Python could solve for me, but I have become stuck for days now after only 2 lines of code. My son has a Microsoft game on a shared family computer, which Microsoft in its infinite wisdom requires you to run as 'administrator'. Call me old-fashioned but I don't want to promote an 8 year-old to administrator just so he can run his game! Enter 'runas.exe'... However, because we are on Windows 2000, runas does not allow you to save a password - it has to be entered every time: not much further forward. So I'm thinking along these lines: import subprocess sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe /user:administrator C:\Program Files\Microsoft Games\Age of Mythology\aom.exe') #some sort of code to send the password here... #help! Sure enough, this brings up a prompt asking for the administrator's password, but I can't get anything to work in terms of getting the script to provide the password. Am I barking up the wrong tree here? Any clues would be gratefully received. (Even if I do get this to work, my next trick is to hide the password from any prying eyes looking at the script...) Thanks Barnaby Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communicating with Win2000 runas.exe
Tim Golden wrote: > [Barnaby Scott] > > | So I'm thinking along these lines: > | > | import subprocess > | sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe > | /user:administrator > | C:\Program Files\Microsoft Games\Age of Mythology\aom.exe') > | #some sort of code to send the password here... > | #help! > > I *think* -- and I'm happy to be wrong -- that there's > no way you're going to get that password in there. One > place to start looking might be: > > pywinauto - http://pywinauto.pbwiki.com/ > > which lets you automate Windows in general; don't know > how much use it'll be here. > > Alternatively, look into the pywin32 package, and in > particular at the win32security functions which let you > impersonate another user. They're not trivial to use, > but their use has been explained a few times over the > years I think. Mostly by Roger Upole who wrote most if > not all of the Python bindings. > > Here's a post which looks useful; you'll have to hunt > around for others: > > http://groups.google.com/group/comp.lang.python/msg/6bbefb9d4d45d253 > > I suggest you ask this question again on the main > python / python-win32 lists; it's a bit too platform-specific > for the tutor list, I would say. > > TJG Thanks for your tips. In fact the first link you gave put me onto Sendkeys (http://www.rutherfurd.net/python/sendkeys/), which is a prerequisite for pywinauto. In the end that was all I needed. In case anyone else is interested here is my code now (with SendKeys installed): import subprocess, SendKeys subprocess.Popen(r'C:\WINNT\system32\runas.exe /user:administrator "C:\Program Files\Microsoft Games\Age of Mythology\aom.exe"') SendKeys.SendKeys('{PAUSE 1}MyAdministratorPassword{ENTER}') Worth knowing about - might be quite useful for all sorts of things, however 'quick and dirty' it feels as a technique! Thanks again BDS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] string.uppercase: too many for locale
Can anyone explain the following: I was getting string.uppercase returning an unexpected number of characters, given that the Python Help says that it should normally be A-Z. Being locale-dependent, I checked that my locale was not set to something exotic, and sure enough it is only what I expected - see below: IDLE 1.1 No Subprocess >>> import locale, string >>> locale.getlocale() ['English_United Kingdom', '1252'] >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZŠŒŽŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ >>> print string.lowercase abcdefghijklmnopqrstuvwxyzƒšœžßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ >>> What am I missing here? Surely for UK English, I really should just be getting A-Z and a-z. In case it is relevant, the platform is Windows 2000. Thanks Barnaby Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string.uppercase: too many for locale
Kent Johnson wrote: > Barnaby Scott wrote: >> Can anyone explain the following: I was getting string.uppercase >> returning an unexpected number of characters, given that the Python >> Help says that it should normally be A-Z. Being locale-dependent, I >> checked that my locale was not set to something exotic, and sure >> enough it is only what I expected - see below: >> >> >> IDLE 1.1 No Subprocess >> >>> import locale, string >> >>> locale.getlocale() >> ['English_United Kingdom', '1252'] >> >>> print string.uppercase >> ABCDEFGHIJKLMNOPQRSTUVWXYZŠŒŽŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ >> >>> print string.lowercase >> abcdefghijklmnopqrstuvwxyzƒšœžßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ >> >>> >> >> What am I missing here? Surely for UK English, I really should just be >> getting A-Z and a-z. In case it is relevant, the platform is Windows >> 2000. > > Interesting. Here is what I get: > >>> import locale, string > >>> locale.getlocale() > (None, None) > >>> string.uppercase > 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' > > Somehow the locale for your system has changed from the 'C' locale. If I > set the default locale I get similar results to yours: > >>> locale.setlocale(locale.LC_ALL, '') > 'English_United States.1252' > >>> locale.getlocale() > ('English_United States', '1252') > >>> print string.uppercase > ABCDEFGHIJKLMNOPQRSTUVWXYZèîă└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╪┘┌█▄▌▐ > > which doesn't print correctly because my console encoding is actually > cp437 not cp1252. > > It looks like string.uppercase is giving you all the characters which > are uppercase in the current encoding, which seems reasonable. You can > use string.ascii_uppercase if you want just A-Z. > > Kent > Thanks, but this raises various questions: Why would my locale have 'changed' - and from what? What *would* be the appropriate locale given that I am in the UK and use English, and how would I set it? Why on earth does the ['English_United Kingdom', '1252'] locale setting consider ŠŒŽŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ to be appropriate? Is this less to do with Python than the operating system? Where can I read more on the subject? Sorry for all the open-ended questions, but I am baffled by this and can find no information. Sadly, just using string.ascii_uppercase is not a solution because I am trying to develop something for different locales, but only want the actual letters that a particular language uses to be returned - e.g. English should be A-Z only, Swedish should be A-Z + ÅÄÖ (only) etc. The thing I really want to avoid is having to hard-code for every language on the planet - surely this is the whole point of locale settings, and locale-dependent functions and constants? Thanks Barnaby Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] miniwiki 1.3 BETA bugs
Kirk Z. Bailey wrote: > ok, let's post this again. last time went into purgatory instead of the list. > hmmm > > I am working on updating miniwiki. the current beta code has rendering > problems with wikiwords and external sites under some circumstances. Here is > a link to the latest code: > > http://www.tinylist.org/MW.txt > > > > > > > > > Blessed Be! >- Kirk Bailey > Largo FL USA > > > kniht > +-+ http://www.mylemonadestand.biz/ - play the lemonade game! > | BOX | http://www.tinylist-org/ Freedom software > +-+ In HER Service- http://www.pinellasintergroupsociety.org/ > think http://www.seaxtradusa.org/ - The Seax Wica Trad in the USA! > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > No idea if it has anything to do with your problem, but it struck me that the iswikiword() function (and processword() which seems to be a helper for it) could be replaced with one line, and it would be reliable! def iswikiword(word): return bool(re.match('^([A-Z][a-z]+){2,}$', word)) Of course you need to import re, but that seems a small price to pay! HTH Barnaby Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] miniwiki 1.3 BETA bugs
Kirk Z Bailey wrote: > RE leaves me totally confuzzzeddded. Yep, so confuised I'm having > trouble spelling it. Sp this one line will replace both words and give a > reliable result? > > Barnaby Scott wrote: > [snip] >> No idea if it has anything to do with your problem, but it struck me >> that the iswikiword() function (and processword() which seems to be a >> helper for it) could be replaced with one line, and it would be reliable! >> >> def iswikiword(word): >> return bool(re.match('^([A-Z][a-z]+){2,}$', word)) >> >> Of course you need to import re, but that seems a small price to pay! >> >> HTH >> >> Barnaby Scott >> >> > As far as I know this is 100% reliable - at least it works for me (www.waywood.co.uk/MonkeyWiki/). I suggest you test the function to your own satisfaction - feed it tricky 'possible' WikiWords, and see how it does! I know what you mean - RE syntax is an unruly beast to try and wrestle with, but I *so* glad I made the effort. I don't claim to be anything like an expert, but I now find it very useful indeed. Here's how the function's statement works in case you're interested: bool(re.match('^([A-Z][a-z]+){2,}$', word)) re.match() will look for a match for us, according to the RE given as the first argument, and the string you want to match against as the second ^ means we demand that the pattern matches from the beginning of the string to be tested - we don't want to say yes to anEmbeddedWikiWordLikeThis. (In fact because we are using re.match instead of re.search this is not strictly necessary, but makes it clearer) ([A-Z][a-z]+) means we want a group of letters, starting with a one in the range [A-Z] i.e. a capital, followed by [a-z]+ , meaning one or more lowercase letters ('one or more' is specified by the +). That whole pattern is parenthesised because we want the next element to refer to the whole thing {2,} means we want a match only if our preceding pattern (i.e. a capitalised word) occurs a minimum of 2 times in a row, and a maximum of - well, we don't want to specify a maximum, so we leave it out. (YouMightInFactWantToSpecifyTheMaximumNumberOfWordsThatAreAllowedToAppearInYourWikiLinksToStopPeopleDoingSillyThingsLikeThis). $ means we want a match only if the pattern reaches the end of the test string - i.e. we don't want to match a WordLikeThis62734. As for bool() - nothing to do with RE, but if a match occurs, the result returned by re.match() is a MatchObject instance, otherwise None. I have used bool() to convert these two possible results into True or False though I guess this is not strictly necessary - the truth testing would happen implicitly outside the function anyway. However it seems right to return a boolean if that's what the function's obvious intent is. HTH Barnaby Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] win32gui, SetForegroundWindow() and setting focus
Greetings all... I'm looking to use the win32api and win32gui modules to do a bit of Windows tinkering (win2k) and I've hit a snag. I'd like to programmatically set which window has the focus. But win32gui.SetForegroundWindow(hwnd) seems to be what I'm looking for, but, it isn't working quite as I expect meaning I probably have a bad assumption. SetForegroundWindow() works like a charm in simple cases from the command line. However, when I enumerate all top level windows and try to set each one as the foreground window in turn, it gets thru 1-2 windows out of the 8-10 I have open before giving me this: Traceback (most recent call last): File "D:\_code\python\apps\WinTests.py", line 25, in ? cycle_foreground() File "D:\_code\python\apps\WinTests.py", line 20, in cycle_foreground win32gui.SetForegroundWindow(handle) pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available') What am I doing wrong in this case? Can my app "give away" its own focus but can't force a different app's window with focus to "give away" its focus? Is there any other way to accomplish this? I've attempted using a mix of SetFocus(), BringWindowToTop(), and EnableWindow() but couldn't find the magic combo. I've attached my test script. Run it as "WinTests cycle" to attempt to cycle the focus through all top level windows and see the traceback above. Run it as "WinTests 12345" to set focus the window with hwnd of 12345. Run it as "WinTests" to get a list of all top level windows and their hwnd's. I've tried reading the very-sparse win32 docs provided with ActiveState's PythonWin, I've read a bit on the win32 API on MSDN and I've googled around a bit, and haven't found much. Thanks for making this a great list, all... -Scott import win32gui import time import sys import win32con def win_enum_callback(hwnd, results): if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) != '': results.append(hwnd) def print_list(): handles = [] win32gui.EnumWindows(win_enum_callback, handles) print '\n'.join(['%d\t%s' % (h, win32gui.GetWindowText(h)) for h in handles]) def cycle_foreground(): handles = [] win32gui.EnumWindows(win_enum_callback, handles) for handle in handles: print handle, win32gui.GetWindowText(handle) win32gui.SetForegroundWindow(handle) time.sleep(2.0) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'cycle': cycle_foreground() sys.exit(0) if len(sys.argv) == 2: win32gui.SetForegroundWindow(int(sys.argv[1])) else: print_list() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which Python Script Editor of Choice?
> > Komodo also often gets props from the "IDE People" I've known. To throw another one into the mix, ActiveState has a free/open source version of its Komodo IDE called "Komodo Edit". I downloaded it and played with it for a few minutes awhile ago. Seems pretty slick. Anyone have any first hand experience with this one? It also supports more than just Python (also does Perl, PHP, Ruby, Rails, etc.) http://www.activestate.com/Products/komodo_ide/komodo_edit.mhtml (FWIW, most of the time, I use PythonWin to edit code and a command prompt to run scripts) > Btw, if people know of good IDE's other than PIDA that are free, run on windows and linux and allow use of VIM as the editor, please let me know. Looking at Komodo Edit's page, it supports Win/Mac/Linux, has "Vi emulation", and is free (not crippled in any way that I know of. It just has a smaller feature set when compared to the full Komodo). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Best Practice/Style Guide question
Per the interesting read at <http://www.python.org/dev/peps/pep-0008/> Can anyone explain the rationale behind this: - More than one space around an assignment (or other) operator to align it with another. Yes: x = 1 y = 2 long_variable = 3 No: x = 1 y = 2 long_variable = 3 The example is rather simplistic and I find the latter form much easier to read when there is more than three or four assignments. Furthermore, I don't like the use of 'x' and 'y' style variables for anything but classical references and concise loops favoring 'chart_x' and 'chart_y' (I have a crappy memory, more descriptive names help me, and those reading my code, keep track of what I'm doing). I _do_ see that in this example, it could be hard to follow which value is assigned to its respective name, but considering this _slightly_ less simplistic (though flawed) example: string_item = some_method(with_argument) y = 2 long_variable = antoher_method(with, multiple, arguments) another_string_item = some_method(with, more, arguments) Is easier to read (for me) as follows: string_item= some_method(with_argument) y = 2 long_variable = antoher_method(with, multiple, arguments) another_assignment = some_method(with, more, arguments) _Yes_ the order can be changed, but there are reasons why it might be inapropriate to reorder i.e. dependencies. TIA, Scott PS. There is a good best-practice link here too: <http://www.fantascienza.net/leonardo/ar/python_best_practices.html> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Providing Solutions for all the Common Questions
To throw out an idea... http://www.showmedo.com/ is a site that believes that learning-by-watching is a very effective way to teach people new skills. So, they host lots of (user-generated) screencasts (usually 5-10 minutes) that show people how to do things. Because the site is Python focused, there are 350+ videos on learning Python (150+ beginner oriented vids). Would it be helpful to take the most common questions and create screencasts that demonstre the answers to common questions, post them to ShowMeDo and get a collection of links togeher? Just a thought... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Possible to search text file for multiple string values at once?
Hi all, I understand that python excels at text processing, and wondered if there is a way to use python to accomplish a certain task. I am trying to search large text files for multiple strings (like employee ID number, or name). Any text editor (I use Windows mostly) will certainly have a "find", "replace", or even "find in files" (to search multiple files for a value) function, but this is searching for one string at a time. I would like to search a text file for a list of strings, like a sql query. For instance: To search a text file for the values 'Bob', 'John', 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do five separate searches. Lots of copying and pasting, lots of room for typos. But if you were in a SQL database, you could do something like: "SELECT * FROM my_table WHERE first_name IN ('Bob', 'John', 'Joe', 'Jim', 'Fred')" and you would get results for all five values. I would love to set up a script to parse a file and show results from a list of strings. Is this possible with python? Thanks for the input and help, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Possible to search text file for multiple string values at once?
Thanks for the help so far - it seems easy enough. To clarify on the points you have asked me about: A sqlite3 database on my machine would be an excellent idea for personal use. I would like to be able to get a functional script for others on my team to use, so maybe a script or compiled program (Win32) eventually. As for output, I would probably like to return the entire lines that contain any search results of those strings. Maybe just output to a results.txt that would have the entire line of each line that contains 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. Speed isn't as important as ease of use, I suppose, since non-technical people should be able to use it, ideally. Maybe, since I am on Win32, I could have a popup window that asks for input filename and path, and then asks for string(s) to search for, and then it would process the search and output all lines to a file. Something like that is what I am imagining, but I am open to suggestions on items that may be easier to use or code. Is that reasonably simple to code for a beginner? Thanks again, Scott On Fri, Jan 23, 2009 at 11:52 AM, Kent Johnson wrote: > On Fri, Jan 23, 2009 at 1:25 PM, Scott Stueben wrote: > >> I would like to search a text file for a list of strings, like a sql query. > > What do you want to do if you find one? Do you want to get every line > that contains any of the strings, or a list of which strings are > found, or just find out if any of the strings are there? > >> For instance: To search a text file for the values 'Bob', 'John', >> 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do >> five separate searches. Lots of copying and pasting, lots of room for >> typos. > > You can do this with a regular expression. For example, > > import re > findAny = re.compile('Bob|John|Joe|Jim|Fred') > > for found in findAny.findall(s): > print found > > will print all occurrences of any of the target names. > > You can build the regex string dynamically from user input; if > 'toFind' is a list of target words, use > findAny = re.compile('|'.join(re.escape(target) for target in toFind)) > > re.escape() cleans up targets that have special characters in them. > -- "Shine on me baby, cause it's rainin' in my heart" --Elliott Smith ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Possible to search text file for multiple string values at once?
Excellent ideas...thanks to you all for the input. I will see what I can work out in the next few days and report back. :) Scott On Sat, Jan 24, 2009 at 2:16 AM, spir wrote: > Le Fri, 23 Jan 2009 14:45:32 -0600, > W W a écrit : > >> On Fri, Jan 23, 2009 at 1:11 PM, Scott Stueben wrote: >> >> > Thanks for the help so far - it seems easy enough. To clarify on the >> > points you have asked me about: >> > >> > A sqlite3 database on my machine would be an excellent idea for >> > personal use. I would like to be able to get a functional script for >> > others on my team to use, so maybe a script or compiled program >> > (Win32) eventually. >> >> >> As long as everyone on your team has python installed (or as long as python >> is installed on the machines they'll be using), a functional script would be >> fairly easy to get rolling. Sqlite is (AFAIK) included with the newer >> versions of python by default. Heck, it's on the version I have installed on >> my phone! (Cingular 8525). Simply zipping up the directory should provide an >> easy enough distribution method. Although, you *could* even write a python >> script that does the "install" for them. >> >> >> > As for output, I would probably like to return the entire lines that >> > contain any search results of those strings. Maybe just output to a >> > results.txt that would have the entire line of each line that contains >> > 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. >> >> >> The simplest method: >> >> In [5]: f = open('interculturalinterview2.txt', 'r') >> >> In [6]: searchstrings = ('holy', 'hand', 'grenade', 'potato') >> >> In [7]: for line in f.readlines(): >>...: for word in searchstrings: >>...: if word in line: >>...: print line >>...: >>...: >> Hana: have a bonfire n candy apples n make potatoes on a car lol! >> >> Wayne: potatoes on a car? >> >> Hana .: yer lol its fun and they taste nicer lol, you wrap a potato in >> tinfoil a >> nd put in on the engine of a car and close the bonnet and have the engine >> run an >> d it cooks it in about 30 mins >> >> Speed isn't as important as ease of use, I suppose, since >> > non-technical people should be able to use it, ideally. > > I guess the easiest for your team would be to: > * let the script write the result lines into a text file > * let the script open the result in an editor (using module called subprocess) > * put a link to your script on the desk > > ### just an example > # write to file > target = open("target.txt",'w') > for line in lines: >target.write(line) > target.close() > > # open in editor > import subprocess > subprocess.call(["gedit","target.txt"]) > print "*** end ***" > > denis > > -- > la vida e estranya > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- "Shine on me baby, cause it's rainin' in my heart" --Elliott Smith ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor