Re: [Tutor] Projects
On Jan 22, 2008 5:10 PM, Damian Archer [EMAIL PROTECTED] wrote: So anyone have any good project ideas, perhaps projects that people have undertaken before?? I'm taking a Java class this semester and our first program is a number translator. Here's the assignment: *Below is a sample run:* Welcome to my number translator! Enter amount [0-99.99; 0 to exit]: 1234.56 Translation: one thousand two hundred thirty-four and 56/100 Enter amount [0-99.99; 0 to exit]: 17775 Translation: seventeen thousand seven hundred seventy-five and 00/100 Enter amount [0-99.99; 0 to exit]: -45 Enter amount [0-99.99; 0 to exit]: 9.99 Enter amount [0-99.99; 0 to exit]: 22.95 Translation: twenty-two and 95/100 Enter amount [0-99.99; 0 to exit]: 0.01 Translation: zero and 01/100 Enter amount [0-99.99; 0 to exit]: 909909.99 Translation: nine hundred nine thousand nine hundred nine and 99/100 Enter amount [0-99.99; 0 to exit]: 0 Bye bye! *Input* You may assume that your input is in floating point format (no dollar signs or commas or other special characters other than a single decimal point). But you will need to check to make sure your input satisfies the specs given above. (Although with exception handling it's not difficult to validate that you have floating point format.) --- An example routine to translate a number into it's english equivalent was given (again, this is Java): static String convertDigitToEnglish(int d) { switch ( d ) { case 1: return one; case 2: return two; case 3: return three; case 4: return four; case 5: return five; case 6: return six; case 7: return seven; case 8: return eight; case 9: return nine; default: return \nFatal Error!\n; // should I abort pgm? } // end of switch } // end of convertDigitToEnglish In Python I'd just use a dictionary. HTH, jason ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Generator
Easy enough. You'll want to import the random module and use the functions in it. Also, http://docs.python.org/lib/lib.html is going to be your best friend. You'll notice on that page among many other things is a section on random number generation. As to your code: import random a = random.randint(1,20) a 3 On Dec 4, 2007 12:56 PM, earlylight publishing [EMAIL PROTECTED] wrote: Hello All, I'm a bare beginner to python (or indeed) any programming. I'm helping myself become more proficient by making a text adventure game. The problem is I need a function (or module) that will generate a random number within a range, say 1-20 for example. The ability to program this is beyond my meager abilities at the moment but I'd really like to get started. Would anyone out there be willing to provide me the code for me? Or at least point me in the right direction for finding it myself? TYIA :-) -- Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how. http://us.rd.yahoo.com/evt=51732/*http://overview.mail.yahoo.com/ ___ 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] update a ws.ListBox
Inserting this line: self.listbox2.InsertItems([choice],0) in your OnListBox1 method after your if/then/else statement puts the item you select in ListBox1 appear in ListBox2. You have to force choice into a list, otherwise it will insert each individual letter in the string into the box one at a time. Docs: http://wxwidgets.org/manuals/stable/wx_wxlistbox.html#wxlistbox Now, admittedly, this is on a Windows XP machine, but I don't think that such basic functionality would be different between platforms. On Nov 28, 2007 12:24 PM, John Gerdeman [EMAIL PROTECTED] wrote: Hello, I'm trying to create a gui using wxpython on ubuntu 6.10 (read, that some functions of wx differ on different OS). I have two Listbox items, Listbox1 and Listbox2. I want to update Listbox2 according to the choice made in Listbox1. I already looked at the wx API doc, but only found methods to insert items or (de)select. I know I can update a textctrl, but I need a way to make a choice based on the first. Here a Minimal example: #!/usr/bin/python import wx class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (550, 350)) self.listbox1_items = [ 'item1', 'item2'] self.listbox2_items = ['select a item from the right'] hbox1 = wx.BoxSizer(wx.HORIZONTAL) vbox = wx.BoxSizer(wx.VERTICAL) panel = wx.Panel(self, -1) self.listbox1 = wx.ListBox(panel, 1, wx.DefaultPosition, (170, 130), self.listbox1_items, wx.LB_SINGLE) self.listbox1.SetSelection(0) self.listbox2 = wx.ListBox(panel, 2, wx.DefaultPosition, (170, 130), self.listbox2_items, wx.LB_SINGLE) self.listbox2.SetSelection(0) hbox1.Add(self.listbox1, 0, wx.TOP, 40) hbox1.Add(self.listbox2, 0, wx.TOP, 40) vbox.Add(hbox1, 0, wx.ALIGN_CENTRE) panel.SetSizer(vbox) self.Bind(wx.EVT_LISTBOX, self.OnListBox1, id=1) self.Bind(wx.EVT_LISTBOX, self.OnListBox2, id=2) def OnListBox1(self, event): index = event.GetSelection() choice = self.listbox1_items[index] print You chose + str(choice) if choice == 'item1': ret = ['choice1', 'choice2'] elif choice == 'item2': ret = ['choice3', 'choice4'] else: ret = ['Ooops'] print Now I somehow need a way to pass to self.listbox2 I can set self.listbox2_items to ret, but self.listbox2 doesn't get updated print ret def OnListBox2(self, event): return True class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, 'minexample.py') frame.Centre() frame.Show(True) return True app = MyApp(0) app.MainLoop() ___ 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] for a given file, how to find file size?
Are you sure? From the link you provided it looks as if: *stat*( path) Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the statstructure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink(number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows): import os statinfo = os.stat('somefile.txt') statinfo (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732) statinfo.st_size 926L does exactly what you want. On 10/2/07, Kamal [EMAIL PROTECTED] wrote: never mind found my answer here http://docs.python.org/lib/os-file-dir.html On 10/2/07, Kamal [EMAIL PROTECTED] wrote: would appreciate any pointers. -- Thanks, Kamal -- Thanks, Kamal ___ 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] Capturing ctrl-c
Interesting. As Michael suggested this works, mostly: from time import sleep def loop(): x = 0 while 1: print x:,x x += 1 sleep(0.5) if __name__ == __main__: while 1: try: loop() except KeyboardInterrupt: print Nope, not going to stop. Ctrl-C is ignored. But on Win XP, at least, Ctrl-Break still exits the program. On 9/22/07, Michael Langford [EMAIL PROTECTED] wrote: When I do real applications with exception based languages, I almost always wrap the main function with a try/except block to allow me to gracefully shut down. In the case of python, this means 1 Use the main method 2 wrap its execution in a try catch: import mymodule def do_stuff(): pass def graceful_cleanup() pass if __main__ == __name__: try: do_stuff() except: graceful_cleanup() --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/22/07, James [EMAIL PROTECTED] wrote: Hi. :) I'm whipping up a program in Python and am having to deal with a user potentially hitting ctrl-c at any point in the program. I'd like my Python program to wrap up cleanly when it receives this signal. I did some Googling and read that Python throws a KeyboardInterrupt error. What's the best way to run a specific cleanup function at *any* time the interrupt is received, regardless of where the program is in execution? Most of the stuff I've read involves try-except blocks. This makes sense to me if I want to protect a specific function or area of the code from being interrupted by ctrl-c, but I'm not sure what kind of structure my program must have to catch the exception at any point during execution. Thoughts/ideas appreciated. :) Thanks! .james ___ 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] Bundle help!
A nice tutorial on using regular expressions in Python: http://www.amk.ca/python/howto/regex/ On 7/15/07, bhaaluu [EMAIL PROTECTED] wrote: Hi! http://docs.python.org/lib/module-re.html Regular Expressions module. On 7/15/07, Sara Johnson [EMAIL PROTECTED] wrote: Just curious, but in this link (' http://xahlee.org/perl-python/sort_list.html ') you mentioned, what does the re part mean? At first I thought it was the name of the list or 'return' but that's included later. *** def myComp (x,y): import re def getNum(str): return float(re.findall(r'\d+',str)[0]) return cmp(getNum(x),getNum(y)) li.sort(myComp) print li # returns ['web7-s.jpg', 'my23i.jpg', 'fris88large.jpg', 'my283.jpg'] Thanks, Sara Someone recently showed this to me: $ python import re dir(re) ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U', 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sub', 'subn', 'template'] dir(re.match) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] All those quoted things that the dir() function spit out are in the module. dir(re.match.__doc__) 'Try to apply the pattern at the start of the string, returning\n a match object, or None if no match was found.' You can find all sorts of stuff like this. It's somewhat cryptic at first, but with the above documentation in hand, you can figure it out eventually. =) -- bhaaluu at gmail dot com ___ 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] Fastest way to iterate through a file
Also since you're writing your found results to a file there's no need to print the results to the screen. That should shave off some time, especially if you have a lot of hits. On 6/26/07, Kent Johnson [EMAIL PROTECTED] wrote: Robert Hicks wrote: idList only has about 129 id numbers in it. That is quite a few times to be searching each line of the file. Try using a regular expression search instead, like this: import re regex = re.compile('|'.join(idList)) for line in f2: if regex.search(line): # process a hit A simple test shows that to be about 25 times faster. Searching for each of 100 id strings in another string: In [6]: import timeit In [9]: setup = import re; import string; ids=[str(i) for i in range(1000, 1100)];line=string.letters In [10]: timeit.Timer('for i in ids: i in line', setup).timeit() Out[10]: 15.298269987106323 Build a regular expression to match all the ids and use that to search: In [11]: setup2=setup + ;regex=re.compile('|'.join(ids)) In [12]: timeit.Timer('regex.search(line)', setup2).timeit() Out[12]: 0.58947491645812988 In [15]: _10 / _12 Out[15]: 25.95236804820507 I am running it straight from a Linux console. I thought about buffering but I am not sure how Python handles that. I don't think the console should be buffered. Do you know if Python has a slower startup time than Perl? That could be part of it though I suspect the buffering thing more. I don't know if it is slower than Perl but it doesn't take a few seconds on my computer. How long does it take you to get to the interpreter prompt if you just start Python? You could put a simple print at the start of your program to see when it starts executing. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess and launching an editor
I'm running Feisty as well. I launched python in two separate consoles and tried this: 1st console import subprocess subprocess.call('gedit --new-window window1',shell=True) gedit launches with a blank file called window1. The python shell is now waiting for gedit to exit before it does anything else. 2nd console --- import subprocess subprocess.call('gedit --new-window window2',shell=True) Another instance of gedit launches with a blank file called window2. The difference here is that the 2nd python shell instantly returns an exit code of 0. So you can definately launch multiple instances, but I'm not sure how you would determine when the user was done editing the file after the first instance of gedit has been launched. Perhaps you could use this: http://live.gnome.org/Gedit/PythonPluginHowTo If you're going to stick with gedit. On 6/22/07, Brian van den Broek [EMAIL PROTECTED] wrote: Hi all, I want to have a script launch an editor open to a particular file and wait until that editor has closed before continuing. The aim is to allow the user to make edits to the file, have to script know that the edits are completed, and then make use of the newly saved file contents. gedit is the default text editor on my ubuntu feisty system, so in the first instance, I've tried to do this with gedit. The subprocess.call: subprocess.call(gedit somefilename, shell=True) works just fine *provided* that no instance of gedit is running when I invoke .call. However, if there is a gedit window up and running (there usually is on my system ;-), the .call immediately returns exit status 0: subprocess.Popen(ps -e|grep gedit, shell=True) subprocess.Popen object at 0xb7d06b4c 26066 pts/200:00:01 gedit subprocess.call(gedit somefilename, shell=True) 0 # The exit code is produced instantaneously Interestingly, it works just fine if I use emacs in place of gedit, irrespective of whether emacs was running before the subprocess.call invocation or not. Is there any way to get it to work with gedit as it is with emacs? I am largely ignorant of the family of modules which subprocess was designed to replace, and also of the details of processes on linux. (In particular, I've no clue why gedit and emacs behave differently in this respect.) Thanks and best, Brian vdB ___ 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] Help converting base32 to base16
Nice entry at wikipedia: http://en.wikipedia.org/wiki/Base_32 I like the naming of Base32: *duotrigesimal *Gotta try to work that into a conversation somehow.* * On 6/18/07, Alan Gauld [EMAIL PROTECTED] wrote: cms cms [EMAIL PROTECTED] wrote Newbie here trying to find a module that I can use to convert a number of strings (sha1 values) from base32 to base16 (hex), and vice versa. I'm intrigued. What does a base 32 number look like? For example what is 29 in base 32? Or 1022 for that matter? I undeetsanmd the principle but I'm wondering what characters are used above the F of hex. Also who uses base 32 and for what purpose? 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
Re: [Tutor] Python for s60
Google is your friend: http://www.google.com/search?sourceid=navclientie=UTF-8rls=GGLR,GGLR:2006-33,GGLR:enq=python+symbian The first link in particular looks good. On 5/16/07, Chenthil [EMAIL PROTECTED] wrote: Hi can some one show nd some good tutorials for writing scripts for symbian s60 devices. Thanks is advance. ___ 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] Text matching
heh... forwarding to the list, too. -- Forwarded message -- From: Jason Massey [EMAIL PROTECTED] Date: May 15, 2007 6:51 AM Subject: Re: [Tutor] Text matching To: Gardner, Dean [EMAIL PROTECTED] Look at it a different way. If the one thing that is sure to be there is the SomeSpec portion, then how about making a listing of where they occur and slicing everything up. Concretely, as Mr. Yoo would say: f = open(rc:\python24\test.txt,'r').readlines() logList = [] indices = [x for x,line in enumerate(f) if 'SomeSpec' in line] for x in range(len(indices)-1): logList.append(f[indices[x]:indices[x+1]]) #tack on the last record logList.append(f[indices[-1]:]) for count,x in enumerate(logList): print count,':',x C:\Python24test.py 0 : [' SomeSpec -0001 \n', '\n', ' some commit 1\n', '\n', 'Reviewed By: someone\n'] 1 : [' SomeSpec -0002 \n', ' some commit 2\n', '\n'] 2 : [' SomeSpec -0003 \n', 'some commit 1\n', 'Reviewed By: Someone'] On 5/15/07, Gardner, Dean [EMAIL PROTECTED] wrote: So I took Kents advice and refactored but I have uncovered another problem which I am hoping people may be able to help with. I realized that the string I was using to identify the end of a record can in some cases not be found ( i.e. if a commit wasn't reviewed). This can lead to additional records being returned. Can anyone suggest how I can get round this? Text file example ( in this case looking for commit 1 would give details of commit two also): SomeSpec -0001 some commit 1 Reviewed By: someone SomeSpec -0002 some commit 2 SomeSpec -0003 some commit 1 Reviewed By: Someone Code: def searchChangeLog(self,filename): uid = self.item.Uid() record=[] logList=[] displayList=[] f = open(filename) logTextFile=temp.txt searched through the changelog 'breaking' it up into individual entries for line in f: if (Reviewed: 000 in line): logList.append(record) record = [] else: record.append(line) searches to determine if we can find entries for a particualr item for record in logList: for item in record: if uid in item: displayList.append(record) creates a temporary file to write our find results to removeFile = os.path.normpath( os.path.join(os.getcwd(), logTextFile)) # if the file exists, get rid of it before writing our new findings if Shared.config.Exists(removeFile): os.remove(removeFile) recordLog = open(logTextFile,a) for record in range(len(displayList)): for item in displayList[record]: recordLog.write (item) recordLog.close() #display our results commandline = start cmd /C + logTextFile os.system(commandline) Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com [EMAIL PROTECTED] -Original Message- From: Kent Johnson [mailto: [EMAIL PROTECTED] Sent: 04 May 2007 11:26 To: Gardner, Dean Cc: tutor@python.org Subject: Re: [Tutor] Text matching Gardner, Dean wrote: So here it isit might not be pretty (it seems a bit un-python like to me) but it works exactly as required. If anyone can give any tips for possible optimisation or refactor I would be delighted to hear from them. Thanks uid = self.item.Uid() record=[] logList=[] displayList=[] f = open(filename) logTextFile= temp.txt searched through the changelog 'breaking' it up into individual entries try: while 1: endofRecord=0 l = f.next() if l.startswith(): record.append(l) l=f.next() while endofRecord==0: if Reviewed: 000 not in l: record.append(l) l=f.next() else: logList.append(record) record=[] endofRecord=1 except StopIteration: pass I don't think you need endofRecord and the nested loops here. In fact I think you could use a plain for loop here. AFAICT all you are doing is accumulating records with no special handling for anything except the end records. What about this: record = [] for line in f: if Reviewed: 000 in line: logList.append(record) record = [] else: record.append(line) searches to determine if we can find entries for a particualr item for record in logList: currRec = record for item in currRec
Re: [Tutor] 'word jumble' game
The main thing your program lacks is flexibility. Adding new puzzles requires chaining together a series of if..else statements and creating variables for each hint. Here's my quick version. I store the puzzles and the hints in a two-tuple sequence. Following this method you could easily add additional hints for each puzzle. (I changed up the scoring system a bit too...just my spin on it) import random # create a series of puzzles to choose from puzzles = ((python,It's the best programming language for the absolute beginner ...), (jumble,It's what this program does to words to make it difficult to guess them ...), (easy,It's not difficult ...), (difficult,It's not easy ...), (answer,It's not a question ...), (xylophone,It's a musical instrument you have to hit with 2 small sticks ...)) # pick one word randomly from the sequence which_puzzle = random.choice(range(len(puzzles))) correct_word = puzzles[which_puzzle][0] jumbled_word = list(correct_word) hint = puzzles[which_puzzle][1] random.shuffle(jumbled_word) jumbled_word = ''.join(jumbled_word) print \ Welcome to Word Jumple! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) score = 0 while 1: print The jumble:, jumbled_word guess = raw_input(\nYour guess: ) guess = guess.lower() if guess == '': break if guess != correct_word: print Sorry that's not it. hint_prompt = raw_input(Would you like a hint? Y/N: ) hint_prompt = hint_prompt.lower() if hint_prompt.startswith('y'): print hint+\n score -= 50 if guess == correct_word: score += 200 print \nThat's it! You guessed it!\n if score == 200: print Because you never asked for a hint you get %d points.\n % (score) else: print Since you asked for a hint or two you're score is %d points.\n % (score) break print \nThanks for playing. On 4/17/07, Alexander Kapshuk [EMAIL PROTECTED] wrote: Hello Everyone, This is Alexander Kapshuk writing here again … Could you please have a look at the code below and let me know of any shortcuts that could be used there. The code works fine as it is. I was just wandering if there was a better, more compact and elegant way of writing the program. Thanking you all in advance. Alexander Kapshuk # Word Jumble Game # # The computer picks a random word and then jumbles it. # The player has to guess the original word. # # Should the player be stuck and require a hint, they will be prompted for a hint. # If the player answers 'yes', the appropriate hint will be displayed and the player will be asked to guess again. # If the player answers 'no', they will be asked to guess again and awarded some points if they manage to guess the jumbled word without ever asking for a hint. import random # create a sequence of words to choose from WORDS = (python, jumble, easy, difficult, answer, xylophone) # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word # create hints for all the jumbled words hint0 = \nIt's the best programming language for the absolute beginner ...\n hint1 = \nIt's what this program does to words to make it difficult to guess them ...\n hint2 = \nIt's not difficult ...\n hint3 = \nIt's not easy ...\n hint4 = \nIt's not a question ...\n hint5 = \nIt's a musical instrument you have to hit with 2 small sticks ...\n # create a jumbled version of the word jumble = while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # start the game print \ Welcome to Word Jumple! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) print The jumble:, jumble guess = raw_input(\nYour guess: ) guess = guess.lower() score = 0 while (guess != correct) and (guess != ): print \nSorry, that's not it.\n hint_prompt = raw_input(Would you like a hint? Y/N: ) hint_prompt = hint_prompt.lower() if hint_prompt == yes and correct == WORDS[0]: print hint0 elif hint_prompt == yes and correct == WORDS[1]: print hint1 elif hint_prompt == yes and correct == WORDS[2]: print hint2 elif hint_prompt == yes and correct == WORDS[3]: print hint3 elif hint_prompt == yes and correct == WORDS[4]: print hint4 elif hint_prompt == yes and correct == WORDS[5]: print hint5 elif hint_prompt == no: score += 50 guess = raw_input(Your guess: ) guess = guess.lower() if guess == correct and hint_prompt == no: print \nThat's it! You guessed it!\n print Because you never asked for a hint you get, score, points.\n print \nThanks
Re: [Tutor] Why is it...
In the interpreter this doesn't work: f = open(rc:\python24\image.dat) line = f.readline() while line: ... line = f.readline() ... f.close() Traceback ( File interactive input, line 3 f.close() ^ SyntaxError: invalid syntax But this does: f = open(rc:\python24\image.dat) line = f.readline() while line: ... line = f.readline() ... f.close() Note the differing placement of the f.close() statement, it's not part of the while. On 3/22/07, Kent Johnson [EMAIL PROTECTED] wrote: Jay Mutter III wrote: Why is it that when I run the following interactively f = open('Patents-1920.txt') line = f.readline() while line: print line, line = f.readline() f.close() I get an error message File stdin, line 4 f.close() ^ SyntaxError: invalid syntax but if i run it in a script there is no error? Can you copy/paste the actual console transcript? BTW a better way to write this is f = open(...) for line in f: print line, f.close() Kent Thanks Jay ___ 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] declaring decaration on ul list
You'll need a style sheet. See: http://alistapart.com/articles/taminglists/ On 3/14/07, Kirk Bailey [EMAIL PROTECTED] wrote: It just occurred to me that when my wiki does a backsearch it is useful to list the results with a * for decorating the unordered list results, so I can mousecopy it to update the category(foo) page, /the normal bullet is mousecopied as a poundsign (#}. How does one specify what to render as a item decoration in an unordered list? -- Salute! -Kirk Bailey Think +-+ | BOX | +-+ knihT Fnord. ___ 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] Squlite3 problem
I found a similar discussion on the pysqlite mailing list ( http://lists.initd.org/pipermail/pysqlite/2005-August/000127.html) Try committing your changes and then closing your cursor. db.commit() cur.close() db.close() On 3/13/07, Jim Roush [EMAIL PROTECTED] wrote: I'm geting the following error message and I'm stumped Traceback (most recent call last): File C:\markets\source\QuantScan\QuantScan4_3.py, line 1362, in module db.close() sqlite3.OperationalError: Unable to close due to unfinalised statements Here 's the relevant code db = sqlite.connect('c:/markets/db/market_2.db') cur_stocks = db.cursor() cur_quant = db.cursor() cur_subind = db.cursor() # update ROC table in db print '\nupdate ROC table in db...\n' cur = db.cursor() cur.execute(delete from subind_ROC) for row in range(0, num_of_subinds): (subind, si_ROC_10, si_ROC_10_1, si_ROC_10_2, si_ROC_20, si_ROC_20_1, \ si_ROC_20_2, si_ROC_30, si_ROC_30_1, si_ROC_30_2) = si_ROC[row] cur.execute(INSERT INTO subind_ROC (subind, ROC_10, ROC_10_1, ROC_10_2, ROC_20, ROC_20_1, ROC_20_2, ROC_30, ROC_30_1, ROC_30_2) Values (?,?,?,?,?,?,?,?,?,?), (subind, si_ROC_10, si_ROC_10_1, si_ROC_10_2, si_ROC_20, si_ROC_20_1, si_ROC_20_2, si_ROC_30, si_ROC_30_1, si_ROC_30_2)) cur.close() db.commit() db.close() ___ 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] Two sys.exit questions
When you call sys.exit() you're raising a SystemExit exception. help(sys.exit) Help on built-in function exit in module sys: exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). So that explains why you're falling through to except clause. You can see the same type of behavior if you manually raise an exception (ValueError for example) within a try clause In your example concerning the reading and writing to files, as far as a close() statement goes you would get this error: try: ... i_file = open('doesnt_exit.tmp','r') ... except IOError: ... i_file.close() ... Traceback (most recent call last): File interactive input, line 4, in ? NameError: name 'i_file' is not defined Since i_file never got defined because the open wasn't successful. BTW don't use file as a variable since it will mask python's built-in file object On 2/28/07, Cecilia Alm [EMAIL PROTECTED] wrote: I have two quick questions: 1) Why does sys.exit() not work in a try clause (but it does in the except clause)? try: ...print 1 ...sys.exit(0) ... except: ...print 2 ...sys.exit(0) ... 1 2 # python exited 2) If opening a file fails in the below 2 cases, sys.exit(message) prints a message in the except clause before program termination. Some use file.close() in the except clause (or in a finally clause). It seems superflous in the below case of read and write. (?) try: file = open('myinfile.txt', 'r') except IOError: sys.exit('Couldn't open myinfile.txt') try: file = open('myoutfile.txt', 'w') except IOError: sys.exit('Couldn't open myoutfile.txt') ___ 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] Reg Google Web Toolkit and Python
Oh, the irony...googling for python and gwt gave me: http://pyjamas.pyworks.org/ On 2/16/07, Shadab Sayani [EMAIL PROTECTED] wrote: Hi , We have a project where I need to read files store them in database in the backend.We have done this in python.Now we decided to use Ajax technique for user interface.For that we found that GWT is one of the best toolkits.Now I got a doubt can I interface GWT with python. Thanks , Shadab. Send instant messages to your online friends http://uk.messenger.yahoo.com ___ 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 gui for file input
The simplest way would be to use TkInter which is distributed with Python. Check out the cookbook recipe at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438123 for a bunch of examples. jason On 1/5/07, Mike Ellis [EMAIL PROTECTED] wrote: Hi all, I am looking to create a simple gui interface to a small script. The script requires the user to input a directory. I would like to allow the user to browse the windows file system for the desired directory rather than type in the full path by hand. This would operate in much the same way as any program when you select FileOpen. Is this possible to do with python? Can anyone point me in the proper direction to find more info on this or perhaps an example script using a similar feature? Thanks for your help, Michael __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ 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] How to allow user to choose an option from a window
If you mean which type of GUI model to use you have at least two popular choices. Tkinter: It's bundled with Python, and there's a tutorial at: http://www.pythonware.com/library/tkinter/introduction/ wxPython: My GUI of choice. http://wxpython.org A quick and dirty example in wxPython of what you wanted: import wx class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,200)) self.radiobox = wx.RadioBox(self,wx.ID_ANY ,'Options',choices=['One','Two','Three'],style=wx.RA_SPECIFY_ROWS) self.Bind(wx.EVT_RADIOBOX,self.OnRadioBoxChoose,self.radiobox) self.Show() def OnRadioBoxChoose(self,event): choice = self.radiobox.GetStringSelection() wx.MessageBox(You selected: %s % choice) app = wx.PySimpleApp() frame = MainWindow(None,-1,Options) app.MainLoop() On 12/12/06, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I'm trying to allow a user to select one option from a list. My simple code works: OptionList = ['One', 'Two', 'Three'] while 1: print 'Here are your options:' for option in OptionList: print option optionChosen = raw_input(Which one do you want? ) if optionChosen in OptionList: break print That is not a valid option. Please re-enter your choice. print You have chosen: , optionChosen However, Now I'd like to display the options within a MsgBox-type display and have the user click on the option of choice. Any suggestions of a model I can adapt to accomplish this? Thanks. Urban Landreman ___ 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] Why SelectAll() cannot work well ?
I'm running WinXP and the entire text is selected when you enter a new choice. In fact, on XP at least, you don't have to use SelectAll, SetFocus selected the entire text. On 11/30/06, Jia Lu [EMAIL PROTECTED] wrote: Hi all I am using wx Py with FC6. I ran the program below but I found the method SelectAll() cannot work well.(The last letter didnot be selected.!!) -- import wx ComboList = ['Akari', 'Aika', 'Alice'] class MyApp(wx.App): def OnInit(self): frame = wx.Frame(None, -1, ARIA, size=(250, 100)) frame.Show() self.CBox = wx.ComboBox(frame, -1, Alicia, pos=(20, 20), size=(100,30), choices=ComboList) self.Text = wx.StaticText(frame, -1, ARIA, pos=(20,50)) # Note: EVT self.CBox.Bind(wx.EVT_COMBOBOX, self.OnSelect) self.CBox.Bind(wx.EVT_TEXT_ENTER, self.OnEnter) #self.CBox.SetSelection(2) return 1 def OnSelect(self, event): Text = self.CBox.GetStringSelection() self.Text.SetLabel(Text) def OnEnter(self, event): Text = self.CBox.GetValue() self.Text.SetLabel(Text) self.CBox.SetFocus() self.CBox.SelectAll() app = MyApp() app.MainLoop() -- -- Jia LU http://www.lujia.us Registered Linux user #434792 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- \ Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus. -- | _o__) Peter H. Coffin | ___ 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] Having trouble with table % listTable.values() line
So you want to convert a list into a tuple. Here ya go, using your example of the table setup: raw_table = %s | %s | %s -- %s | %s | %s -- %s | %s | %s from random import choice x_o = [choice(['x','o']) for i in range(9)] x_o ['x', 'x', 'x', 'x', 'o', 'o', 'o', 'x', 'x'] filled_table = raw_table % tuple(x_o) print filled_table x | x | x -- x | o | o -- o | x | x On 11/24/06, Mihai Iacob [EMAIL PROTECTED] wrote: Hello, This is my first post so if i make any kind of mistakes take it easy on me :). I don't know how to explain clearly what is the problem but i'll try. table = %s |%s |%s --- %s |%s |%s --- %s |%s |%s listTable is a dictionary. listTable = {0 :'X', 1 :' ' , 2 :' ', 3 :'O', 4 :' ', 5 :' ', 6 :'O', 7 :' ', 8 :'X',} I am trying to take the values from the dictionary listTable.values() and print them in the table. The problem is that listTable.values() returns a list ['X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X'] and python won't assign the values of the dictionary in the table. table % listTable.values() This error message appears: Traceback (most recent call last): File pyshell#81, line 1, in module table % listTable.values() TypeError: not enough arguments for format string So instead of the list ['X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X'] which won't let me assign strings in the table, i want to get ('X', ' ', ' ', 'O', ' ', ' ', 'O', ' ', 'X') from listTable.values() I know i can make it work using: table % (listTable[0],listTable[1], listTable[2],listTable[3],listTable[4], listTable[5],listTable[6],listTable[7],listTable[8]) but it's kinda long. If somebody can tell me how to convert the []list into () i'll make him a little shrine and worship him for 5 seconds :P I'm trying to make a OXO game, so don't give me any hints even if you spot mistakes (i hope i can make it alone) Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com ___ 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] Problem making '.exe' from python.
Check to make sure that under the shortcut properties that you have the Start in field filled out with the directory the script is located. On 11/17/06, Chris Hengge [EMAIL PROTECTED] wrote: Whether using py2exe or pyInstaller I've noticed a problem and I'm not sure how to fix it... When I create a .exe and then make a shortcut to the file and run it.. the program will crash without warning. If I run the .exe directly it runs fine. My assumption of the problem: Since it is still built on python and my variables for files or module calls are designed for they are in the same location I run the script from when I run the script from a shortcut it will fail finding the wanted pieces. Is this true? And if so, how do I fix it? I could write fixed paths into my code, but that is unrealistic and makes running my scripts to test them a pain. Thanks. ___ 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] how to extract time from datetime.date.time()
How about two different ways: import datetime t = datetime.datetime.now() t datetime.datetime(2006, 11, 16, 11, 28, 15, 75) t.hour 11 t.minute 28 t.second 15 a = %d:%d:%d % (t.hour,t.minute,t.second) a '11:28:15' or, a bit more succinctly: t.strftime('%H:%M:%S') '11:28:15' All of this info is readily avaliable in the python docs. http://docs.python.org/lib/module-datetime.html On 11/16/06, Asrarahmed Kadri [EMAIL PROTECTED] wrote: Hi, I want to extract hh:mm:ss from below mentioned code: import datetime t = datetime.datetime.now() print t 2006-11-16 16:59:02.843000 How to do it? TIA. Regards, Asrarahmed -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tuple and Dicts?
How about something like: data = "" 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'}) id = 0 result = [x for x in data if x['id'] == id][{'id': 0, 'title': 'Linux'}] result = [x for x in data if x['id'] == id] result[0]{'id': 0, 'title': 'Linux'} You get the entire dict entry out of the tuple that way. On 11/9/06, Basil Shubin [EMAIL PROTECTED] wrote: Hi friends!Imagine the tuple that has dictionaries as it's item: print data({'id': 0, 'title': 'Linux'}, {'id': 1, 'title': 'FreeBSD'})How I can get index of tuple item where dict's key 'id' equal to appropriate value? And can this be done without 'for' loops, just in onestring?--Basil ShubinFreelance Software Developer___Tutor maillist- Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem importing class
Shawn,Python already has a module called site. From http://docs.python.org/lib/module-site.html :This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter's -S option. Importing this module will append site-specific paths to the module search path.Easiest thing would be to rename your module.On 10/26/06, shawn bright [EMAIL PROTECTED] wrote:hey therei have written a module called site.pyin the file i have this: import DbConnectorimport sensorclass Site(object): site object def __init__(self, id): self.id = id self.con = DbConnector.DbConnector() id = str( self.id) stats = self.con.getOne(selct `group_id`, `name`, `ivr_code`, \ `site_type`, `notes`, `sensor_id` \ from `sites` where `id` = '+str(id)+' ) self.group_id = stats[0] self.name = stats[1] self.ivr_code = stats[2] self.site_type = stats[3] self.notes = stats[4] self.sensor_id = stats[5] def get_sensor(self): self.sensor = sensor.Sensor (self.sensor_id) return self.sensorok, in the program i am trying to run i have these lines:import sitenew_site = site.Site(id_number)and this is what my output is:Traceback (most recent call last): File ./new_camp.py, line 2014, in on_site_tree_view_row_activated acitve_site = site.Site(id_number)AttributeError: 'module' object has no attribute 'Site'It looks like the same code works for a different module i have ; i don't get what i could be missing here, any tips?if you have read this far, thanks for your time.sk ___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] Decimal truncation, rounding etc.
More specifically, Joe, where and what types of errors are you getting?When I type in your example exactly as above I get the following:from decimal import * Decimal('7.').quantize(Decimal('1.000'),rounding=decimal.ROUND_DOWN)Traceback (most recent call last): File interactive input, line 1, in ?NameError: name 'decimal' is not defined That error appears because you've imported all of the decimal functions into the global namespace and you're trying to reference a value in the decimal namespace. In your example it'd have to look like this to work: Decimal('7.').quantize(Decimal('1.000'),rounding=ROUND_DOWN) #note the lack of decimal in front of ROUND_DOWNDecimal(7.000)Or is the problem that you're not able to read and parse the text file properly? On 10/25/06, Joe Cox [EMAIL PROTECTED] wrote: My next project is to read a doc file and do some number editing. I can alter numbers in the Interactive Shell OK: import mathprint round(7.12345,4)7.1234 from decimal import*Decimal('7.0').quantize(Decimal('1.000'),rounding = decimal.ROUND_DOWN)Decimal(7.) But when I go in to IDLE, I just don't seem to be able to make this work. A typical line of code for me to read and edit will look like: G01 G91 X7.12345 Y7. Z-0.0086 The underlines is what I need to edit, as above. I must not understand something fundamental. Joe Cox 513-293-4830 ___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] regarding GNUPLOT and MATPLOTLIB..
Very possible:For gnuplot:http://gnuplot-py.sourceforge.net/ See the instructions for using on Windows.For Matplotlib: http://matplotlib.sourceforge.net/installing.htmlPossibly what's confusing you is that both versions have external dependencies such as Numpy and Numeric (are those the same? I'll admit to being confused on the whole numpy, numeric, numarray which is which probelm). Both pages have the dependencies listed as well as links and installation instructions. In fact the error message you posted earlier about importing Matplotlib includes detailed information about why you couldn't import matplotlib: You didn't have numeric installed.-A bit of googling goes a long way. On 10/23/06, Asrarahmed Kadri [EMAIL PROTECTED] wrote: Is it possible to use these tools on WIndows machine -- To HIM you shall return. ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regarding GNUPLOT and MATPLOTLIB..
Asrarahmed, I saw this on the matplotlib site, perhaps it pertains to your situation: The latest matplotlib-0.87.6 for windows was compiled with numpy 1.0rc2. Please do not upgrade matplotlib for windows if you are running the latest numpy 1.0rc3. Check back soon as we hope to get a binary build for the latest numpy ASAP. You can check your numpy version by doing import numpy print numpy.__version__ Note, the latest matplotlib compiles and runs fine against the latest numpy -- this only affects binary builds such as the windows installer.On 10/23/06, Asrarahmed Kadri [EMAIL PROTECTED] wrote: I have installed numpy but still I am not able to use matplotlib. the error is same: from pylab import *RuntimeError: module compiled against version 102 of C-API but this versionof numpy is 109 The import of the numpy version of the nxutils module,_nsnxutils, failed. This is is either because numpy wasunavailable when matplotlib was compiled, because a dependency of_nsnxutils could not be satisfied, or because the build flag for this module was turned off in setup.py. If it appears that_nsnxutils was not built, make sure you have a working copy ofnumpy and then re-install matplotlib. Otherwise, the followingtraceback gives more details: Traceback (most recent call last): File stdin, line 1, in ? File C:\python\Lib\site-packages\pylab.py, line 1, in ? from matplotlib.pylab import * File C:\python\Lib\site-packages\matplotlib\pylab.py, line 199, in ? import mlab #so I can override hist, psd, etc... File C:\python\Lib\site-packages\matplotlib\mlab.py, line 64, in ? import nxutils File C:\python\Lib\site-packages\matplotlib\nxutils.py, line 17, in ? from matplotlib._ns_nxutils import *ImportError: numpy.core.multiarray failed to import On 10/23/06, Jason Massey [EMAIL PROTECTED] wrote: Very possible:For gnuplot: http://gnuplot-py.sourceforge.net/ See the instructions for using on Windows.For Matplotlib: http://matplotlib.sourceforge.net/installing.htmlPossibly what's confusing you is that both versions have external dependencies such as Numpy and Numeric (are those the same? I'll admit to being confused on the whole numpy, numeric, numarray which is which probelm). Both pages have the dependencies listed as well as links and installation instructions. In fact the error message you posted earlier about importing Matplotlib includes detailed information about why you couldn't import matplotlib: You didn't have numeric installed.-A bit of googling goes a long way. On 10/23/06, Asrarahmed Kadri [EMAIL PROTECTED] wrote: Is it possible to use these tools on WIndows machine -- To HIM you shall return. ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best way to replace items in a list.
Why not:if item in list:loc = list.index(item)list[loc] = strOn 10/20/06, Chris Hengge [EMAIL PROTECTED] wrote:I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do.str = This was replacedff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location?Is this how / best way?if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) Thanks. ___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] Best way to replace items in a list.
You can access and change the elements in a list by directly referencing their position in the list.Something like: foo = [1,2,3] foo[0]1 foo[0] = 'a' foo ['a', 2, 3]On 10/20/06, Chris Hengge [EMAIL PROTECTED] wrote: Will that replace the location? or add to it? Thanks.On 10/20/06, Jason Massey [EMAIL PROTECTED] wrote:Why not:if item in list:loc = list.index(item) list[loc] = strOn 10/20/06, Chris Hengge [EMAIL PROTECTED] wrote: I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do.str = This was replacedff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location?Is this how / best way?if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) Thanks. ___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] passing a variable ?
It should look like this:fout = file('/home/cable/sandbox/%s' % savename, 'a''w')The variables come immediately after the string your formatting.On 10/19/06, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I am stumped.I am trying to pass the variable 'savename' to a stringand get errors.can someone tell me why?Thanks to all on this list.(The problemhappens in the for loop 1st line)This is my error Traceback (most recent call last):File ./ArpAcl.py, line 39, in ?fout = file('/home/cable/sandbox/%s', 'a''w' % savename)TypeError: not all arguments converted during string formatting import pexpectimport getpassimport sys#Go through all the routers and gather Access-list or ARP information,return the info into it's own file. print '\n'print 'Router scrub will take approx 60 Seconds.'print '\n'print For the ARP list enter '1'print For the ACL list enter '2'print '\n'choice = input('Enter 1 or 2: ') print '\n'telpass = getpass.getpass('Please enter the telnet password: ')enablepass = getpass.getpass('Please enter the enable password: ')if choice == 1:command = 'show arp'savename = ' arp.txt'else:command = 'sh ip access-l'savename = 'acl.txt'print '\n'print '-' * 48print 'You will be notified when program is finished.'print '-' * 48x = open('/home/cable/router.list','r') routers = x.readlines()for i in routers:fout = file('/home/cable/sandbox/%s', 'a''w' % savename)c = pexpect.spawn('/usr/bin/telnet %s' %i)c.expect('Please Enter Password:') c.sendline(telpass +'\r')c.sendline('enable\r')c.expect('Password:')c.sendline(enablepass + '\r')c.expect('#')c.logfile = foutc.sendline('skip\r') c.expect('#')c.sendline(command + '\r')c.expect('#')fout.close()c.close()x.close()print '\n'print 'Finished!'print '\n'print 'File has been save to /home/cable/sandbox/%s' % savename raw_input('Press any key to exit')___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] [tutor] ipconfig
I found this on an artima forum:http://www.artima.com/forums/flat.jsp?forum=181thread=113874 This worked on my machine (win xp):socket.getaddrinfo(socket.gethostname(), None)[0][4][0]On 8/10/06, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:hello list is there in python an independent from the system way toobtain the IPi am playng aroundcodeimport sysimport osipconfname={'nt':'ipconfig', 'posix':'ifconfig'}ipstr = os.popen (ipconfname[os.name] ).read()#print ipstr/codebut i found out that answer depends on os.name ...in this case i have to use a different parser for each system ... so is there another way to retrieve the IP?regards,e.-http://www.atol.bg - Намери бившите си съученици и стари приятели! ___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] AmigaOS like ReadArgs() for Python ?
I came across this at: http://www.monkeyhouse.eclipse.co.uk/amiga/python/For more powerful operation under AmigaDOS, and because it is needed for the ARexx implementation, there are two additional modules. The first is the low-level builtin module Doslib, and the other, the Dos module, is written on top of it (in Python). They work together much the same as the strop and string modules do: you don't use the builtin one directy but rather the higher-level module. So, you will only need to use the Dos module which provides the following: set of AmigaDOS specific functions, like Relabel, Examine, SetComment, SetFileDate, etc. functions for waiting on and checking of AmigaDOS signal flags definition of a set of AmigaDOS flags (break signals, file protection bits etc.) higher level wrapper and utility functions like touch, AssignAdd, etc. ArgParser class. This is an argument string parser to parse strings according to a template as understood by the standard AmigaDOS ReadArgs function. The ARexx module uses it for parsing the ARexx command arguments. This is actually a very powerful class! On 7/20/06, Andreas Mixich [EMAIL PROTECTED] wrote: Hi,does anyone know about a ReadArgs() implementation for Python as seen onAmigaDOS ? Thanks.--Andreas___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] modbus communication with python?
Googling for modbus python turned up:https://lintouch.org/repos/lintouch/lsp-modbus/trunk/tests/ On 7/5/06, Jeff Peery [EMAIL PROTECTED] wrote: Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks. Jeff How low will we go? Check out Yahoo! Messenger's low PC-to-Phone call rates. ___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] If then else question
How about:elif ch_val in ['040','011','012']:On 6/14/06, Andrew Robert [EMAIL PROTECTED] wrote:-BEGIN PGP SIGNED MESSAGE-Hash: SHA1Hi Everyone, In the middle of an if then else, I have the following lineelif ch_val == '040' or ch_val == '011' or ch_val == '012':The line works but it is a little ungainly.Anyone have a better way of accomplishing the same thing? - --Thank you,Andrew Robert-BEGIN PGP SIGNATURE-Version: GnuPG v1.2.1 (MingW32)Comment: GnuPT 2.7.2iD8DBQFEkFgfDvn/4H0LjDwRAophAKCZbJaMWBr2G8dLjHO3VtOA98/+1gCbBsys4B/Q6g9m+3DW+PzcnCpki6k= =t0E4-END PGP SIGNATURE-___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 challenge
David,What answer did you get? One of the things to rember on the challenge is to take your answer and put .html (no qutoes) on the end of it in the url.So for the first problem the url would be: http://www.pythonchallenge.com/pc/def/your answer.htmlOn 5/4/06, David Holland [EMAIL PROTECTED] wrote: I looked at this and got stuck on the first one :- http://www.pythonchallenge.com/pc/def/0.html It says try changing the url. I assumed that it either meant 2*38 or 2 to the power of 38 but I can't see how to put either of those in the url.What have I missed ?Thanks in advance. David Holland Yahoo! Photos – NEW, now offering a quality print service from just 7p a photo. ___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] Halting execution
How about:import syssys.exit()On 5/3/06, Matthew Webber [EMAIL PROTECTED] wrote:This has got to be trivial, but I can't find the answer ... I want to stop execution of my main script half way through. This is just for debugging -the code in the bottom half of the script generates a whole lot of outputthat I don't want. Inserting break or return doesn't work, but something like that is what I had in mind.I'm running under ipython on windows, FWIW.Thanks___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] Checking in lists
John,Basically it's not evaluating it the way you think it is:Your first example really equates to:if (1 or 5) in rollList: etc...(1 or 5) equals 1 and 1 isn't in the your list. On 4/26/06, John Connors [EMAIL PROTECTED] wrote: G'day,I found something today that has me confused. I'm making a list of 6 randomdice rolls and I want to check if any 1's or 5's were rolled. I tried thisway first and it returns true even if there are no 1's or 5's. I'll use a roll of all 2's as an example.rollList = [2,2,2,2,2,2]if 1 or 5 in rollList: print 'yes'else: print 'no'Then I tried this and it works fine.rollList = [2,2,2,2,2,2]if 1 in rollList or 5 in rollList: print 'yes'else: print 'no'It doesn't really matter because the second way does what I want but I wouldlike to know why the first way doesn't work and if the syntax is wrong whydoesn't it return an error. JohnPS I apologise if this is a duplicate, hotmail did some kind of spam checkwhen I tried to send it, I've waited 30 mins and I don't think it went the1st time so I'll post it again._ New year, new job – there's more than 100,00 jobs at SEEKhttp://a.ninemsn.com.au/b.aspx?URL="" ___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] import of source code still not working
The problem here is that you need to reference the factor30 namespace to get to your functions: Your calls to your functions would then look like: factor30.factor(109) factor30.factor0(109) If you don't want to have to put the factor30 in front of all your function names you can do this: from factor30 import * Which will put all of your functions into the global namespace. Then you can call factor() factor0() as you would expect to. On 2/20/06, Kermit Rose [EMAIL PROTECTED] wrote: IDLE 1.1.2 import factor30 factor(109)Traceback (most recent call last):File pyshell#1, line 1, in -toplevel-factor(109)NameError: name 'factor' is not defined factor0(109)Traceback (most recent call last):File pyshell#2, line 1, in -toplevel-factor0(109)NameError: name 'factor0' is not defined ___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] map vs. list comprehension
How about: [pow(2,x) for x in [1,2,3,4]] [2, 4, 8, 16] On 2/14/06, Michael Broe [EMAIL PROTECTED] wrote: I read somewhere that the function 'map' might one day be deprecatedin favor of list comprehensions.But I can't see a way to do this in a list comprehension: map (pow, [2, 2, 2, 2], [1, 2, 3, 4]) [2, 4, 8, 16]Is there a way?Cheers,Mike___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] getting around ValueError in os.walk
Andrew, I put in your code, exactly as you have it, with only three changes: #!/usr/bin/python import os for (dirpath, subdirs, filenames) in os.walk(/python24): # a comma instead of a period after dirpath for file in filenames: if file.endswith(.py): # py instead of baz, just for my machine print os.path.join(dirpath,file) # file instead of f This walks the directories and prints out the path and filename. On a side note I've never had a problem throwing several thousand files or lines at python. On 1/30/06, Andrew D. Fant [EMAIL PROTECTED] wrote: I'm working on a program to do some processing on a directory tree. If I hadbeen doing it in a shell script, the core of the processing would have been ina find $ROOT -type f -name FOO -print command On the web, I found a snippet of code that demonstrated the os.walk module andI created a simple test program to work on my tree that looked like this:#!/usr/bin/pythonimport osfor (dirpath. subdirs, filenames) in os.walk(/foo/bar):for file in filenames:if file.endswith(.baz):print os.path.join(dirpath,f)when I try to run it, I get a ValueError: too many values to unpack which Ithinkcomes from the fact that there is a subdirectory of /foo/bar which hasover 2500 files in it.The tree can't be easily restructured for legacy reasons.Can anyone suggest the best way to get around this in code?Thanks,Andy--Andrew Fant| And when the night is cloudy| This space to letMolecular Geek | There is still a light|-- [EMAIL PROTECTED] | That shines on me | Disclaimer:I don'tBoston, MA | Shine until tomorrow, Let it be | even speak for myself___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] dynamic lists
googled for rsa python: http://www.python.org/workshops/1995-05/pct.html On 1/3/06, lfiedor [EMAIL PROTECTED] wrote: Hiim looking for very simple DES and RSA algorithms writen in python (orC), can anyone know where i can find them___Tutor maillist- Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Syntax Errors
I've just finished ripping out a bunch of lines in one of my wxPython programs. Testing it out I get: C:\Python24tla2.py File C:\Python24\tla2.py, line 412 self.grid.SetCellValue(0,0,Site) ^ SyntaxError: invalid syntax There's nothing wrong with that line. I didn't even touch it in the overhaul (refactoring is much too delicate of a word for the surgery I just did). I can make the error go away by unindenting the line, but all that happens then is the error gets passed onto the next line down. I've had this happen before on a smaller scale. Python wouldn't like a certain line and I found that if I moved it up in the function the error would go away. Unfortunately this overhaul touched on at least three functions. Oddly enough the function where I did the majority of the work seemed to come out fine. Any pointers on tracing this down? In C I would expect I didn't have a set of matching braces or a missing semi-colon. thanks, jason ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Syntax Errors
Danny! Thanks! It's the tab vs spaces, alright. I use tabs for my spacing and I was touching a part of the code that a co-worker wrote. Guess what he uses? Spaces. Thanks for that insight and I'll be sure to read up on the command line options. On 1/3/06, Danny Yoo [EMAIL PROTECTED] wrote: On Tue, 3 Jan 2006, Jason Massey wrote: I've just finished ripping out a bunch of lines in one of my wxPython programs.Testing it out I get: C:\Python24tla2.py File C:\Python24\tla2.py, line 412 self.grid.SetCellValue(0,0,Site) ^ SyntaxError: invalid syntax There's nothing wrong with that line.I didn't even touch it in the overhaul (refactoring is much too delicate of a word for the surgery I just did).I can make the error go away by unindenting the line, but all that happens then is the error gets passed onto the next line down.Hi Jason,Can you show us the line in context?That is, can you show us a few lines above and below?Also, let's make sure we're not running into a silly tab-vs-spaces issue.Can you try running Python with the '-tt' command line option?This willenable Python to strictly treat mixed tabs and spaces as a bad thing. Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI?
Nathan, Look here: http://effbot.org/tkinterbook/entry.htm Apparently you can change the default setting for the entry box so that it will show whatever character you like rather than what the user is typing. On 11/29/05, Nathan Pinno [EMAIL PROTECTED] wrote: Hey Danny and all,Alberto told me that there was a password entry box in TKInter. Can anyonetell me about that, please?Thanks,Nathan Pinno,Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/MSN Messenger: [EMAIL PROTECTED]Yahoo! Messenger: spam_swatter31AIM: f3mightyICQ: 199020705-Original Message- From: Danny Yoo [mailto:[EMAIL PROTECTED]]Sent: November 28, 2005 2:57 PMTo: Nathan PinnoCc: Albertito Troiano; Tutor Mailing ListSubject: Re: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI?On Sun, 27 Nov 2005, Nathan Pinno wrote: Is it a good idea to use TKInter to change my password program into a GUI? I know it needs improvements, and I've noted them below: Hi Nathan,Yes, some of it should be usable if it were in a GUI.The easy way to pickout what functions will and won't be useful is this: what functions useprint and input statements?If you exclude those, then what's left will be useful for both your GUI and terminal programs.Actually, that's not quite accurate.For functions that do use printstatements, it's possible to split off the console-driven stuff from thepure computation stuff, so there's actualy quite a bit you can reuse. Let's go into this.load_file() and safe_file() are directly reusable, since they don't interactwith the user.Let's look at something that mixes computation with userinteraction: def add_site(): print Add a login info card site = raw_input(Site: ) ID = raw_input(User ID and passcard, seperated by a space: ) sitelist[site] = ID It's possible to break this down into two parts: the part that asks forlogin info:##def ask_for_login_info():print Add a login info cardsite = raw_input(Site: ) ID = raw_input(User ID and passcard, seperated by a space: )return (site, ID)##and the part that really does the gruntwork of entering into the sitelist:##def add_to_sitelist(site, ID): sitelist[site] = ID##Because this example is so small, doing the breakup this way is a bit silly,so maybe this is overkill for your program.But, in general, when we designa program to be used from both the console and the GUI, we'd break out the direct user interface stuff into a separate set of user interfacefunctions, and have those interface functions reuse the common modelfunctions that do the underlying work. In a GUI framework like Tkinter, the ask_for_login_info() function might usea dialog box.http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm On a first pass to GUI-ify your program, each 'print' statement could bereplaced with something like a printDialogMessage():##import tkSimpleDialogimport Tkinterdef printDialogMessage(root, msg): Uses a dialog window to display a message.If ok is pressed,returns True.If cancel is pressed, returns False.class Dialog(tkSimpleDialog.Dialog):def body(self, master): Tkinter.Label(master, text=msg).pack()def apply(self):self.result = Trued = Dialog(root)if d.result:return Truereturn False## Similarly, we can write something (let's call it readDialogInput) thatsimulates the console raw_input()function.And if you replace each use of'print' with 'printDialogBox' and 'raw_input' with 'readDialogInput', we could argue that we have a GUI program.But if we take this route and just stop here, then this is no better thanthe console program.Getting GUIs right is more than just taking existingprograms and putting nice shiny windows on them: it involves good user interface design that takes advantage of the things that GUIs get right.I don't know if there's a quick-and-dirty way to design such GUIs, though.You might find: http://www.manning.com/books/graysonhelpful in getting started with Tkinter programming.Hope this helps!___Tutor maillist- Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using help
Boyan, A listing of all the built-in exceptions can be found at: http://docs.python.org/lib/module-exceptions.html And is this what you're looking for? a='123' int(a) 123 A description of this, and the other built-in functions, is at: http://docs.python.org/lib/built-in-funcs.html#built-in-funcs On 11/28/05, Boyan R. [EMAIL PROTECTED] wrote: How can I see all error keywords for using Try..Except,like EOFError, ValueError etc by typing help('something') ?Also, what to type to see string handling commands ?like int [number = int(raw_input(Enter a number: ))] What's python equivalent for basic val command ?___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] UnboundLocal Error
I've got a problem with scope that I can't say I've ever encountered. The comments explain the situation pretty well. import player class Game: def __init__(self,screen): self.market = Market.Market() self.countries = pickle.load(open(sup.coords,'r')) self.deck = deck.Deck() self.players = {} print player.Player('foo') # this line works fine, prints out a player instance self.setupPlayers() # want to set up all the players so... self.screen = screen def setupPlayers(self): print player.Player('bar') # this line fails, with the unbound local error for super_power in SUPER_POWERS: self.players[super_power] = player.Player(super_power) for position,card in enumerate(self.deck): if card.location in SUPER_POWERS[super_power]: Ouput and traceback: player.Player instance at 0x00AD3F58 Traceback (most recent call last): File C:\Python24\sup.py, line 199, in ? game = Game(screen) File C:\Python24\sup.py, line 51, in __init__ self.setupPlayers() File C:\Python24\sup.py, line 56, in setupPlayers print player.Player('bar') UnboundLocalError: local variable 'player' referenced before assignment Something blindingly obvious probably, but I'm at a loss. thanks, jason ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] triangulation
lol, wipes tear from eye that's just funny. On 11/10/05, Shi Mu [EMAIL PROTECTED] wrote: the Internet is down for one day and so wonderful to have so many responses. i have checked all the links you guys mentioned. what i want is delaunay triangulation and the available ones online are written in C, Java and FORTRAN. I want to see some in Python because it is hard for me to figure out using python to do Fortune's sweeping line algorithm. Is python is not good in doing that kind of computation or some other reason? Thanks a lot for all of your responses!!! On 11/9/05, Gregor Lingl [EMAIL PROTECTED] wrote: Alex Hunsley schrieb: Shi Mu wrote: is there any sample code of triangulation? many thanks! Yes, probably. Indeed, there is. See attachment regards Gregor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net ## Run this program and create a polygon without ## intersecting edges by clicking the vertices with the mouse from Tkinter import * def area2(A,B,C): 2 * Flaeche des 2D-Dreiecks ABC return (A[0]-C[0])*(B[1]-C[1]) - (A[1]-C[1])*(B[0]-C[0]) def insideTriangle(A, B, C, P): Liegt P im Dreieck ABC?, ABC sind im Gegenuhrzeigersinn angenommen! return area2(A,B,P)=0 and area2(B,C,P)=0 and area2(C,A,P)=0 def triangulate(poly): tri = [] while len(poly) 2: triaFound = False count = 0 while not triaFound and count len(poly): #n: count += 1 A, B, C = poly[:3] if area2(A, B, C) = 0: for P in poly[3:]: if insideTriangle(A,B,C,P): break else: tri.append( (A,B,C) ) poly.remove(B) triaFound = True poly.append(poly.pop(0)) if count == len(poly): # n: print Not a simple polygon return None return tri class CvDefPoly(Canvas): def __init__(self, root): Canvas.__init__(self, root, bg=white, cursor=crosshair) self.v = () self.rWidth, self.rHeight = 10.0, 7.5 self.bind(Configure, self.repaint) self.bind(Button-1, self.mousePressed) self.done = False def mousePressed(self, event): if self.done: self.done = False self.v = () x ,y = self.fx(event.x), self.fy(event.y) if self.v: x0, y0 = self.v[:2] if abs(x-x0)self.rWidth*0.01 and abs(y-y0)self.rHeight*0.01: self.done = True if not self.done: self.v += (x,y) self.repaint(None) def iX(self,x): return self.centerX + x/self.pixelSize def iY(self,y): return self.centerY - y/self.pixelSize def fx(self,x): return (x-self.centerX)*self.pixelSize def fy(self,y): return (self.centerY - y)*self.pixelSize def repaint(self, event): items = self.find_all() for item in items: self.delete(item) if event: self.w, self.h = event.width, event.height w,h = self.w, self.h self.minX = self.minY = 2.0 self.maxX, self.maxY = w-3.0, h-3.0 dx, dy = self.maxX-self.minX, self.maxY-self.minY self.centerX = 2.0 + dx/2.0 self.centerY = 2.0 + dy/2.0 self.pixelSize = max(self.rWidth/dx, self.rHeight/dy) left = self.iX(-self.rWidth/2.0) right = self.iX(self.rWidth/2.0) bottom = self.iY(-self.rHeight/2.0) top = self.iY(self.rHeight/2.0) self.create_rectangle(left,top,right,bottom, outline=red) if len(self.v) 1: x,y = self.v[:2] self.create_rectangle(self.iX(x)-2, self.iY(y)-2, self.iX(x)+2, self.iY(y)+2, outline=green) if len(self.v) 3: if self.done: v = [] sv = self.v[:] while sv: a,b=sv[:2] v.extend([self.iX(a), self.iY(b)]) sv = sv[2:] self.create_polygon( v, fill=, outline=blue) else: coo = list(self.v[2:]) while coo: x1,y1 = coo[:2] self.create_line(self.iX(x),self.iY(y), self.iX(x1),self.iY(y1),fill=blue) x,y=x1,y1 coo = coo[2:] def ccw(poly): n = len(poly) k =
Re: [Tutor] IDLE error msgs and line continuations?
All you need is the line continuation character, '\': if (condition 123 and \ condition 456) : On 10/27/05, CPIM Ronin [EMAIL PROTECTED] wrote: When using IDLE, after hitting F5 to save and run, if an error occurs, it merely flashes at the code location of the error. While I usually figure out what is wrong, why don't I get the detailed text error messages that the command line gives? Also, I'm getting most error messages when I try line continuation for clarity: if (condition 123 and condition 456): I distinctly remember Python allowing the above. Thanks. RC _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ ___ 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] string.split() into a list
well that would definitely cause your error. The string.split sends the list to a, but after that it's looking for something to assign to l and there's nothing leftover from the command for it to assign. On 10/18/05, Randy Bush [EMAIL PROTECTED] wrote: l = [] a='1|2|3|4' l=a.split('|') l ['1', '2', '3', '4'] and stupid question of the morning (for me) i want to string.split() into a sequence, a la l = [] l = myString.split('|') but, of course it whines about too many values. what is the common way to do this? maybe it's that i am actually doing l = [] a, l = string.split('|') ? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor