From smichr at bigfoot.com Sun May 1 07:36:41 2005 From: smichr at bigfoot.com (Chris Smith) Date: Sun May 1 07:37:52 2005 Subject: [Tutor] Re: input() : part two Message-ID: > I found a work around for the terminal it appears that the message in > the input("message") was being assigned to the next variable making > Matrix=error=alpha It's good to see that you got this working. Just a couple notes: 1) Regarding your comment above, it just *looks* like it was doing an assignment because of the "=" that you had for the Matrix and error prompt strings. If you had used the prompt "?" instead, the first line of the file would have been "???". One way you could also get around this is being interpreted in your program is to print a "#" before doing any input: ### print "#", # note the comma which keeps the output on the same line. Matrix = input("Matrix=") error = input("error=") alpha = input("alpha=") ### This would produce "# Matrix=error=alpha=" in your redirected output. 2) Also, it is possible to do a "redirect" from the IDE by just opening a file and then redirecting output to this file: #----------------------------------------------------------------------- -------------- # normal output fav_number = input("What is your favorite number?") # output redirected to file import sys file_name = 'myCode.py' file = open(file_name, 'w') #careful; this overwrites an already existing file old_stdout = sys.stdout #let's remember where we *were* sending output sys.stdout = file #now everything that gets printed will go the the file print "print 'my favorite number is',",fav_number file.close() #close the file sys.stdout = old_stdout #restore the output # normal output again print "Now open and run",file_name #----------------------------------------------------------------------- -------------- '''--the output-- What is your favorite number?42 Now open and run myCode.py --end output--''' In the file that was created there is a single line that, for this case, says ### print 'my favorite number is', 42 ### If it starts to get tricky keeping track of what is being printed to the program, you might want to check out the string interpolation module that allows you to substitute in variables from your main script just by putting a $ before the variable name in a string (e.g. this: printpl("print 'The favorite number is $fav_number'") will make (with the input from above): print 'The favorite number is 42' The module and demos are at http://lfw.org/python/Itpl.py Best regards, /c From logesh at iafrica.com Sun May 1 20:53:26 2005 From: logesh at iafrica.com (Logesh Pillay) Date: Sun May 1 20:53:55 2005 Subject: [Tutor] permutations using list comprehensions Message-ID: <427525A6.10606@iafrica.com> Dear list I was really impressed by this version of quicksort:- def qsort (t): if len (t) == 0: return [] else: return qsort([x for x in t[1:] if x <= t[0]]) + [t[0]] + qsort([x for x in t[1:] if x > t[0]]) I'm trying to produce something of a similar structure to generate the permutations of a sequence by translating the ffg bit of Haskell:- perms [] = [[]] perms xs = [ x : ps | x <- xs , ps <- perms ( xs\\[x]) ] '\\' applies to lists & means elements of the first list excluding any elements in common with the second list. The best I've been able to do is pretty obvious:- def perms (t): if len (t) == 0: return [] else: return [[x] + perms ([y for y in t if y <> x]) for x in t] Needless to say, it doesn't work. It does produce a list of lists but they are so horribly nested that I've no idea whether I am getting close. I've also tried adding and removing square brackets in various combinations. Any ideas? Logesh From sigurd at 12move.de Mon May 2 00:18:33 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Mon, 02 May 2005 00:18:33 +0200 Subject: [Tutor] permutations using list comprehensions In-Reply-To: <427525A6.10606@iafrica.com> (Logesh Pillay's message of "Sun, 01 May 2005 20:53:26 +0200") References: <427525A6.10606@iafrica.com> Message-ID: On 1 Mai 2005, logesh at iafrica.com wrote: > I'm trying to produce something of a similar structure to generate the > permutations of a sequence by translating the ffg bit of Haskell:- > perms [] = [[]] > perms xs = [ x : ps | x <- xs , ps <- perms ( xs\\[x]) ] > > '\\' applies to lists & means elements of the first list excluding any > elements in common with the second list. > > The best I've been able to do is pretty obvious:- > def perms (t): > if len (t) == 0: > return [] > else: > return [[x] + perms ([y for y in t if y <> x]) for x in t] > > Needless to say, it doesn't work. It does produce a list of lists but > they are so horribly nested that I've no idea whether I am getting > close. I've also tried adding and removing square brackets in various > combinations. Just do the same as the Haskell code does: def perms (lst): if lst: return [[x] + ps for x in lst for ps in perms([e for e in lst if e != x])] else: return [[]] But remember that recursion in Python isn't as nice as in e.g Haskell (sadly). Karl -- Please do *not* send copies of replies to me. I read the list From andre.roberge at gmail.com Mon May 2 01:15:04 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Sun, 01 May 2005 20:15:04 -0300 Subject: [Tutor] Better way to do some parsing? Message-ID: [Apologies for the long post.] Hi all, I have created a "severely restricted" environment within with users can learn the basics of programming in Python. Within that environment, I want to have the user test the five valid forms that an import statement can have, by attempting to import a fake module whose name is "useful". Other "import" statements are disallowed. 1. import useful 2. from useful import * 3. from useful import valid_function1 [, valid_function2, ...] 4. from useful import valid_function as better_named_function 5. import useful as not_so_useful_after_all As far as I can tell, the following works, but it looks rather "clunky" to me. My *very limited* experience with the "re" module may have something to do with this. Any suggestion would be most welcome. Andr? =======Here's the code formatted (fingers crossed) to work if cut and pasted from email ========================= # test_import.py import re isolate_words = re.compile(r'\W+') # used with .split() # pre-compiled some regular expression with allowable use of "import" imp_use = re.compile('^import useful', re.MULTILINE) imp_use_as = re.compile('^import useful as (\w+)', re.MULTILINE) from_use_imp_star = re.compile('^from useful import \*', re.MULTILINE) from_use_imp_names = re.compile( "^from useful import (\w+(,[ ]*\w+)*)", re.MULTILINE) from_use_imp_as = re.compile( "^from useful import (\w+) as (\w+)", re.MULTILINE) # In the following, "r" is used so that \b identifies a word boundary, # and is not interpreted as backslash by Python. import_misuse = re.compile(r'\bimport\b', re.MULTILINE) # use to commenting out the valid "import" statements after processed. comment_from = re.compile('^from ', re.MULTILINE) comment_import = re.compile('^import ', re.MULTILINE) # Create a fake module which can be "imported" right = "turn_right():\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " turn_left()\n\n" around = "turn_around():\n"+\ " turn_left()\n"+\ " turn_left()\n\n" up_east = "climb_up_east():\n"+\ " turn_left()\n"+\ " move()\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " turn_left()\n\n" up_west = "climb_up_west():\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " move()\n"+\ " turn_left()\n\n" down_west = "climb_down_west():\n"+\ " turn_left()\n"+\ " move()\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " turn_left()\n\n" down_east = "climb_down_east():\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " turn_left()\n"+\ " move()\n"+\ " turn_left()\n\n" commands = {'turn_right': right, 'turn_around': around, 'climb_up_east': up_east, 'climb_up_west': up_west, 'climb_down_east': down_east, 'climb_down_west': down_west} #=== end of info on fake module # The following fonctions are helper functions to # process the "import" statement: # they add the appropriate "imported commands" # before the "import" statement, # before commenting out (by pre-pending #) the "import" statement line def import_useful(): added_text = '' for instruction in commands: new = "def " + 'useful.' + commands[instruction] added_text += new return added_text, True def from_useful_import_star(): added_text = '' for instruction in commands: new = "def " + commands[instruction] added_text += new return added_text, True def import_useful_as(syn): added_text = '' for instruction in commands: new = "def " + syn + '.' + commands[instruction] added_text += new return added_text, True def from_useful_import_names(names): added_text = '' for instruction in isolate_words.split(names): try: new = "def " + commands[instruction] except: print instruction, " not found in module useful" added_text += new return added_text, True def from_useful_import_as(name, syn): added_text = '' try: new = "def " + commands[name].replace(name, syn) except: print name, " not found in module useful" added_text += new return added_text, True def process_no_import(): added_text = '' return added_text, True # the basic processing function def process_file(file_text): if imp_use_as.search(file_text): # look for "import useful as ..." syn = imp_use_as.findall(file_text) added_text, safe_import_flag = import_useful_as(syn[0]) file_text = comment_import.sub('#import ', file_text) elif imp_use.search(file_text): # perhaps the "as ..." part is # missing added_text, safe_import_flag = import_useful() file_text = comment_import.sub('#import ', file_text) elif from_use_imp_star.search(file_text): added_text, safe_import_flag = from_useful_import_star() file_text = comment_from.sub('#from ', file_text) elif from_use_imp_as.search(file_text): names = from_use_imp_as.findall(file_text) name = names[0][0] syn = names[0][1] added_text, safe_import_flag = from_useful_import_as(name, syn) file_text = comment_from.sub('#from ', file_text) elif from_use_imp_names.search(file_text): names = from_use_imp_names.findall(file_text) added_text, safe_import_flag = \ from_useful_import_names(names[0][0]) file_text = comment_from.sub('#from ', file_text) elif import_misuse.search(file_text): safe_import_flag = False file_text = '' # remove it all added_text = '# import keyword used improperly' else: added_text = '' safe_import_flag = True # nothing found added_text += file_text return added_text, safe_import_flag #======== Various test cases == only self-testing stuff follows test1 = '''# test1: no import other instructions''' test2 = '''# test2 import useful other instructions''' test3 = '''# test3 from useful import * other instructions''' test4 = '''# test4 from useful import turn_around, turn_right, climb_up_east other instructions''' test5 = '''# test5 import useful as use other instructions''' test6 = '''# test6 from useful import turn_right other instructions''' test7 = '''# test6 from useful import turn_right other instructions''' test8 = '''# test8 from useful import turn_right as vire_a_droite other instructions''' test9 = '''# test9 import sys other instructions''' test10 = '''# test10 from sys import * other instructions''' test11 = '''# test11 # import in comment import useful other instructions''' test12 = '''# test12 important test''' test13 = '''# test 13 import useful # import sys other instructions''' test14 = '''# test14: two import statements; good one first import useful import sys other instructions''' test15 = '''# test15: two import statements; bad one first import useful import sys other instructions''' test16 = '''# test16: bad import, indented import sys other instructions''' if __name__ == "__main__": print "=====begin 1: no import======" added_text, safe_import_flag = process_file(test1) print added_text print "safe import flag = ", safe_import_flag print "=====begin 2======" added_text, safe_import_flag = process_file(test2) print added_text print "safe import flag = ", safe_import_flag print "=====begin 3======" added_text, safe_import_flag = process_file(test3) print added_text print "safe import flag = ", safe_import_flag print "=====begin 4======" added_text, safe_import_flag = process_file(test4) print added_text print "safe import flag = ", safe_import_flag print "=====begin 5======" added_text, safe_import_flag = process_file(test5) print added_text print "safe import flag = ", safe_import_flag print "=====begin 6======" added_text, safe_import_flag = process_file(test6) print added_text print "safe import flag = ", safe_import_flag print "=====begin 7======" added_text, safe_import_flag = process_file(test7) print added_text print "safe import flag = ", safe_import_flag print "=====begin 8======" added_text, safe_import_flag = process_file(test8) print added_text print "safe import flag = ", safe_import_flag print "=====begin 9: import not allowed======" added_text, safe_import_flag = process_file(test9) print added_text print "safe import flag = ", safe_import_flag print "=====begin 10: import not allowed======" added_text, safe_import_flag = process_file(test10) print added_text print "safe import flag = ", safe_import_flag print "=====begin 11: import ok in text and import in comment======" added_text, safe_import_flag = process_file(test11) print added_text print "safe import flag = ", safe_import_flag print "=====begin 12: word used: important; should be ok ======" added_text, safe_import_flag = process_file(test12) print added_text print "safe import flag = ", safe_import_flag print "=====begin 13: 2nd import in comment ======" added_text, safe_import_flag = process_file(test13) print added_text print "safe import flag = ", safe_import_flag print "=====begin 14: two import statements; good one first ======" added_text, safe_import_flag = process_file(test14) print added_text print "safe import flag = ", safe_import_flag print "=====begin 15: two import statements; bad one first ======" added_text, safe_import_flag = process_file(test15) print added_text print "safe import flag = ", safe_import_flag print "=====begin 16: bad import, indented ======" added_text, safe_import_flag = process_file(test16) print added_text print "safe import flag = ", safe_import_flag print "=====" wait = input("Press enter to exit.") From dyoo at hkn.eecs.berkeley.edu Mon May 2 01:41:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 1 May 2005 16:41:19 -0700 (PDT) Subject: [Tutor] permutations using list comprehensions In-Reply-To: <427525A6.10606@iafrica.com> Message-ID: > The best I've been able to do is pretty obvious:- > def perms (t): > if len (t) == 0: > return [] > else: > return [[x] + perms ([y for y in t if y <> x]) for x in t] > > Needless to say, it doesn't work. It does produce a list of > lists but they are so horribly nested that I've no idea whether I am > getting close. Hi Logesh, Ok, let's try this out. Let's assume for the moment that it works for lists of length two. That is, let's say that we know that: perms([2, 3]) == [[2, 3], [3, 2]] will work. I'll pretend this without even looking at the function definition. *grin* With our "let's pretend" hat on, now let's think about what happens if we trying doing perms() on a slightly larger example: perms([1, 2, 3]) on the function. We know what we expect to get, and now we're checking to see if our function gives that to us. We look at the function definition, and the list isn't empty, so we hit the recursive case: return [[x] + perms ([y for y in t if y <> x]) for x in t] This is a bit nested, but if we expand these list comprensions out, then we get: return [[1] + perms([2, 3]), [2] + perms([1, 3]), [3] + perms([1, 2])] This looks slightly off. From looking at this, we already notice that the return value only has three elements, and that's probably not what we want. We want a list of six elements. (3! == 6) But let's also take a look at one of those subexpressions --- let's look at: [1] + perms([2, 3]) We know that perms() returns a list of list of integers, and: [1] + perms([2, 3]) will do something slightly funky! We already know what we expect out of perms([2, 3]), so let's work this out. We'll get back: [1] + perms([2, 3]) ==> [1] + [[2, 3], [3, 2]] ==> [1, [2, 3], [3, 2]] So just from a pure typing point of view, we're in a slight mess, because we now have a mixed list of either sublists or integers. What I think you want to get, instead, is something like: [[1, 2, 3], [1, 3, 2]] for the value of the first subexpression. Does this make sense so far? > I've also tried adding and removing square brackets in various > combinations. Don't flail randomly. Just adding brackets here and there will not help. Recursive functions demand more respect than that. *grin* If you have more questions, please feel free to ask. From project5 at redrival.net Mon May 2 13:07:00 2005 From: project5 at redrival.net (Andrei) Date: Mon, 2 May 2005 11:07:00 +0000 (UTC) Subject: [Tutor] tokenize row numbering References: <8DA5600F-B902-11D9-BF5A-000393C0D100@bigfoot.com> Message-ID: Chris Smith bigfoot.com> writes: > ### > # line 1 according to tokenize tuple > # line 2 > a=b #line 3 > ### > > Does anyone have an idea of *why* the rows/physical lines of code > beginning their count at 1 instead of 0? In order to process the code I The snippet above shows that numbering begins at 0, with the fourth line having number 3. So either I misunderstand the question, or the snippet is confusing. That being said, I can imagine counting lines from 1 because programming editors also tend to count from 1 instead of 0 and this way it's consistent. Yours, Andrei From kent37 at tds.net Mon May 2 13:52:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 02 May 2005 07:52:21 -0400 Subject: [Tutor] missing module? In-Reply-To: <20050428203929.93467.qmail@web30501.mail.mud.yahoo.com> References: <20050428203929.93467.qmail@web30501.mail.mud.yahoo.com> Message-ID: <42761475.20602@tds.net> Jeff Peery wrote: > Hello, I get an error message from py2exe that it can't find a module ntpath.py. I pasted the error message below: > > Traceback (most recent call last): > File "wxApp1.py", line 4, in ? > File "wx\__init__.pyc", line 42, in ? > File "wx\_core.pyc", line 4, in ? > File "wx\_core_.pyc", line 9, in ? > File "wx\_core_.pyc", line 3, in __load > File "C:\Python24\lib\os.py", line 62, in ? > import ntpath as path > zipimport.ZipImportError: can't find module 'ntpath' > > > I can find ntpath why can't py2exe? how can I get this thing working? thanks for the help. This thread suggests you delete your build and dist folders and try again: http://sourceforge.net/mailarchive/forum.php?thread_id=7023305&forum_id=40690 Kent From albertito_g at hotmail.com Mon May 2 23:36:48 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 02 May 2005 21:36:48 +0000 Subject: [Tutor] Problem with threading Message-ID: Hey all This is the program I need to do and I haven't been able to figure out >From a web page (PHP), I'm creating users and an IP Camera that sends me photos all the time. The user configure his recording time and then a daemon has to check for the photos that does not belong to the recording time. Now I need to start a process for each user because I think is the only way to accomplish this. Someone suggested the use of CRON (I'm working over Linux) but how can I built a program to which I can pass an argument??????? I mean in CRON I will have to put one task for each user and each script has to check only one user, so I think I have to make something like this in cron: at 5 o clock run python2.2 application_I_build(username) I don't know if I make myself clear about what I want Thanks in advanced Alberto From dyoo at hkn.eecs.berkeley.edu Tue May 3 00:26:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 2 May 2005 15:26:12 -0700 (PDT) Subject: [Tutor] Problem with threading In-Reply-To: Message-ID: [Side note: try to just send messages to either tutor at python.org, or help at python.org, but not both.] > Someone suggested the use of CRON (I'm working over Linux) but how can I > built a program to which I can pass an argument??????? > > I mean in CRON I will have to put one task for each user and each script > has to check only one user, so I think I have to make something like > this in cron: > > at 5 o clock run python2.2 application_I_build(username) Hi Alberto, Would things work for you if the list of usernames was defined externally, in some sort of text file? It really sounds like each user has some set of configuration state, so perhaps it might be useful to do something like: at 5 o clock, run python2.2 application_wrapper configuration_file.txt where configuration_file.txt holds a list of users and other miscellaneous server-specific variables. Here, 'application_wrapper' is a simple wrapper that itself calls the real 'application_I-build' program with the right command line arguments, for each user in the configuration_file.txt. Best of wishes! From 3dbernard at gmail.com Tue May 3 05:57:24 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 02 May 2005 23:57:24 -0400 Subject: [Tutor] Appending to many lists with list comprehension Message-ID: <4276F6A4.9050509@gmail.com> Hello, I have an object, and this object has attributes. These attributes are objects in their own right, and each attribute also have its own attributes. So I loop over the "top" object, and for each attribute encountered, I want to put in a list two of the attributes of this attribute. Hope it makes sense. Right now, here is what I'm doing: aList = [ [], [] ] # Iterate attributes of the top object for oAttribute in oObj.attributes: # Append to list 0 the attribute "type" of the current attribute aList[0].append( str(oAttribute.type) ) # Append to list 1 the attribute "name" of the current attribute aList[1].append( str(oAttribute.name) ) Instead of having two separate lists and a for loop, I'd like to perform a list comprehension that would do this all in one go, if this is doable. Thanks Bernard From albertito_g at hotmail.com Tue May 3 06:24:36 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 03 May 2005 04:24:36 +0000 Subject: [Tutor] Problem with threading In-Reply-To: Message-ID: Hey I have the users config in a database so the use of a text file is double work In answer to Matt the cameras push the photos via ftp at my server at 1 photo every 3 seconds What can I do???????????? Regards Alberto >From: Danny Yoo >To: Alberto Troiano >CC: Tutor >Subject: Re: [Tutor] Problem with threading >Date: Mon, 2 May 2005 15:26:12 -0700 (PDT) > > >[Side note: try to just send messages to either tutor at python.org, or >help at python.org, but not both.] > > > > Someone suggested the use of CRON (I'm working over Linux) but how can I > > built a program to which I can pass an argument??????? > > > > I mean in CRON I will have to put one task for each user and each script > > has to check only one user, so I think I have to make something like > > this in cron: > > > > at 5 o clock run python2.2 application_I_build(username) > > >Hi Alberto, > >Would things work for you if the list of usernames was defined externally, >in some sort of text file? It really sounds like each user has some set >of configuration state, so perhaps it might be useful to do something >like: > > at 5 o clock, > run python2.2 application_wrapper configuration_file.txt > >where configuration_file.txt holds a list of users and other miscellaneous >server-specific variables. Here, 'application_wrapper' is a simple >wrapper that itself calls the real 'application_I-build' program with the >right command line arguments, for each user in the configuration_file.txt. > > >Best of wishes! > From jfouhy at paradise.net.nz Tue May 3 06:31:24 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 03 May 2005 16:31:24 +1200 (NZST) Subject: [Tutor] Appending to many lists with list comprehension In-Reply-To: <4276F6A4.9050509@gmail.com> References: <4276F6A4.9050509@gmail.com> Message-ID: <1115094684.4276fe9c3022a@www.paradise.net.nz> Quoting Bernard Lebel <3dbernard at gmail.com>: > aList = [ [], [] ] > > > # Iterate attributes of the top object > for oAttribute in oObj.attributes: > > # Append to list 0 the attribute "type" of the current attribute > aList[0].append( str(oAttribute.type) ) > > # Append to list 1 the attribute "name" of the current attribute > aList[1].append( str(oAttribute.name) ) > > Instead of having two separate lists and a for loop, I'd like to perform > a list comprehension that would do this all in one go, if this is > doable. You could do: [(str(x.type), str(x.name)) for x in oObj.attributes] This won't produce the same result as your code; it will give you a list of pairs, rather than a pair of lists. For a list of pairs, you could do it in two list comprehensions: [[str(x.type) for x in oObj.attributes], [str(x.name) for x in oObj.attributes]] Or you could do a bit of subtle magic with zip: zip(*[(str(x.type), str(x.name)) for x in oObj.attributes]) Or maybe some bonus magic: [[str(x.__dict__[y]) for y in dir(x) if not y.startswith('_')] for x in oObj.attributes] This will give you a list of lists, analogous to the list of tuples earlier. It will grab all the attributes not starting with an _ (so it should avoid the baggage all objects come with, but caution is still advised). [is using __dict__ here the best way of doing this?] Of course, you can unzip it as before: zip(*[[str(x.__dict__[y]) for y in dir(x) if not y.startswith('_')] for x in oObj.attributes]) HTH! -- John. From dyoo at hkn.eecs.berkeley.edu Tue May 3 09:57:48 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 May 2005 00:57:48 -0700 (PDT) Subject: [Tutor] Problem with threading In-Reply-To: Message-ID: On Tue, 3 May 2005, Alberto Troiano wrote: > In answer to Matt the cameras push the photos via ftp at my server at 1 > photo every 3 seconds Hi Alberto, Just as another note: the folks here have no idea who you mean by Matt. I do know that you mean Matt from python-help at python.org, but the folks on Tutor now have no clue what we're talking about. *grin* That's sorta why it's not such a good idea to crosspost to both lists, because now we have a conversation where not everyone can see each other. I'll put Matt in CC, but let's try to avoid this situation next time. > What can I do???????????? I believe that cron has a resolution of a minute, so now it doesn't sound that cron is so viable. But how about writing a program that just continues to run as a "daemon" service in the background? A simple example is something like: ###### import time while True: ## do something time.sleep(delay) ###### This isn't a true daemon, since it's not detached from the terminal. But the Python Cookbook mentions something a little more polished here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 and this should be a basis for writing a ftp-polling daemon. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Tue May 3 10:24:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 May 2005 01:24:15 -0700 (PDT) Subject: [Tutor] missing module? In-Reply-To: <20050428203929.93467.qmail@web30501.mail.mud.yahoo.com> Message-ID: > Hello, I get an error message from py2exe that it can't find a module > ntpath.py. I pasted the error message below: > > Traceback (most recent call last): > File "wxApp1.py", line 4, in ? > File "wx\__init__.pyc", line 42, in ? > File "wx\_core.pyc", line 4, in ? > File "wx\_core_.pyc", line 9, in ? > File "wx\_core_.pyc", line 3, in __load > File "C:\Python24\lib\os.py", line 62, in ? > import ntpath as path > zipimport.ZipImportError: can't find module 'ntpath' > > I can find ntpath why can't py2exe? how can I get this thing working? > thanks for the help. Hi Jeff, Has anyone answered you about this? I did a quick Google search, and it looks like this has been discussed a bit on the py2exe-users's mailing list: http://aspn.activestate.com/ASPN/Mail/Message/py2exe-users/2551705 Looks like there might be an issue where old files in 'build' and 'dist' confuses py2exe. Check with the py2exe folks just to confirm this issue. Best of wishes to you! From feziwe at sanbi.ac.za Tue May 3 16:42:29 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Tue, 03 May 2005 16:42:29 +0200 Subject: [Tutor] Weird import problem with PythonIDE on Mac (was 'import problem') In-Reply-To: <774F538A-B58C-11D9-BB74-000393C0D100@bigfoot.com> References: <774F538A-B58C-11D9-BB74-000393C0D100@bigfoot.com> Message-ID: <42778DD5.7000601@sanbi.ac.za> Chris Smith wrote: > > On Friday, Apr 22, 2005, at 10:00 America/Chicago, Max Noel wrote: > >> >>> Do you have a suggestion as to what can I give a module so it has >>> enough information to execute a function that resides in __main__? >>> Here is a visual of what is going on: >>> >>> ------__main__ >>> def y1(): >>> pass >>> import foo >>> foo.run(string_from_main) #what should I pass? >>> >>> ------external module, foo >>> >>> def run(string_from_main): >>> # >>> exec(string_from_main) #y1 is run as if it were in __main__ >>> >>> >>> /c >> >> >> Python makes it easy to do because functions (and classes) are >> objects. Here: >> >> # in __main__ >> def y1(): >> pass >> import foo >> foo.run(y1) >> >> >> # in foo >> def run(functionFromMain): >> functionFromMain() >> > > Yes, I know about this, but this is not the problem. The problem is > knowing what *strings* to pass to the timeit module so it can access a > function that is written in one's __main__. Basically, the timeit > module uses a template to construct a function which is (in the timeit > module) compiled and then executed. You get to send two strings: an > initialization string that is run once and the code string that > appears in a loop. Here, for example, is the function that is > reconstructed and run without success (in mac's pythonIDE: > > ### > def inner(_it, _timer): > from __main__ import y1 # I supplied this > _t0 = _timer() > for _i in _it: > y1() # and I supplied this > _t1 = _timer() > return _t1 - _t0 > ### > > The way the IDE works, this import fails. There are two ways I have > found around the problem: > > 1) wrap the functions of __main__ into a triple quoted string and then > parsing it apart and sending it to timeit (not too elegant/pythonic): > > ### brute force passing of function to timeit > funcs=''' > > def y1(): > print 'y1 executed' > > def y2(): > print 'y2 executed' > ''' > > for f in funcs.split('def'): > f = f.strip() > if not f: > continue > name = f.split('(')[0] > t=timeit.Timer('def '+f) > print name,t.timeit(1) > ### > > 2) the other approach is to add an additional argument to the timeit > __init__ that accepts globals() from the calling program: > > ### > def __init__(self, stmt="pass", setup="pass", timer=default_timer, > glbls = globals): > """Constructor. See class doc string.""" # changed > here - -^ > self.timer = timer > stmt = reindent(stmt, 8) > setup = reindent(setup, 4) > src = template % {'stmt': stmt, 'setup': setup} > self.src = src # Save for traceback display > code = compile(src, dummy_src_name, "exec") > ns = {} > exec code in glbls, ns # and here > self.inner = ns["inner"] > ### > > Then __main__ can send functions like this: > > ### > def y1(): > print 'y1 executed' > def y2(): > print 'y2 executed' > for f in [y1,y2]: > func = f.__name__ > t=timeit.Timer(stmt = "%s()" % func, glbls = globals()) > print func, t.timeit(1) > ### > > {If you read to here, thanks. Is there a better way to accomplish > this with the current timeit module without modifying timeit? i.e. is > there another way to pass the needed information as a string that > timeit's created function can execute?} > > /c > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor hello problem : question says modify a guessing program and to keep track of how many times the user has entered the password wrong. if it more than 3 times, print "that must have bin though" From kent37 at tds.net Tue May 3 14:53:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 May 2005 08:53:25 -0400 Subject: [Tutor] Guessing program In-Reply-To: <42778DD5.7000601@sanbi.ac.za> References: <774F538A-B58C-11D9-BB74-000393C0D100@bigfoot.com> <42778DD5.7000601@sanbi.ac.za> Message-ID: <42777445.3070905@tds.net> Feziwe Mpondo wrote: > hello > problem : question says modify a guessing program and to keep track of > how many times the user has entered the password wrong. if it more than > 3 times, print "that must have bin though" A few tips: - Start a new thread for your question, don't add it at the end of a long, unrelated message - Show us some code - what have you tried? What don't you understand? Kent From feziwe at sanbi.ac.za Tue May 3 17:15:57 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Tue, 03 May 2005 17:15:57 +0200 Subject: [Tutor] problem Message-ID: <427795AD.3050002@sanbi.ac.za> hi problem :modification of a guessing game excersize to a password asking program. her's what i tried. s = raw_input #asks for a password #prints it if correct password = input( "Tell me a password: ") password ==dal print password,"Tell me a password: " elif password ==dal print "accurate" while password != flower : password = input ("tell me a password: ") From smichr at bigfoot.com Tue May 3 16:21:06 2005 From: smichr at bigfoot.com (Chris Smith) Date: Tue, 3 May 2005 09:21:06 -0500 Subject: [Tutor] tokenize row numbering In-Reply-To: Message-ID: <96984CB4-BBDE-11D9-BBD0-000393C0D100@bigfoot.com> > From: Andrei >> ### >> # line 1 according to tokenize tuple >> # line 2 >> a=b #line 3 >> ### >> >> Does anyone have an idea of *why* the rows/physical lines of code >> beginning their count at 1 instead of 0? In order to process the code >> I > > The snippet above shows that numbering begins at 0, with the fourth > line having > number 3. So either I misunderstand the question, or the snippet is > confusing. > Sorry, don't count the ### which are snippet delimiters. Here's another example I ran before sending this: for the single line program, print "hello, world" This is what comes back from the tokenizer: NAME 'print' (1, 0) (1, 5) STRING '"hello, world"' (1, 6) (1, 20) ENDMARKER '' (2, 0) (2, 0) It shows that 'print' starts at position 1,0 whereas if I were to number the rows like I numbered the columns, it would be at position 0,0. I was just wondering if someone knew a good reason for this, otherwise I would submit it as a feature change at source forge. But I'm not sure how long this behavior has been around and if people actually use this information. I did, but what I ended up doing was adding 1 to every row position returned by the tokenizer. /c From ajschmidt at fredericksburg.com Tue May 3 16:43:53 2005 From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.) Date: Tue, 03 May 2005 10:43:53 -0400 Subject: [Tutor] problem In-Reply-To: <427795AD.3050002@sanbi.ac.za> References: <427795AD.3050002@sanbi.ac.za> Message-ID: <42778E29.5060509@fredericksburg.com> Feziwe Mpondo wrote: >hi >problem :modification of a guessing game excersize to a password asking >program. her's what i tried. >s = raw_input > > What is this here for? >#asks for a password >#prints it if correct >password = input( "Tell me a password: ") > > This is correct, but >password ==dal > print password,"Tell me a password: " >elif password ==dal > print "accurate" > > should be: if password!="dal": print password,"Tell me a password: " elif password=="dal": print "accurate" >while password != flower : > password = input ("tell me a password: ") > > And here you should have flower as "flower", since you are checking a string. Hope that helps! From John.Gooch at echostar.com Tue May 3 18:57:34 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Tue, 3 May 2005 10:57:34 -0600 Subject: [Tutor] Subract Month From Date Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D378@riv-excha5.echostar.com> What would be the simplest way to extract the Month and Year for one month prior to the current month? I have been looking for a way to create a Date object with the current date, and then subtract a month from it. Say it is currently "January 1st, 2005", I would like to be able to subtract a month and get "December 1, 2004". For the code I am working with I am only interested in the Month and the Year. Is there a way to use datetime or date modules to do this? Or perhaps I need to use a different module? Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From kent37 at tds.net Tue May 3 19:23:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 03 May 2005 13:23:16 -0400 Subject: [Tutor] Subract Month From Date In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D378@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D378@riv-excha5.echostar.com> Message-ID: <4277B384.1030409@tds.net> Gooch, John wrote: > What would be the simplest way to extract the Month and Year for one month > prior to the current month? I have been looking for a way to create a Date > object with the current date, and then subtract a month from it. Say it is > currently "January 1st, 2005", I would like to be able to subtract a month > and get "December 1, 2004". What if it is March 30 or June 31 today? > > For the code I am working with I am only interested in the Month and the > Year. Is there a way to use datetime or date modules to do this? Or perhaps > I need to use a different module? To just get the month and year you can use datetime and timedelta; just keep subtracting days until the month changes: >>> import datetime >>> t = datetime.datetime.today() >>> t datetime.datetime(2005, 5, 3, 13, 21, 52, 370000) >>> oneday = datetime.timedelta(days=1) >>> month = t.month >>> while t.month == month: ... t -= oneday ... >>> t datetime.datetime(2005, 4, 30, 13, 21, 52, 370000) >>> t.month 4 >>> t.year 2005 Kent From John.Gooch at echostar.com Tue May 3 20:05:50 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Tue, 3 May 2005 12:05:50 -0600 Subject: [Tutor] Subract Month From Date Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D379@riv-excha5.echostar.com> Thank you for the idea, I could have been more clear that days part of the date isn't important. Here is what I came up with: currentDate = datetime.datetime.fromtimestamp( time.time() ) archMonth = 0 archYear = 0 if ( currentDate.month == 1 ): archMonth = 12 archYear = currentYear - 1 else: archMonth = currentDate.month -1 archYear = currentDate.year archDate = datetime.datetime( archYear, archMonth, 1 )#Year/Month of target files Even using datetime instead of Date is overkill, but I think this will work fine in real-world applications. Does anyone have a more elegant solution? -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Tuesday, May 03, 2005 11:23 AM Cc: tutor at python.org Subject: Re: [Tutor] Subract Month From Date Gooch, John wrote: > What would be the simplest way to extract the Month and Year for one > month prior to the current month? I have been looking for a way to > create a Date object with the current date, and then subtract a month > from it. Say it is currently "January 1st, 2005", I would like to be > able to subtract a month and get "December 1, 2004". What if it is March 30 or June 31 today? > > For the code I am working with I am only interested in the Month and > the Year. Is there a way to use datetime or date modules to do this? > Or perhaps I need to use a different module? To just get the month and year you can use datetime and timedelta; just keep subtracting days until the month changes: >>> import datetime >>> t = datetime.datetime.today() >>> t datetime.datetime(2005, 5, 3, 13, 21, 52, 370000) >>> oneday = datetime.timedelta(days=1) >>> month = t.month >>> while t.month == month: ... t -= oneday ... >>> t datetime.datetime(2005, 4, 30, 13, 21, 52, 370000) >>> t.month 4 >>> t.year 2005 Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From tim.peters at gmail.com Tue May 3 20:16:34 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 3 May 2005 14:16:34 -0400 Subject: [Tutor] Subract Month From Date In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D379@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D379@riv-excha5.echostar.com> Message-ID: <1f7befae050503111646e9bb45@mail.gmail.com> [Gooch, John] > Thank you for the idea, I could have been more clear that days part of the > date isn't important. Here is what I came up with: > > currentDate = datetime.datetime.fromtimestamp( time.time() ) Easier: today = datetime.date.today() > archMonth = 0 > archYear = 0 > if ( currentDate.month == 1 ): > archMonth = 12 > archYear = currentYear - 1 > else: > archMonth = currentDate.month -1 > archYear = currentDate.year > archDate = datetime.datetime( archYear, archMonth, 1 )#Year/Month of > target files Easier: lastmonth = today.replace(day=1) - datetime.timedelta(days=1) IOW, it moves to the first day of the current month, and then subtracts one day. That moves you to the last day of the preceding month. lastmonth.month is then the month you want, and lastmonth.year is the year you want. From sigurd at 12move.de Tue May 3 20:40:11 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue, 03 May 2005 20:40:11 +0200 Subject: [Tutor] Subract Month From Date In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D378@riv-excha5.echostar.com> (John Gooch's message of "Tue, 3 May 2005 10:57:34 -0600") References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D378@riv-excha5.echostar.com> Message-ID: On 3 Mai 2005, John.Gooch at echostar.com wrote: > What would be the simplest way to extract the Month and Year for one month > prior to the current month? I have been looking for a way to create a Date > object with the current date, and then subtract a month from it. Say it is > currently "January 1st, 2005", I would like to be able to subtract a month > and get "December 1, 2004". > > For the code I am working with I am only interested in the Month and the > Year. Is there a way to use datetime or date modules to do this? Or perhaps > I need to use a different module? You could use the datetime module, create a date object use a function to subtract the months. import datetime as dt dat = dt.date.today() def subtract_date(date, year=0, month=0): year, month = divmod(year*12 + month, 12) if date.month <= month: year = date.year - year - 1 month = date.month - month + 12 else: year = date.year - year month = date.month - month return date.replace(year = year, month = month) e.g. >>> for i in range(10): ... print subtract_date(dat, month=i) ... 2005-05-03 2005-04-03 2005-03-03 2005-02-03 2005-01-03 2004-12-03 2004-11-03 2004-10-03 2004-09-03 2004-08-03 Instead you could create a timedelta object from the number of months or years and subtract it from the date. The problem is that you have to convert your months to days; so you have to know the number of days of each of the months you want to subtract. The above approach (which only works with your simple needs) doesn't need that information. Karl -- Please do *not* send copies of replies to me. I read the list From flamesrock at gmail.com Tue May 3 21:12:30 2005 From: flamesrock at gmail.com (Aaron Elbaz) Date: Tue, 3 May 2005 19:12:30 +0000 Subject: [Tutor] Text Directly to Screen? Message-ID: <2c2812b6050503121256d20423@mail.gmail.com> Hi, My question has to do with outputting text. Normally, you ouput to a console or a gui...but for my task, a hack might be needed.. What I want to do is output text *directly* to the screen. And if possible, restrict the window area to specific dimensions (top right in mind). It should basically be like a layer of Cellophane over all other windows, so that users can't interact, they only 'see' the output of the chat session, and this chat session would be visible over all windows, including the native OS gui. It sounds awfully cool, but awfully complicated too. I'm not sure where to start looking.. Any ideas? -thanks From maxnoel_fr at yahoo.fr Tue May 3 21:28:40 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 3 May 2005 20:28:40 +0100 Subject: [Tutor] Problem with threading In-Reply-To: References: Message-ID: <54194866-1101-47B6-B5F3-4EDA1A2887E7@yahoo.fr> On May 3, 2005, at 08:57, Danny Yoo wrote: > I believe that cron has a resolution of a minute, so now it doesn't > sound > that cron is so viable. But how about writing a program that just > continues to run as a "daemon" service in the background? A simple > example is something like: > Actually, cron has a resolution of one second, so it may still be useful. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Tue May 3 21:52:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 May 2005 12:52:34 -0700 (PDT) Subject: [Tutor] Problem with threading In-Reply-To: <54194866-1101-47B6-B5F3-4EDA1A2887E7@yahoo.fr> Message-ID: On Tue, 3 May 2005, Max Noel wrote: > > I believe that cron has a resolution of a minute, so now it doesn't > > sound that cron is so viable. But how about writing a program that > > just continues to run as a "daemon" service in the background? A > > simple example is something like: > > Actually, cron has a resolution of one second, so it may still be > useful. Hi Max, Oh! Ok, I need to update my knowledge on this... *grin* I was reading the man page off of cron (man 5 crontab) on my Gentoo box: ###### cron(8) examines cron entries once every minute. The time and date fields are: field allowed values ----- -------------- minute 0-59 hour 0-23 day of month 1-31 month 0-12 (or names, see below) day of week 0-7 (0 or 7 is Sun, or use names) ###### but I see that there are now other programs that provide second resolution, such as 'runwhen' and 'uschedule': http://code.dogmap.org/runwhen/ http://www.ohse.de/uwe/uschedule.html I didn't know about those programs! Thank you. But even if cron had second-resolution, there's other factor that might come to play: it might take a while to initiate an FTP connection in Alberto's situation. That is, if starting up the FTP connection itself takes up a some time, then it might make sense to keep the connection up, just so that we pay the cost of startup just once. Best of wishes! From julesbravo at gmail.com Tue May 3 22:04:32 2005 From: julesbravo at gmail.com (Jules Bravo) Date: Tue, 3 May 2005 13:04:32 -0700 Subject: [Tutor] nested os.popen() Message-ID: <2ba26d2c0505031304650c1926@mail.gmail.com> I'm trying to create a program that can recreate the unix pipe. So basically I need to be able to take something like "ls *.py | du | wc" and be able to run it just like unix would, doing a wordcount of the du of all files that end with .py. My question is how would I do this without being able to create pipes that have both read and write capabilities. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050503/0fe08288/attachment.htm From maxnoel_fr at yahoo.fr Tue May 3 22:23:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 3 May 2005 21:23:51 +0100 Subject: [Tutor] Problem with threading In-Reply-To: References: Message-ID: <3F6DCEFF-2BC6-426F-BE32-FFFAF38F335A@yahoo.fr> On May 3, 2005, at 20:52, Danny Yoo wrote: > ###### > cron(8) examines cron entries once every minute. > > The time and date fields are: > > field allowed values > ----- -------------- > minute 0-59 > hour 0-23 > day of month 1-31 > month 0-12 (or names, see below) > day of week 0-7 (0 or 7 is Sun, or use names) > ###### > Whoops. You're right, I stand corrected. > But even if cron had second-resolution, there's other factor that > might > come to play: it might take a while to initiate an FTP connection in > Alberto's situation. > > That is, if starting up the FTP connection itself takes up a some > time, > then it might make sense to keep the connection up, just so that we > pay > the cost of startup just once. > Good point. Of course, that also involves keeping it alive by sending NOPs every once in a while when there is no activity. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Tue May 3 23:50:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 3 May 2005 14:50:29 -0700 (PDT) Subject: [Tutor] nested os.popen() In-Reply-To: <2ba26d2c0505031304650c1926@mail.gmail.com> Message-ID: On Tue, 3 May 2005, Jules Bravo wrote: > I'm trying to create a program that can recreate the unix pipe. So > basically I need to be able to take something like "ls *.py | du | wc" > and be able to run it just like unix would, doing a wordcount of the du > of all files that end with .py. My question is how would I do this > without being able to create pipes that have both read and write > capabilities. Hi Jules, You may want to look at the 'subprocess' module: http://www.python.org/doc/lib/module-subprocess.html The documentation in: http://www.python.org/doc/lib/node237.html shows how to implement pipelines. The example is slightly cut down, since you'll probably need to add something like: ###### from subprocess import Popen, PIPE ###### to make it work. But, otherwise, it should be self-contained. If you have more questions, please feel free to ask. Good luck! From janos.juhasz at VELUX.com Wed May 4 08:09:23 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 4 May 2005 08:09:23 +0200 Subject: [Tutor] overlap of ranges In-Reply-To: Message-ID: Hi All, one of my colleague asked me, about how the overlap of two ranges can be calculated easily. >>> a = (24,27) # range1 (endpoint1,endpoint2) >>> b = (10,227) # range1 (endpoint1,endpoint2) >>> min( max(a), max(b) ) - max( min(a), min(b) ) 3 When the result is positive, then the two ranges overlap together. When the result is negative, then the two ranges doesn't overlap together and the distance between them is the result multiplied with -1. As we are using max() and min(), a=(24,27) means the same as a=(27,24). I haven't seen this calculation method before, and I think it could be interesting and usefull for coders. Best regards, J?nos From polatel at gmail.com Wed May 4 10:39:50 2005 From: polatel at gmail.com (Ali Polatel) Date: Wed, 4 May 2005 11:39:50 +0300 Subject: [Tutor] Importing C,C++,Asm modules Message-ID: <3c51d518050504013956a163b4@mail.gmail.com> Dear friends, Is there a way to import C,C++ or Asm modules to python scripts? If yes how? Thanks and regards, From feziwe at sanbi.ac.za Wed May 4 15:15:40 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Wed, 04 May 2005 15:15:40 +0200 Subject: [Tutor] problem In-Reply-To: <427795AD.3050002@sanbi.ac.za> References: <427795AD.3050002@sanbi.ac.za> Message-ID: <4278CAFC.7060500@sanbi.ac.za> #keeps asking for password until it has been entered 3 times password = input(" tell me a password: ") correct = False answer = "Flower" if password == answer: while correct == False From albertito_G at hotmail.com Wed May 4 17:18:19 2005 From: albertito_G at hotmail.com (Alberto Troiano) Date: Wed, 4 May 2005 11:18:19 -0400 Subject: [Tutor] Problem with threading In-Reply-To: Message-ID: Hi I took a look at the code and now I'm confused I'll use CRON and I will make a python script that take parameters (username) and work only for that user but the script will never finish ?The FTP connection that starts the camera never ends unless I shutdown my server. Now I'm thinking that CRON will start my script only once and I will make a script that check for the record time of the user and insert all the photos that are in the record time but is there a quick to insert the filename with path to the database???? I'll have all the photos in one directory and I want to check all directory quickly cause after it finish it will start again and again and again and again and again and again.....i think you get the picture Imagine 40 users running all at the same time. I have to ask, does the machine will overhead with this process???Does CRON make my script run as a daemon or should I insert the daemon code you gave me: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 What is the difference in running with CRON without the daemon code with running with the daemon code?????? Regards Alberto ---------------------------------------------------------------------------- - Alberto -------------------------------------------------------------- The one who stands beside me, does not share my pythonistic way to do things -----Mensaje original----- De: tutor-bounces at python.org [mailto:tutor-bounces at python.org] En nombre de Danny Yoo Enviado el: Martes, 03 de Mayo de 2005 03:58 a.m. Para: Alberto Troiano CC: Tutor; matt at mondoinfo.com Asunto: Re: [Tutor] Problem with threading On Tue, 3 May 2005, Alberto Troiano wrote: > In answer to Matt the cameras push the photos via ftp at my server at 1 > photo every 3 seconds Hi Alberto, Just as another note: the folks here have no idea who you mean by Matt. I do know that you mean Matt from python-help at python.org, but the folks on Tutor now have no clue what we're talking about. *grin* That's sorta why it's not such a good idea to crosspost to both lists, because now we have a conversation where not everyone can see each other. I'll put Matt in CC, but let's try to avoid this situation next time. > What can I do???????????? I believe that cron has a resolution of a minute, so now it doesn't sound that cron is so viable. But how about writing a program that just continues to run as a "daemon" service in the background? A simple example is something like: ###### import time while True: ## do something time.sleep(delay) ###### This isn't a true daemon, since it's not detached from the terminal. But the Python Cookbook mentions something a little more polished here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 and this should be a basis for writing a ftp-polling daemon. Best of wishes to you! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From cpu.crazy at gmail.com Wed May 4 17:35:49 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 04 May 2005 09:35:49 -0600 Subject: [Tutor] Psyco (Joseph Quigley) In-Reply-To: References: Message-ID: <6.1.0.6.2.20050504093301.01ef6250@pop.gmail.com> For those who use Psyco: Is it any good? I'm searching for instructions on how to use it, should I stop? For those who don't know about Psyco: It is supposed to be a Python Compiler. The programs are said to run faster than normal Python and they almost run as fast as C. From cpu.crazy at gmail.com Wed May 4 17:54:28 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 04 May 2005 09:54:28 -0600 Subject: [Tutor] No Need to press Enter (Joseph Quigley) Message-ID: <6.1.0.6.2.20050504095106.01ee1100@pop.gmail.com> What is the secret to have the user press the "Q" key, and the program exits without pressing the "Enter" key? Or the "Control" and "Q" keys to exit? For the Macintosh, would the same command/s for "Control Q" keys be the same as the "Apple Q" key? Thanks, JQ From kent37 at tds.net Wed May 4 18:21:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 04 May 2005 12:21:58 -0400 Subject: [Tutor] Psyco (Joseph Quigley) In-Reply-To: <6.1.0.6.2.20050504093301.01ef6250@pop.gmail.com> References: <6.1.0.6.2.20050504093301.01ef6250@pop.gmail.com> Message-ID: <4278F6A6.5010508@tds.net> Joseph Quigley wrote: > For those who use Psyco: > Is it any good? Yes, it can give significant speedups in Python on Windows. I'm searching for instructions on how to use it, should I > stop? No, look here: http://psyco.sourceforge.net/psycoguide/node8.html Kent From maxnoel_fr at yahoo.fr Wed May 4 18:30:48 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed, 4 May 2005 17:30:48 +0100 Subject: [Tutor] Psyco (Joseph Quigley) In-Reply-To: <6.1.0.6.2.20050504093301.01ef6250@pop.gmail.com> References: <6.1.0.6.2.20050504093301.01ef6250@pop.gmail.com> Message-ID: On May 4, 2005, at 16:35, Joseph Quigley wrote: > For those who use Psyco: > Is it any good? I'm searching for instructions on how to use > it, should I > stop? I hear it's quite good at what it does. Note, however, that it only works on x86 computers (i.e. IBM PC compatibles). Also, if speed is what your program needs, you should go all the way and rewrite the critical parts in pure C. It's not very difficult to do -- the tutorial on www.python.org explains how to do it. > For those who don't know about Psyco: > It is supposed to be a Python Compiler. The programs are said > to run > faster than normal Python and they almost run as fast as C. It's not a compiler. It's a JIT (Just-In-Time) compiler, a little bit like HotSpot for Java. Also, while it is faster than regular Python, it is still much slower than C. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From mark.brown at rogers.com Wed May 4 20:21:26 2005 From: mark.brown at rogers.com (Mark Brown) Date: Wed, 04 May 2005 14:21:26 -0400 Subject: [Tutor] Web Calendar written in Python Message-ID: <427912A6.4070702@rogers.com> Does anyone know of a Web Calendar written in Python? TIA Mark From denise.hartley at gmail.com Wed May 4 20:33:53 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 4 May 2005 11:33:53 -0700 Subject: [Tutor] Fwd: No Need to press Enter (Joseph Quigley) In-Reply-To: <6.1.0.6.2.20050504095106.01ee1100@pop.gmail.com> References: <6.1.0.6.2.20050504095106.01ee1100@pop.gmail.com> Message-ID: <8daabe5605050411332f7b1a41@mail.gmail.com> I don't know if this is what you're looking for, but in my game I set Running = 1, and then had: if event.key == K_q: running = 0 ... which exits the game as soon as you hit q (i.e., no hitting enter). I can send the full code if it would be more helpful, if this is what you're talking about? ~Denise ---------- Forwarded message ---------- From: Joseph Quigley Date: May 4, 2005 8:54 AM Subject: [Tutor] No Need to press Enter (Joseph Quigley) To: Tutor at python.org What is the secret to have the user press the "Q" key, and the program exits without pressing the "Enter" key? Or the "Control" and "Q" keys to exit? For the Macintosh, would the same command/s for "Control Q" keys be the same as the "Apple Q" key? Thanks, JQ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Thu May 5 01:43:52 2005 From: project5 at redrival.net (Andrei) Date: Thu, 5 May 2005 01:43:52 +0200 Subject: [Tutor] Psyco (Joseph Quigley) References: <6.1.0.6.2.20050504093301.01ef6250@pop.gmail.com> Message-ID: Max Noel wrote on Wed, 4 May 2005 17:30:48 +0100: > On May 4, 2005, at 16:35, Joseph Quigley wrote: >> For those who use Psyco: >> Is it any good? I'm searching for instructions on how to use >> it, should I >> stop? Depends on the application. If you have a performance problem in the code (this is an important aspect: don't waste your time on optimizing if there is no problem), profile it to identify the source and try psyco-ing it. It might help, but it might also not help. It's hard to predict its effects without profiling beforehand, the speed increase factor may be anywhere from say 100x (in extremely lucky situations) to 0, with code of average optimizability probably being in the 2-5 range. Note that in some cases algorithm improvements can give tremendous speed boosts without any external help (e.g. I've seen in several cases factor 20 speed gains just by swithing from 'normal' algorithms to fancier features in Python, using the built-in libraries wisely or implementation of simple caching systems). > I hear it's quite good at what it does. Note, however, that it > only works on x86 computers (i.e. IBM PC compatibles). > Also, if speed is what your program needs, you should go all the > way and rewrite the critical parts in pure C. It's not very difficult > to do -- the tutorial on www.python.org explains how to do it. I disagree there. Psyco can deliver significant speed improvements on certain types of code at virtually no cost (something along the lines of 2 lines of Python code) and to make things even better, your code will still run on computers without Psyco (only slower). That could be worth doing even if you only shave a couple of seconds off something that runs repeatedly. Coding in C might give better speed improvements, but at a significantly larger investment of time *and* your code won't work unless your custom module is present on the target machine. >> For those who don't know about Psyco: >> It is supposed to be a Python Compiler. The programs are said >> to run >> faster than normal Python and they almost run as fast as C. > > It's not a compiler. It's a JIT (Just-In-Time) compiler, a > little bit like HotSpot for Java. > Also, while it is faster than regular Python, it is still much > slower than C. Except in some amusing cases: http://mail.python.org/pipermail/python-list/2004-April/215272.html -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From gsf at panix.com Thu May 5 02:03:38 2005 From: gsf at panix.com (Gabriel Farrell) Date: Wed, 4 May 2005 20:03:38 -0400 Subject: [Tutor] making a cgi search safe(r) Message-ID: <20050505000338.GA13528@panix.com> Greetings, I'm setting up a search for an online catalog. It works right now by passing the cgi search query to the command-line swish-e via os.popen. I'll do it via a direct interface as soon as I figure out how to do that with swig or the swishe module. In the meantime, I'm trying to sanitize the query so it's safer on the shell. The swish-e documentation says it's better to include only the characters that you want rather than knock out the known offenders. It seems like there should be a simple way with string methods or the re module. Right now I've got: def getquery(): kosher = re.compile(r'\w|"|\'|[ ]') sanitized = ''.join(kosher.findall(form['query'].value)) Is this about the best way to do this? gabe From jfouhy at paradise.net.nz Thu May 5 01:53:07 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 05 May 2005 11:53:07 +1200 (NZST) Subject: [Tutor] Python riddles Message-ID: <1115250787.427960631ff18@www.paradise.net.nz> As seen on python-announce (via Dr Dobbs): http://www.pythonchallenge.com/ Good fun! -- John. [currently on riddle 6] From missive at hotmail.com Thu May 5 04:01:34 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 05 May 2005 06:31:34 +0430 Subject: [Tutor] Web Calendar written in Python Message-ID: >Does anyone know of a Web Calendar written in Python? I believe that SchoolBell is using Zope 3 ... http://www.schooltool.org/schoolbell _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From billburns at pennswoods.net Thu May 5 04:58:02 2005 From: billburns at pennswoods.net (Bill Burns) Date: Wed, 4 May 2005 22:58:02 -0400 Subject: [Tutor] Importing C,C++,Asm modules In-Reply-To: <3c51d518050504013956a163b4@mail.gmail.com> References: <3c51d518050504013956a163b4@mail.gmail.com> Message-ID: <200505042258.02854.billburns@pennswoods.net> On Wednesday 04 May 2005 4:39 am, Ali Polatel wrote: > Dear friends, > Is there a way to import C,C++ or Asm modules to python scripts? > If yes how? > Thanks and regards, Hi Ali, If you're asking if you can take C or C++ code and compile it in such a way as to be able to import it into python, them the answer is yes. Take a look at the following sites: http://www.swig.org/ Here's a nice, easy tutorial on using SWIG: http://www.swig.org/tutorial.html Boost.Python http://www.boost.org/libs/python/doc/index.html SIP http://www.riverbankcomputing.co.uk/sip/index.php I noticed a Tutor post today entitled '[Tutor] Psyco (Joseph Quigley)' in which Max Noel mentions a tutorial on the Python web site. So do a search there as well. Of the above, I've only used SWIG and it was very easy to use. The hard part was figuring out how to get six lines of C to compile without complaints, damn those type declarations :-) HTH Bill From smichr at bigfoot.com Thu May 5 07:11:48 2005 From: smichr at bigfoot.com (Chris Smith) Date: Thu, 5 May 2005 00:11:48 -0500 Subject: [Tutor] No Need to press Enter In-Reply-To: Message-ID: <2EA78105-BD24-11D9-8A66-000393C0D100@bigfoot.com> > From: Joseph Quigley > What is the secret to have the user press the "Q" key, and the program > exits without pressing the "Enter" key? > Or the "Control" and "Q" keys to exit? > For the Macintosh, would the same command/s for "Control Q" keys be the > same as the "Apple Q" key? > I see that Diane has suggested (what I believe to be) a pyGame solution. I had asked this question before and Danny Yoo wrote up a script that is posted at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 With the modifications that I added (just before sending this) the code there has the ability to get the getch() behavior (not having to press enter) on the Mac (whether you are running under the pythonIDE or the Terminal), Windows, or Unix. An example of usage (assuming that the code is stored in a file named getch.py) might be, ### import getch inkey = getch._Getch() print 'Press any key to end' while inkey()=='': pass print 'ok' ### From bds at waywood.co.uk Thu May 5 15:03:30 2005 From: bds at waywood.co.uk (Barnaby Scott) Date: Thu, 5 May 2005 14:03:30 +0100 Subject: [Tutor] database applications with Python - where to start Message-ID: <000001c55172$d65b81d0$7c00a8c0@frankbruno> 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. From maxnoel_fr at yahoo.fr Thu May 5 15:50:28 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 5 May 2005 14:50:28 +0100 Subject: [Tutor] Python riddles In-Reply-To: <1115250787.427960631ff18@www.paradise.net.nz> References: <1115250787.427960631ff18@www.paradise.net.nz> Message-ID: On May 5, 2005, at 00:53, jfouhy at paradise.net.nz wrote: > As seen on python-announce (via Dr Dobbs): > > http://www.pythonchallenge.com/ > > Good fun! > Very interesting indeed! I'm stuck on number 7, though -- looks like it requires the use of PIL, which I've never used before. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From william.ohiggins at utoronto.ca Thu May 5 16:52:31 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Thu, 5 May 2005 10:52:31 -0400 Subject: [Tutor] database applications with Python - where to start In-Reply-To: <000001c55172$d65b81d0$7c00a8c0@frankbruno> References: <000001c55172$d65b81d0$7c00a8c0@frankbruno> Message-ID: <20050505145231.GA4243@sillyrabbi.dyndns.org> On Thu, May 05, 2005 at 02:03:30PM +0100, Barnaby Scott wrote: >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. Good reasons for doing something - just remember that, as you are discovering, this is a pretty extensive project, and the reasons need to be good enough if you are to finish. >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! This is a very reasonable response when you look at a project and begin to appreciate its complexities. I am the opposite of a Python expert (most of the code I read leaves me with questions and confusion - that's why I'm lurking here), but I know something about problem-solving. Here is an approach that may help: Programming is, by definition, something that can be decomposed into smaller problems. When you are thinking about your project, write everything you think of down. Once it is written down, attempt to break up your notes into categories - features, behaviours, functional activities of the finished product. This does not need to take a long time. Once you think you have a collection of things you need from your project (these are called Requirements by many), try to organize them by type: data storage, data manipulation, human interfaces, computer systems interfaces, etc. Now, take one of these aspects at a time, and try to quantify what exactly this piece of the project needs to do - for example, write data into a database. Once you have in your head a clear picture of one activity of your program, write a small piece of code that does what you want. If it doesn't work, ask for help - small problems are easier to solve (generally) than big ones, and always easier to ask for help about. Something that helps is to make each proof of concept script with a name that relates back to your Requirements document - so you know by the file name how it fits in the whole project. At some point you will have to commit to which tools you are going to use (database, language, interface, etc.). For your first major project, try to use what you know, or what you have the best support systems in place for - local gurus, lists, user groups etc. Even while you commit to one set of tools, try to think of your program as a set of interacting pieces that can be abstracted from one another, so if you need to change one piece the whole structure doesn't collapse (this is called "loose coupling"). >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? Tool kits are very worthwhile - once you have code that works, you'll reuse it a lot. Which tools comes down to an optimization of your ability and comfort, your support network and features. > What on earth is my application's model going to >look like? should I get involved with object-relational mapping? If it will gain you something yes, if you don't understand what the gains are or how to implement them, probably not. >how much work should I delegate to the RDBMS, and how much logic should >I code in Python? If you decide at some other point to change databases, delegating core functions to the database may hurt. If you decide to re-write your project in C later, you may regret not handing some things to the database. In all cases, try not to reinvent the wheel habitually, but only where it serves a purpose (learning how it works is a purpose). >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? What do you *really* understand, and what can you implement without having an aneurysm. >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? Look for an Open Source app that almost works the way you need it to, and look at how it's done. You may find that getting involved with an existing project will get you the features you need sooner than building something from scratch, and by getting involved you can learn a lot. >Sorry it is such a vague question, but any pointers gratefully received. Vague questions are hard to answer specifically, but they are often worth asking. You may find more success decomposing your vague questions into specific sub-questions - they are easier to answer quickly. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050505/7d8a08cc/attachment.pgp From ajschmidt at fredericksburg.com Thu May 5 17:37:06 2005 From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.) Date: Thu, 05 May 2005 11:37:06 -0400 Subject: [Tutor] Dictionary Inserts... Message-ID: <427A3DA2.2000807@fredericksburg.com> Ok, I have had enough. I have looked all through the python docs and I cannot find it. How do you insert an entry into a dictionary? Thanx! From eculpepper at hcc-care.com Thu May 5 17:50:26 2005 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Thu, 5 May 2005 10:50:26 -0500 Subject: [Tutor] Dictionary Inserts... Message-ID: <48CA63C679F03D4187762B7CE066AAD20304C121@hccexchange.hcccorp.hcc-care.com> Here's some quick examples: >>> dictMe = {} >>> dictMe['SomeKey'] = 'SomeValue' >>> dictMe {'SomeKey': 'SomeValue'} >>> dictMe[1] = 100 >>> dictMe {1: 100, 'SomeKey': 'SomeValue'} >>> type(dictMe) Section 5.5 of the Python tutorial covers dictionaries a little more in depth. http://docs.python.org/tut/node7.html -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Allen John Schmidt, Jr. Sent: Thursday, May 05, 2005 10:37 AM To: tutor at python.org Subject: [Tutor] Dictionary Inserts... Ok, I have had enough. I have looked all through the python docs and I cannot find it. How do you insert an entry into a dictionary? Thanx! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From andre.roberge at gmail.com Thu May 5 17:48:16 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Thu, 05 May 2005 12:48:16 -0300 Subject: [Tutor] Dictionary Inserts... In-Reply-To: <427A3DA2.2000807@fredericksburg.com> References: <427A3DA2.2000807@fredericksburg.com> Message-ID: Allen John Schmidt, Jr. wrote: > Ok, I have had enough. I have looked all through the python docs and I > cannot find it. How do you insert an entry into a dictionary? > > Thanx! > >>> my_dict = {} >>> my_dict['new_entry'] = ['simple', 'as', 1, 2, 3] >>> my_dict {'new_entry': ['simple', 'as', 1, 2, 3]} From maxnoel_fr at yahoo.fr Thu May 5 17:52:12 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 5 May 2005 16:52:12 +0100 Subject: [Tutor] Dictionary Inserts... In-Reply-To: <427A3DA2.2000807@fredericksburg.com> References: <427A3DA2.2000807@fredericksburg.com> Message-ID: <6804C081-9A11-4E32-82C9-73652A17D79F@yahoo.fr> On May 5, 2005, at 16:37, Allen John Schmidt, Jr. wrote: > Ok, I have had enough. I have looked all through the python docs and I > cannot find it. How do you insert an entry into a dictionary? > The way you think it's done: >>> a = {'foo': 1, 'bar': 2} >>> a {'foo': 1, 'bar': 2} >>> a['baz'] = 'boo' >>> a {'baz': 'boo', 'foo': 1, 'bar': 2} >>> Interactive Python is your friend ^^. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From ajschmidt at fredericksburg.com Thu May 5 19:38:23 2005 From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.) Date: Thu, 05 May 2005 13:38:23 -0400 Subject: [Tutor] Dictionary Inserts... In-Reply-To: <200505051553.j45FrIms020280@sws002.fredericksburg.com> References: <200505051553.j45FrIms020280@sws002.fredericksburg.com> Message-ID: <427A5A0F.1090204@fredericksburg.com> Arrgh! How could I be so stupid! :) Thanks for the help! I know many things about python, but I can't believe that I didn't know that! Thanx again! From Bxny1971 at wmconnect.com Wed May 4 23:40:41 2005 From: Bxny1971 at wmconnect.com (Bxny1971@wmconnect.com) Date: Wed, 4 May 2005 17:40:41 EDT Subject: [Tutor] help Message-ID: <24.7055f71d.2faa9b59@wmconnect.com> i need help with my wmconnect service. it keeps on losing connection once logged on-line every 5 or 10 minutes. i have to continuosly keep trying to make a connetion. could you please help . thanks keisha -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050504/d3c37c9e/attachment.html From newgat11 at yahoo.com Thu May 5 18:31:08 2005 From: newgat11 at yahoo.com (the New me) Date: Thu, 5 May 2005 09:31:08 -0700 (PDT) Subject: [Tutor] running a compiled module from another module Message-ID: <20050505163108.60211.qmail@web54506.mail.yahoo.com> I need to compile what it amounts to a subroutine in the old way of looking at it. it's a module that accepts input from another module. need to run: mod-A that initializes input and output files. mod-B that acts on data from input gives output Matr mod-C module that gets (Matr) as input and gets other output out. mod-D continues processing and does input/output from/into a DB. I'd like mod-C preferably compiled if I run these from a .bat file, each one will not know about the output af the other module, unless I make them look like subroutines. if I run them fro the IDLE, it restarts the workspace so again they do not know of the previous output. unless i run them by copy and paste into the python >>> command line by hand, then it keeps the output in the workspace; but the idea is to automate the process and get away from doing stuff manually and eventually sun them from a scheduler. Any ideas, Thanks Newt __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From denise.hartley at gmail.com Thu May 5 20:39:23 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 5 May 2005 11:39:23 -0700 Subject: [Tutor] Fwd: Python riddles In-Reply-To: References: <1115250787.427960631ff18@www.paradise.net.nz> Message-ID: <8daabe56050505113922d05380@mail.gmail.com> Ok, now, I'm sure this sounds like a very dumb question. But I clicked on riddle 1, and I don't know how this thing works - "about" didnt give a lot of extra info. Am I trying to duplicate something on my screen that looks like the picture on the monitor? If someone would give me the (probably obvious) push in the right direction, I think some challenges would be really fun. Perhaps off the mailing list so everyone who gets it doesnt have to be bombarded ;) Thanks! ~Denise ---------- Forwarded message ---------- From: Max Noel Date: May 5, 2005 6:50 AM Subject: Re: [Tutor] Python riddles To: jfouhy at paradise.net.nz Cc: tutor at python.org On May 5, 2005, at 00:53, jfouhy at paradise.net.nz wrote: > As seen on python-announce (via Dr Dobbs): > > http://www.pythonchallenge.com/ > > Good fun! > Very interesting indeed! I'm stuck on number 7, though -- looks like it requires the use of PIL, which I've never used before. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From maxnoel_fr at yahoo.fr Thu May 5 20:53:37 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 5 May 2005 19:53:37 +0100 Subject: [Tutor] Fwd: Python riddles In-Reply-To: <8daabe56050505113922d05380@mail.gmail.com> References: <1115250787.427960631ff18@www.paradise.net.nz> <8daabe56050505113922d05380@mail.gmail.com> Message-ID: <48A774B5-7A26-4762-BA09-C892021C34F2@yahoo.fr> On May 5, 2005, at 19:39, D. Hartley wrote: > Ok, now, I'm sure this sounds like a very dumb question. But I > clicked on riddle 1, and I don't know how this thing works - "about" > didnt give a lot of extra info. Am I trying to duplicate something on > my screen that looks like the picture on the monitor? If someone would > give me the (probably obvious) push in the right direction, I think > some challenges would be really fun. Perhaps off the mailing list so > everyone who gets it doesnt have to be bombarded ;) > > Thanks! > > ~Denise The goal for each riddle is to use the clues found on the page and in its source code (together with some Python bits) to find the URL (page name) for the next one. So the question you have to ask yourself is, what do you see on the first page that could be a clue? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Thu May 5 21:28:32 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 5 May 2005 12:28:32 -0700 Subject: [Tutor] Fwd: Fwd: Python riddles In-Reply-To: <6.1.2.0.0.20050505115627.03775948@pop.sbcglobal.yahoo.com> References: <1115250787.427960631ff18@www.paradise.net.nz> <8daabe56050505113922d05380@mail.gmail.com> <6.1.2.0.0.20050505115627.03775948@pop.sbcglobal.yahoo.com> Message-ID: <8daabe56050505122850caba70@mail.gmail.com> ha ha. ok. I figured out the riddle (the computational part), i just had calculated it myself and wondered where python came in. if I had remembered to bring my brain with me this morning, I suppose I would have thought that I could write a python script to do the math problem for me instead of a normal calculator. Thanks! ~Sheepish Denise ---------- Forwarded message ---------- From: Bob Gailer Date: May 5, 2005 11:57 AM Subject: Re: [Tutor] Fwd: Python riddles To: "D. Hartley" At 11:39 AM 5/5/2005, you wrote: Ok, now, I'm sure this sounds like a very dumb question. But I clicked on riddle 1, and I don't know how this thing works - "about" didnt give a lot of extra info. Am I trying to duplicate something on my screen that looks like the picture on the monitor? If someone would give me the (probably obvious) push in the right direction, I think some challenges would be really fun. Perhaps off the mailing list so everyone who gets it doesnt have to be bombarded ;) Also follow the forum link to the Python Challenge Hints Where you will find for the first challenge: Hint 1: do the math Hint 2: change the address Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell From alan.gauld at freenet.co.uk Fri May 6 00:02:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 5 May 2005 23:02:25 +0100 Subject: [Tutor] database applications with Python - where to start References: <000001c55172$d65b81d0$7c00a8c0@frankbruno> Message-ID: <003101c551be$1fd66eb0$e54b8651@xp> Well I'm currently working on a database programmers guide for my tutorial and I'm happy to send you what I've done so far - but its only half complete. However any feedback would be good. (It assumes the use of SQLite as the actual database) Alan G. PS It'll probably be another month at least before its fully done! I've got an awful lot in my diary just now! ----- Original Message ----- From: "Barnaby Scott" To: Sent: Thursday, May 05, 2005 2:03 PM Subject: [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. > > > From dyoo at hkn.eecs.berkeley.edu Fri May 6 02:00:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 5 May 2005 17:00:17 -0700 (PDT) Subject: [Tutor] help In-Reply-To: <24.7055f71d.2faa9b59@wmconnect.com> Message-ID: On Wed, 4 May 2005 Bxny1971 at wmconnect.com wrote: > i need help with my wmconnect service. it keeps on losing connection > once logged on-line every 5 or 10 minutes. i have to continuosly keep > trying to make a connetion. Hello Keisha, I hope you don't mind me asking, but how is this related to Python? I'm trying to figure out what we can do to help, but I think this is out of scope --- it sounds more like a problem with your 'wmconnect' ISP than anything. You could probably write a "keep the connection alive" program in Python, but there are so many of those kinds of programs out there already, that it's probably worthwhile to just use a preexisting one, rather than code your own. Most home routers these days also support an option to periodically poll to keep an internet connection up, too. Good luck to you. From denise.hartley at gmail.com Fri May 6 02:10:12 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 5 May 2005 17:10:12 -0700 Subject: [Tutor] python challenges Message-ID: <8daabe560505051710268fabd3@mail.gmail.com> I seem to have lost the original link, but thanks to whoever posted the url for the python challenges. I've been working through them and they've made for a fun afternoon :) I even came up with a really elegant solution for #2 that I was really proud of - being new to python, very often I find problem solutions that work but are ugly and/or convoluted, and I always know there's a better way. I think my mental structuring must be improving with practice. ;) I do have one question, however. I'm on riddle 3 ("re"), and got sent to the howto about regular expressions by the hint. But it did not seem (at least to me) very user-friendly: or perhaps I'm just not applying it to the problem correctly. I can see how I would use it if I were matching an exact bit of a string, for instance (like the "search" method), but if I'm checking for a series of cap/lowercase letters (but am not particular which character), I can't figure out how to use regular expressions to help me out. Anyone have a gentle hint, or pointer to another 'beginner' tutorial to regular expressions? Thanks! I dont want to get stuck here in the riddles! ~Denise From maxnoel_fr at yahoo.fr Fri May 6 02:23:49 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 01:23:49 +0100 Subject: [Tutor] python challenges In-Reply-To: <8daabe560505051710268fabd3@mail.gmail.com> References: <8daabe560505051710268fabd3@mail.gmail.com> Message-ID: <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> On May 6, 2005, at 01:10, D. Hartley wrote: > Anyone have a gentle hint, or pointer to another 'beginner' tutorial > to regular expressions? > > Thanks! I dont want to get stuck here in the riddles! > > ~Denise I learned most of what I know about regular expressions while I was learning Perl a few years ago. Most Perl books and tutorials include a small part that deals with RE's, but perhaps that's not gonna help you much. However, I find that the documentation for the Python "sre" module is quite good. You may want to have a look at it -- should be enough for what you have to do with this riddle. (Also, note that however simple they may seem, one can never completely master regular expressions. There are entire books dedicated to the things, and when properly used, they're the most powerful text processing tool available for any language. In other words, try to remember what you'll learn about them: they're very useful.) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jfouhy at paradise.net.nz Fri May 6 02:30:31 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 06 May 2005 12:30:31 +1200 (NZST) Subject: [Tutor] python challenges In-Reply-To: <8daabe560505051710268fabd3@mail.gmail.com> References: <8daabe560505051710268fabd3@mail.gmail.com> Message-ID: <1115339431.427abaa78ce8a@www.paradise.net.nz> Quoting "D. Hartley" : > I do have one question, however. I'm on riddle 3 ("re"), and got sent > to the howto about regular expressions by the hint. But it did not > seem (at least to me) very user-friendly: or perhaps I'm just not > applying it to the problem correctly. I can see how I would use it if > I were matching an exact bit of a string, for instance (like the > "search" method), but if I'm checking for a series of cap/lowercase > letters (but am not particular which character), I can't figure out > how to use regular expressions to help me out. [a-z] will match any single lower-case letter. [A-Z] will match a single upper case letter. I guess this is the intended attack. That said, when I solved riddle 3, I didn't even think to use regular expressions. I just used a list comprehsnsion :-) (regex probably is a better way, though) -- John. From denise.hartley at gmail.com Fri May 6 02:33:21 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 5 May 2005 17:33:21 -0700 Subject: [Tutor] python challenges In-Reply-To: <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> References: <8daabe560505051710268fabd3@mail.gmail.com> <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> Message-ID: <8daabe560505051733515a111a@mail.gmail.com> They do seem to be useful! But with all those special characters, it certainly doesnt make for an easy read. I think I'm making some progress - I got it to make me a list of all the {uppercaseuppercaseuppercaselowercaseuppercaseuppercaseuppercase} chunks (477 of them?!?!) - turns out the first time through I missed something very small (and very helpful, in this case): [A-Z]. Thanks for the pointers :) ~Denise On 5/5/05, Max Noel wrote: > > On May 6, 2005, at 01:10, D. Hartley wrote: > > > Anyone have a gentle hint, or pointer to another 'beginner' tutorial > > to regular expressions? > > > > Thanks! I dont want to get stuck here in the riddles! > > > > ~Denise > > I learned most of what I know about regular expressions while I > was learning Perl a few years ago. Most Perl books and tutorials > include a small part that deals with RE's, but perhaps that's not > gonna help you much. > > However, I find that the documentation for the Python "sre" > module is quite good. You may want to have a look at it -- should be > enough for what you have to do with this riddle. > > (Also, note that however simple they may seem, one can never > completely master regular expressions. There are entire books > dedicated to the things, and when properly used, they're the most > powerful text processing tool available for any language. In other > words, try to remember what you'll learn about them: they're very > useful.) > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From maxnoel_fr at yahoo.fr Fri May 6 02:46:06 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 01:46:06 +0100 Subject: [Tutor] python challenges In-Reply-To: <8daabe560505051733515a111a@mail.gmail.com> References: <8daabe560505051710268fabd3@mail.gmail.com> <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> <8daabe560505051733515a111a@mail.gmail.com> Message-ID: On May 6, 2005, at 01:33, D. Hartley wrote: > They do seem to be useful! But with all those special characters, it > certainly doesnt make for an easy read. I think I'm making some > progress - I got it to make me a list of all the > {uppercaseuppercaseuppercaselowercaseuppercaseuppercaseuppercase} > chunks (477 of them?!?!) - turns out the first time through I missed > something very small (and very helpful, in this case): [A-Z]. > > Thanks for the pointers :) > > ~Denise Oh, here's another piece of advice when you're dealing with regular expressions: they use a lot of backslashes, so use raw strings in order not to have to escape them all. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Fri May 6 02:58:30 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 5 May 2005 17:58:30 -0700 Subject: [Tutor] python challenges In-Reply-To: References: <8daabe560505051710268fabd3@mail.gmail.com> <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> <8daabe560505051733515a111a@mail.gmail.com> Message-ID: <8daabe56050505175863752c37@mail.gmail.com> It took a little bit of playing to limit it so that it got ONLY 3 cap letters on either side, but I just got the riddle and just about jumped out of my chair when it worked. Progress is possible! ha ha! On 5/5/05, Max Noel wrote: > > On May 6, 2005, at 01:33, D. Hartley wrote: > > > They do seem to be useful! But with all those special characters, it > > certainly doesnt make for an easy read. I think I'm making some > > progress - I got it to make me a list of all the > > {uppercaseuppercaseuppercaselowercaseuppercaseuppercaseuppercase} > > chunks (477 of them?!?!) - turns out the first time through I missed > > something very small (and very helpful, in this case): [A-Z]. > > > > Thanks for the pointers :) > > > > ~Denise > > Oh, here's another piece of advice when you're dealing with > regular expressions: they use a lot of backslashes, so use raw > strings in order not to have to escape them all. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From jfouhy at paradise.net.nz Fri May 6 03:05:27 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 06 May 2005 13:05:27 +1200 (NZST) Subject: [Tutor] python challenges In-Reply-To: <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> References: <8daabe560505051710268fabd3@mail.gmail.com> <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> Message-ID: <1115341527.427ac2d789a50@www.paradise.net.nz> Quoting Max Noel : > (Also, note that however simple they may seem, one can never > completely master regular expressions. There are entire books > dedicated to the things, and when properly used, they're the most > powerful text processing tool available for any language. In other > words, try to remember what you'll learn about them: they're very > useful.) At the risk of being pedantic --- This is not actually true. There are things you can't do with regular expressions. The normal example is bracket counting: If I give you a string like '(1+(2-4/(3+8)*(5+9)))-(8+1)', can you write me a regex which will produce matches for only the chucks defined by the brackets? (in this case, the answer is this list of substrings: ['(1+(2-4/(3+8)*(5+9)))', '(2-4/(3+8)*(5+9))', '(3+8)', '(5+9)', '(8+1)'] ) -- John. From tim at johnsons-web.com Fri May 6 03:44:13 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 5 May 2005 17:44:13 -0800 Subject: [Tutor] Class and Scope Question Message-ID: <20050506014413.GH1808@johnsons-web.com> The following test script is kind of got me baffled: #!/usr/local/bin/python class Eval: def __getitem__(self,key): return eval(key) ##def test(): ## i = 100 ## b = ["My", "name", "is", "Tim"] ## test = "this is number %(str(i))s for a test %(' '.join(b))s" ## s = test % Eval() ## print s ##test() i = 100 b = ["My", "name", "is", "Tim"] test = "this is number %(str(i))s for a test %(' '.join(b))s" print test % Eval() ## ============================================================ Running this gives me the following : [tim at linus baker]$ python test.py this is number 100 for a test My name is Tim ## cool! Now if I comment out the last four lines and uncomment the previous 7, I get the following error message: [tim at linus baker]$ python test.py Traceback (most recent call last): File "test.py", line 11, in ? test() File "test.py", line 9, in test s = test % Eval() File "test.py", line 4, in __getitem__ return eval(key) File "", line 0, in ? NameError: name 'i' is not defined ## It's been a lloooonngg day. What am I missing here? Explanation and solution is no doubt going to further edify me about python. TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From jsmith at medplus.com Fri May 6 04:30:32 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu, 5 May 2005 22:30:32 -0400 Subject: [Tutor] XML to Python Message-ID: I'm able to use the built in XML parser to effect "normal" XML parsing usage but frequently, I'm not doing anything to complicated and would simply like to translate the XML file into a more "Pythonic" structure. What's the best way to do this? Something from the standard libraries would be preferable. Jeff From kent37 at tds.net Fri May 6 04:50:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 05 May 2005 22:50:06 -0400 Subject: [Tutor] XML to Python In-Reply-To: References: Message-ID: <427ADB5E.80806@tds.net> Smith, Jeff wrote: > I'm able to use the built in XML parser to effect "normal" XML parsing usage but frequently, I'm not doing anything to complicated and would simply like to translate the XML file into a more "Pythonic" structure. What's the best way to do this? Something from the standard libraries would be preferable. I don't think there is anything in the std lib for this. I like ElementTree a lot for XML parsing. It is easy to use for simple tasks; for more complicated stuff I find I often have to add a little glue code to it but that is not hard either. http://effbot.org/zone/element.htm This article is a survey of Python XML tool. Look at the Data Bindings and Specialized APIs section for more suggestions: http://www.xml.com/pub/a/2004/10/13/py-xml.html Kent From alan.gauld at freenet.co.uk Fri May 6 08:49:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 6 May 2005 07:49:34 +0100 Subject: [Tutor] python challenges References: <8daabe560505051710268fabd3@mail.gmail.com> Message-ID: <006b01c55207$c3dce6d0$e54b8651@xp> > Anyone have a gentle hint, or pointer to another 'beginner' tutorial > to regular expressions? You can try the regex page in my tutorial - under advanced topics. Its not as in-depth as the how-to but it should get you to the point where the how-to makes sense... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kraus at hagen-partner.de Fri May 6 09:02:30 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 06 May 2005 09:02:30 +0200 Subject: [Tutor] Text Directly to Screen? In-Reply-To: <2c2812b6050503121256d20423@mail.gmail.com> References: <2c2812b6050503121256d20423@mail.gmail.com> Message-ID: Aaron Elbaz wrote: > Hi, > > My question has to do with outputting text. > > Normally, you ouput to a console or a gui...but for my task, a hack > might be needed.. > > What I want to do is output text *directly* to the screen. And if > possible, restrict the window area to specific dimensions (top right > in mind). It should basically be like a layer of Cellophane over all > other windows, so that users can't interact, they only 'see' the > output of the chat session, and this chat session would be visible > over all windows, including the native OS gui. > > It sounds awfully cool, but awfully complicated too. I'm not sure > where to start looking.. > > Any ideas? > > -thanks I don't think that there is a OS independent solution for this problem, but if you are using KDE under Linux you can try superkaramba (http://netdragon.sourceforge.net/ssuperkaramba.html). There is a similar package for gnome, too, google is your friend. HTH, Wolfram From polatel at gmail.com Fri May 6 12:47:09 2005 From: polatel at gmail.com (Ali Polatel) Date: Fri, 6 May 2005 13:47:09 +0300 Subject: [Tutor] Smtp Message-ID: <3c51d5180505060347443d6a81@mail.gmail.com> Dear Friends, I tried to use the mailserver script in library reference to send mails but it gives an error:The script and the error are below.Why does it give this error?How can i fix? import smtplib def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print "Enter message, end with ^D (Unix) or ^Z (Windows):" # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " + repr(len(msg)) server = smtplib.SMTP('localhost') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() ERROR: Traceback (most recent call last): File "D:\Python23\mailserver.py", line 26, in -toplevel- server.sendmail(fromaddr, toaddrs, msg) File "d:/python23\Lib\smtplib.py", line 676, in sendmail raise SMTPSenderRefused(code, resp, from_addr) SMTPSenderRefused: (550, 'Cannot connect to SMTP server localhost (127.0.0.1:25), self connecting', 'polatel at gmail.com) From rmkrauter at yahoo.com Fri May 6 14:07:13 2005 From: rmkrauter at yahoo.com (Rich Krauter) Date: Fri, 06 May 2005 08:07:13 -0400 Subject: [Tutor] Class and Scope Question In-Reply-To: <20050506014413.GH1808@johnsons-web.com> References: <20050506014413.GH1808@johnsons-web.com> Message-ID: <427B5DF1.1060704@yahoo.com> Tim Johnson wrote: > The following test script is kind of got me baffled: > #!/usr/local/bin/python > class Eval: > def __getitem__(self,key): > return eval(key) > ##def test(): > ## i = 100 > ## b = ["My", "name", "is", "Tim"] > ## test = "this is number %(str(i))s for a test %(' '.join(b))s" > ## s = test % Eval() > ## print s > ##test() > i = 100 > b = ["My", "name", "is", "Tim"] > test = "this is number %(str(i))s for a test %(' '.join(b))s" > print test % Eval() > ## ============================================================ > Running this gives me the following : > [tim at linus baker]$ python test.py > this is number 100 for a test My name is Tim > ## cool! > Now if I comment out the last four lines and uncomment > the previous 7, I get the following error message: > [tim at linus baker]$ python test.py > Traceback (most recent call last): > File "test.py", line 11, in ? > test() > File "test.py", line 9, in test > s = test % Eval() > File "test.py", line 4, in __getitem__ > return eval(key) > File "", line 0, in ? > NameError: name 'i' is not defined > ## It's been a lloooonngg day. What am I missing here? > Explanation and solution is no doubt going to further edify > me about python. > > TIA > tim > Tim, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 has a more general solution in the comments at the bottom. Basically, you need to put an __init__ in the Eval class, pass locals() and globals() to it, and use those passed-in values in your call to the eval() built-in. I believe the result you see is due to python's lexical scoping rules. Scope is determined by a function- or class-definition's position in the text of the program. def f(): x = 20 def g(): print x g() def h(): x = 50 i() def i(): print x if __name__ == '__main__': f() # works h() # doesn't work Here's another example: g = 'module level' class A: def print_locals_and_globals(self): for k,v in locals().items()+globals().items(): print k,v def func(): # a couple names that won't appear # in a's locals or globals i = 10 s = 'a string' a = A() a.print_locals_and_globals() if __name__ == '__main__': func() So it seems the locals and globals visible to an instance of a class is determined by where the class is defined, not by where the instance is created. HTH, Rich From sigurd at 12move.de Fri May 6 14:44:07 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri, 06 May 2005 14:44:07 +0200 Subject: [Tutor] Class and Scope Question In-Reply-To: <20050506014413.GH1808@johnsons-web.com> (Tim Johnson's message of "Thu, 5 May 2005 17:44:13 -0800") References: <20050506014413.GH1808@johnsons-web.com> Message-ID: On 6 Mai 2005, tim at johnsons-web.com wrote: > > The following test script is kind of got me baffled: >#!/usr/local/bin/python > class Eval: > def __getitem__(self,key): > return eval(key) >##def test(): >## i = 100 >## b = ["My", "name", "is", "Tim"] >## test = "this is number %(str(i))s for a test %(' '.join(b))s" >## s = test % Eval() >## print s >##test() > i = 100 > b = ["My", "name", "is", "Tim"] > test = "this is number %(str(i))s for a test %(' '.join(b))s" > print test % Eval() >## ============================================================ > Running this gives me the following : > [tim at linus baker]$ python test.py > this is number 100 for a test My name is Tim >## cool! > Now if I comment out the last four lines and uncomment > the previous 7, I get the following error message: > [tim at linus baker]$ python test.py > Traceback (most recent call last): > File "test.py", line 11, in ? > test() > File "test.py", line 9, in test > s = test % Eval() > File "test.py", line 4, in __getitem__ > return eval(key) > File "", line 0, in ? > NameError: name 'i' is not defined >## It's been a lloooonngg day. What am I missing here? > Explanation and solution is no doubt going to further edify > me about python. If you look in the Python reference manual under 'Execution model -> Naming and binding -> Interaction with dynamic features' you will find the following paragraph: ,---- | The `eval()', `execfile()', and `input()' functions and the `exec' | statement do not have access to the full environment for resolving | names. Names may be resolved in the local and global namespaces of the | caller. Free variables are not resolved in the nearest enclosing | namespace, but in the global namespace.(1) The `exec' statement and the | `eval()' and `execfile()' functions have optional arguments to override | the global and local namespace. If only one namespace is specified, it | is used for both. | | ---------- Footnotes ---------- | | (1) This limitation occurs because the code that is executed by these | operations is not available at the time the module is compiled. `---- So you had a free variable `i' which was in your first example found in the global namespace but in your second example it existed only in the local namespace. So it wasn't found by `eval'. You could write your class definition so that you call eval with the correct environment. E.g. : class Eval (object): def __init__(self, Globals = globals(), Locals = locals()): self.Globals = Globals self.Locals = Locals def __getitem__(self,key): return eval(key, self.Globals, self.Locals) Then your function definition could become: def test(): i = 100 b = ["My", "name", "is", "Tim"] test = "this is number %(str(i))s for a test %(' '.join(b))s" s = test % Eval(Locals=locals()) print s Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Fri May 6 14:57:05 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri, 06 May 2005 14:57:05 +0200 Subject: [Tutor] Smtp In-Reply-To: <3c51d5180505060347443d6a81@mail.gmail.com> (Ali Polatel's message of "Fri, 6 May 2005 13:47:09 +0300") References: <3c51d5180505060347443d6a81@mail.gmail.com> Message-ID: On 6 Mai 2005, polatel at gmail.com wrote: > I tried to use the mailserver script in library reference to send > mails but it gives an error:The script and the error are below.Why > does it give this error?How can i fix? [...] > ERROR: > > Traceback (most recent call last): > File "D:\Python23\mailserver.py", line 26, in -toplevel- > server.sendmail(fromaddr, toaddrs, msg) > File "d:/python23\Lib\smtplib.py", line 676, in sendmail > raise SMTPSenderRefused(code, resp, from_addr) > SMTPSenderRefused: (550, 'Cannot connect to SMTP server localhost > (127.0.0.1:25), self connecting', 'polatel at gmail.com) This is an error from your smtp server; perhaps you have to log in first. Perhaps the server is bound to another IP and accepts only connections from that IP. Perhaps you use some kind of filter (e.g. firewall). That doesn't seem to be a problem of Python. Can you connect with telnet to your smtp server? Does its log file help? Karl -- Please do *not* send copies of replies to me. I read the list From smichr at bigfoot.com Fri May 6 15:43:59 2005 From: smichr at bigfoot.com (Chris Smith) Date: Fri, 6 May 2005 08:43:59 -0500 Subject: [Tutor] Python challenges In-Reply-To: Message-ID: On Thursday, May 5, 2005, at 19:33 America/Chicago, tutor-request at python.org wrote: > Anyone have a gentle hint, or pointer to another 'beginner' tutorial > to regular expressions? > > Thanks! I dont want to get stuck here in the riddles! > How about counting how many times each character is used and look for the ones that are used infrequently (like only once). Dictionaries can do this. /c From smichr at bigfoot.com Fri May 6 15:46:44 2005 From: smichr at bigfoot.com (Chris Smith) Date: Fri, 6 May 2005 08:46:44 -0500 Subject: [Tutor] Python challenges Message-ID: <48C5465C-BE35-11D9-A49C-000393C0D100@bigfoot.com> > >> Anyone have a gentle hint, or pointer to another 'beginner' tutorial >> to regular expressions? >> >> Thanks! I dont want to get stuck here in the riddles! >> > > How about counting how many times each character is used and look for > the ones that are used infrequently (like only once). Dictionaries can > do this. > Oops! Please disregard this irrelevant advice. wishin-for-an-unsend, /c From sunyong.jin at gmail.com Fri May 6 19:37:38 2005 From: sunyong.jin at gmail.com (Evi Wyns) Date: Fri, 6 May 2005 19:37:38 +0200 Subject: [Tutor] Basics Message-ID: I am studying the basics for programming in Python at the moment. I have been studying Python in that past too because I heard the language is really flexible and a great use for scripting too. I am working on OS's like Windows XP and Unix Open BSD at the moment and am trying to figure out what the python language would be really inreresting to implement into. I am studying VBA at the moment in school and will study Java and C#, C++ soon too. I would like to learn how to implement the code into other programming languages. I know this is probably too soon still. I am busy with classes at the moment and I am having a difficult time understanding the use of classes... do you have a good tutorial or good explanation for me how to understand classes more better? Greetings, Evi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050506/c4f89f11/attachment.html From tim at johnsons-web.com Fri May 6 21:13:00 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 6 May 2005 11:13:00 -0800 Subject: [Tutor] Class and Scope Question In-Reply-To: References: <20050506014413.GH1808@johnsons-web.com> Message-ID: <20050506191259.GB2180@johnsons-web.com> * Karl Pfl?sterer [050506 10:40]: > Karl > -- > Please do *not* send copies of replies to me. > I read the list My Thanks to both Karl and Rich for help me to understand this problem. I also appreciate the documentation reference. cheers tim -- Tim Johnson http://www.alaska-internet-solutions.com From alan.gauld at freenet.co.uk Fri May 6 21:15:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 6 May 2005 20:15:37 +0100 Subject: [Tutor] Text Directly to Screen? References: <2c2812b6050503121256d20423@mail.gmail.com> Message-ID: <00bd01c5526f$fcc45560$e54b8651@xp> > > What I want to do is output text *directly* to the screen. On Unix it is very platform specific. On a PC (including Linux) you could do it from assembler by writing direct to the screen memory map via the BIOS but that would probably break all the other stuff since the OS does a pile of mapping from the original memory area to the graphics card and in Windows it writes direct to the graphics card, so the direct memory writes may not even work at all! In fact in NT/W2K/XP I suspect they wouldn't. If you want to get really technical and low level in X Windows you could define a transparent window with no decorations that filled the screen. Writing to that would have the desired effect. A similar technique may be possible in Win32 but I have no idea how to do it, never had to get that far down into the API. In either case it will require a lot of code to manage the window securely and allow it to operate without messing up the others underneath. - You would have to map all mouse movements and focus keystrokes to pass them to the underlying windows. If anyone knows of an easier route I'll be interested to see it. Alan G. From denise.hartley at gmail.com Fri May 6 21:56:04 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 6 May 2005 12:56:04 -0700 Subject: [Tutor] function runs w/o error but produces no output (?) - possible spoiler Message-ID: <8daabe560505061256a31cb54@mail.gmail.com> Hey guys, I wrote the following function, and if I do it line-by-line in the interpreter, each line works exactly as it should. However, when I run the function by its name, nothing happens. It doesnt print the print statement, it doesnt give me an error, it just goes to the next >>> line. This is probably an easy fix, but I traced through it about twelve times and can't figure out why it's not doing what it should. The pdb debugger didnt give me anything I could actually read. Any ideas? def urlsearch(): x = 12345 count = 0 # pdb.set_trace() while count > 10: param = urllib.urlencode({'nothing': x}) f = urllib.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?%s" % param) text = f.read() print text lister = string.split(text) x = lister[-1] count = count + 1 Thanks :) ~Denise From denise.hartley at gmail.com Fri May 6 21:59:43 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 6 May 2005 12:59:43 -0700 Subject: [Tutor] please disregard last mssg @ function problem Message-ID: <8daabe5605050612591c42c1c3@mail.gmail.com> Did you ever send an email, and then as soon as you sent it, realize that you are in fact a colossal idiot and you already know the answer? Yes, I saw my typo. Heh. Nevermind...! *sweeps that email under the rug, hopefully unread* ~Denise From dyoo at hkn.eecs.berkeley.edu Fri May 6 22:01:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 6 May 2005 13:01:28 -0700 (PDT) Subject: [Tutor] python challenges In-Reply-To: <6B017C69-29D3-43DD-94AF-7328D92BD67E@yahoo.fr> Message-ID: > > Anyone have a gentle hint, or pointer to another 'beginner' tutorial > > to regular expressions? > > > > Thanks! I dont want to get stuck here in the riddles! Yeah, there is also a great regular expression HOWTO here: http://www.amk.ca/python/howto/regex/ Best of wishes! From dyoo at hkn.eecs.berkeley.edu Fri May 6 22:05:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 6 May 2005 13:05:20 -0700 (PDT) Subject: [Tutor] Basics In-Reply-To: Message-ID: On Fri, 6 May 2005, Evi Wyns wrote: > I know this is probably too soon still. I am busy with classes at the > moment and I am having a difficult time understanding the use of > classes... do you have a good tutorial or good explanation for me how to > understand classes more better? Hi Evi, You may find Alan's tutorial useful: http://www.freenetpages.co.uk/hp/alan.gauld/ especially because it does show how the concepts of OOP apply in several different languages; with your background, I think this will be valuable. If you have any questions, please feel free to ask. From albertito_g at hotmail.com Fri May 6 22:06:56 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 06 May 2005 20:06:56 +0000 Subject: [Tutor] python challenges In-Reply-To: Message-ID: Hey I'm stucked in number 5 It says pronounce it and there is nothing else not in page nor in the source code What can I do?? I know someone is at 7 now What's this riddler about??? regards Alberto >From: Danny Yoo >To: Max Noel >CC: Python tutor >Subject: Re: [Tutor] python challenges >Date: Fri, 6 May 2005 13:01:28 -0700 (PDT) > > > > > > Anyone have a gentle hint, or pointer to another 'beginner' tutorial > > > to regular expressions? > > > > > > Thanks! I dont want to get stuck here in the riddles! > > >Yeah, there is also a great regular expression HOWTO here: > > http://www.amk.ca/python/howto/regex/ > >Best of wishes! > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From maxnoel_fr at yahoo.fr Fri May 6 22:28:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 21:28:51 +0100 Subject: [Tutor] python challenges In-Reply-To: References: Message-ID: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> On May 6, 2005, at 21:06, Alberto Troiano wrote: > Hey > > I'm stucked in number 5 > It says pronounce it and there is nothing else not in page nor in > the source > code > What can I do?? Well... Go ahead and pronounce it (the title of the page, that is)... Sounds awfully close to a certain Python module, doesn't it? > I know someone is at 7 now > What's this riddler about??? In fact, I am (and will probably give up) at number 9. I was able to do #7 without using PIL, but it seems that it is once again necessary for #9, and I'm not gonna be able to use a workaround this time. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From marilyn at deliberate.com Fri May 6 22:26:28 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri, 6 May 2005 13:26:28 -0700 (PDT) Subject: [Tutor] function runs w/o error but produces no output (?) - possible spoiler In-Reply-To: <8daabe560505061256a31cb54@mail.gmail.com> Message-ID: On Fri, 6 May 2005, D. Hartley wrote: > Hey guys, > > I wrote the following function, and if I do it line-by-line in the > interpreter, each line works exactly as it should. However, when I > run the function by its name, nothing happens. It doesnt print the > print statement, it doesnt give me an error, it just goes to the next > >>> line. This is probably an easy fix, but I traced through it about > twelve times and can't figure out why it's not doing what it should. > The pdb debugger didnt give me anything I could actually read. > > Any ideas? > > def urlsearch(): > x = 12345 > count = 0 > # pdb.set_trace() > while count > 10: If count is set to 0 above, then this will never happen because 0 is not > 10. > param = urllib.urlencode({'nothing': x}) > f = urllib.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?%s" > % param) > text = f.read() > print text > lister = string.split(text) > x = lister[-1] > count = count + 1 > > Thanks :) > ~Denise > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- From denise.hartley at gmail.com Fri May 6 22:40:29 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 6 May 2005 13:40:29 -0700 Subject: [Tutor] python challenges In-Reply-To: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> Message-ID: <8daabe5605050613407825f0ce@mail.gmail.com> I figured out what module you're supposed to use for 5, and the thing that kills me is it's a module I've actually *used* too! But I don't know what to ..... man this is hard to say without using a spoiler. I dont know what particular thing to apply it to (and i tried to read it from the source code - i thought it might have something to do with - but when i tried to apply the module to something in that mess the only way i know how, it couldnt handle it). any hints on where to apply this thing? On 5/6/05, Max Noel wrote: > > On May 6, 2005, at 21:06, Alberto Troiano wrote: > > > Hey > > > > I'm stucked in number 5 > > It says pronounce it and there is nothing else not in page nor in > > the source > > code > > What can I do?? > > Well... Go ahead and pronounce it (the title of the page, that > is)... Sounds awfully close to a certain Python module, doesn't it? > > > I know someone is at 7 now > > What's this riddler about??? > > In fact, I am (and will probably give up) at number 9. I was > able to do #7 without using PIL, but it seems that it is once again > necessary for #9, and I'm not gonna be able to use a workaround this > time. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri May 6 22:54:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 6 May 2005 13:54:17 -0700 (PDT) Subject: [Tutor] Importing C,C++,Asm modules In-Reply-To: <3c51d518050504013956a163b4@mail.gmail.com> Message-ID: On Wed, 4 May 2005, Ali Polatel wrote: > Dear friends, > Is there a way to import C,C++ or Asm modules to python scripts? > If yes how? Hi Ali, Python can be "extended" to use external libraries, as long as we can call them from C. There's a tutorial for C programmers here: http://docs.python.org/ext/ext.html There are several projects out there to make the process less painful. One of these is SWIG: http://www.swig.org and there are several other packages out there, including the PyRex project: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ In short, if you can do a C function call, you can integrate it with Python, and it might not even be too bad. If you have a particular example in C, I'm sure that one of us here would be happy to demonstrate how to expose that function in Python. Good luck! From tim.peters at gmail.com Fri May 6 22:57:44 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 6 May 2005 16:57:44 -0400 Subject: [Tutor] python challenges In-Reply-To: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> Message-ID: <1f7befae05050613571cc8b6ee@mail.gmail.com> [Max Noel] ... > In fact, I am (and will probably give up) at number 9. I was > able to do #7 without using PIL, but it seems that it is once again > necessary for #9, and I'm not gonna be able to use a workaround this > time. What do you have against PIL ? Processing images has played no part in my life (neither professional nor personal), and solving level 7 was the first time I ever tried using PIL. It's been a lot of fun! Really. PIL proved very useful for several levels (there are 16 now, BTW), and learning to use PIL in simple ways has been part of the fun for me. I don't know how you solved level 7, but it's just a few lines of Python code using PIL once you know what you're after. Some later levels involve trickier transformations, but they remain easy to program using just the simplest Image methods. From maxnoel_fr at yahoo.fr Fri May 6 23:16:50 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 22:16:50 +0100 Subject: [Tutor] python challenges In-Reply-To: <8daabe5605050613407825f0ce@mail.gmail.com> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> <8daabe5605050613407825f0ce@mail.gmail.com> Message-ID: On May 6, 2005, at 21:40, D. Hartley wrote: > I figured out what module you're supposed to use for 5, and the thing > that kills me is it's a module I've actually *used* too! But I don't > know what to ..... man this is hard to say without using a spoiler. I > dont know what particular thing to apply it to (and i tried to read it > from the source code - i thought it might have something to do with > - but when > i tried to apply the module to something in that mess the only way i > know how, it couldnt handle it). > > any hints on where to apply this thing? It's elsewhere in the page's source code... Look carefully. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri May 6 23:19:16 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 22:19:16 +0100 Subject: [Tutor] python challenges In-Reply-To: <1f7befae05050613571cc8b6ee@mail.gmail.com> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> <1f7befae05050613571cc8b6ee@mail.gmail.com> Message-ID: On May 6, 2005, at 21:57, Tim Peters wrote: > What do you have against PIL ? Nothing in particular, just no idea how to use it. > simple ways has been part of the fun for me. I don't know how you > solved level 7, Hint: it's a stupid and inelegant method involving a certain program by Adobe and lots of mouse clicks. Yes, you can laugh at me now. > but it's just a few lines of Python code using PIL > once you know what you're after. Could you send me the code you used? (off-list, we don't want any spoilers here, do we?) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Fri May 6 23:20:37 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 6 May 2005 14:20:37 -0700 Subject: [Tutor] python challenges In-Reply-To: References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> <8daabe5605050613407825f0ce@mail.gmail.com> Message-ID: <8daabe5605050614201f571a69@mail.gmail.com> Yes, I realized my original guess was wrong. I think I found the target file but now none of the module commands I'm used to will do anything useful on it. I'm just getting "file not found" errors and the like. There's something in the big picture that I'm not getting here, I think. All I know is this is about an hour of solid frustration and I'm going to have to get one of those stress-ball things! On 5/6/05, Max Noel wrote: > > On May 6, 2005, at 21:40, D. Hartley wrote: > > > I figured out what module you're supposed to use for 5, and the thing > > that kills me is it's a module I've actually *used* too! But I don't > > know what to ..... man this is hard to say without using a spoiler. I > > dont know what particular thing to apply it to (and i tried to read it > > from the source code - i thought it might have something to do with > > - but when > > i tried to apply the module to something in that mess the only way i > > know how, it couldnt handle it). > > > > any hints on where to apply this thing? > > It's elsewhere in the page's source code... Look carefully. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From maxnoel_fr at yahoo.fr Fri May 6 23:27:20 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 22:27:20 +0100 Subject: [Tutor] python challenges In-Reply-To: <8daabe5605050614201f571a69@mail.gmail.com> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> <8daabe5605050613407825f0ce@mail.gmail.com> <8daabe5605050614201f571a69@mail.gmail.com> Message-ID: <3AE1B734-76EF-48EC-BEEA-A33206C9FE7E@yahoo.fr> On May 6, 2005, at 22:20, D. Hartley wrote: > Yes, I realized my original guess was wrong. I think I found the > target file but now none of the module commands I'm used to will do > anything useful on it. I'm just getting "file not found" errors and > the like. There's something in the big picture that I'm not getting > here, I think. If you've found the target file, saved it to your hard disk, used the module on it and it says "file not found", I suspect there's something wrong with your computer. If it was the wrong file it'd give you another error. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Fri May 6 23:32:47 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 6 May 2005 14:32:47 -0700 Subject: [Tutor] python challenges In-Reply-To: <3AE1B734-76EF-48EC-BEEA-A33206C9FE7E@yahoo.fr> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> <8daabe5605050613407825f0ce@mail.gmail.com> <8daabe5605050614201f571a69@mail.gmail.com> <3AE1B734-76EF-48EC-BEEA-A33206C9FE7E@yahoo.fr> Message-ID: <8daabe560505061432308d6e23@mail.gmail.com> Maybe that's my problem. I dont know how to save this particular file onto my computer first. I can't.... 'reach' it from the url. It's not like a picture I can right click on and save image, or something. My first thought was i needed to use the module to do that. but apparently i need to use the module AFTER i get the file onto my hard disk? sorry to be so dense, i just dont get it. On 5/6/05, Max Noel wrote: > > On May 6, 2005, at 22:20, D. Hartley wrote: > > > Yes, I realized my original guess was wrong. I think I found the > > target file but now none of the module commands I'm used to will do > > anything useful on it. I'm just getting "file not found" errors and > > the like. There's something in the big picture that I'm not getting > > here, I think. > > If you've found the target file, saved it to your hard disk, > used the module on it and it says "file not found", I suspect there's > something wrong with your computer. If it was the wrong file it'd > give you another error. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From maxnoel_fr at yahoo.fr Fri May 6 23:34:57 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 6 May 2005 22:34:57 +0100 Subject: [Tutor] python challenges In-Reply-To: <8daabe560505061432308d6e23@mail.gmail.com> References: <3987C6B5-3808-4612-9FF0-86E675C191BC@yahoo.fr> <8daabe5605050613407825f0ce@mail.gmail.com> <8daabe5605050614201f571a69@mail.gmail.com> <3AE1B734-76EF-48EC-BEEA-A33206C9FE7E@yahoo.fr> <8daabe560505061432308d6e23@mail.gmail.com> Message-ID: On May 6, 2005, at 22:32, D. Hartley wrote: > Maybe that's my problem. I dont know how to save this particular file > onto my computer first. I can't.... 'reach' it from the url. It's not > like a picture I can right click on and save image, or something. My > first thought was i needed to use the module to do that. but > apparently i need to use the module AFTER i get the file onto my hard > disk? sorry to be so dense, i just dont get it. > Just enter the file's URL into your browser's address bar. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From carroll at tjc.com Sat May 7 01:11:29 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 6 May 2005 16:11:29 -0700 (PDT) Subject: [Tutor] XML to Python In-Reply-To: Message-ID: On Thu, 5 May 2005, Smith, Jeff wrote: > I'm able to use the built in XML parser to effect "normal" XML parsing > usage but frequently, I'm not doing anything to complicated and would > simply like to translate the XML file into a more "Pythonic" structure. > What's the best way to do this? Something from the standard libraries > would be preferable. I've made a mental note to try Amara next time I attack an XML problem. The description of Amara's Bindery sounds like it tries to take that "'Pythonic' structure" approach you refer to: Amara XML Toolkit [is] a collection of Pythonic tools for XML data binding. Not just tools that happen to be written in Python, but tools built from the ground up to use Python idioms and take advantage of the many advantages of Python over other programming languages.... Bindery: a data binding tool (fancy way of saying it's a very Pythonic XML API) http://uche.ogbuji.net/uche.ogbuji.net/tech/4Suite/amara/ Mind you, I haven't tried Amara yet, but it looks worth looking into. From andre.roberge at gmail.com Sat May 7 01:28:39 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri, 06 May 2005 20:28:39 -0300 Subject: [Tutor] ANN: version 0.8 of RUR-PLE Message-ID: For those interested in a different approach for learning to program using Python, I would be interested in your thoughts about RUR-PLE. The latest version (0.8) is available on sourceforge: https://sourceforge.net/project/showfiles.php?group_id=125834 Note that the home page for the project is hopelessly out of date. RUR-PLE has evolved greatly since. I really should do something about it... :-( RUR-PLE requires wxPython. The download is fairly large, due to the many graphical elements included in the lessons. Even if you can't afford to spend much time with it, I would *really* welcome the feedback of at least some of the many experienced tutors on this list. Even if you just had a look at it for 5 minutes (after the download!) I have much to thank you for already, as I feel I have learnt *lots* from reading messages on this list ============== (one of my first post here: http://mail.python.org/pipermail/tutor/2004-September/031884.html ... After many years of doing other stuff, I'm starting to program again, just for the fun of it (and to teach my kids), learning Python along the way. ... ============== Thanks in advance to any or all that show some interest and give me some feedback. Andr? From gsf at panix.com Sat May 7 01:35:01 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri, 6 May 2005 19:35:01 -0400 Subject: [Tutor] XML to Python In-Reply-To: References: Message-ID: <20050506233501.GB29536@panix.com> On Thu, 5 May 2005, Smith, Jeff wrote: > I'm able to use the built in XML parser to effect "normal" XML parsing > usage but frequently, I'm not doing anything to complicated and would > simply like to translate the XML file into a more "Pythonic" structure. > What's the best way to do this? Something from the standard libraries > would be preferable. I just went through the same process of trying to find a quick and easy way to parse XML in Python, and ended up choosing ElementTree. Out of everything I tried (including Amara and minidom), ElementTree seemed to be the one that made the most intuitive sense. The only downside is that I don't like the way ElementTree handles namespaces. My quick and dirty solution was to strip the default namespace out with re before parsing the file with ElementTree, then put it back in again after the altered document was written out. I would rather the default namespace be ignored than an ns0 or ns1 added in front of every element. gabe From max_russell2000 at yahoo.co.uk Sat May 7 10:46:46 2005 From: max_russell2000 at yahoo.co.uk (Max Russell) Date: Sat, 7 May 2005 09:46:46 +0100 (BST) Subject: [Tutor] elegant way to turn list into string? Message-ID: <20050507084646.90276.qmail@web25402.mail.ukl.yahoo.com> Hello- I've started writing a suite of tools to help me do Crypto puzzles (slowly...) My first snippet of code allos me to print out a Caesar shifting alphabet, as I tend to write them out by hand; which is a waste of time. alph = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] print "\n" print alph print "\n" x = 1 while x < 26: alph.append(alph.pop(0)) print alph print "\n" x += 1 anyway- I don't like the output which come in the form: ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a'] What I'd like to do is take my list and turn it into a string, which looks neater when printed. I've tried using join() but that didn't work, can anyone give me a pointer here? the other method I've used was dealing with a string directly: alph = 'abcdefghijklmnopqrstuvwxyz' print alph #print "\n" x = 1 while x < 26: new_alph = alph[1:] + alph[:1] print new_alph print "\n" x += 1 But this has the drawback of not progressing with my newly create alphabet, it just returns: abcdefghijklmnopqrstuvwxyz bcdefghijklmnopqrstuvwxyza bcdefghijklmnopqrstuvwxyza etc... HELP!! thanks Max ___________________________________________________________ Yahoo! Messenger - want a free and easy way to contact your friends online? http://uk.messenger.yahoo.com From tanja.pislar at gmail.com Sat May 7 10:52:26 2005 From: tanja.pislar at gmail.com (tanja pislar) Date: Sat, 7 May 2005 10:52:26 +0200 Subject: [Tutor] elegant way to turn list into string? In-Reply-To: <20050507084646.90276.qmail@web25402.mail.ukl.yahoo.com> References: <20050507084646.90276.qmail@web25402.mail.ukl.yahoo.com> Message-ID: hi Max, you can use: alph = ["a","b", ....] myString = "".join(alph) print myString regards, tanja On 5/7/05, Max Russell wrote: > Hello- > > I've started writing a suite of tools to help me do > Crypto puzzles (slowly...) My first snippet of code > allos me to print out a Caesar shifting alphabet, as I > tend to write them out by hand; which is a waste of > time. > > alph = > ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] > print "\n" > print alph > print "\n" > x = 1 > while x < 26: > alph.append(alph.pop(0)) > print alph > print "\n" > x += 1 > > anyway- I don't like the output which come in the > form: > ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', > 'w', 'x', 'y', 'z', 'a'] > > What I'd like to do is take my list and turn it into a > string, which looks neater when printed. > > I've tried using join() but that didn't work, can > anyone give me a pointer here? > > the other method I've used was dealing with a string > directly: > alph = 'abcdefghijklmnopqrstuvwxyz' > print alph > #print "\n" > > x = 1 > > while x < 26: > new_alph = alph[1:] + alph[:1] > print new_alph > print "\n" > x += 1 > > But this has the drawback of not progressing with my > newly create alphabet, it just returns: > abcdefghijklmnopqrstuvwxyz > bcdefghijklmnopqrstuvwxyza > > bcdefghijklmnopqrstuvwxyza > > etc... > > HELP!! > > thanks > Max > > > ___________________________________________________________ > Yahoo! Messenger - want a free and easy way to contact your friends online? http://uk.messenger.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- www.klaustrofobik.org From jfouhy at paradise.net.nz Sat May 7 12:31:07 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Sat, 07 May 2005 22:31:07 +1200 (NZST) Subject: [Tutor] elegant way to turn list into string? In-Reply-To: <20050507084646.90276.qmail@web25402.mail.ukl.yahoo.com> References: <20050507084646.90276.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <1115461867.427c98eb7cbd8@www.paradise.net.nz> Quoting Max Russell : > anyway- I don't like the output which come in the > form: > ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', > 'w', 'x', 'y', 'z', 'a'] > > > What I'd like to do is take my list and turn it into a > string, which looks neater when printed. > > I've tried using join() but that didn't work, can > anyone give me a pointer here? As Tanja points out, you can use ''.join(). You may also be interested in the chr() and ord() built-in functions. eg: >>> alphabet = [chr(i) for i in range(ord('a'), ord('z')+1)] >>> alphabet ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] See also this.py in your lib directory :-) -- John. From alan.gauld at freenet.co.uk Sat May 7 13:00:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 7 May 2005 12:00:57 +0100 Subject: [Tutor] elegant way to turn list into string? References: <20050507084646.90276.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <012301c552f4$0c4e67d0$e54b8651@xp> > alph = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q"," r","s","t","u","v","w","x","y","z"] import string alph = string.lowercase > print "\n" > print alph > print "\n" print '\n%s\n' % alph > x = 1 > while x < 26: for letter in alph: > alph.append(alph.pop(0)) > print alph > print "\n" Or: first = alph[0] alph = alph[1:] + first Or more generically: def rotate(seq, n): first = seq[:n] return seq{n:] + first result = rotate(string.lowercase, 1) > anyway- I don't like the output which come in the > form: > ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', > 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', > 'w', 'x', 'y', 'z', 'a'] > > > What I'd like to do is take my list and turn it into a > string, which looks neater when printed. Or start with a string in the first place? But if you must use a list then ''.join(alph) should work. > I've tried using join() but that didn't work, can > anyone give me a pointer here? What happened? Did you remember to use the empty string as the joining string? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From clajo04 at mac.com Sat May 7 13:28:34 2005 From: clajo04 at mac.com (John Clark) Date: Sat, 07 May 2005 07:28:34 -0400 Subject: [Tutor] Generator function question? Message-ID: Hello, I am working on learning Python and writing some console applications to apply what I am learning - I am using a generator function to implement a status indicator as follows: import sys def neverEndingStatus(currentChar_ = '|'): while 1: if currentChar_ == '|': currentChar_ = '\\' elif currentChar_ == '\\': currentChar_ = '-' elif currentChar_ == '-': currentChar_ = '/' elif currentChar_ == '/': currentChar_ = '|' yield currentChar_ x = neverEndingStatus() def Test1(): for w in range(1, 100): sys.stderr.write('\b'+x.next()) for z in range(1, 10000): z = z + 1 def Test2(): for y in range(1, 10): sys.stderr.write('\b \nTesting'+str(y)+'\t') Test1() Test2() My question - the creation of the global variable x seems kludged - when I first started with this I thought I was going to be coding something like sys.stderr.write('\b'+neverEndingStatus()) but that just returns '\' each time and I now recognize why. I am just thinking there has to be a way to encapsulate the generator function, the global variable and the .next() call so that it is much cleaner in the client code. My guess is that I could create a class, override the __call__ method and get to the point where my code is something like: sys.stderr.write('\b'+statusClass()) but that seems to be heavy (implementing a class) and intrusive (overriding the __call__ method seems a bit heavy handed) - my reluctance may be just because I am less familiar with those particular constructs in Python, but it still feels like I should be able to do this more cleanly without that. Also - I look at the code in the neverEndingStatus() function and I just _know_ there has to be a better way to write that - it's just not coming to me. Any suggestions are embarrassingly appreciated... Thanks, -jdc From maxnoel_fr at yahoo.fr Sat May 7 14:00:03 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 7 May 2005 13:00:03 +0100 Subject: [Tutor] Generator function question? In-Reply-To: References: Message-ID: <9419E6A6-F476-4B78-8393-72AAB33D790F@yahoo.fr> On May 7, 2005, at 12:28, John Clark wrote: > My question - the creation of the global variable x seems kludged - > when I > first started with this I thought I was going to be coding > something like > sys.stderr.write('\b'+neverEndingStatus()) but that just returns > '\' each > time and I now recognize why. I am just thinking there has to be a > way to > encapsulate the generator function, the global variable and > the .next() call > so that it is much cleaner in the client code. > > My guess is that I could create a class, override the __call__ > method and > get to the point where my code is something like: > sys.stderr.write('\b'+statusClass()) but that seems to be heavy > (implementing a class) and intrusive (overriding the __call__ > method seems a > bit heavy handed) - my reluctance may be just because I am less > familiar > with those particular constructs in Python, but it still feels like > I should > be able to do this more cleanly without that. > > Also - I look at the code in the neverEndingStatus() function and I > just > _know_ there has to be a better way to write that - it's just not > coming to > me. Any suggestions are embarrassingly appreciated... > > Thanks, > -jdc > This is (IMO) more elegant: def neverEndingStatus(): index = 0 statusChars = ['|', '\\', '-', '/'] while True: yield statusChars[index] index = (index + 1) % 4 As for how to access it, use a for loop (for i in neverEndingStatus()). xrange, for example, is a generator function. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From clajo04 at mac.com Sat May 7 14:12:40 2005 From: clajo04 at mac.com (John Clark) Date: Sat, 07 May 2005 08:12:40 -0400 Subject: [Tutor] Generator function question? In-Reply-To: <9419E6A6-F476-4B78-8393-72AAB33D790F@yahoo.fr> Message-ID: Lightbulb! It's clear that I don't yet fully understand the power of generator functions... It never occurred to me to yield out of the middle of a loop, and yet, seeing your code, it's obvious that that's one of the primary purposes of "yield". Thanks, -jdc On 5/7/05 8:00 AM, "Max Noel" wrote: > > This is (IMO) more elegant: > > def neverEndingStatus(): > index = 0 > statusChars = ['|', '\\', '-', '/'] > while True: > yield statusChars[index] > index = (index + 1) % 4 > > > As for how to access it, use a for loop (for i in > neverEndingStatus()). xrange, for example, is a generator function. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > From jeannot18 at hotmail.com Sat May 7 14:17:05 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Sat, 07 May 2005 12:17:05 +0000 Subject: [Tutor] python challenges In-Reply-To: <1f7befae05050613571cc8b6ee@mail.gmail.com> Message-ID: Hi to everybody reading this thread, can anybody point me to the URL where I can find these challenges. Many thanks JC From jfouhy at paradise.net.nz Sat May 7 14:17:22 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Sun, 08 May 2005 00:17:22 +1200 (NZST) Subject: [Tutor] Generator function question? In-Reply-To: References: Message-ID: <1115468242.427cb1d20ec94@www.paradise.net.nz> Quoting John Clark : > import sys > > def neverEndingStatus(currentChar_ = '|'): > while 1: > if currentChar_ == '|': > currentChar_ = '\\' > elif currentChar_ == '\\': > currentChar_ = '-' > elif currentChar_ == '-': > currentChar_ = '/' > elif currentChar_ == '/': > currentChar_ = '|' > yield currentChar_ > > > x = neverEndingStatus() > > def Test1(): > for w in range(1, 100): > sys.stderr.write('\b'+x.next()) > for z in range(1, 10000): > z = z + 1 One of the big uses for generators is in loops. eg: >>> import time >>> def nes(): ... chars = ('|', '\\', '-', '/') ... i = 0 ... while True: ... yield chars[i] ... i = (i + 1) % len(chars) ... >>> for c in nes(): ... print c, ... time.sleep(0.5) ... | \ - / | \ - / | \ - / | \ - / | \ - / | \ ... Of course, you'll need _some_ way of breaking out of the loop eventually (either a 'break' statement in the for loop, or something in nes() to raise StopIteration, which will cause the for loop to exit naturally). -- John. From clajo04 at mac.com Sat May 7 14:22:21 2005 From: clajo04 at mac.com (John Clark) Date: Sat, 07 May 2005 08:22:21 -0400 Subject: [Tutor] Generator function question? In-Reply-To: <9419E6A6-F476-4B78-8393-72AAB33D790F@yahoo.fr> Message-ID: Ooops - sorry - I spoke too soon... It's clear that your code is a more elegant implementation of neverEndingStatus() but I am still having to initialize a global variable and call .next() when I want to get the next value... So the generator function has been cleaned up, but the client code interaction with the function is still pretty much the same. (Either that, or I am not following what you mean when you say: > As for how to access it, use a for loop (for i in > neverEndingStatus()). xrange, for example, is a generator function. Can you please provide an example of how my Test1() function changes based on your suggestion? (sorry to be dense) Thanks, -jdc On 5/7/05 8:00 AM, "Max Noel" wrote: > > This is (IMO) more elegant: > > def neverEndingStatus(): > index = 0 > statusChars = ['|', '\\', '-', '/'] > while True: > yield statusChars[index] > index = (index + 1) % 4 > > > As for how to access it, use a for loop (for i in > neverEndingStatus()). xrange, for example, is a generator function. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > From clajo04 at mac.com Sat May 7 14:52:51 2005 From: clajo04 at mac.com (John Clark) Date: Sat, 07 May 2005 08:52:51 -0400 Subject: [Tutor] Generator function question? In-Reply-To: <9419E6A6-F476-4B78-8393-72AAB33D790F@yahoo.fr> Message-ID: Okay, take two... import sys def neverEndingStatus(): def statusGen(): index = 0 statusChars = ['|', '\\', '-', '/'] while True: yield statusChars[index] index = (index + 1) % 4 try: neverEndingStatus.x except AttributeError: neverEndingStatus.x = statusGen() return neverEndingStatus.x.next() def Test1(): for w in range(1, 100): sys.stderr.write('\b'+neverEndingStatus()) for z in range(1, 10000): z = z + 1 def Test2(): for y in range(1, 10): sys.stderr.write('\b \nTesting'+str(y)+'\t') Test1() Test2() This borrows (read: shamelessly copies) the implementation of the generator function that Max suggested, it removes the global variable, and it removes the need for the client code to call .next() to get the next status character. However, this is my first foray into the world of function attributes and local functions, so this may not be the best way to do this - any suggestions / critiques? Thanks, -jdc On 5/7/05 8:00 AM, "Max Noel" wrote: > > On May 7, 2005, at 12:28, John Clark wrote: > >> My question - the creation of the global variable x seems kludged - >> when I >> first started with this I thought I was going to be coding >> something like >> sys.stderr.write('\b'+neverEndingStatus()) but that just returns >> '\' each >> time and I now recognize why. I am just thinking there has to be a >> way to >> encapsulate the generator function, the global variable and >> the .next() call >> so that it is much cleaner in the client code. >> >> My guess is that I could create a class, override the __call__ >> method and >> get to the point where my code is something like: >> sys.stderr.write('\b'+statusClass()) but that seems to be heavy >> (implementing a class) and intrusive (overriding the __call__ >> method seems a >> bit heavy handed) - my reluctance may be just because I am less >> familiar >> with those particular constructs in Python, but it still feels like >> I should >> be able to do this more cleanly without that. >> >> Also - I look at the code in the neverEndingStatus() function and I >> just >> _know_ there has to be a better way to write that - it's just not >> coming to >> me. Any suggestions are embarrassingly appreciated... >> >> Thanks, >> -jdc >> > > This is (IMO) more elegant: > > def neverEndingStatus(): > index = 0 > statusChars = ['|', '\\', '-', '/'] > while True: > yield statusChars[index] > index = (index + 1) % 4 > > > As for how to access it, use a for loop (for i in > neverEndingStatus()). xrange, for example, is a generator function. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > From Michael.Coll-Barth at VerizonWireless.com Sat May 7 15:56:35 2005 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth@VerizonWireless.com) Date: Sat, 7 May 2005 09:56:35 -0400 Subject: [Tutor] scoping oddity Message-ID: <20050507135637.9D65E1E4003@bag.python.org> Good morning, I came across a rather odd issue with scoping. Can someone explain why testa and testc works, but not testb. I am running under python 2.4.1 on Windows NT. thanks, Michael x = 5 def testa(astr): print astr, x testa(22) def testb(astr): x = x - 1 print astr, x testb(22) def testc(astr): print astr, x-1 testc(22) ___________________________________________________________________ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From sigurd at 12move.de Sat May 7 16:04:44 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sat, 07 May 2005 16:04:44 +0200 Subject: [Tutor] Generator function question? In-Reply-To: (John Clark's message of "Sat, 07 May 2005 08:22:21 -0400") References: Message-ID: On 7 Mai 2005, clajo04 at mac.com wrote: > It's clear that your code is a more elegant implementation of > neverEndingStatus() but I am still having to initialize a global variable > and call .next() when I want to get the next value... So the generator > function has been cleaned up, but the client code interaction with the > function is still pretty much the same. > > (Either that, or I am not following what you mean when you say: > >> As for how to access it, use a for loop (for i in >> neverEndingStatus()). xrange, for example, is a generator function. > > Can you please provide an example of how my Test1() function changes based > on your suggestion? (sorry to be dense) The for loop does all the work for you: generating an iterator from the generator function and calling its `next' method until the iterator is exhausted (raises StopIteration). So you first should write a generator function which produces the values you need (perhaps with some way to stop it after a defined number of characters) and then you u8se a for loop to get the values from the iterator (which is what you get when you call a generator function). So here is an example. First the generator function: def status (chars=r'|\-/', num_of_chars=None): if num_of_chars <= 0: return elif num_of_chars: while True: for c in chars: yield c num_of_chars -= 1 if num_of_chars <= 0: return else: while True: for c in chars: yield c Now to print the characters from the function you could write: for c in status(num_of_chars=10): sys.stdout.write(c) and it would print 10 characters (starting with '|' and ending with '\'. So far so good but that looks a bit ugly. Python has a great library if you want to work with iterators: the itertools. There you find alot of functions which help you to write the above code much shorter and nicer. import itertools as it def status2 (chars=r'|\-/', num_of_chars=None): for c in it.islice(it.cycle(chars), num_of_chars): yield c The best is you look in the documentation of itertools to understand what's happening here, but a short explanation might help. 'itertools.cycle' takes an iterator and if it's exhausted it starts to emit the same values again and again and again ... If you want to stop the ietrator somewhere there are several possibilities but one is to use another function from itertools `itertools.islice'. It works a bit like a normal slice (with which you can take some values from e.g. a list or a string) but generates an iterator. So the above it.islice(it.cycle(chars), num_of_chars) returns an iterator which yields num_of_chars characters from the iterator which was returned from it.cycle(chars) If num_of_chars is None then it yields an unlimited numkber of chars. The above may be a bit to advanced for you if you just start with Python but maybe also not (if you know programming at all). Look in the documentation, try it ot and then ask again. Karl -- Please do *not* send copies of replies to me. I read the list From maxnoel_fr at yahoo.fr Sat May 7 16:06:53 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 7 May 2005 15:06:53 +0100 Subject: [Tutor] Generator function question? In-Reply-To: References: Message-ID: <55508297-D0F5-42E3-8BDA-9DF4644FF0EB@yahoo.fr> On May 7, 2005, at 13:22, John Clark wrote: > (Either that, or I am not following what you mean when you say: > > >> As for how to access it, use a for loop (for i in >> neverEndingStatus()). xrange, for example, is a generator function. >> > > Can you please provide an example of how my Test1() function > changes based > on your suggestion? (sorry to be dense) > Try the following code: for i in neverEndingTest(): print i breaking out of the infinite loop is left to the reader as an exercise ;) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Sat May 7 16:07:17 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 7 May 2005 15:07:17 +0100 Subject: [Tutor] python challenges In-Reply-To: References: Message-ID: On May 7, 2005, at 13:17, John Carmona wrote: > Hi to everybody reading this thread, can anybody point me to the > URL where I can find these challenges. Many thanks > > JC > http://www.pythonchallenge.com/ -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Sat May 7 16:15:36 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 7 May 2005 15:15:36 +0100 Subject: [Tutor] Generator function question? In-Reply-To: <55508297-D0F5-42E3-8BDA-9DF4644FF0EB@yahoo.fr> References: <55508297-D0F5-42E3-8BDA-9DF4644FF0EB@yahoo.fr> Message-ID: <75763C5A-AE38-4E3E-9889-9F2BA84E680E@yahoo.fr> On May 7, 2005, at 15:06, Max Noel wrote: > Try the following code: > > > > for i in neverEndingTest(): > print i > Sorry, i meant "for in in neverEndingStatus()" (not neverEndingTest()), where neverEndingStatus is the function I gave as an example in my previous post (not your modified version). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From tanja.pislar at gmail.com Sat May 7 16:18:42 2005 From: tanja.pislar at gmail.com (tanja pislar) Date: Sat, 7 May 2005 16:18:42 +0200 Subject: [Tutor] scoping oddity In-Reply-To: <20050507135637.9D65E1E4003@bag.python.org> References: <20050507135637.9D65E1E4003@bag.python.org> Message-ID: hi Michael, in Python, names are not declared ahead of time so Python uses the assigment of a name to "bind" it to a particular namespace. you first assigned a "global" x with the value of 5. in your testa and testc functions, you are only using variable x, and because x is already assigned globaly, python sees it and uses it. Meanwhile, in your function testb, you create a local x, assigning to it a value (thus successfuly shadow the global x), but because the assigment itself uses a refference to it, Python complains with a UnboundLocalError: local variable 'x' referenced before assignment. if you want to use the global x in your testb function, you should use the global statement: def testb(astr): global x x = x - 1 print astr, x regards, tanja On 5/7/05, Michael.Coll-Barth at verizonwireless.com wrote: > Good morning, > > I came across a rather odd issue with scoping. Can someone explain why > testa and testc works, but not testb. I am running under python 2.4.1 on > Windows NT. > > thanks, > Michael > > x = 5 > > def testa(astr): > print astr, x > > testa(22) > > def testb(astr): > x = x - 1 > print astr, x > > testb(22) > > def testc(astr): > print astr, x-1 > > testc(22) > ___________________________________________________________________ > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to the intended > recipient, you are hereby notified that any dissemination, > distribution or copying of this communication is strictly prohibited. > If you have received this communication in error, please notify me > immediately by replying to this message and deleting it and all > copies and backups thereof. Thank you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- www.klaustrofobik.org From sigurd at 12move.de Sat May 7 16:25:15 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sat, 07 May 2005 16:25:15 +0200 Subject: [Tutor] scoping oddity In-Reply-To: <20050507135637.9D65E1E4003@bag.python.org> (Michael Coll-Barth's message of "Sat, 7 May 2005 09:56:35 -0400") References: <20050507135637.9D65E1E4003@bag.python.org> Message-ID: On 7 Mai 2005, Michael.Coll-Barth at VerizonWireless.com wrote: > I came across a rather odd issue with scoping. Can someone explain why > testa and testc works, but not testb. I am running under python 2.4.1 on [...] > x = 5 > > def testa(astr): > print astr, x > > testa(22) > > def testb(astr): > x = x - 1 > print astr, x > > testb(22) > > def testc(astr): > print astr, x-1 > > testc(22) In testb you make an assignment to `x'. So `x' is no longer the global `x' but a local `x'. But since is has no local value before the assignment you get an error. You could tell Python to use the global value of `x'. def testb(astr): global x x = x - 1 print astr, x Karl -- Please do *not* send copies of replies to me. I read the list From bvande at po-box.mcgill.ca Sat May 7 16:43:48 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 07 May 2005 10:43:48 -0400 Subject: [Tutor] scoping oddity In-Reply-To: <20050507135637.9D65E1E4003@bag.python.org> References: <20050507135637.9D65E1E4003@bag.python.org> Message-ID: <427CD424.3020007@po-box.mcgill.ca> Michael.Coll-Barth at VerizonWireless.com said unto the world upon 2005-05-07 09:56: > Good morning, > > I came across a rather odd issue with scoping. Can someone explain why > testa and testc works, but not testb. I am running under python 2.4.1 on > Windows NT. > > thanks, > Michael > def testb(astr): > x = x - 1 > print astr, x `x =', with a function def, gets interpreted as "create a new name x in the function-local scope and bind it to whatever is on the right of the `='. But, on the right is an expression involving x itself. You might expect Python to look to the global scope to find x, but by writing `x =', you've already settled that x will be a local scope name, so it looks only in the local scope. Of, course, when it gets to `x -1', x hasn't yet been given a reference and it all barfs. HTH, Brian vdB From bgailer at alum.rpi.edu Sat May 7 17:46:24 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 07 May 2005 08:46:24 -0700 Subject: [Tutor] scoping oddity In-Reply-To: <427CD424.3020007@po-box.mcgill.ca> References: <20050507135637.9D65E1E4003@bag.python.org> <427CD424.3020007@po-box.mcgill.ca> Message-ID: <6.1.2.0.0.20050507084437.031a91a8@pop.sbcglobal.yahoo.com> At 07:43 AM 5/7/2005, Brian van den Broek wrote: >Michael.Coll-Barth at VerizonWireless.com said unto the world upon >2005-05-07 09:56: > > Good morning, > > > > I came across a rather odd issue with scoping. Can someone explain why > > testa and testc works, but not testb. I am running under python 2.4.1 on > > Windows NT. > > > > thanks, > > Michael > > > > > def testb(astr): > > x = x - 1 > > print astr, x > >`x =', with a function def, gets interpreted as "create a new name x >in the function-local scope and bind it to whatever is on the right of >the `='. But, on the right is an expression involving x itself. You >might expect Python to look to the global scope to find x, but by >writing `x =', you've already settled that x will be a local scope >name, so it looks only in the local scope. Of, course, when it gets to >`x -1', x hasn't yet been given a reference and it all barfs. This is what the global statement is for: def testb(astr): global x x = x - 1 etc. Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050507/175a60df/attachment.htm From bvande at po-box.mcgill.ca Sat May 7 18:22:17 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 07 May 2005 12:22:17 -0400 Subject: [Tutor] scoping oddity In-Reply-To: <6.1.2.0.0.20050507084437.031a91a8@pop.sbcglobal.yahoo.com> References: <20050507135637.9D65E1E4003@bag.python.org> <427CD424.3020007@po-box.mcgill.ca> <6.1.2.0.0.20050507084437.031a91a8@pop.sbcglobal.yahoo.com> Message-ID: <427CEB39.2080800@po-box.mcgill.ca> Bob Gailer said unto the world upon 2005-05-07 11:46: > At 07:43 AM 5/7/2005, Brian van den Broek wrote: > >> Michael.Coll-Barth at VerizonWireless.com said unto the world upon >> 2005-05-07 09:56: >> > Good morning, >> > >> > I came across a rather odd issue with scoping. Can someone explain why >> > testa and testc works, but not testb. I am running under python >> 2.4.1 on >> > Windows NT. >> > >> > thanks, >> > Michael >> >> >> >> > def testb(astr): >> > x = x - 1 >> > print astr, x >> >> `x =', with a function def, gets interpreted as "create a new name x >> in the function-local scope and bind it to whatever is on the right of >> the `='. But, on the right is an expression involving x itself. You >> might expect Python to look to the global scope to find x, but by >> writing `x =', you've already settled that x will be a local scope >> name, so it looks only in the local scope. Of, course, when it gets to >> `x -1', x hasn't yet been given a reference and it all barfs. > > > This is what the global statement is for: > > def testb(astr): > global x > x = x - 1 > etc. > > Bob Gailer global will indeed fix that, yes. But, I've been lead to believe that one's first thought when tempted to write a global statement should be to reflect on whether that temptation isn't the symptom of a sub-optimal design. It certainly can (in my case has) lead to bugs when two separate bits of code both declare the same name global and thus each make their changes to it, after I have forgotten that I made both functions declare the name global. While nothing is guaranteed to protect me from myself :-) I have found I make fewer such mistakes when I either design my functions to explicitly take in the argument and return its modified value or instead employ a class and store the data as an instance attribute where the qualifier of self helps me to keep the issues straight. And, to engage in appeal to authority (almost the last refuge of the scoundrel): lots of Python programmers more accomplished than I seem to have the achieved a consensus that global is to be avoided. Best, Brian vdB From Michael.Coll-Barth at VerizonWireless.com Sat May 7 18:56:55 2005 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth@VerizonWireless.com) Date: Sat, 7 May 2005 12:56:55 -0400 Subject: [Tutor] scoping oddity Message-ID: <20050507165659.817501E4004@bag.python.org> Tanja, Bob, Brian, Many thanks for your help. And perhaps the way in which I posed the question was misleading. In a process I am writing, I was actually trying not to use global variables, as I agree with Brian. However, I inadvertantly used a variable within a 'def' block that I had used outside of that 'def' block and got 'bitten'. It was in tracking my bug down that I became a tad confused. Actually, now that I know the answer, it all seems so obvious. At least until I get bitten by it again! D'OH! Michael -----Original Message----- Behalf Of Brian van den Broek >> >> > def testb(astr): >> > x = x - 1 >> > print astr, x >> global will indeed fix that, yes. But, I've been lead to believe that one's first thought when tempted to write a global statement should be to reflect on whether that temptation isn't the symptom of a sub-optimal design. ___________________________________________________________________ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From zamb at saudi.net.sa Sat May 7 21:41:57 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sat, 07 May 2005 22:41:57 +0300 Subject: [Tutor] scoping oddity In-Reply-To: <20050507165659.817501E4004@bag.python.org> References: <20050507165659.817501E4004@bag.python.org> Message-ID: <1115494917.18441.5.camel@localhost.localdomain> On Sat, 2005-05-07 at 12:56 -0400, Michael wrote: > Tanja, Bob, Brian, > > Many thanks for your help. > > And perhaps the way in which I posed the question was misleading. In a > process I am writing, I was actually trying not to use global variables, as > I agree with Brian. However, I inadvertantly used a variable within a 'def' > block that I had used outside of that 'def' block and got 'bitten'. It was > in tracking my bug down that I became a tad confused. > > Actually, now that I know the answer, it all seems so obvious. At least > until I get bitten by it again! D'OH! > > Michael > ...snip... (I wonder why nobody mentioned this method?!!) If you want to use a new variable with the same name as a global one use default argument (credits goes to the authors of O'REILLY's Learning Python): x = 5 def testa(astr): print astr, x testa(22) def testb(astr, x = x): x = x - 1 print astr, x testb(22) def testc(astr): print astr, x-1 testc(22) (By the way, this is my first post to PyTutor!) (Michael, sorry for this duplicate message(s). I didn't realize I replayed to *only* you until now.) Ziyad. From denise.hartley at gmail.com Sat May 7 21:50:58 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Sat, 7 May 2005 12:50:58 -0700 Subject: [Tutor] python challenges In-Reply-To: References: Message-ID: <8daabe560505071250535cce9b@mail.gmail.com> Ok, I hate to ask another question about this riddle. But I have looked and looked and looked. Where can I find more information on 'banner'? Everywhere I look it starts telling me about banner ads and so on, and that is not what I want! Any howto's/tutorials/simple explanations would be appreciated! Thanks :) ~Denise (bound and determined to solve this riddle) From dyoo at hkn.eecs.berkeley.edu Sat May 7 23:37:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 7 May 2005 14:37:36 -0700 (PDT) Subject: [Tutor] python challenges In-Reply-To: Message-ID: > On May 7, 2005, at 13:17, John Carmona wrote: > > > Hi to everybody reading this thread, can anybody point me to the URL > > where I can find these challenges. Many thanks Hi John, By the way, just to make sure you know, the mailing list here has an archive here: http://mail.python.org/pipermail/tutor/ Ignore the stuff from the future. *grin* But the rest of the archive comes in handy if you're trying to find an old message from a few days ago. Best of wishes! From smichr at bigfoot.com Sun May 8 01:06:00 2005 From: smichr at bigfoot.com (Chris Smith) Date: Sat, 7 May 2005 18:06:00 -0500 Subject: [Tutor] elegant way to turn list into string Message-ID: <93F19224-BF4C-11D9-BD17-000393C0D100@bigfoot.com> > while x < 26: > new_alph = alph[1:] + alph[:1] > print new_alph > print "\n" > x += 1 > > But this has the drawback of not progressing with my > newly create alphabet, it just returns: > abcdefghijklmnopqrstuvwxyz The reason that new_alph never changes is that you are calculating it from the same (unchanging) thing every time. The value of alph never changes in your loop, so the value of new_alph is always the same. Others have given suggestions as to what else you might do, but a fix for the above loop is to replace the word new_alph with alph. /c From bgailer at alum.rpi.edu Sun May 8 01:17:31 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 07 May 2005 16:17:31 -0700 Subject: [Tutor] scoping oddity In-Reply-To: <427CEB39.2080800@po-box.mcgill.ca> References: <20050507135637.9D65E1E4003@bag.python.org> <427CD424.3020007@po-box.mcgill.ca> <6.1.2.0.0.20050507084437.031a91a8@pop.sbcglobal.yahoo.com> <427CEB39.2080800@po-box.mcgill.ca> Message-ID: <6.1.2.0.0.20050507161427.036c5008@pop.sbcglobal.yahoo.com> At 09:22 AM 5/7/2005, Brian van den Broek wrote: >[snip] > >global will indeed fix that, yes. But, I've been lead to believe that >one's first thought when tempted to write a global statement should be >to reflect on whether that temptation isn't the symptom of a >sub-optimal design. It certainly can (in my case has) lead to bugs >when two separate bits of code both declare the same name global and >thus each make their changes to it, after I have forgotten that I made >both functions declare the name global. Yes I agree. I was pondering this as I wrote my "reply". For quick and dirty programming global can save the day. For anything intended to be larger, more permanent I usually advocate use of classes. [snip] Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050507/4d4f30c3/attachment.htm From maxnoel_fr at yahoo.fr Sun May 8 01:20:02 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun, 8 May 2005 00:20:02 +0100 Subject: [Tutor] python challenges In-Reply-To: <8daabe560505071250535cce9b@mail.gmail.com> References: <8daabe560505071250535cce9b@mail.gmail.com> Message-ID: <1A6D80F1-1E7B-47BC-ACD9-0720D64B90DF@yahoo.fr> On May 7, 2005, at 20:50, D. Hartley wrote: > Ok, I hate to ask another question about this riddle. But I have > looked and looked and looked. > > Where can I find more information on 'banner'? Everywhere I look it > starts telling me about banner ads and so on, and that is not what I > want! > The banner in question is the UNIX program "banner". Try running a search on "UNIX +banner". Also, the theory of Run-Length Encoding may come in handy for this part of the challenge. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From clajo04 at mac.com Sun May 8 02:32:54 2005 From: clajo04 at mac.com (John Clark) Date: Sat, 07 May 2005 20:32:54 -0400 Subject: [Tutor] Generator function question? Message-ID: Okay, I guess I was not being clear, or my example was not communicating the situation of my code. In function Test2, I am iterating through database tables (this is simulated by the for loop across the range(1, 10), printing out a message that states that I am operating on that particular table, and then calls another function for each table (Test1) - in Test1, I retrieve each row of the table (as simulated by the for loop on the range(1, 100) and operate on that row (simulated by the loop on range(1, 10000) that effectively does nothing... - to show progress as I do that, I want to show the "spinning wheel" so for each row I print a backspace and then I wanted to call my function neverEndingStatus() and get back the next character in the "cycle" of "|\-/". I realize I can write a generator function and then use a for loop to cycle through it forever, but I have the iterator on the rows of the table driving the loop of the Test1 function, and would rather have that drive the operation of the function than turning the loop inside out to have the status cycle driving the loop. My second take on the code is much closer to what I wanted - a function that returned the next character in the cycle of |\-/ based on what the last results were. This code looked like: import sys def neverEndingStatus(): def statusGen(): index = 0 statusChars = ['|', '\\', '-', '/'] while True: yield statusChars[index] index = (index + 1) % 4 try: neverEndingStatus.x except AttributeError: neverEndingStatus.x = statusGen() return neverEndingStatus.x.next() def Test1(): for w in range(1, 100): sys.stderr.write('\b'+neverEndingStatus()) for z in range(1, 10000): z = z + 1 def Test2(): for y in range(1, 10): sys.stderr.write('\b \nTesting'+str(y)+'\t') Test1() Test2() However, at this point I have begun wondering why I need a generator at all - it seems like I can do the same thing with something with something like: def neverEndingStatus(): try: neverEndingStatus.index = (neverEndingStatus.index + 1) % 4 except AttributeError: neverEndingStatus.index = 0 neverEndingStatus.chars = r'|\-/' return neverEndingStatus.chars[neverEndingStatus.index] Or I can borrow a generator from itertools (as per suggestion from Karl) perhaps a bit more cleanly (although I haven't yet looked at the overhead): import itertools def neverEndingStatus(): try: neverEndingStatus.cycle except AttributeError: neverEndingStatus.cycle = itertools.cycle(r'|\-/') return neverEndingStatus.cycle.next() So I started out saying that I wasn't quite happy with the way that a generator function was making me code my application, and I am pretty sure I've come to the conclusion that I didn't really want to expose a generator function at all. Which maybe a victory for the TOOWTDI concept... Anyway, if anyone sees something to be concerned about in either of these last approaches, I would appreciate hearing about it, I thank Max and Karl for their guidance... -jdc On 5/7/05 10:06 AM, "Max Noel" wrote: > > On May 7, 2005, at 13:22, John Clark wrote: > >> (Either that, or I am not following what you mean when you say: >> >> >>> As for how to access it, use a for loop (for i in >>> neverEndingStatus()). xrange, for example, is a generator function. >>> >> >> Can you please provide an example of how my Test1() function >> changes based >> on your suggestion? (sorry to be dense) >> > > Try the following code: > > > > for i in neverEndingTest(): > print i > > > breaking out of the infinite loop is left to the reader as an > exercise ;) > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > From 3dbernard at gmail.com Sun May 8 04:02:25 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sat, 7 May 2005 22:02:25 -0400 Subject: [Tutor] Else in list comprehension Message-ID: <61d0e2b405050719021b10e70e@mail.gmail.com> Hello, I just started using list comprehensions (loving them!) I know you can add an if statement, but can you put in there an else? I could not find an example of this. Thanks Bernard From maxnoel_fr at yahoo.fr Sun May 8 04:08:37 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun, 8 May 2005 03:08:37 +0100 Subject: [Tutor] Else in list comprehension In-Reply-To: <61d0e2b405050719021b10e70e@mail.gmail.com> References: <61d0e2b405050719021b10e70e@mail.gmail.com> Message-ID: On May 8, 2005, at 03:02, Bernard Lebel wrote: > Hello, > > I just started using list comprehensions (loving them!) > > I know you can add an if statement, but can you put in there an else? > I could not find an example of this. > Apparently, no. I just tried: >>> b = [i for i in range(10) if (i % 2) == 0 else 0] And it raises a SyntaxError. The "if" statement is a filter, not an operation. The "else" would be an abuse. You could, however, do the following instead: >>> def f(x): ... if (x % 2) == 0: return i ... else: return 0 ... >>> b = [f(i) for i in range(10)] >>> b [0, 0, 2, 0, 4, 0, 6, 0, 8, 0] -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jfouhy at paradise.net.nz Sun May 8 05:54:48 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Sun, 08 May 2005 15:54:48 +1200 (NZST) Subject: [Tutor] Else in list comprehension In-Reply-To: References: <61d0e2b405050719021b10e70e@mail.gmail.com> Message-ID: <1115524488.427d8d883c13c@www.paradise.net.nz> Quoting Max Noel : > Apparently, no. I just tried: > > >>> b = [i for i in range(10) if (i % 2) == 0 else 0] You can sometimes do a bit of trickery with and/or. eg: >>> odds = [(i % 2 == 1 and i or -1) for i in range(10)] >>> odds [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9] The big gotcha here is if any of the data you are interested in could be 0. You can progress to further trickery, but the payoff isn't always worth it. Sometimes you just have to write a loop :-) -- John. From keridee at jayco.net Sun May 8 20:02:00 2005 From: keridee at jayco.net (Jacob S.) Date: Sun, 8 May 2005 13:02:00 -0500 Subject: [Tutor] Generator function question? References: Message-ID: <001701c553f8$691e37b0$a85428cf@JSLAPTOP> > import sys > > def neverEndingStatus(currentChar_ = '|'): > while 1: > if currentChar_ == '|': > currentChar_ = '\\' > elif currentChar_ == '\\': > currentChar_ = '-' > elif currentChar_ == '-': > currentChar_ = '/' > elif currentChar_ == '/': > currentChar_ = '|' > yield currentChar_ > > > x = neverEndingStatus() > > def Test1(): > for w in range(1, 100): > sys.stderr.write('\b'+x.next()) ######################################## > for z in range(1, 10000): > z = z + 1 What on earth is the point of this? Why put a loop in there that does nothing? Are you just trying to take time? ######################################## > def Test2(): > for y in range(1, 10): > sys.stderr.write('\b \nTesting'+str(y)+'\t') > Test1() > > Test2() import sys from itertools import cycle # nesl = Never ending status list nesl = ["|","\\","-","/"] a = cycle(nesl) ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ## ## | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ## ## This is just using itertools' cycle to automatically make the iterator you were trying for ## # Now we rewrite your test cases def Test1(): sys.stderr.write("\b"+"\b".join(a.next() for x in range(1,100))) ## You realize that this will only give you 99 characters, not 100 def Test2(): for i in range(1,10): ## You realize again that this only runs 9 times... sys.stderr.write("\b \nTesting %s\t" % y) Test1() Test2() Well, this is not tested, but it shows that you can use itertools.cycle to do what you want. Also, the test cases are slightly neater (to me) too. Okay, I'm done Jacob From clajo04 at mac.com Sun May 8 20:28:44 2005 From: clajo04 at mac.com (John Clark) Date: Sun, 08 May 2005 14:28:44 -0400 Subject: [Tutor] Generator function question? In-Reply-To: <001701c553f8$691e37b0$a85428cf@JSLAPTOP> Message-ID: Jacob, The "z loop" is in fact just to take time while the screen refreshes with each output of the status character - as someone else pointed out I could use a wait() call as well - if I don't put something there to eat up time, I don't get to display the "spinning wheel" produced by the sys.stderr.write('\b'+x.next()) line. - All I see displayed is the final character. I think I oversimplified my example here in my first post - my actual code works on rows of database tables, and the "z loop" is meant to simulate that work being performed. The "w loop" is meant to simulate the rows of each table, and the "y loop" simulates each table. Your example reduced the Test1() function into just printing each character of the cycle - given the simplified code, that reduction is justified, but the spirit of my request was to preserve each of the loops, and provide a function that when called, would result in the next character of the cycle being returned without having to resort to the creation of a global variable ("x" in my example) or expose to the client code the need to make a .next() call. Many suggested that I use a for loop to remove the .next() call, but that would force me to turn the "y loop" inside out and drive the work being performed based on the status cycle rather than on the collection of rows of the table. This I think results in real-world code that is harder to understand (although in the simplified example there is no real difference) I first thought a generator function was the appropriate way to implement and expose this status cycle, but through the evolution of this thread, I think that a generator function isn't appropriate in this case (although a generator function is one way that the exposed function could use to select the next character in the sequence). At this point with help from others on this list, I have refined the function to the following alternatives: def neverEndingStatus(): try: neverEndingStatus.index = (neverEndingStatus.index + 1) % 4 except AttributeError: neverEndingStatus.index = 0 neverEndingStatus.chars = r'|\-/' return neverEndingStatus.chars[neverEndingStatus.index] - or - import itertools def neverEndingStatus(): try: neverEndingStatus.cycle except AttributeError: neverEndingStatus.cycle = itertools.cycle(r'|\-/') return neverEndingStatus.cycle.next() The main (philosophical) problem I have with these is that they both use the EAFP approach to function attributes - I am much more of a LBYL person - but I have not seen a LBYL implementation of function attributes. I hope this explains a bit of what should have been explained in the first post... -jdc On 5/8/05 2:02 PM, "Jacob S." wrote: >> import sys >> >> def neverEndingStatus(currentChar_ = '|'): >> while 1: >> if currentChar_ == '|': >> currentChar_ = '\\' >> elif currentChar_ == '\\': >> currentChar_ = '-' >> elif currentChar_ == '-': >> currentChar_ = '/' >> elif currentChar_ == '/': >> currentChar_ = '|' >> yield currentChar_ >> >> >> x = neverEndingStatus() >> >> def Test1(): >> for w in range(1, 100): >> sys.stderr.write('\b'+x.next()) > > ######################################## >> for z in range(1, 10000): >> z = z + 1 > > What on earth is the point of this? Why put a loop in there that does > nothing? > Are you just trying to take time? > ######################################## > >> def Test2(): >> for y in range(1, 10): >> sys.stderr.write('\b \nTesting'+str(y)+'\t') >> Test1() >> >> Test2() > > import sys > from itertools import cycle > > # nesl = Never ending status list > nesl = ["|","\\","-","/"] > > a = cycle(nesl) > > ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ## > ## | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | > | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ## > ## This is just using itertools' cycle to automatically make the iterator > you were trying for ## > > # Now we rewrite your test cases > > def Test1(): > sys.stderr.write("\b"+"\b".join(a.next() for x in range(1,100))) > ## You realize that this will only give you 99 characters, not 100 > > def Test2(): > for i in range(1,10): ## You realize again that this only runs 9 > times... > sys.stderr.write("\b \nTesting %s\t" % y) > Test1() > > Test2() > > > Well, this is not tested, but it shows that you can use itertools.cycle to > do what you want. > > Also, the test cases are slightly neater (to me) too. > > Okay, I'm done > Jacob > From dave.jaeckel at arcor.de Sun May 8 22:10:15 2005 From: dave.jaeckel at arcor.de (Ferry Dave =?iso-8859-1?q?J=E4ckel?=) Date: Sun, 8 May 2005 22:10:15 +0200 Subject: [Tutor] Talking to hardware with python Message-ID: <200505082210.15992.dave.jaeckel@arcor.de> Hello list, I want to talk to a custom usb-device (cypress CY7C63001A with firmware from ? ak modulbus) with python on win32 and linux (and maybe mac). For win32 there is a driver (as sys-file) and for linux an old deprecated driver which I'm going to rewrite for kernel 2.6.x. As I have only minimal experience with c and c++ this project is hard, but fun. And I have many questions ;);) Only some of them are python specific, so ignore them if you feel they are way too OT. I'm not sure about the way I should go: I think I want to have a c++-interface (or just plain c? but this doesn't give me a nice python object?!?), exposed to python by swig. This interface has to be the same across all platforms. On every platform I want to have a device driver. The linux one should be quite simple (good usb-howtos, an old driver as basis to work on), but I'm not sure whether it would be better to use libusb instead. On win32 there already is a driver, but I don't know how to talk to a win32 device and write a c++-interface for it, without any headers. I have never done any win32 programming and don't know the win32 api. My IDE of choice is Eclipse with PyDev and CDT (and cygwin/gcc for win32), so I can use the same tools with all platforms (and all tools are OSS). Is this a reasonable choice? If I understood the docs, I got the big picture right. Any hints and tips (better ways/tools or typical pitfalls...) are welcome! Thank you, ????????Dave From keridee at jayco.net Mon May 9 00:58:26 2005 From: keridee at jayco.net (Jacob S.) Date: Sun, 8 May 2005 17:58:26 -0500 Subject: [Tutor] Python riddles References: <1115250787.427960631ff18@www.paradise.net.nz> Message-ID: <000f01c55421$89cec2d0$7a5328cf@JSLAPTOP> Ok, I'm stuck on #4 I tried using urllib like the source hints... but, when I run my automation of the process of typing in the new nothing, I run through about 15 pages, then I notice that they add an extra number in the text. 60167 or something like that This is encouraging. 1) I'm must be getting somewhere--it's not just while 1 random number generator 2) The way they set it up, it looks like they expected me to make the mistake that i made to mislead me to a wrong side link. 3) This means that I must be doing the right thing. Unfortunately, after about 50 pages or so, it stops, apparently using too much memory, or something causing the computer to lock badly enough I have to wait for 5 minutes for the keyboard interupt to work. I believe it also hints in the source that I should do this about 300 times? I just want to know if I'm on the right track, and maybe a slight push in a better, less memory consuming direction... Can you help? Jacob -- also known as "The Schmidtty" ----- Original Message ----- From: "Max Noel" To: Cc: Sent: Thursday, May 05, 2005 8:50 AM Subject: Re: [Tutor] Python riddles > > On May 5, 2005, at 00:53, jfouhy at paradise.net.nz wrote: > >> As seen on python-announce (via Dr Dobbs): >> >> http://www.pythonchallenge.com/ >> >> Good fun! >> > > Very interesting indeed! I'm stuck on number 7, though -- looks > like it requires the use of PIL, which I've never used before. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jfouhy at paradise.net.nz Mon May 9 01:15:31 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 09 May 2005 11:15:31 +1200 (NZST) Subject: [Tutor] Python riddles In-Reply-To: <000f01c55421$89cec2d0$7a5328cf@JSLAPTOP> References: <1115250787.427960631ff18@www.paradise.net.nz> <000f01c55421$89cec2d0$7a5328cf@JSLAPTOP> Message-ID: <1115594131.427e9d9367210@www.paradise.net.nz> Quoting "Jacob S." : > Unfortunately, after about 50 pages or so, it stops, apparently using > too much memory, or something causing the computer to lock badly enough I > have to wait for 5 minutes for the keyboard interupt to work. I believe it > also hints in the source that I should do this about 300 times? I just want > to know if I'm on the right track, and maybe a slight push in a better, > less memory consuming direction... When I did riddle 4, my loop was "for i in range(320)", and I had a break condition as well (if I didn't find a number of the right form). The break condition triggered before the for loop exhausted its range. If you saw the line with two numbers, and you modified your code so that it only picks up the right one, then you should be able to solve the riddle, I think.. -- John. From tim.peters at gmail.com Mon May 9 02:03:00 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 8 May 2005 20:03:00 -0400 Subject: [Tutor] Python riddles In-Reply-To: <000f01c55421$89cec2d0$7a5328cf@JSLAPTOP> References: <1115250787.427960631ff18@www.paradise.net.nz> <000f01c55421$89cec2d0$7a5328cf@JSLAPTOP> Message-ID: <1f7befae050508170330a2bc51@mail.gmail.com> [Jacob S.] > Ok, I'm stuck on #4 > > I tried using urllib like the source hints... but, when I run my automation > of the process of typing in the new nothing, I run through about 15 pages, > then I notice that they add an extra number in the text. > 60167 or something like that > This is encouraging. 1) I'm must be getting somewhere--it's not just while 1 > random number generator > 2) The way they set it up, it looks like they expected me to make the > mistake that i made to mislead me to a wrong side link. 3) This means that I > must be doing the right thing. > Unfortunately, after about 50 pages or so, it stops, apparently using too > much memory, or something causing the computer to lock badly enough I > have to wait for 5 minutes for the keyboard interupt to work. I believe it also > hints in the source that I should do this about 300 times? I just want to > know if I'm on the right track, and maybe a slight push in a better, less > memory consuming direction... Just a guess, but if you use urllib.urlopen() to open a URL, you should call .close() on the file-like object it returns when you're done using it. Otherwise you consume an ever-growing number of sockets (and other resources) under the covers. If you follow links more than 300 times, you're definitely doing something wrong. Print out everything it's reading to see what you may be missing then. From jfouhy at paradise.net.nz Mon May 9 02:35:01 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 09 May 2005 12:35:01 +1200 (NZST) Subject: [Tutor] Copying lists Message-ID: <1115598900.427eb03502b97@www.paradise.net.nz> For making a shallow copy of a list, which syntax is preferable: >>> lst2 = lst1[:] or >>> lst2 = list(lst1) ? -- John. From dave at eddy.uni-duisburg.de Sun May 8 21:48:15 2005 From: dave at eddy.uni-duisburg.de (Ferry Dave =?iso-8859-1?q?J=E4ckel?=) Date: Sun, 8 May 2005 21:48:15 +0200 Subject: [Tutor] Talking to hardware with python Message-ID: <200505082148.15731.dave@eddy.uni-duisburg.de> Hello list, I want to talk to a custom usb-device (cypress CY7C63001A with firmware from ak modulbus) with python on win32 and linux (and maybe mac). For win32 there is a driver (as sys-file) and for linux an old deprecated driver which I'm going to rewrite for kernel 2.6.x. As I have only minimal experience with c and c++ this project is hard, but fun. And I have many questions ;) Only some of them are python specific, so ignore them if you feel they are way too OT. I'm not sure about the way I should go: I think I want to have a c++-interface (or just plain c? but this doesn't give me a nice python object?!?), exposed to python by swig. This interface has to be the same across all platforms. On every platform I want to have a device driver. The linux one should be quite simple (good usb-howtos, an old driver as basis to work on), but I'm not sure whether it would be better to use libusb instead. On win32 there already is a driver, but I don't know how to talk to a win32 device and write a c++-interface for it, without any headers. I have never done any win32 programming and don't know the win32 api. My IDE of choice is Eclipse with PyDev and CDT (and cygwin/gcc for win32), so I can use the same tools with all platforms (and all tools are OSS). Is this a reasonable choice? If I understood the docs, I got the big picture right. Any hints and tips (better ways/tools or typical pitfalls...) are welcome! Thank you, Dave From brianwisti at yahoo.com Mon May 9 05:05:10 2005 From: brianwisti at yahoo.com (Brian Wisti) Date: Sun, 8 May 2005 20:05:10 -0700 (PDT) Subject: [Tutor] Copying lists In-Reply-To: 6667 Message-ID: <20050509030510.39376.qmail@web53602.mail.yahoo.com> --- jfouhy at paradise.net.nz wrote: > For making a shallow copy of a list, which syntax is preferable: > > >>> lst2 = lst1[:] > > or > > >>> lst2 = list(lst1) > > ? I guess my personal preference would be for the first option. I'm not sure if there is an officially blessed way to go about it, though. Try one, and if somebody starts shouting at you, switch to the other ;-) Kind Regards, Brian Wisti http://coolnamehere.com/ From alan.gauld at freenet.co.uk Mon May 9 08:07:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 9 May 2005 07:07:54 +0100 Subject: [Tutor] Talking to hardware with python References: <200505082148.15731.dave@eddy.uni-duisburg.de> Message-ID: <01a101c5545d$711b3f70$e54b8651@xp> Hi, The only advice I'd offer is to stick to a C interface rather than C++ and provide the OO wrapper at the Python layer. C is much easier to use than C++ and simpler to intregrate with Python - which is itself written in C. Also a C library is more open in that it can be used by other projects who may not have an OO language to map to C++. > My IDE of choice is Eclipse with PyDev and CDT (and cygwin/gcc for win32), > so I can use the same tools with all platforms (and all tools are OSS). Is > this a reasonable choice? OSS is reasonable - indeed very sensible for cross platform work, but the IDE should be irrelevant, just use whatebver you find most natural. I'm a vim/emacs man myself! :-) Alan G. From jeannot18 at hotmail.com Mon May 9 12:40:25 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Mon, 09 May 2005 10:40:25 +0000 Subject: [Tutor] Python Challenge - Riddle 2 Message-ID: OK I am stuck on this one. I see what I need to do (correct me if I am wrong). But I need to write a script that will replace each letter by another one (In this case a --> c etc.). I look at String, List and Dictionary. I thought I could use the text.replace option but I am not sure. Anybody to put me in the right track. Also how can I add my work email address (but keeping this one) to have the mail forwarded to me, they have cut access to my hotmail at work and I am wasting too much time in waiting to go home to check my emails from Python.org. Many thanks JC From cyresse at gmail.com Mon May 9 13:45:44 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 9 May 2005 23:45:44 +1200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: Message-ID: Hi John, took me awhile to solve this one too, it's quite good, teaches you about a part of Python that you wouldn't normally use. Do you want hints or spoilers? I've give hints for now, search the Python docus for 'trans', check the string methods. Hope that didn't make it too obvious. Now, if anybody can assist me with problem 3... Good luck, Liam Clarke On 5/9/05, John Carmona wrote: > > OK I am stuck on this one. I see what I need to do (correct me if I am > wrong). But I need to write a script that will replace each letter by > another one (In this case a --> c etc.). I look at String, List and > Dictionary. I thought I could use the text.replace option but I am not > sure. > Anybody to put me in the right track. > > Also how can I add my work email address (but keeping this one) to have > the > mail forwarded to me, they have cut access to my hotmail at work and I am > wasting too much time in waiting to go home to check my emails from > Python.org . > > Many thanks > JC > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050509/65ac7188/attachment.html From jeannot18 at hotmail.com Mon May 9 14:13:37 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Mon, 09 May 2005 12:13:37 +0000 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: Message-ID: Thanks Liam, I will start checking this afternoon. Regards JC From Michael.Coll-Barth at VerizonWireless.com Mon May 9 15:39:30 2005 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth@VerizonWireless.com) Date: Mon, 9 May 2005 09:39:30 -0400 Subject: [Tutor] scoping oddity Message-ID: <20050509133932.523961E4003@bag.python.org> Ziyad, Thanks for the tip. Much of the code written here in my office, do exactly what you describe. The code I am working on is purely personal and educational. I guess I got sloppy, which in a way is educational. All, Obviously, you can't put every variable on the 'def' line. Is there a utility of some sort that will present me with a list of the variables used in an application? Preferably, something that might pick up possible scope 'collisions'? If you know what I mean. And if that isn't the right word, what is? thanks guys! Michael -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of ZIYAD A. M. AL-BATLY def testb(astr, x = x): x = x - 1 print astr, x ___________________________________________________________________ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From rschroev_nospam_ml at fastmail.fm Mon May 9 15:49:43 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 09 May 2005 15:49:43 +0200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: Message-ID: John Carmona wrote: > OK I am stuck on this one. I see what I need to do (correct me if I am > wrong). But I need to write a script that will replace each letter by > another one (In this case a --> c etc.). I look at String, List and > Dictionary. I thought I could use the text.replace option but I am not sure. > Anybody to put me in the right track. There are different ways to do this; IIRC I did it using ord, chr and a list comprehension. Note that there is a forum for hints: http://www.pythonchallenge.com/forums/ -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From cpu.crazy at gmail.com Mon May 9 16:38:29 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 09 May 2005 08:38:29 -0600 Subject: [Tutor] No Need to Press Enter In-Reply-To: References: Message-ID: <6.1.0.6.2.20050509083411.01ebc578@pop.gmail.com> yes. That's exactly what I was looking for. Do you know the code for the ^Q ^Z (control + letter keys) to quit? Like ^Z to quit the Python shell? At 06:03 PM 5/4/2005, you wrote: >Message: 8 >Date: Wed, 4 May 2005 11:33:53 -0700 >From: "D. Hartley" >Subject: [Tutor] Fwd: No Need to press Enter (Joseph Quigley) >To: Python tutor >Message-ID: <8daabe5605050411332f7b1a41 at mail.gmail.com> >Content-Type: text/plain; charset=ISO-8859-1 > >I don't know if this is what you're looking for, but in my game I set >Running = 1, and then had: > if event.key == K_q: > running = 0 > >... which exits the game as soon as you hit q (i.e., no hitting >enter). I can send the full code if it would be more helpful, if this >is what you're talking about? >~Denise -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050509/366765b8/attachment.html From jsoares at Safe-mail.net Mon May 9 16:55:18 2005 From: jsoares at Safe-mail.net (jsoares@Safe-mail.net) Date: Mon, 9 May 2005 10:55:18 -0400 Subject: [Tutor] Tutor Digest, Vol 15, Issue 19 Message-ID: I was pleasantly surprised with the Dr. Python editor. Great for Python beginners like me. Also, this editor seems to support the wxWidgets and wxPython bindings library, which I'm trying to learn. John Soares jsoares at safe-mail.net -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050509/bf2c2217/attachment.htm From albertito_g at hotmail.com Mon May 9 16:55:28 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 09 May 2005 14:55:28 +0000 Subject: [Tutor] Fwd: Fwd: Python riddles In-Reply-To: <8daabe560505071745d62eea1@mail.gmail.com> Message-ID: Thanks I got it........finally Now I'm stucked in the riddle 6 As I understand I have to find a secret file (which I have but inside there is like 900 files) and do something with it Can someone give a hint?????? Is it like number 4?????????the one with urllib??????? thanks Alberto >From: "D. Hartley" >Reply-To: "D. Hartley" >To: Alberto Troiano >Subject: Re: [Tutor] Fwd: Fwd: Python riddles >Date: Sat, 7 May 2005 17:45:32 -0700 > >Alberto, "banner" is not a method or a function or anything, it's a >unix trick. also look at run-length encoding for a hint. > >hope this helps! i finally got it :) > >On 5/7/05, D. Hartley wrote: > > the only thing i found with "banner" in it was this: > > > > http://www.python.org/doc/2.2.3/lib/module-code.html > > > > and i dont know what those are or if it would help. it'd be nice if > > they just had a definition or something! this puzzle has been so hard > > and has frustrated me a million times. i want to solve it! > > > > On 5/7/05, D. Hartley wrote: > > > i dont know what the banner program is. it didnt say anything about it > > > in the python documentation? > > > > > > On 5/7/05, Alberto Troiano wrote: > > > > What's a 'banner'????????? > > > > Can you explain me how a banner works???? > > > > I think we can focus on that > > > > Max suggested me that I take a look to the banner program (which I >couldn't > > > > find anywhere) > > > > I'm stucked too in this riddle. > > > > > > > > Regards > > > > > > > > Alberto > > > > > > > > >From: "D. Hartley" > > > > >Reply-To: "D. Hartley" > > > > >To: Alberto Troiano > > > > >Subject: Re: [Tutor] Fwd: Fwd: Python riddles > > > > >Date: Fri, 6 May 2005 23:57:47 -0700 > > > > > > > > > >I got the file... and see several patterns... but i'm not sure what >to > > > > >do about it now. something about if it were in one big flat >list.... > > > > >like a ... 'banner'.... but the ".p" isnt any kind of a meaningful > > > > >hint to me and i'm still stuck :P > > > > > > > > > >On 5/6/05, Alberto Troiano wrote: > > > > > > I'm in 5 !!!!!!!!!!!!!!!! > > > > > > But I don't understand it thou.........:D > > > > > > > > > > > > Good luck > > > > > > > > > > > > Alberto > > > > > > > > > > > > >From: "D. Hartley" > > > > > > >Reply-To: "D. Hartley" > > > > > > >To: Alberto Troiano > > > > > > >Subject: Re: [Tutor] Fwd: Fwd: Python riddles > > > > > > >Date: Fri, 6 May 2005 11:43:02 -0700 > > > > > > > > > > > > > >right. the trick is it can be ONLY three cap letters on either >side. > > > > > > >the first solution you come up with will probably return a lot >more > > > > > > >letters because it will return things like AAAAaAAA too. ;) i'm >trying > > > > > > >to figure out what puzzle 4 is asking right now > > > > > > > > > > > > > >On 5/6/05, Alberto Troiano wrote: > > > > > > > > Hey > > > > > > > > > > > > > > > > I'm on riddle 3 right now. I figured out just after I sent >you the > > > > >email > > > > > > >:D > > > > > > > > On riddle 3 let me know if I'm wrong but I suppose there is >a > > > > >lowercase > > > > > > > > letter between three uppercase letters on eachside >wright???????? > > > > > > > > > > > > > > > > Thanks again > > > > > > > > > > > > > > > > Alberto > > > > > > > > > > > > > > > > >From: "D. Hartley" > > > > > > > > >Reply-To: "D. Hartley" > > > > > > > > >To: Alberto Troiano > > > > > > > > >Subject: Re: [Tutor] Fwd: Fwd: Python riddles > > > > > > > > >Date: Fri, 6 May 2005 11:30:06 -0700 > > > > > > > > > > > > > > > > > >Alberto, > > > > > > > > > > > > > > > > > >Right now the url ends in "0.html". eventually when you >figure out > > > > > > > > >the riddle, you'll get something to replace the "0" with. >try > > > > > > > > >"1.html" for a hint (it's not the solution but it will give >you a > > > > >hint > > > > > > > > >as to what they're asking - i wasnt sure at first either). >The "0" > > > > >on > > > > > > > > >the screen is the number of the riddle you're on, it's >unrelated to > > > > > > > > >the riddle itself. > > > > > > > > > > > > > > > > > >Lemme know if you need another hint! > > > > > > > > > > > > > > > > > >~Denise > > > > > > > > > > > > > > > > > >On 5/6/05, Alberto Troiano wrote: > > > > > > > > > > Hey > > > > > > > > > > > > > > > > > > > > I have recently entered to the riddle but I don't >understand > > > > >what I > > > > > > >have > > > > > > > > >to > > > > > > > > > > do with those numbers > > > > > > > > > > > > > > > > > > > > I see 238 and a 0 but what does it have to do with the >URL?? > > > > > > > > > > > > > > > > > > > > HELPPPPPPPPPPPPPPPPPP > > > > > > > > > > > > > > > > > > > > Thanks > > > > > > > > > > > > > > > > > > > > Alberto > > > > > > > > > > > > > > > > > > > > >From: "D. Hartley" > > > > > > > > > > >Reply-To: "D. Hartley" > > > > > > > > > > >To: Python tutor > > > > > > > > > > >Subject: [Tutor] Fwd: Fwd: Python riddles > > > > > > > > > > >Date: Thu, 5 May 2005 12:28:32 -0700 > > > > > > > > > > > > > > > > > > > > > >ha ha. ok. I figured out the riddle (the computational >part), i > > > > > > >just > > > > > > > > > > >had calculated it myself and wondered where python came >in. if > > > > >I > > > > > > >had > > > > > > > > > > >remembered to bring my brain with me this morning, I >suppose I > > > > > > >would > > > > > > > > > > >have thought that I could write a python script to do >the math > > > > > > >problem > > > > > > > > > > >for me instead of a normal calculator. Thanks! > > > > > > > > > > >~Sheepish Denise > > > > > > > > > > > > > > > > > > > > > >---------- Forwarded message ---------- > > > > > > > > > > >From: Bob Gailer > > > > > > > > > > >Date: May 5, 2005 11:57 AM > > > > > > > > > > >Subject: Re: [Tutor] Fwd: Python riddles > > > > > > > > > > >To: "D. Hartley" > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >At 11:39 AM 5/5/2005, you wrote: > > > > > > > > > > >Ok, now, I'm sure this sounds like a very dumb >question. But I > > > > > > > > > > >clicked on riddle 1, and I don't know how this thing >works - > > > > > > >"about" > > > > > > > > > > >didnt give a lot of extra info. Am I trying to >duplicate > > > > >something > > > > > > >on > > > > > > > > > > >my screen that looks like the picture on the monitor? >If > > > > >someone > > > > > > >would > > > > > > > > > > >give me the (probably obvious) push in the right >direction, I > > > > >think > > > > > > > > > > >some challenges would be really fun. Perhaps off the >mailing > > > > >list > > > > > > >so > > > > > > > > > > >everyone who gets it doesnt have to be bombarded ;) > > > > > > > > > > >Also follow the forum link to the Python Challenge >Hints > > > > > > > > > > >Where you will find for the first challenge: > > > > > > > > > > >Hint 1: do the math > > > > > > > > > > >Hint 2: change the address > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >Bob Gailer > > > > > > > > > > >mailto:bgailer at alum.rpi.edu > > > > > > > > > > >510 558 3275 home > > > > > > > > > > >720 938 2625 cell > > > > > > > > > > >_______________________________________________ > > > > > > > > > > >Tutor maillist - Tutor at python.org > > > > > > > > > > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > Gaucho > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > Gaucho > > > > > > > > > > > > > > > > > > > > > > > > > > > > Gaucho > > > > > > > > > > > > > > > > > > > > > > > > > Gaucho From cpu.crazy at gmail.com Mon May 9 18:57:25 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 09 May 2005 10:57:25 -0600 Subject: [Tutor] How do I squish this bug? Message-ID: <6.1.0.6.2.20050509105427.01f00928@pop.gmail.com> Traceback (most recent call last): File "C:\Python24\saved\Geek Dictionary\jargon_file.py", line 39, in -toplevel- main() File "C:\Python24\saved\Geek Dictionary\jargon_file.py", line 26, in main lobby.lobby() File "C:/Python24/saved/Geek Dictionary\lobby.py", line 51, in lobby import jargon_file File "C:\Python24\saved\Geek Dictionary\jargon_file.py", line 39, in -toplevel- main() File "C:\Python24\saved\Geek Dictionary\jargon_file.py", line 26, in main lobby.lobby() File "C:/Python24/saved/Geek Dictionary\lobby.py", line 52, in lobby main() NameError: global name 'main' is not defined Source code is here: def lobby(): print "The Lobby" while True: mode = raw_input('\nLobby>> ') if mode == "commands": commands() elif ((mode == "exit()") or ("exit" == mode) or ("bye" == mode)): print"\nThanks for using the Geek Dictionary!\n" time.sleep(2) raise SystemExit elif mode == "email": print print " ", cv.prog_email elif mode == "cemail": print print " ", cv.rcn_email elif mode == "site": print print " ", cv.prog_site elif mode == "info": print "Version: ", cv.ver print "Created by", cv.rel_creator_nm, "( a.k.a", cv.creator, ")" print "Hope you are enjoying the program!" print "Thanks to whoever it was at IM 2005 for the idea!\n" print "Johny Lane is not part of Warmouth Studios" elif ((mode == "geeker()") or ("geeker" == mode)): print "Loading Geeker prompt...\n" #load the gkd prompt gkd.commands() gkd.geeker() elif ((mode == "jargon()") or ("jargon" == mode)): import jargon_file main() elif mode == "": print else: print "Command Error! Not a recognized command: " , mode return and the other module is: def main(): while True: print """\nPlease note that you may see weird symbols while using the console when you run this module. There are also some bugs when changing between The Lobby and the Jargon File twice.\n""" print "\nThe Jargon File 4.4.7\n" print "Type 'ls' for a list of words in the Jargon File 4.4.7 or back() to go back to\nthe lobby. As usual, 'exit()' closes the whole program" prompt = raw_input(">> ") if prompt == "ls": print """ Type Q to go back to the prompt (TM) /dev/null /me""" elif prompt == "back()": import lobby lobby.lobby() elif prompt == "exit()": raise SystemExit elif ((prompt == "(TM)") or (prompt == "(tm)")): print TM elif prompt == "/dev/null": print dev_null elif prompt == "/me": print backslash_me elif prompt == "0": print num0 elif prompt == "1TBS": print num1TBS main() Why do I get the error: NameError: global name 'main' is not defined when switching between the two module twice (ie: type: jargon type:back() type:jargon type:back() )? Thanks JQ From bwinton at latte.ca Mon May 9 21:01:49 2005 From: bwinton at latte.ca (Blake Winton) Date: Mon, 9 May 2005 15:01:49 -0400 Subject: [Tutor] Generator function question? In-Reply-To: <9419E6A6-F476-4B78-8393-72AAB33D790F@yahoo.fr> Message-ID: <20050509185040.0B760BC@short.latte.ca> Sorry for jumping in to this a little late, but... > This is (IMO) more elegant: > def neverEndingStatus(): > index = 0 > statusChars = ['|', '\\', '-', '/'] > while True: > yield statusChars[index] > index = (index + 1) % 4 Why not go a step further? def neverEndingStatus(): statusChars = ['|', '\\', '-', '/'] while True: for char in statusChars: yield char or def neverEndingStatus(): while True: yield '|' yield '\\' yield '-' yield '/' Later, Blake. From maxnoel_fr at yahoo.fr Mon May 9 21:10:01 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon, 9 May 2005 20:10:01 +0100 Subject: [Tutor] How do I squish this bug? In-Reply-To: <6.1.0.6.2.20050509105427.01f00928@pop.gmail.com> References: <6.1.0.6.2.20050509105427.01f00928@pop.gmail.com> Message-ID: <4A61E647-8899-4C99-8E66-63FC5F57858E@yahoo.fr> On May 9, 2005, at 17:57, Joseph Quigley wrote: > Why do I get the error: > NameError: global name 'main' is not defined > > when switching between the two module twice (ie: type: jargon > type:back() > type:jargon type:back() )? > > Thanks > JQ > Namespaces. Each module has its own namespace. To run the function "main" from the imported module "jargon_file", you have to call jargon_file.main(). Feels a bit weird at the beginning, but after using them for a little while, you suddenly realize that namespaces are an instance of BestThingEver. By the way, it looks like your code induces an endless recursion in an attempt to emulate GOTO statements (been programming in a variant of BASIC?). That's a Bad Thing. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Mon May 9 22:10:35 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Mon, 9 May 2005 13:10:35 -0700 Subject: [Tutor] challenges - general Message-ID: <8daabe560505091310562294b2@mail.gmail.com> Hello, everyone! Well after hours of struggle, I finally managed to get the peak riddle solved. Very frustrating, but I think I learned a lot. However on the channel one - I cant get any ideas. It may just be best for me to bow out at this point. One of my biggest problems has been that not only is python a new language to me, but it's my first step into programming at all: so many of the subjects that have come up in these riddles are "background information" i didnt have. Also very good things for me to learn (I'll have to learn a lot of non-python stuff if I want to learn programming!) but it does make it difficult at this beginning stage. It's too bad they dont have something like "Jr. Python Challenges" (!!) Actually, perhaps this is something you guys would know about! In your own learning python (or as you watched others learn, if you're one of the resident experts), have you come across some good challenges for python learners? I have worked on some, but here's what I have found: Too easy: every tutorial in the universe has a "guess my number" game, and there are only so many times you can create that one ;) Too much explanation: My current python book teaches by way of creating games, which I think is a great approach (that's what I'm interested in anyway). But it gives explicit instructions on how to do every single step. The end-of-chapter "additional challenges" have proved to be closest to what I am looking for: problems that take creative thinking, further research, and/or lots of experimentation to figure out. For instance - of course it had the guess my number game, but the chapter-end problem was to flip the roles so that the computer tried to guess the user's number. Not terribly difficult, but fun to work with. Too little explanation/direction: At least for a beginner, it's helpful to have some idea of what you're trying to do ;) I also worked with the Livewires worksheets, altho there were a couple of their suggested exercises I could not get (for instance: when I was working on my space invaders game and trying to figure out how to render text onto the screen, one of the livewires extra tasks was to do something exactly like that. But it didnt have anything about rendering text in the course!) I think a really good example was the Regular Expressions puzzle in the python challenges. I didnt know anything about regular expressions, but there was enough of a hint so that I could find the right module/library/direction, and, after reading it through a handful of times and trying a bunch of things out (with a helpful nudge or two in the right direction), I could solve the riddle *and* I really feel like I learned something about regular expressions. I definitely do want to learn some of these more complicated topics, and I think that challenge really worked for me. So if anyone has a source of other challenges, I would really love to see them. I need things to practice on! :) I like the way the python challenges are set up, I'm just stuck where I am right now and there's only the one to work on at a time so I'm pretty much at a loss there, at the moment. I know there are a lot of new learners here who would probably also appreciate challenges to try! ~Denise P.S. I still keep looking at riddle #6, even tho it's getting me nowhere. I might try just searching python docs for channels or loops or zippers or something. ha ha ;) From albertito_g at hotmail.com Mon May 9 22:18:37 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 09 May 2005 20:18:37 +0000 Subject: [Tutor] challenges - general In-Reply-To: <8daabe560505091310562294b2@mail.gmail.com> Message-ID: Hey I have recently got stuck (jejeje) on riddle 7 Yes!!!! I managed to solve riddle 6 after hours of struggle with the ................ riddle Now I don't know what to do because there is no hint anywhere Regarding to Denise I would say don't give up, I didn't know anything that helped to solve riddle 6 but doing a little research and playing with IDLE I managed to get what I was looking for Thanks Alberto >From: "D. Hartley" >Reply-To: "D. Hartley" >To: Python tutor >Subject: [Tutor] challenges - general >Date: Mon, 9 May 2005 13:10:35 -0700 > >Hello, everyone! > >Well after hours of struggle, I finally managed to get the peak riddle >solved. Very frustrating, but I think I learned a lot. > >However on the channel one - I cant get any ideas. It may just be best >for me to bow out at this point. One of my biggest problems has been >that not only is python a new language to me, but it's my first step >into programming at all: so many of the subjects that have come up in >these riddles are "background information" i didnt have. Also very >good things for me to learn (I'll have to learn a lot of non-python >stuff if I want to learn programming!) but it does make it difficult >at this beginning stage. It's too bad they dont have something like >"Jr. Python Challenges" (!!) > >Actually, perhaps this is something you guys would know about! In your >own learning python (or as you watched others learn, if you're one of >the resident experts), have you come across some good challenges for >python learners? > >I have worked on some, but here's what I have found: > >Too easy: every tutorial in the universe has a "guess my number" >game, and there are only so many times you can create that one ;) > >Too much explanation: My current python book teaches by way of >creating games, which I think is a great approach (that's what I'm >interested in anyway). But it gives explicit instructions on how to >do every single step. The end-of-chapter "additional challenges" have >proved to be closest to what I am looking for: problems that take >creative thinking, further research, and/or lots of experimentation to >figure out. For instance - of course it had the guess my number game, >but the chapter-end problem was to flip the roles so that the computer >tried to guess the user's number. Not terribly difficult, but fun to >work with. > >Too little explanation/direction: At least for a beginner, it's >helpful to have some idea of what you're trying to do ;) I also worked >with the Livewires worksheets, altho there were a couple of their >suggested exercises I could not get (for instance: when I was working >on my space invaders game and trying to figure out how to render text >onto the screen, one of the livewires extra tasks was to do something >exactly like that. But it didnt have anything about rendering text in >the course!) > >I think a really good example was the Regular Expressions puzzle in >the python challenges. I didnt know anything about regular >expressions, but there was enough of a hint so that I could find the >right module/library/direction, and, after reading it through a >handful of times and trying a bunch of things out (with a helpful >nudge or two in the right direction), I could solve the riddle *and* I >really feel like I learned something about regular expressions. I >definitely do want to learn some of these more complicated topics, and >I think that challenge really worked for me. > >So if anyone has a source of other challenges, I would really love to >see them. I need things to practice on! :) I like the way the python >challenges are set up, I'm just stuck where I am right now and there's >only the one to work on at a time so I'm pretty much at a loss there, >at the moment. I know there are a lot of new learners here who would >probably also appreciate challenges to try! > >~Denise >P.S. I still keep looking at riddle #6, even tho it's getting me >nowhere. I might try just searching python docs for channels or loops >or zippers or something. ha ha ;) >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From rschroev_nospam_ml at fastmail.fm Mon May 9 22:31:42 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 09 May 2005 22:31:42 +0200 Subject: [Tutor] Fwd: Fwd: Python riddles In-Reply-To: References: <8daabe560505071745d62eea1@mail.gmail.com> Message-ID: Alberto Troiano wrote: > Now I'm stucked in the riddle 6 > > As I understand I have to find a secret file (which I have but inside there > is like 900 files) > and do something with it One of the files has a name that is unlike all the other ones; take a look at that one. > Is it like number 4?????????the one with urllib??????? Yes, the general principle is the same. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From alan.gauld at freenet.co.uk Mon May 9 22:37:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 9 May 2005 21:37:50 +0100 Subject: [Tutor] No Need to Press Enter References: <6.1.0.6.2.20050509083411.01ebc578@pop.gmail.com> Message-ID: <004d01c554d6$f850da30$247e8651@xp> > yes. That's exactly what I was looking for. Do you know the code for > the ^Q ^Z (control + letter keys) to quit? Like ^Z to quit the Python shell? Be careful with that one. The ^Z only works on Windows. On Linux or MacOS its ^D. In both cases its the end of file character used by the operating system, so you should check for eof not a specific character if you want to use the native quit command. To find out what any particular key emits try using the program in my "event Driven Programming" topic in my tutor., it should print out the key codes for any key... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon May 9 22:45:29 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 9 May 2005 21:45:29 +0100 Subject: [Tutor] scoping oddity References: <20050509133932.523961E4003@bag.python.org> Message-ID: <005201c554d8$0a256860$247e8651@xp> > Obviously, you can't put every variable on the 'def' line. Obviously. Or at least maybe not. If your program is well designed its unusual to have more that a few global varoables so you could in fact pass them in to each fuinctrion - but thats bad practice too. You shouldn't ever have to. If you access every variable in every function (or even in one function!) then there is something fundamentally wrong with your design. In an ideal world: Functions should be designed to be highly cohesive - meaning all the things inside are related to each other - and loosely coupled - meaning they don't rely on a lot of data being passed between them. Functions should also have few side-effcts - they shouldn't alter global variables - and should be predictable and stateless - meaning calling the same function with the same arguments should return the same results each time. Following these rules should result in code that is more reliable, more maintainable and easier to reuse. > utility of some sort that will present me with a list of the variables used > in an application? dir() will tell you what names exist in the namespace of the argument. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon May 9 22:50:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 May 2005 16:50:19 -0400 Subject: [Tutor] challenges - general In-Reply-To: <8daabe560505091310562294b2@mail.gmail.com> References: <8daabe560505091310562294b2@mail.gmail.com> Message-ID: <427FCD0B.1060503@tds.net> D. Hartley wrote: > Actually, perhaps this is something you guys would know about! In your > own learning python (or as you watched others learn, if you're one of > the resident experts), have you come across some good challenges for > python learners? The questions on this mailing list are often good beginner challenges. Many learners have graduated from asking questions to answering them. At first you may want to just try to figure out an answer for yourself, but as you gain confidence you can post answers to the list. Kent From amonroe at columbus.rr.com Tue May 10 00:13:34 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 9 May 2005 18:13:34 -0400 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: Message-ID: <104202483335.20050509181334@columbus.rr.com> > Hi John, took me awhile to solve this one too, it's quite good, teaches you > about a part of Python that you wouldn't normally use. > Do you want hints or spoilers? > I've give hints for now, search the Python docus for 'trans', check the > string methods. You can also do it with a convoluted list comprehension - that's what I did. Alan From denise.hartley at gmail.com Tue May 10 00:37:46 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Mon, 9 May 2005 15:37:46 -0700 Subject: [Tutor] Python riddles - zip question In-Reply-To: References: <8daabe560505071745d62eea1@mail.gmail.com> Message-ID: <8daabe56050509153764ff0737@mail.gmail.com> How do I open a zipfile? I see commands for closing it, but i only see "class zipfile" - no command like urlopen() (!!!) Thanks! ---------- Forwarded message ---------- From: Roel Schroeven Date: May 9, 2005 1:31 PM Subject: Re: [Tutor] Fwd: Fwd: Python riddles To: tutor at python.org Alberto Troiano wrote: > Now I'm stucked in the riddle 6 > > As I understand I have to find a secret file (which I have but inside there > is like 900 files) > and do something with it One of the files has a name that is unlike all the other ones; take a look at that one. > Is it like number 4?????????the one with urllib??????? Yes, the general principle is the same. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Tue May 10 00:46:29 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 9 May 2005 23:46:29 +0100 Subject: [Tutor] challenges - general References: <8daabe560505091310562294b2@mail.gmail.com> Message-ID: <006901c554e8$f1205120$247e8651@xp> > So if anyone has a source of other challenges, I would > really love to see them. The ACM has a set of computing challenges. They are mainly math based though so you might not like them. There are those plus many others on the Useless Python web site - Recently relaunched - and go to the old site because the new one is trying to start afresh so has relatively few items just now. (BTW Does anyone know how to submit a challenge as opposed to a solution?!) > I need things to practice on! :) But the best challenges are the ones you find yourself. Any job you do regularly omn the computer, or any job that requires a lot of repetition should be a candidate for writing a propgram to automate. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jfouhy at paradise.net.nz Tue May 10 00:43:33 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 10 May 2005 10:43:33 +1200 (NZST) Subject: [Tutor] Python riddles - zip question In-Reply-To: <8daabe56050509153764ff0737@mail.gmail.com> References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> Message-ID: <1115678613.427fe795a1818@www.paradise.net.nz> Quoting "D. Hartley" : > How do I open a zipfile? I see commands for closing it, but i only see > "class zipfile" - no command like urlopen() (!!!) Look at the constructor :-) >>> import zipfile >>> z = zipfile.ZipFile('myzip.zip') >>> z.printdir() ... -- John. From smichr at bigfoot.com Tue May 10 01:06:47 2005 From: smichr at bigfoot.com (Chris Smith) Date: Mon, 9 May 2005 18:06:47 -0500 Subject: [Tutor] Tutor Digest, Vol 15, Issue 21 (python.org: trusted sender for your account) In-Reply-To: Message-ID: <05028161-C0DF-11D9-9932-000393C0D100@bigfoot.com> On Monday, May 9, 2005, at 15:45 America/Chicago, tutor-request at python.org wrote: > Actually, perhaps this is something you guys would know about! In your > own learning python (or as you watched others learn, if you're one of > the resident experts), have you come across some good challenges for > python learners? > > The ACM Programming problems are archived at http://www.acm.inf.ethz.ch/ProblemSetArchive.html These are tasks on which one's python tool may be sharpened. /c From servando at mac.com Tue May 10 01:22:11 2005 From: servando at mac.com (Servando Garcia) Date: Mon, 9 May 2005 18:22:11 -0500 Subject: [Tutor] need a example of translate or maketrans Message-ID: Hello list As you can guess I am working on the riddles. I have looked in vain for a simple example and or a explanation of the string function "translate" or even "maketrans" Can someone please send me a working example,please. thanks From carroll at tjc.com Tue May 10 02:08:23 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 9 May 2005 17:08:23 -0700 (PDT) Subject: [Tutor] need a example of translate or maketrans In-Reply-To: Message-ID: On Mon, 9 May 2005, Servando Garcia wrote: > As you can guess I am working on the riddles. I have looked in vain > for a simple example and or a explanation of the string function > "translate" or even "maketrans" > Can someone please send me a working example,please. Here's a quick example, in which every (lower-case) vowel in a string is replaced by its vowel position; e.g, 'a' gets replaced by '1', 'e' by '2', etc., and all consonants (including 'y', for this example) and other characters are left alone: >>> from string import maketrans >>> intab="aeiou" >>> outtab="12345" >>> trantab=maketrans(intab, outtab) >>> instring = "Life of Brian" >>> outstring = instring.translate(trantab) >>> outstring 'L3f2 4f Br31n' >>> From denise.hartley at gmail.com Tue May 10 02:18:55 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Mon, 9 May 2005 17:18:55 -0700 Subject: [Tutor] zip question In-Reply-To: <8daabe5605050915591c5800e@mail.gmail.com> References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> <1115678613.427fe795a1818@www.paradise.net.nz> <8daabe5605050915591c5800e@mail.gmail.com> Message-ID: <8daabe5605050917187c5d704d@mail.gmail.com> This is a problem I'm having with instances of classes and their objects. John suggested: > Look at the constructor :-) > > >>> import zipfile > >>> z = zipfile.ZipFile('myzip.zip') > >>> z.printdir() I admitted that my grasp of classes (and "constructors") is a bit fuzzy. I did get this particular class to work, and got the first half of the problem done. However, now i'm working in another class, zipinfo. It says: Instances of the ZipInfo class are returned by the getinfo() and infolist() methods of ZipFile objects. Each object stores information about a single member of the ZIP archive. Instances have the following attributes: filename, comment, etc. I've tried about ten things to get "filename" to work: myzip.filename("99905.txt") (str not callable) myzip.comment(file("99905.txt")) (no file with this name - i suppose, if it's still zipped?) myzip.getinfo(99905.txt) (invalid syntax) and, trying to do this one the same way as the zipfile one (a long shot): mynote = zipfile.ZipInfo("channel.zip") >>> mynote mynote.filename(file("99905.txt")) (again, no such file name) i know this trial-and-error method is sloppy, trying to find the right format, but i'm still getting used to dot notations and modules and classes and so on - was trying to figure out a way to make it work without having to ask and feel dumb, ha ha. Does anyone have a (hopefully simple) explanation of how to format this command? I'd really appreciate it! Thanks, Denise From denise.hartley at gmail.com Tue May 10 02:26:54 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Mon, 9 May 2005 17:26:54 -0700 Subject: [Tutor] zip question In-Reply-To: <8daabe5605050917187c5d704d@mail.gmail.com> References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> <1115678613.427fe795a1818@www.paradise.net.nz> <8daabe5605050915591c5800e@mail.gmail.com> <8daabe5605050917187c5d704d@mail.gmail.com> Message-ID: <8daabe5605050917266dcf8ab5@mail.gmail.com> P.S. I realize that zipfile has commands, and zipinfo only seems to list "attributes." Each instance of ZipInfo is a collection of information about the file in the archive: its filename, its comments, etc. So filename is not filename() - it's not a callable command. But how can i access/see this information about a given member of the archive? On 5/9/05, D. Hartley wrote: > This is a problem I'm having with instances of classes and their > objects. John suggested: > > > Look at the constructor :-) > > > > >>> import zipfile > > >>> z = zipfile.ZipFile('myzip.zip') > > >>> z.printdir() > > I admitted that my grasp of classes (and "constructors") is a bit > fuzzy. I did get this particular class to work, and got the first half > of the problem done. However, now i'm working in another class, > zipinfo. It says: > > Instances of the ZipInfo class are returned by the getinfo() and > infolist() methods of ZipFile objects. Each object stores information > about a single member of the ZIP archive. > > Instances have the following attributes: > > filename, comment, etc. > > I've tried about ten things to get "filename" to work: > > myzip.filename("99905.txt") (str not callable) > myzip.comment(file("99905.txt")) (no file with this name - i suppose, > if it's still zipped?) > > myzip.getinfo(99905.txt) (invalid syntax) > > and, trying to do this one the same way as the zipfile one (a long shot): > mynote = zipfile.ZipInfo("channel.zip") > >>> mynote > > mynote.filename(file("99905.txt")) (again, no such file name) > > i know this trial-and-error method is sloppy, trying to find the right > format, but i'm still getting used to dot notations and modules and > classes and so on - was trying to figure out a way to make it work > without having to ask and feel dumb, ha ha. > > Does anyone have a (hopefully simple) explanation of how to format > this command? I'd really appreciate it! > > Thanks, > Denise > From carroll at tjc.com Tue May 10 02:28:15 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 9 May 2005 17:28:15 -0700 (PDT) Subject: [Tutor] Any easy way to invoke the default browser on a specified URL? Message-ID: Is there any way, from within Python, to cause the default browser (Firefox, in my case) to be invoked with a specific URL? I'd like to do something like (totally made-up name and syntax): OpenBrowser("http://www.google.com/") and have a new browser window opened up pointing to Google. (Okay, the truth is, this is intended as a handy way of checking answers on the Python Challenge, but what the heck.) From kent37 at tds.net Tue May 10 02:44:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 09 May 2005 20:44:39 -0400 Subject: [Tutor] Any easy way to invoke the default browser on a specified URL? In-Reply-To: References: Message-ID: <428003F7.5070004@tds.net> Terry Carroll wrote: > Is there any way, from within Python, to cause the default browser > (Firefox, in my case) to be invoked with a specific URL? > > I'd like to do something like (totally made-up name and syntax): > > OpenBrowser("http://www.google.com/") > > and have a new browser window opened up pointing to Google. >>> import webbrowser >>> webbrowser.open("http://www.google.com/") From maxnoel_fr at yahoo.fr Tue May 10 02:45:21 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 10 May 2005 01:45:21 +0100 Subject: [Tutor] zip question In-Reply-To: <8daabe5605050917187c5d704d@mail.gmail.com> References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> <1115678613.427fe795a1818@www.paradise.net.nz> <8daabe5605050915591c5800e@mail.gmail.com> <8daabe5605050917187c5d704d@mail.gmail.com> Message-ID: <044D40AF-DC4D-48D5-A3E8-043146C3FC0E@yahoo.fr> On May 10, 2005, at 01:18, D. Hartley wrote: > I admitted that my grasp of classes (and "constructors") is a bit > fuzzy. I did get this particular class to work, and got the first half > of the problem done. However, now i'm working in another class, > zipinfo. It says: > > Instances of the ZipInfo class are returned by the getinfo() and > infolist() methods of ZipFile objects. Each object stores information > about a single member of the ZIP archive. > > Instances have the following attributes: > > filename, comment, etc. > > > I've tried about ten things to get "filename" to work: > > myzip.filename("99905.txt") (str not callable) ZipFile.filename is an attribute, not a method. It contains the name of the archive (in other words, in your case myzip.filename == "myzip.zip"). > myzip.comment(file("99905.txt")) (no file with this name - i suppose, > if it's still zipped?) What you're doing in that line is open a file for reading, named 99905.txt and located in the current folder, and *then* passing it to the ZipFile.comment method. Obviously not working. :D > myzip.getinfo(99905.txt) (invalid syntax) Aah! So close! The quotes, dear, you forgot about the quotes! ;) >>> myzip.getinfo("99905.txt") (cue Final Fantasy VII victory fanfare) Also, you may want to have a look at the ZipFile.NameToInfo attribute. In your case, myzip.NameToInfo is a dictionary which contains ZipInfo's for each of the files contained in the archive, where the key for each ZipInfo is the name of the corresponding files. In other words, >>> myzip.NameToInfo["99905.txt"] Yeah, used that way it pretty much does the same thing as getinfo (), but I think it's more Pythonic (using a getinfo method feels Java- ish). Hope that helps, -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jfouhy at paradise.net.nz Tue May 10 02:50:28 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 10 May 2005 12:50:28 +1200 (NZST) Subject: [Tutor] Any easy way to invoke the default browser on a specified URL? In-Reply-To: References: Message-ID: <1115686228.4280055499460@www.paradise.net.nz> Quoting Terry Carroll : > Is there any way, from within Python, to cause the default browser > (Firefox, in my case) to be invoked with a specific URL? If you're on Win32, try: >>> import win32api >>> win32api.ShellExecute(0, 'open', 'http://www.google.com/', None, '', 1) Parameters in order: - Handle to the parent window (0 for no parent) - Operation to perform (you can also use 'print', and maybe others?) - Name of the file/shortcut to execute - Optional parameters for the new process - Initial directory for the new process - Flag indicating if the new window should be shown or not. [information from Mark Hammond's book] Basically, this does the same thing as double-clicking on the file/shortcut in Windows Explorer. If you're on Linux, I'm not sure. I think different distros / window managers may have different ways of defining things like a default browser, or different ways of getting at them. And I don't know anything about Mac OS X :-) -- John. From carroll at tjc.com Tue May 10 02:57:57 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 9 May 2005 17:57:57 -0700 (PDT) Subject: [Tutor] Any easy way to invoke the default browser on a specified URL? In-Reply-To: <428003F7.5070004@tds.net> Message-ID: On Mon, 9 May 2005, Kent Johnson wrote: > >>> import webbrowser > >>> webbrowser.open("http://www.google.com/") Beautiful; just what I needed. Thanks. From jfouhy at paradise.net.nz Tue May 10 03:19:52 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 10 May 2005 13:19:52 +1200 (NZST) Subject: [Tutor] zip question In-Reply-To: <8daabe5605050917187c5d704d@mail.gmail.com> References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> <1115678613.427fe795a1818@www.paradise.net.nz> <8daabe5605050915591c5800e@mail.gmail.com> <8daabe5605050917187c5d704d@mail.gmail.com> Message-ID: <1115687992.42800c38985c1@www.paradise.net.nz> Quoting "D. Hartley" : > Instances have the following attributes: > > filename, comment, etc. > > > I've tried about ten things to get "filename" to work: > > myzip.filename("99905.txt") (str not callable) Check out the error message: "str not callable". You are trying to call something whose type is "str" --- ie: a string. In python, there is no distinction between callable and noncallable attributes. try: >>> print myzip.filename It should print the filename that this ZipInfo object refers to. Likewise, myzip.comment is a string which is the comment attached to the file in the zip. If you have any background in other languges, it might help you to think of these as "member variables" (or whatever they call them). And a ZipInfo object appears to be similar to a struct in C/C++. I hope this helps. (and if it doesn't, the fault is probably in the explanation, so keep asking, and I (or someone else) will try again :-) ) -- John. From denise.hartley at gmail.com Tue May 10 03:28:54 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Mon, 9 May 2005 18:28:54 -0700 Subject: [Tutor] zip question In-Reply-To: <1115687992.42800c38985c1@www.paradise.net.nz> References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> <1115678613.427fe795a1818@www.paradise.net.nz> <8daabe5605050915591c5800e@mail.gmail.com> <8daabe5605050917187c5d704d@mail.gmail.com> <1115687992.42800c38985c1@www.paradise.net.nz> Message-ID: <8daabe56050509182862a570d4@mail.gmail.com> Hey everyone - I finally got it. Just did a.filename, or a.comment or whatever. I think I was feeling like if it wasnt a method, I couldnt make it display. Then I typed in a.filename, and it popped up "file.txt" right there in the interpreter window and I felt like a big idiot. Why couldn't that have been one of the ten things I tried *before* I sent the email? ha ha. Since this is my first language (re:john's comment), I am still having trouble keeping all the jargon straight - have to remember the differences between functions and methods and attributes and instances and fifteen hundred other words I'm not used to worrying about much ;) Thanks again for all your help everyone, I finally solved the riddle (!!!) and am onto the next one! And here I thought I'd be stuck ;) ~Denise On 5/9/05, jfouhy at paradise.net.nz wrote: > Quoting "D. Hartley" : > > > Instances have the following attributes: > > > > filename, comment, etc. > > > > > > I've tried about ten things to get "filename" to work: > > > > myzip.filename("99905.txt") (str not callable) > > Check out the error message: "str not callable". You are trying to call > something whose type is "str" --- ie: a string. In python, there is no > distinction between callable and noncallable attributes. > > try: > >>> print myzip.filename > It should print the filename that this ZipInfo object refers to. > > Likewise, myzip.comment is a string which is the comment attached to the file in > the zip. > > If you have any background in other languges, it might help you to think of > these as "member variables" (or whatever they call them). And a ZipInfo object > appears to be similar to a struct in C/C++. > > I hope this helps. > (and if it doesn't, the fault is probably in the explanation, so keep asking, > and I (or someone else) will try again :-) ) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Tue May 10 03:29:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 10 May 2005 13:29:00 +1200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: <104202483335.20050509181334@columbus.rr.com> References: <104202483335.20050509181334@columbus.rr.com> Message-ID: Yeah, I was going that way, got a half translation, saw the word 'trans' in the text, went from there. On 5/10/05, R. Alan Monroe wrote: > > > Hi John, took me awhile to solve this one too, it's quite good, teaches > you > > about a part of Python that you wouldn't normally use. > > > Do you want hints or spoilers? > > > I've give hints for now, search the Python docus for 'trans', check the > > string methods. > > You can also do it with a convoluted list comprehension - that's what > I did. > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/ee1ff6f3/attachment.html From cyresse at gmail.com Tue May 10 03:34:38 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 10 May 2005 13:34:38 +1200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: Message-ID: Hmmm... the forums don't overly explain level 3. Am I looking for something like this - XXXjXXX? or something like XjXX or XXjX? I've also looked for - ooXXXoo XXXjXXX ooXXXoo and oooXooo oooXooo oooXooo XXXjXXX oooXooo oooXooo oooXooo Argh. My head is going to explode. On 5/10/05, Roel Schroeven wrote: > > John Carmona wrote: > > > OK I am stuck on this one. I see what I need to do (correct me if I am > > wrong). But I need to write a script that will replace each letter by > > another one (In this case a --> c etc.). I look at String, List and > > Dictionary. I thought I could use the text.replace option but I am not > sure. > > Anybody to put me in the right track. > > There are different ways to do this; IIRC I did it using ord, chr and a > list comprehension. > > Note that there is a forum for hints: > http://www.pythonchallenge.com/forums/ > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/11295d3a/attachment.htm From amonroe at columbus.rr.com Tue May 10 03:47:15 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 9 May 2005 21:47:15 -0400 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: Message-ID: <156215304070.20050509214715@columbus.rr.com> > Am I looking for something like this - > XXXjXXX? or something like XjXX or XXjX? I've also looked for - Take the challenge's hint a little more literally, it's quite specific. This one had me stumped for a little while until I realized my mistake. Alan From cyresse at gmail.com Tue May 10 04:31:28 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 10 May 2005 14:31:28 +1200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: <156215304070.20050509214715@columbus.rr.com> References: <156215304070.20050509214715@columbus.rr.com> Message-ID: Hi all, > Hint: the hint on the screen says "exactly three." -Arcege Hah, yeah, but it also says 'all sides' and that had me following a dead-end for awhile, and something in the challenge hint forums made me think it might be exactly three in total, but surrounding the lowercase letter. i.e. XjXX OK, proceeding down the right direction, I've matched a 477 character string, which apparently means you're doing it wrong, it seems to be a common number. So... how do you use a regex to match AAA but not AAB - ZZZ? I'm trying to use this pattern - (?P[A-Z]{1})(?P=first)(?P=first) and it's not doing it for me. Basically, all I want to do is match anything upper-case, as it as it matches the other letters. This matches '[A-Z]{3}[a-z]{1}[A-Z]{3}' 477 occurences... so I hope that it's all the same letter. But yeah, any help on the regex would be great. Regards, Liam Clarke On 5/10/05, R. Alan Monroe wrote: > > > > Am I looking for something like this - > > > XXXjXXX? or something like XjXX or XXjX? I've also looked for - > > Take the challenge's hint a little more literally, it's quite > specific. This one had me stumped for a little while until I realized > my mistake. > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/827b6e25/attachment.htm From cyresse at gmail.com Tue May 10 04:37:41 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 10 May 2005 14:37:41 +1200 Subject: [Tutor] Fwd: zip question In-Reply-To: References: <8daabe560505071745d62eea1@mail.gmail.com> <8daabe56050509153764ff0737@mail.gmail.com> <1115678613.427fe795a1818@www.paradise.net.nz> <8daabe5605050915591c5800e@mail.gmail.com> <8daabe5605050917187c5d704d@mail.gmail.com> <1115687992.42800c38985c1@www.paradise.net.nz> <8daabe56050509182862a570d4@mail.gmail.com> Message-ID: Gack. List as well. ---------- Forwarded message ---------- From: Liam Clarke Date: May 10, 2005 2:37 PM Subject: Re: [Tutor] zip question To: "D. Hartley" Hi, Then I typed in a.filename, and it popped up "file.txt" > right there in the interpreter window and I felt like a big idiot. Why > couldn't that have been one of the ten things I tried *before* I sent > the email? ha ha. I wouldn't worry, I can guarantee you that you'll always remember about attributes versus methods now. You can call mistakes experience if you learn from them. :) -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/0ed68232/attachment.html From andre.roberge at gmail.com Tue May 10 05:48:24 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Tue, 10 May 2005 00:48:24 -0300 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) Message-ID: Version 0.8.5 of rur-ple has been released. The web site has completely changed; it includes over 35 pages. http://rur-ple.sourceforge.net/ -------------------------------------- Learning to program computer should be fun, for adults and children alike. RUR-PLE is an environment designed to help you learn computer programming using the language Python. To use RUR-PLE, you need wxPython. You can learn more about RUR-PLE or you can go to the download page. ======= Apprendre ? programmer devrait ?tre amusant, que l'on soit un adulte ou un enfant. RUR-PLE est un environnement con?u pour vous aider ? apprendre la programmation informatique avec le langage Python. Pour utiliser RUR-PLE, vous aurez besoin de wxPython. Vous pouvez en apprendre davantage au sujet de RUR-PLE ou vous pouvez aller ? la page de t?l?chargement. From smichr at bigfoot.com Tue May 10 07:02:56 2005 From: smichr at bigfoot.com (Chris Smith) Date: Tue, 10 May 2005 00:02:56 -0500 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: Message-ID: > Am I looking for something like this - > > XXXjXXX? or something like XjXX or XXjX? The former: 3 on each side. Exactly 3. BTW , you can check your understanding by saving the image you get from riddle 6, compressing it with zlib, filtering out all but string.letters and looking for the same pattern as in riddle 2. You should come up with "scdehtinjgu"...but that's a 404 for a web page. /c From erastley at charter.net Tue May 10 01:45:14 2005 From: erastley at charter.net (EUGENE ASTLEY) Date: Mon, 9 May 2005 16:45:14 -0700 Subject: [Tutor] computer screen resolution Message-ID: <000801c554f1$27deede0$6501a8c0@D3K8PT61> I would like to have a full screen for the game I have programmed regardless of the computer users screen resolution. Is their a way from Python or livewires that I can get the info from the computer and then enter it into the global SCREEN_WIDTH and SCREEN_HEIGHT? Gene -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050509/71f9f225/attachment.html From rschroev_nospam_ml at fastmail.fm Tue May 10 09:51:18 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 10 May 2005 09:51:18 +0200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: <156215304070.20050509214715@columbus.rr.com> Message-ID: Liam Clarke wrote: > This matches '[A-Z]{3}[a-z]{1}[A-Z]{3}' 477 occurences... so I hope > that it's all the same letter. You have to many occurences because that regex matches XXXxXXX, but also XXXXXXxXXXXXX. You should only match exactly 3 guards on each side. IIRC I used something like (sadly I threw my code for levels 1 and 2 away): '[^A-Z][A-Z]{3}[a-z]{1}[A-Z]{3}[^A-Z]' -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rschroev_nospam_ml at fastmail.fm Tue May 10 09:57:47 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 10 May 2005 09:57:47 +0200 Subject: [Tutor] Any easy way to invoke the default browser on a specified URL? In-Reply-To: <428003F7.5070004@tds.net> References: <428003F7.5070004@tds.net> Message-ID: Kent Johnson wrote: > Terry Carroll wrote: > >>Is there any way, from within Python, to cause the default browser >>(Firefox, in my case) to be invoked with a specific URL? >> >>I'd like to do something like (totally made-up name and syntax): >> >>OpenBrowser("http://www.google.com/") >> >>and have a new browser window opened up pointing to Google. > > > >>> import webbrowser > >>> webbrowser.open("http://www.google.com/") Splendid! I've been looking for something like that too, but somehow that module escaped my attention. Thanks! -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From cyresse at gmail.com Tue May 10 13:16:40 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 10 May 2005 23:16:40 +1200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: <156215304070.20050509214715@columbus.rr.com> Message-ID: Hi, So... the [^A-Z] limits the [A-Z]{3}?... /me picks at IDLE. Dang, it does. Thanks a bundle, Roel! And I learn a little more about regexes.... :Z Cheers, Liam Clarke On 5/10/05, Roel Schroeven wrote: > > Liam Clarke wrote: > > > This matches '[A-Z]{3}[a-z]{1}[A-Z]{3}' 477 occurences... so I hope > > that it's all the same letter. > > You have to many occurences because that regex matches XXXxXXX, but also > XXXXXXxXXXXXX. You should only match exactly 3 guards on each side. IIRC > I used something like (sadly I threw my code for levels 1 and 2 away): > '[^A-Z][A-Z]{3}[a-z]{1}[A-Z]{3}[^A-Z]' > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/6ffadf23/attachment.htm From cyresse at gmail.com Tue May 10 13:19:44 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 10 May 2005 23:19:44 +1200 Subject: [Tutor] computer screen resolution In-Reply-To: <000801c554f1$27deede0$6501a8c0@D3K8PT61> References: <000801c554f1$27deede0$6501a8c0@D3K8PT61> Message-ID: Is Livewires a game development package? I'm pretty sure pygame can do what you want, it can handle OpenGL if you're into pain. www.pygame.org Plus, it plays MP3's and MPGs easily. :) Regards, Liam Clarke On 5/10/05, EUGENE ASTLEY wrote: > > I would like to have a full screen for the game I have programmed > regardless of the computer users screen resolution. Is their a way from > Python or livewires that I can get the info from the computer and then enter > it into the global SCREEN_WIDTH and SCREEN_HEIGHT? > > Gene > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/5dfc4048/attachment.htm From zvision at gmail.com Tue May 10 13:33:47 2005 From: zvision at gmail.com (ZVision) Date: Tue, 10 May 2005 06:33:47 -0500 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: References: Message-ID: <9910145305051004331fdc9bb0@mail.gmail.com> Hi Roberge, I wanted to give your program a try. Absoluted beginner. But there dont seem to be enough instructions about how to do this. Maybe I am missing something. I have py2.4 installed. I installed the wxPython, then I tried to run start.py from your program. Didnt work. So I opened python and tried run/run module this is what I get IDLE 1.1 >>> ================================ RESTART ================================ >>> Requested version of wxPython not found Can not import wxversion in rur_start.py Will attempt to import existing version of wxPython. Traceback (most recent call last): File "C:\Documents and Settings\Flo\Desktop\rurple0.8.5\RUR_start.py", line 53, in -toplevel- import wx ImportError: No module named wx >>> On 5/9/05, Andr? Roberge wrote: > Version 0.8.5 of rur-ple has been released. > The web site has completely changed; it includes over 35 pages. > http://rur-ple.sourceforge.net/ > > -------------------------------------- > Learning to program computer should be fun, for adults and children > alike. RUR-PLE is an environment designed to help you learn computer > programming using the language Python. To use RUR-PLE, you need > wxPython. You can learn more about RUR-PLE or you can go to the download > page. > SO I check and wxpyton is installed at C:\Python24\Lib\site-packages by the way I installed wxpython ansi for 2.4 Obviously, I dont know what I am doing, but so will most beginners. So maybe some detailed instructions on how to run the program will help.... sorry if I missed it. thanks Zoogie From andre.roberge at gmail.com Tue May 10 14:12:49 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Tue, 10 May 2005 09:12:49 -0300 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: <9910145305051004331fdc9bb0@mail.gmail.com> References: <9910145305051004331fdc9bb0@mail.gmail.com> Message-ID: ZVision wrote: > Hi Roberge, > I wanted to give your program a try. > Absoluted beginner. But there dont seem to be enough instructions > about how to do this. Maybe I am missing something. No, you are quite right. At this stage of development, I still assume that someone with more experience than a total beginner is around to get the program started. My mistake; I'll have to correct that and give detailed instructions. > I have py2.4 installed. I installed the wxPython, then I tried to run > start.py from your program. > Didnt work. > So I opened python and tried run/run module > this is what I get > IDLE 1.1 > >>>>================================ RESTART ================================ >>>> > > Requested version of wxPython not found > Can not import wxversion in rur_start.py > Will attempt to import existing version of wxPython. > > Traceback (most recent call last): > File "C:\Documents and > Settings\Flo\Desktop\rurple0.8.5\RUR_start.py", line 53, in -toplevel- > import wx > ImportError: No module named wx > You probably have a newer version of wxPython than I have myself. I need to install the newest one myself and do some tests with it. I apologize for this. > > > SO I check and wxpyton is installed at C:\Python24\Lib\site-packages > by the way I installed wxpython ansi for 2.4 I will need to check. > > Obviously, I dont know what I am doing, but so will most beginners. So > maybe some detailed instructions on how to run the program will > help.... sorry if I missed it. No need to apologize; the problem is mine. Thanks for trying! Andr? > thanks > Zoogie > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue May 10 14:49:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 May 2005 08:49:53 -0400 Subject: [Tutor] computer screen resolution In-Reply-To: <000801c554f1$27deede0$6501a8c0@D3K8PT61> References: <000801c554f1$27deede0$6501a8c0@D3K8PT61> Message-ID: <4280ADF1.2040103@tds.net> EUGENE ASTLEY wrote: > I would like to have a full screen for the game I have programmed > regardless of the computer users screen resolution. Is their a way from > Python or livewires that I can get the info from the computer and then > enter it into the global SCREEN_WIDTH and SCREEN_HEIGHT? LiveWires is built on PyGame. AFAICT PyGame has support for setting the video resolution and setting full screen mode but not for reading the resolution! These pages may help: http://pygame.org/docs/tut/DisplayModes.html http://pygame.org/docs/ref/pygame_display.html Kent From albertito_g at hotmail.com Tue May 10 15:00:30 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 10 May 2005 13:00:30 +0000 Subject: [Tutor] zip question In-Reply-To: <1115687992.42800c38985c1@www.paradise.net.nz> Message-ID: The problem is that you have to get the content before you can get the filename or comment of the files. You have to do something like this import zipfile file=zipfile.ZipFile("yourfile.zip") f=file.getinfo(name_of_the_file_inside_yourfile.zip) And then you can take the comments and filenames you want with f.comment f.filename Copy and paste without parenthesis. The getinfo part, You have to get the name of the files inside. I did a program to put the name of the files inside the zip in a list and then I looped inisde the list with the commands I'm sending you Regards Alberto >From: jfouhy at paradise.net.nz >To: Python tutor >Subject: Re: [Tutor] zip question >Date: Tue, 10 May 2005 13:19:52 +1200 (NZST) > >Quoting "D. Hartley" : > > > Instances have the following attributes: > > > > filename, comment, etc. > > > > > > I've tried about ten things to get "filename" to work: > > > > myzip.filename("99905.txt") (str not callable) > >Check out the error message: "str not callable". You are trying to call >something whose type is "str" --- ie: a string. In python, there is no >distinction between callable and noncallable attributes. > >try: > >>> print myzip.filename >It should print the filename that this ZipInfo object refers to. > >Likewise, myzip.comment is a string which is the comment attached to the >file in >the zip. > >If you have any background in other languges, it might help you to think of >these as "member variables" (or whatever they call them). And a ZipInfo >object >appears to be similar to a struct in C/C++. > >I hope this helps. >(and if it doesn't, the fault is probably in the explanation, so keep >asking, >and I (or someone else) will try again :-) ) > >-- >John. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From tomcloyd at bestmindhealth.com Tue May 10 17:46:50 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Tue, 10 May 2005 08:46:50 -0700 Subject: [Tutor] output of dictionaries Message-ID: I'm creating a small database using a dictionary of dictionaries, and I want to output it to a file. It seems that only strings can be output to files, and I cannot quite figure out how to quickly and simply convert my dictionary to a list of strings or whatever. Or maybe I'm going about this all wrong. So, the most general form of my question: how can I store a dictionary containing some data records stored as dictionaries - a dictionary of dictionaries - in a file, so I can read it back in later and process its contents? Thank you very much for your generosity in giving some of your time to this service. I'm very grateful. -- t. ====================================================== Tom Cloyd Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com >> ====================================================== Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From jeannot18 at hotmail.com Tue May 10 18:37:15 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 10 May 2005 16:37:15 +0000 Subject: [Tutor] need a example of translate or maketrans In-Reply-To: Message-ID: Terry, thanks very much that was very helpful right at this moment :) This is what beginners like me needs small example that explain very well how to use some of the functions. I found sometimes that the explanation on the book or the documentation going over my head because they don't show a concrete example. Thanks again JC From gsf at panix.com Tue May 10 19:00:46 2005 From: gsf at panix.com (Gabriel Farrell) Date: Tue, 10 May 2005 13:00:46 -0400 Subject: [Tutor] output of dictionaries In-Reply-To: References: Message-ID: <20050510170046.GE8025@panix.com> take a look at pickle and shelve. info about both can be found at http://docs.python.org/lib/python.html On Tue, May 10, 2005 at 08:46:50AM -0700, Tom Cloyd wrote: > I'm creating a small database using a dictionary of dictionaries, and I > want to output it to a file. It seems that only strings can be output to > files, and I cannot quite figure out how to quickly and simply convert my > dictionary to a list of strings or whatever. Or maybe I'm going about this > all wrong. > > So, the most general form of my question: how can I store a dictionary > containing some data records stored as dictionaries - a dictionary of > dictionaries - in a file, so I can read it back in later and process its > contents? > > Thank you very much for your generosity in giving some of your time to > this service. I'm very grateful. > > -- t. > > ====================================================== > Tom Cloyd > Bellingham, Washington, U.S.A: (360) 920-1226 > << BestMindHealth.com >> > ====================================================== > > Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sigurd at 12move.de Tue May 10 19:00:30 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue, 10 May 2005 19:00:30 +0200 Subject: [Tutor] output of dictionaries In-Reply-To: (Tom Cloyd's message of "Tue, 10 May 2005 08:46:50 -0700") References: Message-ID: On 10 Mai 2005, tomcloyd at bestmindhealth.com wrote: > I'm creating a small database using a dictionary of dictionaries, and I > want to output it to a file. It seems that only strings can be output to > files, and I cannot quite figure out how to quickly and simply convert my > dictionary to a list of strings or whatever. Or maybe I'm going about this > all wrong. > So, the most general form of my question: how can I store a dictionary > containing some data records stored as dictionaries - a dictionary of > dictionaries - in a file, so I can read it back in later and process its > contents? You could use the pickle module to serialize and deserialize your data. Here's an example (very simple): . >>> import pickle . >>> d . {1: {2: 3, 3: 4}, 2: {2: 3, 3: 4}, 3: {2: 3, 3: 4}} . >>> f = open("test.pickle", "w") . >>> pickle.dump(d, f) . >>> f.close() . >>> f = open("test.pickle") . >>> d2 = pickle.load(f) . >>> f.close() . >>> d2 == d . True Or take a look at the shelve module; it could be just what you want. Karl -- Please do *not* send copies of replies to me. I read the list From bgailer at alum.rpi.edu Tue May 10 19:34:00 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 10 May 2005 10:34:00 -0700 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: References: Message-ID: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> At 08:48 PM 5/9/2005, Andr? Roberge wrote: >Version 0.8.5 of rur-ple has been released. >The web site has completely changed; it includes over 35 pages. >http://rur-ple.sourceforge.net/ > >-------------------------------------- >Learning to program computer should be fun, for adults and children >alike. RUR-PLE is an environment designed to help you learn computer >programming using the language Python. To use RUR-PLE, you need >wxPython. You can learn more about RUR-PLE or you can go to the download >page. On http://rur-ple.sourceforge.net/en/errors.htm Reeborg appears as Egrebor. I assume that's incorrect. Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/afd565fd/attachment.htm From alan.gauld at freenet.co.uk Tue May 10 19:39:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 10 May 2005 18:39:26 +0100 Subject: [Tutor] Python Challenge - Riddle 2 References: <156215304070.20050509214715@columbus.rr.com> Message-ID: <006d01c55587$36d79090$8dbc8851@xp> > This matches '[A-Z]{3}[a-z]{1}[A-Z]{3}' 477 occurences... Doesn't the {3} mean a minimum of 3? I may be wrong, its not a feature I use much but I thought there was a gotcha with the {} notation that meant you had to provide a terminating character too? Alan G. (Who has only just started on these riddles...) From jeannot18 at hotmail.com Tue May 10 19:52:57 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 10 May 2005 17:52:57 +0000 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: Message-ID: Hey Liam thanks again for the hint. I have finally managed to use the ???trans function. But now "apply it to the URL", I am lost again. (I did apply it to the URL-twice) but nope, nothing is happening. One more hint if possible. Thanks JC From cpu.crazy at gmail.com Tue May 10 20:09:44 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 10 May 2005 12:09:44 -0600 Subject: [Tutor] No Need To Press Enter Message-ID: <6.1.0.6.2.20050510120801.01f50c48@pop.gmail.com> Darn! I get this error: Traceback (most recent call last): File "C:/Python24/saved/tmp1.py", line 1, in -toplevel- if event.key == K_q: NameError: name 'event' is not defined Do I need to import something? @ Denise: I would like to the full code if you don't mind. Date: Wed, 4 May 2005 11:33:53 -0700 From: "D. Hartley" Subject: [Tutor] Fwd: No Need to press Enter (Joseph Quigley) To: Python tutor Message-ID: <8daabe5605050411332f7b1a41 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 I don't know if this is what you're looking for, but in my game I set Running = 1, and then had: if event.key == K_q: running = 0 ... which exits the game as soon as you hit q (i.e., no hitting enter). I can send the full code if it would be more helpful, if this is what you're talking about? ~Denise From bgailer at alum.rpi.edu Tue May 10 19:56:08 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 10 May 2005 10:56:08 -0700 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> References: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> Message-ID: <6.1.2.0.0.20050510105349.00a61d18@pop.sbcglobal.yahoo.com> At 10:34 AM 5/10/2005, Bob Gailer wrote: >At 08:48 PM 5/9/2005, Andr? Roberge wrote: >>Version 0.8.5 of rur-ple has been released. >>The web site has completely changed; it includes over 35 pages. >>http://rur-ple.sourceforge.net/ >> >>-------------------------------------- >>Learning to program computer should be fun, for adults and children >>alike. RUR-PLE is an environment designed to help you learn computer >>programming using the language Python. To use RUR-PLE, you need >>wxPython. You can learn more about RUR-PLE or you can go to the download >>page. > >On http://rur-ple.sourceforge.net/en/beepers.htm is the text "standing >right next to them". This to me is ambiguous; I'd interpret it as one >avenue or street away from the beeper, but I guess you have in mind the >intersection ocupied by the beeper. I suggest rewording this to remove the >ambiguity. > >Bob Gailer >mailto:bgailer at alum.rpi.edu >510 558 3275 home >720 938 2625 cell Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/256385f5/attachment.html From servando at mac.com Tue May 10 20:37:04 2005 From: servando at mac.com (Servando Garcia) Date: Tue, 10 May 2005 13:37:04 -0500 Subject: [Tutor] following the chain Message-ID: <273f44d97bf687cde708a60fa4f384f3@mac.com> Thanks to the many hints from the list I have made it to level four, of the python challenges. Many thanks to all. I truly have been looking for a solid example to follow on the use of the URL module. I don't feel am using it correctly or I am not understanding/using the clue correctly. Here is how I have been trying to use urlopen() import urllib name="some URL" X = urllib.urlopen(name) print X the output of X in very strange to me. I have include the exact output: > Have I used the urlopen() correctly? What is the meaning of the output? From josh.goldie at mirant.com Tue May 10 20:44:01 2005 From: josh.goldie at mirant.com (Goldie, Josh) Date: Tue, 10 May 2005 14:44:01 -0400 Subject: [Tutor] following the chain Message-ID: Try: print X.readline() -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Servando Garcia Sent: Tuesday, May 10, 2005 2:37 PM To: Python help Subject: [Tutor] following the chain Thanks to the many hints from the list I have made it to level four, of the python challenges. Many thanks to all. I truly have been looking for a solid example to follow on the use of the URL module. I don't feel am using it correctly or I am not understanding/using the clue correctly. Here is how I have been trying to use urlopen() import urllib name="some URL" X = urllib.urlopen(name) print X the output of X in very strange to me. I have include the exact output: > Have I used the urlopen() correctly? What is the meaning of the output? _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Tue May 10 20:30:08 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 10 May 2005 11:30:08 -0700 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: Message-ID: <6.1.2.0.0.20050510112919.03665ab0@pop.sbcglobal.yahoo.com> At 10:52 AM 5/10/2005, John Carmona wrote: >Hey Liam thanks again for the hint. I have finally managed to use the >???trans function. But now "apply it to the URL", I am lost again. (I did >apply it to the URL-twice) but nope, nothing is happening. One more hint if >possible. How did you apply the preceding solutions to the URL? Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/a38d25af/attachment.htm From rschroev_nospam_ml at fastmail.fm Tue May 10 21:03:36 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 10 May 2005 21:03:36 +0200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: <006d01c55587$36d79090$8dbc8851@xp> References: <156215304070.20050509214715@columbus.rr.com> <006d01c55587$36d79090$8dbc8851@xp> Message-ID: Alan Gauld wrote: >>This matches '[A-Z]{3}[a-z]{1}[A-Z]{3}' 477 occurences... > > > Doesn't the {3} mean a minimum of 3? It's exactlu equivalent to [A-Z][A-Z][A-Z] > I may be wrong, its not a feature I use much but I thought there was a > gotcha with the {} notation that meant you had to provide a > terminating > character too? If you want to prevent e.g. 'ABCDE' from matching as opposed to only 'BCD', yes, you need some kind of terminator. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rschroev_nospam_ml at fastmail.fm Tue May 10 21:06:16 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 10 May 2005 21:06:16 +0200 Subject: [Tutor] following the chain In-Reply-To: <273f44d97bf687cde708a60fa4f384f3@mac.com> References: <273f44d97bf687cde708a60fa4f384f3@mac.com> Message-ID: Servando Garcia wrote: > Thanks to the many hints from the list I have made it to level four, of > the python challenges. Many thanks to all. > I truly have been looking for a solid example to follow on the use of > the URL module. I don't feel am using it correctly or I am not > understanding/using the clue correctly. > Here is how I have been trying to use urlopen() > > import urllib > name="some URL" > X = urllib.urlopen(name) > print X > > > the output of X in very strange to me. I have include the exact output: > 0x91068>> > Have I used the urlopen() correctly? > What is the meaning of the output? The return value of urlopen is not a string, but a file-like object. You can use it like you would use a file you opened using file() or open(). To get the contents of the page, you can do: X = urllib.urlopen(name).read() That will load the whole page into memory as a string. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From jeannot18 at hotmail.com Tue May 10 21:26:37 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 10 May 2005 19:26:37 +0000 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: <8daabe56050510115037bab19a@mail.gmail.com> Message-ID: This is what I did. I have tried the whole field, part of the URL (after the .com), etc.. I Just get the old 404 not found message. JC From jeannot18 at hotmail.com Tue May 10 21:28:04 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 10 May 2005 19:28:04 +0000 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: <6.1.2.0.0.20050510112919.03665ab0@pop.sbcglobal.yahoo.com> Message-ID: copied the URL, paste it in my script in Python and run it (once) did not get nowhere, then did it a second time, and again did not get nowhere. JC From alan.gauld at freenet.co.uk Tue May 10 21:30:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 10 May 2005 20:30:37 +0100 Subject: [Tutor] Python Challenge - Riddle 2 References: Message-ID: <00af01c55596$bed4a730$8dbc8851@xp> > ???trans function. But now "apply it to the URL", I am lost again. Its not strictly accurate, it means apply it to a section of the address... Alan G. (I'm catching up! All the previous posts help of course :-) From alan.gauld at freenet.co.uk Tue May 10 21:32:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 10 May 2005 20:32:48 +0100 Subject: [Tutor] following the chain References: <273f44d97bf687cde708a60fa4f384f3@mac.com> Message-ID: <00b601c55597$0d24def0$8dbc8851@xp> > import urllib > name="some URL" > X = urllib.urlopen(name) > print X > > the output of X in very strange to me. I have include the exact output: > 0x91068>> The message is the clue. urlopen returms a fileobject. So you treat X like an open file. You have to read() from it to get the data. Alan G. From albertito_g at hotmail.com Tue May 10 21:51:19 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 10 May 2005 19:51:19 +0000 Subject: [Tutor] zip question In-Reply-To: <8daabe5605051010462342d7fd@mail.gmail.com> Message-ID: Great!!!!!!!!!!!Keep it up!!!!!! Now you can help with number 7...............................I hope jejeje Hi everyone I need some pointers to solve number 7. For what I can see on that picture the only hint is the gray line inside the .png drawing, but what can I do with it????????? Just tell me where to start and I will try to get from there Thanks Alberto >From: "D. Hartley" >Reply-To: "D. Hartley" >To: Alberto Troiano >Subject: Re: [Tutor] zip question >Date: Tue, 10 May 2005 10:46:26 -0700 > >Don't worry, I got it :) Thanks, though! > >On 5/10/05, Alberto Troiano wrote: > > The problem is that you have to get the content before you can get the > > filename or comment of the files. > > You have to do something like this > > > > import zipfile > > file=zipfile.ZipFile("yourfile.zip") > > f=file.getinfo(name_of_the_file_inside_yourfile.zip) > > > > And then you can take the comments and filenames you want with > > f.comment > > f.filename > > > > Copy and paste without parenthesis. The getinfo part, You have to get >the > > name of the files inside. > > I did a program to put the name of the files inside the zip in a list >and > > then I looped inisde the list with the commands I'm sending you > > > > Regards > > > > Alberto > > > > >From: jfouhy at paradise.net.nz > > >To: Python tutor > > >Subject: Re: [Tutor] zip question > > >Date: Tue, 10 May 2005 13:19:52 +1200 (NZST) > > > > > >Quoting "D. Hartley" : > > > > > > > Instances have the following attributes: > > > > > > > > filename, comment, etc. > > > > > > > > > > > > I've tried about ten things to get "filename" to work: > > > > > > > > myzip.filename("99905.txt") (str not callable) > > > > > >Check out the error message: "str not callable". You are trying to >call > > >something whose type is "str" --- ie: a string. In python, there is no > > >distinction between callable and noncallable attributes. > > > > > >try: > > > >>> print myzip.filename > > >It should print the filename that this ZipInfo object refers to. > > > > > >Likewise, myzip.comment is a string which is the comment attached to >the > > >file in > > >the zip. > > > > > >If you have any background in other languges, it might help you to >think of > > >these as "member variables" (or whatever they call them). And a >ZipInfo > > >object > > >appears to be similar to a struct in C/C++. > > > > > >I hope this helps. > > >(and if it doesn't, the fault is probably in the explanation, so keep > > >asking, > > >and I (or someone else) will try again :-) ) > > > > > >-- > > >John. > > >_______________________________________________ > > >Tutor maillist - Tutor at python.org > > >http://mail.python.org/mailman/listinfo/tutor > > From rschroev_nospam_ml at fastmail.fm Tue May 10 21:56:17 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 10 May 2005 21:56:17 +0200 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: References: <8daabe56050510115037bab19a@mail.gmail.com> Message-ID: John Carmona wrote: > This is what I did. I have tried the whole field, part of the URL (after the > .com), etc.. I Just get the old 404 not found message. You just need to apply it to the basename of the filename. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From amonroe at columbus.rr.com Tue May 10 22:23:37 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 10 May 2005 16:23:37 -0400 Subject: [Tutor] zip question In-Reply-To: References: Message-ID: <6282286346.20050510162337@columbus.rr.com> > I need some pointers to solve number 7. For what I can see on that picture > the only hint is the gray line inside the .png drawing, but what can I do > with it????????? > Just tell me where to start and I will try to get from there Have you ever learnt about graphics and pixel colors? You know, like red, green and blue combining to make colors and stuff? Alan From denise.hartley at gmail.com Tue May 10 22:45:57 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 10 May 2005 13:45:57 -0700 Subject: [Tutor] zip question In-Reply-To: <6282286346.20050510162337@columbus.rr.com> References: <6282286346.20050510162337@columbus.rr.com> Message-ID: <8daabe560505101345325ec461@mail.gmail.com> I tried to look at the image band by band, but got three grey-scale-looking images (for r, g, and b), and one white one. I have a feeling my clue lies in the latter, but am having a hard time finding examples of how to manipulate that part (trying hard to avoid a spoiler here!) in the documentation. Any pointers? (if anyone can even understand what I'm trying to ask here, ha ha!) ~Denise On 5/10/05, R. Alan Monroe wrote: > > I need some pointers to solve number 7. For what I can see on that picture > > the only hint is the gray line inside the .png drawing, but what can I do > > with it????????? > > Just tell me where to start and I will try to get from there > > Have you ever learnt about graphics and pixel colors? You know, like > red, green and blue combining to make colors and stuff? > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From andre.roberge at gmail.com Tue May 10 21:41:31 2005 From: andre.roberge at gmail.com (Andre Roberge) Date: Tue, 10 May 2005 16:41:31 -0300 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> References: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> Message-ID: <7528bcdd0505101241376e9cd0@mail.gmail.com> On 5/10/05, Bob Gailer wrote: > At 08:48 PM 5/9/2005, Andr? Roberge wrote: [snip] > On http://rur-ple.sourceforge.net/en/errors.htm Reeborg > appears as Egrebor. I assume that's incorrect. > > You are indeed correct. Thank you for pointing this out. Just for a historical note: rur-ple is inspired by GvR which stands for "Guido van Robot". I can not think of a better name for it (kudos to Steve Howell). I struggled to find the right name. Initially, I called the robot "Cleese" (because of his "funny walk" in addition to the Monty Python reference) but that didn't seem right, given the intended audience. Then, I chose the reverse of my last name (which you caught, I hope, the last mention of it). My spouse suggested an anagram of my name instead. This, I assume, led to the following comment on comp.lang.python: "Surrender to Python - Resistance is futile! " I like that :-) Andr? > Bob Gailer > mailto:bgailer at alum.rpi.edu > 510 558 3275 home > 720 938 2625 cell From josh.goldie at mirant.com Tue May 10 22:58:15 2005 From: josh.goldie at mirant.com (Goldie, Josh) Date: Tue, 10 May 2005 16:58:15 -0400 Subject: [Tutor] zip question Message-ID: A shade of gray is made by having r == g == b. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of D. Hartley Sent: Tuesday, May 10, 2005 4:46 PM Cc: tutor at python.org Subject: Re: [Tutor] zip question I tried to look at the image band by band, but got three grey-scale-looking images (for r, g, and b), and one white one. I have a feeling my clue lies in the latter, but am having a hard time finding examples of how to manipulate that part (trying hard to avoid a spoiler here!) in the documentation. Any pointers? (if anyone can even understand what I'm trying to ask here, ha ha!) ~Denise On 5/10/05, R. Alan Monroe wrote: > > I need some pointers to solve number 7. For what I can see on that > > picture the only hint is the gray line inside the .png drawing, but > > what can I do with it????????? > > Just tell me where to start and I will try to get from there > > Have you ever learnt about graphics and pixel colors? You know, like > red, green and blue combining to make colors and stuff? > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From denise.hartley at gmail.com Tue May 10 23:08:32 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 10 May 2005 14:08:32 -0700 Subject: [Tutor] RGB, images In-Reply-To: References: Message-ID: <8daabe5605051014085ec132f3@mail.gmail.com> > A shade of gray is made by having r == g == b. ... so this has nothing to do with masks and transparency? From jeannot18 at hotmail.com Tue May 10 23:11:56 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 10 May 2005 21:11:56 +0000 Subject: [Tutor] Python Challenge - Riddle 2 In-Reply-To: <00af01c55596$bed4a730$8dbc8851@xp> Message-ID: To all thanks I have got it now!!! JC From albertito_g at hotmail.com Wed May 11 01:08:43 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 10 May 2005 23:08:43 +0000 Subject: [Tutor] RGB, images In-Reply-To: <8daabe5605051014085ec132f3@mail.gmail.com> Message-ID: Hey Can you be a little more specific on how to get certain part of the image to analyze????? I managed to split it in all its bands (though I don't know what is that) How can I work only with the gray part?????? Thanks Alberto >From: "D. Hartley" >Reply-To: "D. Hartley" >To: Python tutor >Subject: [Tutor] RGB, images >Date: Tue, 10 May 2005 14:08:32 -0700 > > > A shade of gray is made by having r == g == b. > >... so this has nothing to do with masks and transparency? >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From bgailer at alum.rpi.edu Wed May 11 00:55:01 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 10 May 2005 15:55:01 -0700 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: <7528bcdd0505101241376e9cd0@mail.gmail.com> References: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> <7528bcdd0505101241376e9cd0@mail.gmail.com> Message-ID: <6.1.2.0.0.20050510154424.0382fce8@pop.sbcglobal.yahoo.com> At 12:41 PM 5/10/2005, Andre Roberge wrote: >On 5/10/05, Bob Gailer wrote: > > At 08:48 PM 5/9/2005, Andr? Roberge wrote: > >[snip] > > > > On http://rur-ple.sourceforge.net/en/errors.htm Reeborg > > appears as Egrebor. I assume that's incorrect. > > > > >You are indeed correct. Thank you for pointing this out. > >Just for a historical note: rur-ple is inspired by GvR which stands >for "Guido van Robot". I can not think of a better name for it (kudos >to Steve Howell). Any allusion to - RUR Rossums Universal Robots by Karel Capek 1920 >[snip] Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050510/a9c59ab6/attachment.htm From denise.hartley at gmail.com Wed May 11 02:10:12 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 10 May 2005 17:10:12 -0700 Subject: [Tutor] yep, still on python challenges Message-ID: <8daabe56050510171054a32d93@mail.gmail.com> To avoid spoilers: Riddle 7, I've got an 87-item long data structure. Any hints on what to do with it? From singingxduck at gmail.com Wed May 11 02:18:18 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Tue, 10 May 2005 20:18:18 -0400 Subject: [Tutor] Python Challenge Level 6 Message-ID: <3449428f05051017186e89bffc@mail.gmail.com> Hello all, First and foremost, for those who don't know, www.pythonchallenge.com is a set of python-related riddles. Now, for those who are past level six, any sort of hint would be appreciated. Right now, all I know is what module to use (i think) and that I have to somehow use it on channel.jpg . . . I have no idea how to do this. The module I think I'm supposed to use is ********, which I derived from the comment in the source of the page and the presence of a certain object in the picture. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From cyresse at gmail.com Wed May 11 02:36:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 11 May 2005 12:36:31 +1200 Subject: [Tutor] following the chain In-Reply-To: <00b601c55597$0d24def0$8dbc8851@xp> References: <273f44d97bf687cde708a60fa4f384f3@mac.com> <00b601c55597$0d24def0$8dbc8851@xp> Message-ID: While we're on challenge 4, I assume a linked list is important. Can anyone point me at a good introduction to linked lists? Oh, and Servando - I use urllib like this - >>>import urllib >>>opener = urllib.URLopener() >>> page = opener.open('http://www.google.co.nz') >>> pageData = page.read() With urllib (& urllib2) you can add some fancy stuff to the basic URLopener object, including cookie handling. Regards, Liam Clarke On 5/11/05, Alan Gauld wrote: > > > import urllib > > name="some URL" > > X = urllib.urlopen(name) > > print X > > > > the output of X in very strange to me. I have include the exact > output: > > > 0x91068>> > > The message is the clue. urlopen returms a fileobject. So you > treat X like an open file. You have to read() from it to get > the data. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/45372185/attachment.html From andre.roberge at gmail.com Wed May 11 02:36:20 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Tue, 10 May 2005 21:36:20 -0300 Subject: [Tutor] [ANN] new version of rur-ple (0.8.5) In-Reply-To: <6.1.2.0.0.20050510154424.0382fce8@pop.sbcglobal.yahoo.com> References: <6.1.2.0.0.20050510103251.0383f188@pop.sbcglobal.yahoo.com> <7528bcdd0505101241376e9cd0@mail.gmail.com> <6.1.2.0.0.20050510154424.0382fce8@pop.sbcglobal.yahoo.com> Message-ID: Bob Gailer wrote: > At 12:41 PM 5/10/2005, Andre Roberge wrote: > >> On 5/10/05, Bob Gailer wrote: >> > At 08:48 PM 5/9/2005, Andr? Roberge wrote: >> >> [snip] >> >> >> > On http://rur-ple.sourceforge.net/en/errors.htm Reeborg >> > appears as Egrebor. I assume that's incorrect. >> > >> > >> You are indeed correct. Thank you for pointing this out. >> >> Just for a historical note: rur-ple is inspired by GvR which stands >> for "Guido van Robot". I can not think of a better name for it (kudos >> to Steve Howell). > > > Any allusion to - RUR Rossums Universal Robots by Karel Capek 1920 > Actually, yes. I just forgot to mention it. In the play by Capek, Rossum is a mad scientist, unlike Guido (right?). [Aside: I can swear I saw (but can't find it after googling for 30 minutes) that the original play in Czech was known by its acronym RUR where the "U" did not stand for "universal". However, the English translation, which everyone seems to remember, retained the RUR acronym.] So, the "RUR" was also inspired from the original play by Capek. And I made sure I could use the same acronym in both English and French in RUR-PLE (English; in French it would be RUR: EAP :-) (le Robot Usag? de Roberge) ( Roberge's Used Robot ) >> [snip] > > Bob Gailer > mailto:bgailer at alum.rpi.edu > 510 558 3275 home > 720 938 2625 cell > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jfouhy at paradise.net.nz Wed May 11 03:17:40 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 11 May 2005 13:17:40 +1200 (NZST) Subject: [Tutor] following the chain In-Reply-To: References: <273f44d97bf687cde708a60fa4f384f3@mac.com> <00b601c55597$0d24def0$8dbc8851@xp> Message-ID: <1115774260.42815d34c532d@www.paradise.net.nz> Quoting Liam Clarke : > While we're on challenge 4, I assume a linked list is important. Can > anyone point me at a good introduction to linked lists? A linked list, at a high level, is a data structure made of "nodes", where each node contains some data and a pointer to the next node. Here is a really simple python example: >>> class Node: ... pass ... >>> root = Node() >>> root.value = "Start" >>> n = root >>> for i in range(10): ... n.next = Node() ... n.next.value = str(i) ... n = n.next ... else: ... n.next = None ... >>> # We now have a linked list starting at root. ... >>> n = root >>> while n != None: ... print n.value ... n = n.next ... Start 0 1 2 3 4 5 6 7 8 9 >>> Of course, the pointer to the next node could be anything; as long as your program logic knows how to use it to get to the next node. One of the advantages linked lists have over arrays in languages like C++ is that they can be as big as you like, whereas arrays are created with a fixed side. But python lists don't have that problem, so they're a lot less useful here... -- John. From cyresse at gmail.com Wed May 11 03:19:17 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 11 May 2005 13:19:17 +1200 Subject: [Tutor] computer screen resolution In-Reply-To: <000001c55584$6d5ecaa0$6501a8c0@D3K8PT61> References: <000001c55584$6d5ecaa0$6501a8c0@D3K8PT61> Message-ID: If it's built on pygame then the following should work - >From http://www.pygame.org/docs/tut/DisplayModes.html *pygame.display.list_modes(depth, flags)* Returns a list of supported display modes with the requested depth and flags. An empty list is returned when there are no modes. The flags argument defaults to FULLSCREEN. If you specify your own flags without FULLSCREEN, you will likely get a return value of -1. This means that any display size is fine, since the display will be windowed. Note that the listed modes are sorted largest to smallest. But, I think this'll solve your problem, using the following command you can always set fullscreen. You should be able to just use - >>>import pygame >>>pygame.display.list_modes(16) #Does it handle 16 bit? Oh, and OpenGL is hardware rendering, supposedly faster on some systems, but far slower to work with. Blitting with it is a bitch, quite frankly. pygame.display.toggle_fullscreen() -> bool Tells the window manager (if available) to switch between windowed and fullscreen mode. If available and successfull, will return true. Note, there is currently limited platform support for this call. On 5/11/05, EUGENE ASTLEY wrote: > > Yes, livewires is a pygame wrapper to make pygame easier for the novice > to use, such as me. I just want to have my game operate on PC's using XP. I > don't want to ask the user to input his resolution, even though I know how > to program this method. > > I appreciate your comment but being a novice at programming I don't know > what an openGL means although I can guess. I can't find anyplace that lets > me look at the list of operating commands available for use and the syntax > required to use them in pygame. > > Gene Astley > > -----Original Message----- > *From:* Liam Clarke [mailto:cyresse at gmail.com] > *Sent:* Tuesday, May 10, 2005 4:20 AM > *To:* EUGENE ASTLEY; tutor at python.org > *Subject:* Re: [Tutor] computer screen resolution > > Is Livewires a game development package? I'm pretty sure pygame can do > what you want, it can handle OpenGL if you're into pain. > > www.pygame.org > > Plus, it plays MP3's and MPGs easily. :) > > Regards, > > Liam Clarke > > On 5/10/05, *EUGENE ASTLEY* wrote: > > I would like to have a full screen for the game I have programmed > regardless of the computer users screen resolution. Is their a way from > Python or livewires that I can get the info from the computer and then enter > it into the global SCREEN_WIDTH and SCREEN_HEIGHT? > > Gene > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/8a662d1d/attachment.htm From cyresse at gmail.com Wed May 11 04:49:39 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 11 May 2005 14:49:39 +1200 Subject: [Tutor] computer screen resolution In-Reply-To: <001801c555cd$ef5e04a0$6501a8c0@D3K8PT61> References: <001801c555cd$ef5e04a0$6501a8c0@D3K8PT61> Message-ID: I see where you're coming from... Yes, depth refers to 32bit/16bit etc. the flags are documented, but default to fullscreen. So... pygame.display.list_modes(32) will return a list of all possible screen sizes with 32bit colour depth, like so - >>> import pygame.display >>> pygame.display.init() #Need to do this first >>> pygame.display.list_modes(32) [(1152, 720), (800, 600), (1280, 1024), (1280, 960), (1280, 800), (1280, 768), (1280, 720), (1152, 864), (1024, 768), (960, 600), (848, 480), (800, 600), (720, 576), (720, 480), (640, 480), (640, 400), (512, 384), (480, 360), (400, 300), (320, 240), (320, 200), (640, 480)] And then you can have your images saved for different res's, like this - ./images/1024768/foo.jpg ./images/1024768/bar.jpg ./images/800600/foo.jpg ./images/800600/bar.jpg and do something like - >>>import pygame >>>import os >>> pygame.display.init() #Initialise display interface >>> modes = pygame.display.list_modes(32) >>>if (1024, 768) in modes: ... imageSet = './images/1024768/' ... pygame.display.set_mode((1024,768)) ... elif (800, 600) in modes: ... imageSet = './images/800600/ ... pygame.display.set_mode((800,600)) >>> images = ['foo.jpg','bar.jpg'] >>> files = [os.join(imageSet, filename) for filename in images] #assuming 1024x768 was available. >>>print files ['./images/1024768/foo.jpg', './images/1024768/bar.jpg'] So basically my point can be summarised as - You can query the systems available resolutions for a given colour depth, FULLSCREEN is default, so any returned res's can run fullscreen. Decide what resolutions you want to support, 1024x768 & 800x600 are 90% of people, 1280x1024 is also popular with big monitors, you could do 640x400 for backwards compatibility. Then - - Have appropriately sized images for each supported res - Query the available res's - Depending on what's available, set your desired resolution. (Or, have it as an option for the user) - Display your images. You can query the current res on Windows, but it involves the win32com package, and far more esoteric ActiveX/COM interface manipulations, the way described above is far simpler. I hope that helps. Follow the pygame tutorials and docs, and you should be right. Pygame is very powerful. http://www.pygame.org/docs/tut/DisplayModes.html Regards, Liam Clarke On 5/11/05, EUGENE ASTLEY wrote: > > Thank you. I intend to fill the background screen by brining in a jpg > file. If I know the size of the screen, I will know what size jpg file to > import. > > However, what does depth and flags refer to? Does depth refer to 32 bit > resolution? Still not clear how I get the values of the width and height > resolution being used. > > Gene > > -----Original Message----- > *From:* Liam Clarke [mailto:cyresse at gmail.com] > *Sent:* Tuesday, May 10, 2005 6:19 PM > *To:* EUGENE ASTLEY; tutor at python.org > *Subject:* Re: [Tutor] computer screen resolution > > If it's built on pygame then the following should work - > > From http://www.pygame.org/docs/tut/DisplayModes.html > > *pygame.display.list_modes(depth, flags)* > > Returns a list of supported display modes with the requested depth and > flags. An empty list is returned when there are no modes. The flags argument > defaults to FULLSCREEN. If you specify your own flags without FULLSCREEN, > you will likely get a return value of -1. This means that any display size > is fine, since the display will be windowed. Note that the listed modes are > sorted largest to smallest. > > > But, I think this'll solve your problem, using the following command you > can always set fullscreen. You should be able to just use - > > >>>import pygame > >>>pygame.display.list_modes(16) #Does it handle 16 bit? > Oh, and OpenGL is hardware rendering, supposedly faster on some systems, > but far slower to work with. > Blitting with it is a bitch, quite frankly. > > pygame.display.toggle_fullscreen() -> bool > > Tells the window manager (if available) to switch between windowed and > fullscreen mode. If available and successfull, will return true. Note, there > is currently limited platform support for this call. > > On 5/11/05, *EUGENE ASTLEY* wrote: > > Yes, livewires is a pygame wrapper to make pygame easier for the novice to > use, such as me. I just want to have my game operate on PC's using XP. I > don't want to ask the user to input his resolution, even though I know how > to program this method. > > I appreciate your comment but being a novice at programming I don't know > what an openGL means although I can guess. I can't find anyplace that lets > me look at the list of operating commands available for use and the syntax > required to use them in pygame. > > Gene Astley > > -----Original Message----- > *From:* Liam Clarke [mailto:cyresse at gmail.com] > *Sent:* Tuesday, May 10, 2005 4:20 AM > *To:* EUGENE ASTLEY; tutor at python.org > *Subject:* Re: [Tutor] computer screen resolution > > Is Livewires a game development package? I'm pretty sure pygame can do > what you want, it can handle OpenGL if you're into pain. > > www.pygame.org > > Plus, it plays MP3's and MPGs easily. :) > > Regards, > > Liam Clarke > > On 5/10/05, *EUGENE ASTLEY* < erastley at charter.net> wrote: > > I would like to have a full screen for the game I have programmed > regardless of the computer users screen resolution. Is their a way from > Python or livewires that I can get the info from the computer and then enter > it into the global SCREEN_WIDTH and SCREEN_HEIGHT? > > Gene > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/19fe5d21/attachment.html From cyresse at gmail.com Wed May 11 04:50:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 11 May 2005 14:50:52 +1200 Subject: [Tutor] at a loss: python challenge In-Reply-To: References: Message-ID: Which challenge? If it's number 4, I've not done that one yet. Regards, Liam Clarke On 5/11/05, Servando Garcia wrote: > > Thanks for the advice on how to use url. I have been following the > links in the pages but as of yet have not had any luck. > Any hints? > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/9fef8307/attachment.htm From cyresse at gmail.com Wed May 11 08:23:08 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 11 May 2005 18:23:08 +1200 Subject: [Tutor] python challenges In-Reply-To: <1A6D80F1-1E7B-47BC-ACD9-0720D64B90DF@yahoo.fr> References: <8daabe560505071250535cce9b@mail.gmail.com> <1A6D80F1-1E7B-47BC-ACD9-0720D64B90DF@yahoo.fr> Message-ID: Ack, banner.p eh? Can anyone explain the significance of the numbers? Are they columns? Regards, Liam Clarke On 5/8/05, Max Noel wrote: > > > On May 7, 2005, at 20:50, D. Hartley wrote: > > > Ok, I hate to ask another question about this riddle. But I have > > looked and looked and looked. > > > > Where can I find more information on 'banner'? Everywhere I look it > > starts telling me about banner ads and so on, and that is not what I > > want! > > > > The banner in question is the UNIX program "banner". Try running > a search on "UNIX +banner". Also, the theory of Run-Length Encoding > may come in handy for this part of the challenge. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/769af1eb/attachment.htm From rschroev_nospam_ml at fastmail.fm Wed May 11 09:47:38 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 11 May 2005 09:47:38 +0200 Subject: [Tutor] Python Challenge Level 6 In-Reply-To: <3449428f05051017186e89bffc@mail.gmail.com> References: <3449428f05051017186e89bffc@mail.gmail.com> Message-ID: Orri Ganel wrote: > Hello all, > > First and foremost, for those who don't know, www.pythonchallenge.com > is a set of python-related riddles. Now, for those who are past level > six, any sort of hint would be appreciated. Right now, all I know is > what module to use (i think) and that I have to somehow use it on > channel.jpg . . . I have no idea how to do this. The module I think > I'm supposed to use is ********, which I derived from the comment in > the source of the page and the presence of a certain object in the > picture. You need to apply that module, but not to the jpeg. Find the zip first!! -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From kent37 at tds.net Wed May 11 11:04:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 May 2005 05:04:38 -0400 Subject: [Tutor] Python Challenge Level 6 In-Reply-To: References: <3449428f05051017186e89bffc@mail.gmail.com> Message-ID: <4281CAA6.9050403@tds.net> I'm stuck on 6 too. I found the comments but I can't make any sense of them. Any hints? Kent Roel Schroeven wrote: > Orri Ganel wrote: > > >>Hello all, >> >>First and foremost, for those who don't know, www.pythonchallenge.com >>is a set of python-related riddles. Now, for those who are past level >>six, any sort of hint would be appreciated. Right now, all I know is >>what module to use (i think) and that I have to somehow use it on >>channel.jpg . . . I have no idea how to do this. The module I think >>I'm supposed to use is ********, which I derived from the comment in >>the source of the page and the presence of a certain object in the >>picture. > > > You need to apply that module, but not to the jpeg. Find the zip first!! > From maxnoel_fr at yahoo.fr Wed May 11 12:19:24 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed, 11 May 2005 11:19:24 +0100 Subject: [Tutor] python challenges In-Reply-To: References: <8daabe560505071250535cce9b@mail.gmail.com> <1A6D80F1-1E7B-47BC-ACD9-0720D64B90DF@yahoo.fr> Message-ID: On May 11, 2005, at 07:23, Liam Clarke wrote: > Ack, banner.p eh? > > Can anyone explain the significance of the numbers? Are they columns? > > Regards, > > > Liam Clarke As I said, read about Run-Length Encoding. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From feziwe at sanbi.ac.za Wed May 11 14:50:02 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Wed, 11 May 2005 14:50:02 +0200 Subject: [Tutor] help Message-ID: <4281FF7A.8060404@sanbi.ac.za> hi i'm trying to extend a list program by adding a test, problem is after getting the menu of taking the test i can't seem to get the test running i.e viewing of questions and answers. here's what i tried to do menu_item = 0 list = [] while menu_item !=9: print "---------------------" print "1. print the questions" print "2. take the test" print "3. quit" menu_item = input("pick an item from the menu: ") if menu_item == 1: current = 0 if len(list) > 0: while current < len(list): print current,".",list[current] current = current > 0 else: print "list is empty" elif menu_item == 2: current = raw_input("do you want to take a test: ") list.append(list) else: print[["what is the third month of the year?" , "march"], ["who is the president of south africa" , "Thabo"], ["whos birthday is it today" , "Allank"], ["which day comes after a friday" , "saturday"]] true = 0 false = 1 def get_questions(): return [["what is the third month of the year?" , "march"], ["who is the president of south africa" , "Thabo"], ["whos birthday is it today" , "Allank"], ["which day comes after a friday" , "saturday"]] def check_question(question_and_answer): question = question_and_answer[0] answer = question_and_answer[1] given_answer = raw_input(question) if answer == given_answer: print "Good" return true else: print "incorrect, correct was:",answer return false def run_test(questions): if len(questions) == 1: print "No questions were given." return index = 0 right = 0 while index < len(questions): if check_question(question[index]): right = right + 1 index = index + 1 print "you got ",right*100/len(questions),"%right out of",len(questions) run_test(get_questions) From rschroev_nospam_ml at fastmail.fm Wed May 11 13:30:43 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 11 May 2005 13:30:43 +0200 Subject: [Tutor] Python Challenge Level 6 In-Reply-To: <4281CAA6.9050403@tds.net> References: <3449428f05051017186e89bffc@mail.gmail.com> <4281CAA6.9050403@tds.net> Message-ID: Kent Johnson wrote: > I'm stuck on 6 too. I found the comments but I can't make any sense of them. Any hints? I'm sorry, I can't make it any clearer without giving it away. Maybe you can try to search the forum (http://www.pythonchallenge.com/forums) for more clues. > > Kent > > Roel Schroeven wrote: > >>Orri Ganel wrote: >> >> >> >>>Hello all, >>> >>>First and foremost, for those who don't know, www.pythonchallenge.com >>>is a set of python-related riddles. Now, for those who are past level >>>six, any sort of hint would be appreciated. Right now, all I know is >>>what module to use (i think) and that I have to somehow use it on >>>channel.jpg . . . I have no idea how to do this. The module I think >>>I'm supposed to use is ********, which I derived from the comment in >>>the source of the page and the presence of a certain object in the >>>picture. >> >> >>You need to apply that module, but not to the jpeg. Find the zip first!! >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From sunyong.jin at gmail.com Wed May 11 14:08:50 2005 From: sunyong.jin at gmail.com (Evi Wyns) Date: Wed, 11 May 2005 14:08:50 +0200 Subject: [Tutor] Tutor Digest, Vol 15, Issue 30 In-Reply-To: References: Message-ID: So? What do you have to do exactly. I just opened the 'challenge me'. But I don't see what they expect me to do now? I mean... where do you have to write the sollution if you find it? -Evi On 5/11/05, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > > 1. Re: Python Challenge Level 6 (Roel Schroeven) > 2. Re: Python Challenge Level 6 (Kent Johnson) > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 11 May 2005 09:47:38 +0200 > From: Roel Schroeven > Subject: Re: [Tutor] Python Challenge Level 6 > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii; format=flowed > > Orri Ganel wrote: > > > Hello all, > > > > First and foremost, for those who don't know, www.pythonchallenge.com > > is a set of python-related riddles. Now, for those who are past level > > six, any sort of hint would be appreciated. Right now, all I know is > > what module to use (i think) and that I have to somehow use it on > > channel.jpg . . . I have no idea how to do this. The module I think > > I'm supposed to use is ********, which I derived from the comment in > > the source of the page and the presence of a certain object in the > > picture. > > You need to apply that module, but not to the jpeg. Find the zip first!! > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven > > ------------------------------ > > Message: 2 > Date: Wed, 11 May 2005 05:04:38 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Python Challenge Level 6 > Cc: tutor at python.org > Message-ID: <4281CAA6.9050403 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > I'm stuck on 6 too. I found the comments but I can't make any sense of > them. Any hints? > > Kent > > Roel Schroeven wrote: > > Orri Ganel wrote: > > > > > >>Hello all, > >> > >>First and foremost, for those who don't know, www.pythonchallenge.com > >>is a set of python-related riddles. Now, for those who are past level > >>six, any sort of hint would be appreciated. Right now, all I know is > >>what module to use (i think) and that I have to somehow use it on > >>channel.jpg . . . I have no idea how to do this. The module I think > >>I'm supposed to use is ********, which I derived from the comment in > >>the source of the page and the presence of a certain object in the > >>picture. > > > > > > You need to apply that module, but not to the jpeg. Find the zip first!! > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > End of Tutor Digest, Vol 15, Issue 30 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/081f077c/attachment.htm From tktucker at gmail.com Wed May 11 14:50:47 2005 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 11 May 2005 08:50:47 -0400 Subject: [Tutor] Python sort with a delimiter Message-ID: <2a278ffe05051105503e18a17e@mail.gmail.com> Good morning! Does Python have a sort function thats supports a delimiter? For example, I want to sort the below hostnames, based on the city. Thanks! Tom Hostnames to be sorted ------------------------------------- sys01-xxx-austin-tx sys02-xxx-austin-tx sys01-yyy-austin-tx sys01-xxx-newark-oh sys01-yyy-newark-oh sys01-zzz-newark-oh sys02-zzz-newark-oh Unwanted Sorted Output ----------------------- >>> hostnames = ['sys01-xxx-austin-tx','sys02-xxx-austin-tx','sys01-yyy-austin-tx','sys01-xxx-newark-oh','sys01-yyy-newark-oh','sys01-zzz-newark-oh','sys02-zzz-newark-oh'] >>> hostnames.sort() >>> hostnames ['sys01-xxx-austin-tx', 'sys01-xxx-newark-oh', 'sys01-yyy-austin-tx', 'sys01-yyy-newark-oh', 'sys01-zzz-newark-oh', 'sys02-xxx-austin-tx', 'sys02-zzz-newark-oh'] Successful Unix Sort Command ? Can Python do something like this ? ------------------------------------------------ ~ >sort -t '-' -k3 /tmp/hostnames sys01-xxx-austin-tx sys01-yyy-austin-tx sys02-xxx-austin-tx sys01-xxx-newark-oh sys01-yyy-newark-oh sys01-zzz-newark-oh sys02-zzz-newark-oh From josh.goldie at mirant.com Wed May 11 15:04:07 2005 From: josh.goldie at mirant.com (Goldie, Josh) Date: Wed, 11 May 2005 09:04:07 -0400 Subject: [Tutor] RGB, images Message-ID: Try using getdata() on the Image: im = Image.open("oxygen.png") im.load() d = im.getdata() print list(d) That will give you a list of the form: [(r,g,b,a), (r,g,b,a)... ] Where r=red, g=green, b=blue, and a=alpha. When r==g==b, you have a gray pixel. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Alberto Troiano Sent: Tuesday, May 10, 2005 7:09 PM To: denise.hartley at gmail.com Cc: tutor at python.org Subject: Re: [Tutor] RGB, images Hey Can you be a little more specific on how to get certain part of the image to analyze????? I managed to split it in all its bands (though I don't know what is that) How can I work only with the gray part?????? Thanks Alberto >From: "D. Hartley" >Reply-To: "D. Hartley" >To: Python tutor >Subject: [Tutor] RGB, images >Date: Tue, 10 May 2005 14:08:32 -0700 > > > A shade of gray is made by having r == g == b. > >... so this has nothing to do with masks and transparency? >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Wed May 11 15:09:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 May 2005 09:09:15 -0400 Subject: [Tutor] Python sort with a delimiter In-Reply-To: <2a278ffe05051105503e18a17e@mail.gmail.com> References: <2a278ffe05051105503e18a17e@mail.gmail.com> Message-ID: <428203FB.7020401@tds.net> Tom Tucker wrote: > Good morning! Does Python have a sort function thats supports a delimiter? > For example, I want to sort the below hostnames, based on the city. This is easy to do in Python but you have to break it up into a few steps - Python's sort doesn't know how to find fields but you can break the text into fields yourself, then sort on the desired field. Here is one way: import operator hostnames = '''sys01-xxx-austin-tx sys02-xxx-austin-tx sys01-xxx-newark-oh sys01-yyy-newark-oh sys01-yyy-austin-tx sys01-zzz-newark-oh sys02-zzz-newark-oh'''.split() # Create a list of field lists by splitting on the first two '-' fieldData = [ line.split('-', 2) for line in hostnames ] # The key parameter must be a function that returns the key # value from a list item. # operator.itemgetter creates a function that accesses the desired index fieldData.sort(key=operator.itemgetter(2)) # Put the fields back together and print for line in fieldData: print '-'.join(line) Kent From tktucker at gmail.com Wed May 11 15:36:57 2005 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 11 May 2005 09:36:57 -0400 Subject: [Tutor] Python sort with a delimiter In-Reply-To: <428203FB.7020401@tds.net> References: <2a278ffe05051105503e18a17e@mail.gmail.com> <428203FB.7020401@tds.net> Message-ID: <2a278ffe05051106367a608671@mail.gmail.com> Interesting! Thank you! On 5/11/05, Kent Johnson wrote: > Tom Tucker wrote: > > Good morning! Does Python have a sort function thats supports a delimiter? > > For example, I want to sort the below hostnames, based on the city. > > This is easy to do in Python but you have to break it up into a few steps - Python's sort doesn't > know how to find fields but you can break the text into fields yourself, then sort on the desired > field. Here is one way: > > import operator > > hostnames = '''sys01-xxx-austin-tx > sys02-xxx-austin-tx > sys01-xxx-newark-oh > sys01-yyy-newark-oh > sys01-yyy-austin-tx > sys01-zzz-newark-oh > sys02-zzz-newark-oh'''.split() > > # Create a list of field lists by splitting on the first two '-' > fieldData = [ line.split('-', 2) for line in hostnames ] > > # The key parameter must be a function that returns the key > # value from a list item. > # operator.itemgetter creates a function that accesses the desired index > fieldData.sort(key=operator.itemgetter(2)) > > # Put the fields back together and print > for line in fieldData: > print '-'.join(line) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed May 11 15:42:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 May 2005 09:42:27 -0400 Subject: [Tutor] Python sort with a delimiter In-Reply-To: <428203FB.7020401@tds.net> References: <2a278ffe05051105503e18a17e@mail.gmail.com> <428203FB.7020401@tds.net> Message-ID: <42820BC3.2020901@tds.net> A more direct approach is to write a helper function that extracts the desired data from a field, and use that as the sort key: hostnames = '''sys01-xxx-austin-tx sys02-xxx-austin-tx sys01-xxx-newark-oh sys01-yyy-newark-oh sys01-yyy-austin-tx sys01-zzz-newark-oh sys02-zzz-newark-oh'''.split() def getCity(hostName): return hostName.split('-', 2)[-1] hostnames.sort(key=getCity) for line in hostnames: print line Kent Kent Johnson wrote: > Tom Tucker wrote: > >>Good morning! Does Python have a sort function thats supports a delimiter? >>For example, I want to sort the below hostnames, based on the city. > > > This is easy to do in Python but you have to break it up into a few steps - Python's sort doesn't > know how to find fields but you can break the text into fields yourself, then sort on the desired > field. Here is one way: > > import operator > > hostnames = '''sys01-xxx-austin-tx > sys02-xxx-austin-tx > sys01-xxx-newark-oh > sys01-yyy-newark-oh > sys01-yyy-austin-tx > sys01-zzz-newark-oh > sys02-zzz-newark-oh'''.split() > > # Create a list of field lists by splitting on the first two '-' > fieldData = [ line.split('-', 2) for line in hostnames ] > > # The key parameter must be a function that returns the key > # value from a list item. > # operator.itemgetter creates a function that accesses the desired index > fieldData.sort(key=operator.itemgetter(2)) > > # Put the fields back together and print > for line in fieldData: > print '-'.join(line) > > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From count0.djd at gmail.com Wed May 11 15:43:03 2005 From: count0.djd at gmail.com (David Driver) Date: Wed, 11 May 2005 09:43:03 -0400 Subject: [Tutor] Debian install problems. Message-ID: <22803ae20505110643260700e2@mail.gmail.com> I don't know is this is the proper place to post this but I need some help. I am running Damn Small Linux at the moment. I enabled apt-get and adjusted the list file to use the testing branch so I could install python2.4. The apt-get went fine, I think. I didn't get and errors. When I went to install quixote from a distutils package I received the following error: root at box:~# cd /home/dsl/Quixote-2.0 root at box:~/Quixote-2.0# python2.4 setup.py install running install error: invalid Python installation: unable to open /usr/lib/python2.4/config/Makefile (No such file or directory) Does anyone have any Idea where I should go from here? I have tried other distutills installs with the same results. Any help is appreciated. Thanks! -- *********************************** See there, that wasn't so bad. *********************************** From cyresse at gmail.com Wed May 11 17:12:12 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 12 May 2005 03:12:12 +1200 Subject: [Tutor] python challenges In-Reply-To: References: <8daabe560505071250535cce9b@mail.gmail.com> <1A6D80F1-1E7B-47BC-ACD9-0720D64B90DF@yahoo.fr> Message-ID: Oops, missed that. Cheers. On 5/11/05, Max Noel wrote: > > > On May 11, 2005, at 07:23, Liam Clarke wrote: > > > Ack, banner.p eh? > > > > Can anyone explain the significance of the numbers? Are they columns? > > > > Regards, > > > > > > Liam Clarke > > As I said, read about Run-Length Encoding. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050512/9e6b3550/attachment.htm From johnp at milwaukielumber.com Wed May 11 17:18:59 2005 From: johnp at milwaukielumber.com (John Purser) Date: Wed, 11 May 2005 08:18:59 -0700 Subject: [Tutor] Debian install problems. In-Reply-To: <22803ae20505110643260700e2@mail.gmail.com> Message-ID: <200505111518.j4BFIxCV013760@email.morseintranet.com> David, If you don't get an answer here on tutor.python.org then you might want to try: http://www.debian.org/MailingLists/ - where you'll find a link to http://lists.debian.org/debian-python/ - the mailing list for debian-python. Don't forget to search the archives. John Purser -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of David Driver Sent: Wednesday, May 11, 2005 06:43 To: tutor at python.org Subject: [Tutor] Debian install problems. I don't know is this is the proper place to post this but I need some help. I am running Damn Small Linux at the moment. I enabled apt-get and adjusted the list file to use the testing branch so I could install python2.4. The apt-get went fine, I think. I didn't get and errors. When I went to install quixote from a distutils package I received the following error: root at box:~# cd /home/dsl/Quixote-2.0 root at box:~/Quixote-2.0# python2.4 setup.py install running install error: invalid Python installation: unable to open /usr/lib/python2.4/config/Makefile (No such file or directory) Does anyone have any Idea where I should go from here? I have tried other distutills installs with the same results. Any help is appreciated. Thanks! -- *********************************** See there, that wasn't so bad. *********************************** _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From light_zls at 163.com Wed May 11 18:05:19 2005 From: light_zls at 163.com (Light) Date: Thu, 12 May 2005 00:05:19 +0800 Subject: [Tutor] Debian install problems. In-Reply-To: <22803ae20505110643260700e2@mail.gmail.com> References: <22803ae20505110643260700e2@mail.gmail.com> Message-ID: <200505120005.20386.light_zls@163.com> You need to install python-devel package. > I don't know is this is the proper place to post this but I need some > help. > > I am running Damn Small Linux at the moment. I enabled apt-get and > adjusted the list file to use the testing branch so I could install > python2.4. The apt-get went fine, I think. I didn't get and errors. > When I went to install quixote from a distutils package I received > the following error: > > root at box:~# cd /home/dsl/Quixote-2.0 > root at box:~/Quixote-2.0# python2.4 setup.py install > running install > error: invalid Python installation: unable to open > /usr/lib/python2.4/config/Makefile (No such file or directory) > > > Does anyone have any Idea where I should go from here? I have tried > other distutills installs with the same results. Any help is > appreciated. Thanks! From count0.djd at gmail.com Wed May 11 18:33:22 2005 From: count0.djd at gmail.com (David Driver) Date: Wed, 11 May 2005 11:33:22 -0500 Subject: [Tutor] Debian install problems. In-Reply-To: <200505111518.j4BFIxCV013760@email.morseintranet.com> References: <22803ae20505110643260700e2@mail.gmail.com> <200505111518.j4BFIxCV013760@email.morseintranet.com> Message-ID: <22803ae20505110933582c4028@mail.gmail.com> Thank you John and Ziyad. That is exactly what I needed to know. Thanks for the Debian resources. I didn't know that there was a list for python on Debian. On 5/11/05, John Purser wrote: > David, > > If you don't get an answer here on tutor.python.org then you might want to > try: > http://www.debian.org/MailingLists/ - where you'll find a link to > http://lists.debian.org/debian-python/ - the mailing list for > debian-python. > > Don't forget to search the archives. > > John Purser From jeannot18 at hotmail.com Wed May 11 18:50:32 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Wed, 11 May 2005 16:50:32 +0000 Subject: [Tutor] read() question Message-ID: MyText = open('The_text.txt','r').read() In the above line could someone tell me what the 'r' stand for. Many thanks JC From dyoo at hkn.eecs.berkeley.edu Wed May 11 19:09:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 10:09:15 -0700 (PDT) Subject: [Tutor] read() question In-Reply-To: Message-ID: On Wed, 11 May 2005, John Carmona wrote: > MyText = open('The_text.txt','r').read() > > In the above line could someone tell me what the 'r' stand for. Hi John, You may want to look at: http://www.python.org/doc/lib/built-in-funcs.html#l2h-25 If you're still unsure about what 'r' means, feel free to ask again, and one of us here can go into more detail. Good luck to you. From kent37 at tds.net Wed May 11 19:18:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 May 2005 13:18:06 -0400 Subject: [Tutor] read() question In-Reply-To: References: Message-ID: <42823E4E.4080506@tds.net> John Carmona wrote: > MyText = open('The_text.txt','r').read() > > In the above line could someone tell me what the 'r' stand for. Many thanks 'read', i.e open the file for reading, as opposed to 'w' for writing. For more options see the docs for file() (a synonym for open) here: http://docs.python.org/lib/built-in-funcs.html Kent From jeannot18 at hotmail.com Wed May 11 19:22:13 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Wed, 11 May 2005 17:22:13 +0000 Subject: [Tutor] read() question In-Reply-To: Message-ID: Got it now, thanks. JC From dyoo at hkn.eecs.berkeley.edu Wed May 11 19:22:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 10:22:41 -0700 (PDT) Subject: [Tutor] Python sort with a delimiter In-Reply-To: <2a278ffe05051105503e18a17e@mail.gmail.com> Message-ID: On Wed, 11 May 2005, Tom Tucker wrote: > Good morning! Does Python have a sort function thats supports a delimiter? Hi Tom, Not directly, but it's actually not too difficult to get this working. Python's sort() function can take in an optional "comparison" function, so we can do something like this: ###### def customCompare(host1, host2): return cmp(host1.split('-')[2], host2.split('-')[2]) ###### and then use this custom comparator by passing it as an additional argument to sort(): ###### somelist.sort(customCompare) ###### The Sorting HOWTO talks about this in more detail: http://www.amk.ca/python/howto/sorting/sorting.html Best of wishes! From 3dbernard at gmail.com Wed May 11 19:32:55 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 11 May 2005 13:32:55 -0400 Subject: [Tutor] map() and lambda to change class instance attribute Message-ID: <61d0e2b405051110323970d05e@mail.gmail.com> Hello, Let say I have several class instances in a list, and these class instances have an attribute named "value", whose value is an integer. I would like to know if it is possible to loop over the list of instances to change their "value" attribute, using a map( ( lambda:...), ... ) type of loop. I'm very new to lambdas as you can see :-) Thanks Bernard From dyoo at hkn.eecs.berkeley.edu Wed May 11 20:01:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 11:01:23 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: <61d0e2b405051110323970d05e@mail.gmail.com> Message-ID: On Wed, 11 May 2005, Bernard Lebel wrote: > Let say I have several class instances in a list, and these class > instances have an attribute named "value", whose value is an integer. > > I would like to know if it is possible to loop over the list of > instances to change their "value" attribute, using a map( ( lambda:...), > ... ) type of loop. Hi Bernard, Hmmm... then map() is probably not what you want. map() is meant to transform a list of things into another list of things, but isn't really meant to mutate its input. It is possible to abuse map() to do what you're trying to do, using the setattr() function: ###### Pseudocode map(lambda instance: setattr(instance, 'value', 42)) ###### but this is definitely language abuse. *grin* map() is not intended to be run just to affect changing assignments on its input. It'll probably be clearest in Python just to write out the loop explicitely. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed May 11 20:32:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 11:32:35 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: Message-ID: > It is possible to abuse map() to do what you're trying to do, using the > setattr() function: > > ###### Pseudocode > map(lambda instance: setattr(instance, 'value', 42)) > ###### Hi Bernard, Grrr... I did label that as Pseudocode, but that doesn't excuse me from not actually trying to make that example work. My apologies! That code above wont' work, just because I neglected to add the required 'list' that we want to map across. Let me try that again. ###### >>> class Person: ... def __init__(self, name): ... self.name = name ... self.age = 4 ... def sayHello(self): ... print "Hi, my name is", self.name, "and I am", self.age ... >>> people = map(Person, ["Danny", "Andy", "Belinda", "Jerry", "Wendy", ... "Tina"]) ###### Here, the use of map() is legitimate: we're mapping a list of names into a list of people. If we wanted to now make a change across them, we could go obfuscated and do another map(): ###### >>> map(lambda p: setattr(p, 'age', 26), people) [None, None, None, None, None, None] >>> for p in people: ... p.sayHello() ... Hi, my name is Danny and I am 26 Hi, my name is Andy and I am 26 Hi, my name is Belinda and I am 26 Hi, my name is Jerry and I am 26 Hi, my name is Wendy and I am 26 Hi, my name is Tina and I am 26 ###### But this is a case when using map() is probably not such a hot idea, just because now we're using it for just the "side effects" of making changes. We aren't even caring about the return value out of map(). And in that case, we may want to make such a change more visible, with an explicit assignment: ###### >>> for p in people: ... p.age = 17 ... >>> for p in people: ... p.sayHello() ... Hi, my name is Danny and I am 17 Hi, my name is Andy and I am 17 Hi, my name is Belinda and I am 17 Hi, my name is Jerry and I am 17 Hi, my name is Wendy and I am 17 Hi, my name is Tina and I am 17 ###### Does this make sense? From dyoo at hkn.eecs.berkeley.edu Wed May 11 20:33:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 11:33:12 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute (fwd) Message-ID: ---------- Forwarded message ---------- Date: Wed, 11 May 2005 14:29:58 -0400 From: Bernard Lebel <3dbernard at gmail.com> To: Danny Yoo Subject: Re: [Tutor] map() and lambda to change class instance attribute Hi Danny, Thanks for the answer. I have to confess that I already use map(), or should I say abuse, for this, although it is the first time I consider using lambdas. Up until now I always used map() to perform a looped call on a function that would change the attribute value, as shown in Mark Lutz & David Ascher's Learning Python: # Perform attribute value change on a single instance def iterateInstances( oInstance ): oInstance.value = myValue # Loop over list of instances map( iterateInstances, aListOfInstances ) However I was looking into lambdas in hope to eliminate the need to define a function. Cheers Bernard On 5/11/05, Danny Yoo wrote: > > > On Wed, 11 May 2005, Bernard Lebel wrote: > > > Let say I have several class instances in a list, and these class > > instances have an attribute named "value", whose value is an integer. > > > > I would like to know if it is possible to loop over the list of > > instances to change their "value" attribute, using a map( ( lambda:...), > > ... ) type of loop. > > Hi Bernard, > > Hmmm... then map() is probably not what you want. map() is meant to > transform a list of things into another list of things, but isn't really > meant to mutate its input. > > It is possible to abuse map() to do what you're trying to do, using the > setattr() function: > > ###### Pseudocode > map(lambda instance: setattr(instance, 'value', 42)) > ###### > > but this is definitely language abuse. *grin* > > map() is not intended to be run just to affect changing assignments on its > input. It'll probably be clearest in Python just to write out the loop > explicitely. > > Best of wishes to you! > > From 3dbernard at gmail.com Wed May 11 20:39:15 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 11 May 2005 14:39:15 -0400 Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: References: <61d0e2b405051110323970d05e@mail.gmail.com> Message-ID: <61d0e2b405051111394d41e9aa@mail.gmail.com> Hi Danny, Thanks for the answer. I have to confess that I already use map(), or should I say abuse, for this, although it is the first time I consider using lambdas. Up until now I always used map() to perform a looped call on a function that would change the attribute value, as shown in Mark Lutz & David Ascher's Learning Python: # Perform attribute value change on a single instance def iterateInstances( oInstance ): oInstance.value = myValue # Loop over list of instances map( iterateInstances, aListOfInstances ) However I was looking into lambdas in hope to eliminate the need to define a function. Cheers On 5/11/05, Danny Yoo wrote: > > > On Wed, 11 May 2005, Bernard Lebel wrote: > > > Let say I have several class instances in a list, and these class > > instances have an attribute named "value", whose value is an integer. > > > > I would like to know if it is possible to loop over the list of > > instances to change their "value" attribute, using a map( ( lambda:...), > > ... ) type of loop. > > Hi Bernard, > > Hmmm... then map() is probably not what you want. map() is meant to > transform a list of things into another list of things, but isn't really > meant to mutate its input. > > It is possible to abuse map() to do what you're trying to do, using the > setattr() function: > > ###### Pseudocode > map(lambda instance: setattr(instance, 'value', 42)) > ###### > > but this is definitely language abuse. *grin* > > map() is not intended to be run just to affect changing assignments on its > input. It'll probably be clearest in Python just to write out the loop > explicitely. > > Best of wishes to you! > > From dyoo at hkn.eecs.berkeley.edu Wed May 11 20:49:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 11:49:47 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: Message-ID: > I have to confess that I already use map(), or should I say abuse, for > this, although it is the first time I consider using lambdas. Up until > now I always used map() to perform a looped call on a function that > would change the attribute value, as shown in Mark Lutz & David Ascher's > Learning Python: > > # Perform attribute value change on a single instance > def iterateInstances( oInstance ): > oInstance.value = myValue > > # Loop over list of instances > map( iterateInstances, aListOfInstances ) What!!! Seriously? I'm making a style judgement here, so perhaps I could be wrong, but I think that's terrible that Learning Python has such an example. If you have a page number, I'll look it up and then write a complaint. *grin* The major problem here is that both map() and list comprehensions are really meant to be used because they generate a list of return values. If we use a map() or list comprehensions, such as: map(lambda x: x^2, [1, 2, 3]) [x^2 for x in [1, 2, 3]] then we're really saying something like this: [1, 2, 3] | | | | | | map() | | | V V V [1, 4, 9] where map() produces a list of values. If we're using map() just because it evaluates something on every element on a list, then, to make the intent more clear, we really should either use something like a foreach() function instead of map(): ###### def foreach(function, l): """Apply some function on every element in l. Does not accumulate return values.""" for x in l: function(l) ###### If we use something like foreach(0, then this makes it clear that we really don't care about return values at all. I should add that I'm arguing for style here. Things do work pefectly well with map() too --- the computer doesn't care that it's throwing return values away --- but we should do our best to document intent in our programs. Best of wishes! From csomerlot at gmail.com Wed May 11 21:02:05 2005 From: csomerlot at gmail.com (Chris Somerlot) Date: Wed, 11 May 2005 15:02:05 -0400 Subject: [Tutor] dicts&lists vs objects Message-ID: <9a8f06705051112026d229267@mail.gmail.com> I have been working on a scientific application for awhile, and have been using dictionaries and lists to store data and attributes of datasets. This is getting cumbersome as there are many, every dict/list is a premutation of another, and I'm having trouble following the code I've written. Is there a golden rule to knowing when to use objects instead of dictionaries and lists? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/0aa2a5d2/attachment.html From 3dbernard at gmail.com Wed May 11 21:17:38 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 11 May 2005 15:17:38 -0400 Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: References: Message-ID: <61d0e2b405051112172575bcec@mail.gmail.com> Hi Danny, Thanks a lot for the advice. I will put that in practice. The blasphemous example is on page 227 of the second edition, under Mapping Functions Over Sequences. Cheers Bernard On 5/11/05, Danny Yoo wrote: > > > I have to confess that I already use map(), or should I say abuse, for > > this, although it is the first time I consider using lambdas. Up until > > now I always used map() to perform a looped call on a function that > > would change the attribute value, as shown in Mark Lutz & David Ascher's > > Learning Python: > > > > # Perform attribute value change on a single instance > > def iterateInstances( oInstance ): > > oInstance.value = myValue > > > > # Loop over list of instances > > map( iterateInstances, aListOfInstances ) > > What!!! Seriously? I'm making a style judgement here, so perhaps I could > be wrong, but I think that's terrible that Learning Python has such an > example. If you have a page number, I'll look it up and then write a > complaint. *grin* > > The major problem here is that both map() and list comprehensions are > really meant to be used because they generate a list of return values. > > If we use a map() or list comprehensions, such as: > > map(lambda x: x^2, [1, 2, 3]) > > [x^2 for x in [1, 2, 3]] > > then we're really saying something like this: > > [1, 2, 3] > | | | > | | | map() > | | | > V V V > [1, 4, 9] > > where map() produces a list of values. > > If we're using map() just because it evaluates something on every element > on a list, then, to make the intent more clear, we really should either > use something like a foreach() function instead of map(): > > ###### > def foreach(function, l): > """Apply some function on every element in l. Does not accumulate > return values.""" > for x in l: > function(l) > ###### > > If we use something like foreach(0, then this makes it clear that we > really don't care about return values at all. > > I should add that I'm arguing for style here. Things do work pefectly > well with map() too --- the computer doesn't care that it's throwing > return values away --- but we should do our best to document intent in our > programs. > > Best of wishes! > > From charmainellchia at gmail.com Wed May 11 22:05:16 2005 From: charmainellchia at gmail.com (Charmaine Chia) Date: Wed, 11 May 2005 16:05:16 -0400 Subject: [Tutor] solutions to API version mismatch Message-ID: Hi there, I'm a new Python user and am basically running scripts that a colleague wrote a few years back. I believe the scripts were written on an older version of Python and aren't updated, and currently I can only run these scripts on an older computer (unix based). I am in the process of trying to run these scripts locally (also unix based), but I've been running into a few problems. My computer only has the following versions installed: Python 2.1.3+, 2.2.3+ and 2.3.4. I have changed my PYTHONPATH to use look for different site-packages (I've tried version 1.5 and 2.2 -- 1.5 was attempted in case the scripts were written in/during that version). *********************************************** I believe I have all the necessary modules to support the scripts, and my best attemp so far still has the following error message (version 1.5 site-packages): /python1.5/site-packages/Numeric/Numeric.py:76: RuntimeWarning: Python C API version mismatch for module multiarray: This Python has API version 1012, module multiarray has version 1007. import multiarray /python1.5/site-packages/Numeric/Numeric.py:76: RuntimeWarning: Python C API version mismatch for module _numpy: This Python has API version 1012, module _numpy has version 1007. import multiarray /python1.5/site-packages/Numeric/Numeric.py:77: RuntimeWarning: Python C API version mismatch for module umath: This Python has API version 1012, module umath has version 1007. from umath import * # Substitute fast_umath for "unsafe" math free(): invalid pointer 0x4029bcf0! free(): invalid pointer 0x4029bd68! free(): invalid pointer 0x4029bdb8! Segmentation fault *********************************************** *********************************************** When trying to run the same script using the 2.2 site-packages, the errors are: /python2.2/site-packages/Numeric/Numeric.py:86: RuntimeWarning: Python C API version mismatch for module multiarray: This Python has API version 1012, module multiarray has version 1011. import multiarray /python2.2/site-packages/Numeric/Numeric.py:86: RuntimeWarning: Python C API version mismatch for module _numpy: This Python has API version 1012, module _numpy has version 1011. import multiarray /python2.2/site-packages/Numeric/Numeric.py:87: RuntimeWarning: Python C API version mismatch for module umath: This Python has API version 1012, module umath has version 1011. from umath import * /python2.2/site-packages/multipack/minpack.py:2: RuntimeWarning: Python C API version mismatch for module _minpack: This Python has API version 1012, module _minpack has version 1011. import _minpack /python2.2/site-packages/multipack/odepack.py:2: RuntimeWarning: Python C API version mismatch for module _odepack: This Python has API version 1012, module _odepack has version 1011. import _odepack /python2.2/site-packages/multipack/quadpack.py:2: RuntimeWarning: Python C API version mismatch for module _quadpack: This Python has API version 1012, module _quadpack has version 1011. import _quadpack /python2.2/site-packages/multipack/fitpack.py:31: RuntimeWarning: Python C API version mismatch for module _fitpack: This Python has API version 1012, module _fitpack has version 1011. import _fitpack /python2.2/site-packages/Numeric/LinearAlgebra.py:8: RuntimeWarning: Python C API version mismatch for module lapack_lite: This Python has API version 1012, module lapack_lite has version 1011. import lapack_lite /python2.2/site-packages/Numeric/RandomArray.py:1: RuntimeWarning: Python C API version mismatch for module ranlib: This Python has API version 1012, module ranlib has version 1011. import ranlib /python2.2/site-packages/SpecialFuncs/SpecialFuncs.py:1: RuntimeWarning: Python C API version mismatch for module cephes: This Python has API version 1012, module cephes has version 1007. from cephes import * /bin/lapack/qr.py:3: RuntimeWarning: Python C API version mismatch for module lapack: This Python has API version 1012, module lapack has version 1007. from lapack import * Traceback (most recent call last): File "/data/mril/mril2/llchia/bin/fit_t2.py", line 568, in ? apply(main,args+[options]) File "/data/mril/mril2/llchia/bin/fit_t2.py", line 505, in main process_volumes(input, output, options) File "/data/mril/mril2/llchia/bin/fit_t2.py", line 358, in process_volumes t2_volume = create_output_volume(input_volume, output) File "/data/mril/mril2/llchia/bin/fit_t2.py", line 302, in create_output_volume t2_image.initialize(input_volume.shape()[1:],input_volume.start()[1:], File "/data/mril/mril2/llchia/bin/minc/minc.py", line 585, in start start[indexdict[dim]] = self.variables[dim].start[0] TypeError: can't convert complex to float; use abs(z) *********************************************** Do you think this problem can be simply solved by installing an older version of Python (matching the version in which the scripts and modules were written in) so that API versions match? If so, would there be any major disadvantage(s) for using an older version of Python? Or is there a simple way to update/convert the modules so that the API versions match? Any help is greatly appreciated. Charmaine From william.ohiggins at utoronto.ca Wed May 11 22:10:37 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Wed, 11 May 2005 16:10:37 -0400 Subject: [Tutor] Python versions and Debian? Message-ID: <20050511201037.GA8318@sillyrabbi.dyndns.org> I am just beginning to experiment with Python, and I'm looking for advice about versions. Debian testing provides version 2.3 by default, (/usr/bin/python is linked to /usr/bin/python2.3) but I am able to install 2.4 as well. What gains do I realize by using the more modern version? Are there gotchas based on that minor-version change? Your insight is appreciated, thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050511/a967f543/attachment.pgp From dyoo at hkn.eecs.berkeley.edu Wed May 11 22:16:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 13:16:17 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: <61d0e2b405051112172575bcec@mail.gmail.com> Message-ID: On Wed, 11 May 2005, Bernard Lebel wrote: > Thanks a lot for the advice. I will put that in practice. > > The blasphemous example is on page 227 of the second edition, under > Mapping Functions Over Sequences. Hi Bernard, Ah, thank you. I'll start the Inquisition shortly. *grin* From 3dbernard at gmail.com Wed May 11 22:22:47 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 11 May 2005 16:22:47 -0400 Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: References: <61d0e2b405051112172575bcec@mail.gmail.com> Message-ID: <61d0e2b405051113221d455fcc@mail.gmail.com> Please tell them who reported them ;-) Bernard On 5/11/05, Danny Yoo wrote: > > > On Wed, 11 May 2005, Bernard Lebel wrote: > > > Thanks a lot for the advice. I will put that in practice. > > > > The blasphemous example is on page 227 of the second edition, under > > Mapping Functions Over Sequences. > > Hi Bernard, > > Ah, thank you. I'll start the Inquisition shortly. *grin* > > From dyoo at hkn.eecs.berkeley.edu Wed May 11 22:37:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 13:37:19 -0700 (PDT) Subject: [Tutor] solutions to API version mismatch In-Reply-To: Message-ID: On Wed, 11 May 2005, Charmaine Chia wrote: > My computer only has the following versions installed: Python 2.1.3+, > 2.2.3+ and 2.3.4. I have changed my PYTHONPATH to use look for > different site-packages (I've tried version 1.5 and 2.2 -- 1.5 was > attempted in case the scripts were written in/during that version). Hi Charmiane, You may want to find which third-party modules are required by that code, as some modules do require some special attention. I would recommend not just trying to get the code to compile, but to also document your work on what additional third-party modules are required. It's good to document external dependencies so that future code maintainers like yourself don't get tripped up so badly. The particular module that's causing you problems appears to be Numeric Python, a third-party module that adds good numerical computing support to Python. Numeric is an example of an "extension module", which can't be just copied directly, but must be specifically compiled to a particular version of Python, because quite a bit of Numeric is compiled in C. Our recommendation is to install Numeric for the current version of Python on your system. Numeric can be found here: http://sourceforge.net/project/showfiles.php?group_id=1369 It looks like you were trying Python 2.2 on a Unix system. You should be able to grab 'Numeric-23.8.tar.gz', untar it, go into its source directory, and then execute: $ rm -rf build $ python2.2 setup.py build $ python2.2 setup.py install to install Numeric for your system. You may need to repeat this process if you have multiple versions of Python on your system. > Do you think this problem can be simply solved by installing an older > version of Python (matching the version in which the scripts and modules > were written in) so that API versions match? Yes, this will also work, although there are some disadvantages to using the legacy versions of Python. > If so, would there be any major disadvantage(s) for using an older > version of Python? There have been bug fixes and some significant improvements to the language and Standard Library. Here are summaries of changes to Python since Python 1.5: http://www.python.org/1.6/#news http://www.amk.ca/python/2.0/ http://www.amk.ca/python/2.1/ http://www.python.org/doc/2.2.3/whatsnew/whatsnew22.html http://www.python.org/doc/2.3/whatsnew/ http://www.python.org/doc/2.4.1/whatsnew/whatsnew24.html Although the language core has stayed fairly consistant between 1.5 to the later versions, I think that the extensive fixes to the Standard Library, as well as the performance enhancements, warrants the upgrade. Code that runs under 1.5 should run under 2.1, 2.2, and 2.3, although there are some rare-and-unusual exceptions that are documented in the summary change notes above. Best of wishes to you! From smichr at bigfoot.com Wed May 11 23:11:41 2005 From: smichr at bigfoot.com (Chris Smith) Date: Wed, 11 May 2005 16:11:41 -0500 Subject: [Tutor] help In-Reply-To: Message-ID: <456BF189-C261-11D9-9BDD-000393C0D100@bigfoot.com> On Wednesday, May 11, 2005, at 08:09 America/Chicago, tutor-request at python.org wrote: > hi > i'm trying to extend a list program by adding a test, problem is after > getting the menu of taking the test i can't seem to get the test > running > i.e viewing of questions and answers. here's what i tried to do > menu_item = 0 > list = [] > while menu_item !=9: > print "---------------------" > print "1. print the questions" > print "2. take the test" > print "3. quit" > menu_item = input("pick an item from the menu: ") > Hi Feziwe, If you are trying to modify someone else's code, then the work that you would have done to write it now has to go into trying to understand what they have already done. Not to lecture too much, but if you didn't write it then work through it piece by piece to see how it works. What you will notice that relates to your problem is that there is a 'while' loop that requires a menu_item to be not equal to 9. Since your menu never asks the user to enter a 9, you will never get out of that loop. Also, check to see what *does* happen when a 2 is pressed: if there is not an instruction to call a function, then the instructions in that part of the 'if...elif...else' section will be done and the 'while' loop will resume (since menu_item was not 9. Does this get you started toward understanding the problem? /c From john.ertl at fnmoc.navy.mil Wed May 11 19:25:22 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed, 11 May 2005 10:25:22 -0700 Subject: [Tutor] read() question Message-ID: John, The 'r' is the mode and is used to indicate you are reading the file. You could also use 'w' for only writing. See the attached link for more. http://www.python.org/doc/current/tut/node9.html#SECTION00920000000000000000 0 John -----Original Message----- From: John Carmona [mailto:jeannot18 at hotmail.com] Sent: Wednesday, May 11, 2005 09:51 To: tutor at python.org Subject: [Tutor] read() question MyText = open('The_text.txt','r').read() In the above line could someone tell me what the 'r' stand for. Many thanks JC _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From jeannot18 at hotmail.com Thu May 12 00:20:53 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Wed, 11 May 2005 22:20:53 +0000 Subject: [Tutor] read() question In-Reply-To: Message-ID: Got it now, thanks John JC From gsf at panix.com Thu May 12 00:24:27 2005 From: gsf at panix.com (Gabriel Farrell) Date: Wed, 11 May 2005 18:24:27 -0400 Subject: [Tutor] Python versions and Debian? In-Reply-To: <20050511201037.GA8318@sillyrabbi.dyndns.org> References: <20050511201037.GA8318@sillyrabbi.dyndns.org> Message-ID: <20050511222427.GA17167@panix.com> Hi William, The short answer is go with the default until you run into something you can't do without 2.4. For the skinny on all the changes you'll want to check out http://python.org/doc/2.4/whatsnew/whatsnew24.html . That document lays it out about as well as can be done. If you find something in there that really makes a difference for you, then go to 2.4. I've only installed the default python (2.3 for now) on my Debian box because the changes don't really affect my programs. There is a short, not-too-informative chat about Python 2.4 and Debian that starts at http://lists.debian.org/debian-python/2005/04/msg00005.html . gabe On Wed, May 11, 2005 at 04:10:37PM -0400, William O'Higgins wrote: > I am just beginning to experiment with Python, and I'm looking for > advice about versions. Debian testing provides version 2.3 by default, > (/usr/bin/python is linked to /usr/bin/python2.3) but I am able to > install 2.4 as well. What gains do I realize by using the more modern > version? Are there gotchas based on that minor-version change? Your > insight is appreciated, thanks. > -- > > yours, > > William > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From albertito_g at hotmail.com Thu May 12 00:27:34 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 11 May 2005 22:27:34 +0000 Subject: [Tutor] Riddle 8 Message-ID: Hey I know it is supposed to be one of the easyiest and I know what I have to find(two nouns) and I know from where (two strings on the page)(it's very difficult to avoid spoilers) but I don't know how. And I see the hint when you try to get to 9 but I don't know what it means Any hints????? Thanks Alberto From carroll at tjc.com Thu May 12 00:30:59 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed, 11 May 2005 15:30:59 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: Message-ID: It's not often I get a chance to correct Danny, but.... On Wed, 11 May 2005, Danny Yoo wrote: > map(lambda x: x^2, [1, 2, 3]) > > [x^2 for x in [1, 2, 3]] > then we're really saying something like this: > > [1, 2, 3] > | | | > | | | map() > | | | > V V V > [1, 4, 9] You probably don't want to invoke a bitwise exclusive-or here! I think Danny meant: map(lambda x: x**2, [1, 2, 3]) [x**2 for x in [1, 2, 3]] From albertito_g at hotmail.com Thu May 12 00:44:00 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 11 May 2005 22:44:00 +0000 Subject: [Tutor] Riddle 8 In-Reply-To: Message-ID: Nevermind It was easy and I figured out But now I'm having serious problems with number 9 Do I really have to connect the dots???????? And how can I do that using the obviuos module? Thanks Alberto >From: "Alberto Troiano" >To: tutor at python.org >Subject: [Tutor] Riddle 8 >Date: Wed, 11 May 2005 22:27:34 +0000 > >Hey > >I know it is supposed to be one of the easyiest and I know what I have to >find(two nouns) and I know from where (two strings on the page)(it's very >difficult to avoid spoilers) >but I don't know how. And I see the hint when you try to get to 9 but I >don't know what it means > >Any hints????? > >Thanks > >Alberto > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Thu May 12 01:01:18 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 11 May 2005 19:01:18 -0400 Subject: [Tutor] Riddle 8 In-Reply-To: References: Message-ID: <191378146696.20050511190118@columbus.rr.com> > Do I really have to connect the dots???????? > And how can I do that using the obviuos module? I used pygame to do it. Also you could probably do it with Image, to a file (and then view that file with your favorite picture viewer). Alan From denise.hartley at gmail.com Thu May 12 02:26:50 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 11 May 2005 17:26:50 -0700 Subject: [Tutor] character format Message-ID: <8daabe5605051117262ff6ff64@mail.gmail.com> Does anyone have a hint as to what things like this: \xaf\x82\r\x00\x00\x01\ refer to? I have googled it and searched python for modules/library sections related to the google pages I found, but as they were pretty all over the place I can't find something helpful. Any hints would be appreciated :) ~Denise From jfouhy at paradise.net.nz Thu May 12 02:50:28 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 12 May 2005 12:50:28 +1200 (NZST) Subject: [Tutor] character format In-Reply-To: <8daabe5605051117262ff6ff64@mail.gmail.com> References: <8daabe5605051117262ff6ff64@mail.gmail.com> Message-ID: <1115859028.4282a85483b4b@www.paradise.net.nz> Quoting "D. Hartley" : > Does anyone have a hint as to what things like this: > \xaf\x82\r\x00\x00\x01\ > > refer to? Basically, they are unprintable characters. >>> ord('\x82') 130 >>> chr(130) '\x82' If you look at http://asciitable.com/, you will see that ascii chracter 130 is an e with a tick on its head. This is not something you can find on your keyboard, so python can't/won't display it. Also, if you do some maths, you will see that 82 in hexadecimal is 130 in decimal: >>> 8*16 + 2 130 So that explains why it is x82 :-) (with the backslash to indicate an escape sequence, and an x to indicate hexadecimal) '\r' is the carriage return character [1]. Looking at asciitable.com, I can see that it is hex d / ascii 13. >>> '\x0d' == '\r' True Hope this helps! -- John. [1] Historical note: In the days of typewriters [2], a carriage return would send the carriage (with the ink in it) back to the left, so you could start typing a new line. A line feed would advance the paper by one line. These were separate operations 'cause sometimes you wouldn't want to do both. The characters entered ASCII (because of early printers?) and different operating systems used them to end lines in different ways: in UNIX, the end-of-line character is a newline character ('\n'); in MSDOS/Windows it is both ('\r\n'); and I think Macintoshes just use a '\r'. Fortunately, python has so-called "universal newline" support, so you don't need to worry about all that :-) [2] Before my time, so there could be errors of fact... From maxnoel_fr at yahoo.fr Thu May 12 03:03:35 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 12 May 2005 02:03:35 +0100 Subject: [Tutor] character format In-Reply-To: <1115859028.4282a85483b4b@www.paradise.net.nz> References: <8daabe5605051117262ff6ff64@mail.gmail.com> <1115859028.4282a85483b4b@www.paradise.net.nz> Message-ID: On May 12, 2005, at 01:50, jfouhy at paradise.net.nz wrote: >>>> chr(130) >>>> > '\x82' > > If you look at http://asciitable.com/, you will see that ascii > chracter 130 is > an e with a tick on its head. This is not something you can find > on your > keyboard, so python can't/won't display it. > You mean ?? Oh, it is perfectly printable. It's even on my keyboard (as unshifted 2), along with ?, ?, ? and ?. Ah, American cultural assumption... ^^ Denise: If it is what I think it is, you may want to have a look at the first 2 characters of the string, which if I recall are printable, and should point you toward the module you have to use to solve that one. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Thu May 12 03:22:29 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 11 May 2005 18:22:29 -0700 Subject: [Tutor] character format In-Reply-To: References: <8daabe5605051117262ff6ff64@mail.gmail.com> <1115859028.4282a85483b4b@www.paradise.net.nz> Message-ID: <8daabe5605051118225c6df811@mail.gmail.com> Max - yep, and the hint was "BUSY" (... BZ...)... Unfortunately that hint doesnt lead me anywhere (except to bz2, which involves compression, and didnt seem very likely). I went through and removed all the \x## 's that represented 'unprintable'/carraigereturn/etc characters, but that wasnt it, ha ha. It just may be that I don't know enough python to recognize the module I need! (I got pickle right away, but bz leaves me blinking). Am I missing something obvious? ~Denise On 5/11/05, Max Noel wrote: > > On May 12, 2005, at 01:50, jfouhy at paradise.net.nz wrote: > > >>>> chr(130) > >>>> > > '\x82' > > > > If you look at http://asciitable.com/, you will see that ascii > > chracter 130 is > > an e with a tick on its head. This is not something you can find > > on your > > keyboard, so python can't/won't display it. > > > > You mean ?? Oh, it is perfectly printable. It's even on my > keyboard (as unshifted 2), along with ?, ?, ? and ?. Ah, American > cultural assumption... ^^ > > Denise: If it is what I think it is, you may want to have a look > at the first 2 characters of the string, which if I recall are > printable, and should point you toward the module you have to use to > solve that one. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tim.peters at gmail.com Thu May 12 03:32:42 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 11 May 2005 21:32:42 -0400 Subject: [Tutor] character format In-Reply-To: <8daabe5605051118225c6df811@mail.gmail.com> References: <8daabe5605051117262ff6ff64@mail.gmail.com> <1115859028.4282a85483b4b@www.paradise.net.nz> <8daabe5605051118225c6df811@mail.gmail.com> Message-ID: <1f7befae05051118321e2a8dcb@mail.gmail.com> [D. Hartley] > Max - yep, and the hint was "BUSY" (... BZ...)... > > Unfortunately that hint doesnt lead me anywhere (except to bz2, which > involves compression, and didnt seem very likely). > > I went through and removed all the \x## 's that represented > 'unprintable'/carraigereturn/etc characters, but that wasnt it, ha ha. > > It just may be that I don't know enough python to recognize the module > I need! (I got pickle right away, but bz leaves me blinking). > > Am I missing something obvious? Not at all. The only problem is a propensity toward dismissing the obvious as being not very likely . Try reading those docs from the end instead of from the beginning. From maxnoel_fr at yahoo.fr Thu May 12 03:37:23 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 12 May 2005 02:37:23 +0100 Subject: [Tutor] character format In-Reply-To: <8daabe5605051118225c6df811@mail.gmail.com> References: <8daabe5605051117262ff6ff64@mail.gmail.com> <1115859028.4282a85483b4b@www.paradise.net.nz> <8daabe5605051118225c6df811@mail.gmail.com> Message-ID: <9E5BE0FF-E1B1-4629-8453-E477C8DF5321@yahoo.fr> On May 12, 2005, at 02:22, D. Hartley wrote: > Max - yep, and the hint was "BUSY" (... BZ...)... > > Unfortunately that hint doesnt lead me anywhere (except to bz2, which > involves compression, and didnt seem very likely). > > I went through and removed all the \x## 's that represented > 'unprintable'/carraigereturn/etc characters, but that wasnt it, ha ha. > > It just may be that I don't know enough python to recognize the module > I need! (I got pickle right away, but bz leaves me blinking). > > Am I missing something obvious? > > ~Denise > Think again. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From tameyer at ihug.co.nz Thu May 12 03:42:55 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Thu, 12 May 2005 13:42:55 +1200 Subject: [Tutor] character format In-Reply-To: Message-ID: > You mean ?? Oh, it is perfectly printable. It's even on my > keyboard (as unshifted 2), along with ?, ?, ? and ?. Ah, American > cultural assumption... ^^ >From the email address, chances are that this was a New Zealand cultural assumption. Ah, the French, lumping all English speakers under the American banner . Anyway, the explanation was right, if the label wasn't. They are simply hexidecimal representations of characters. Denise: there are many uses for this - to know what you need to do, we need to know what you are trying to do. Where are you finding these characters? Are they in a file? If so, what type of file is it, and what do you want to do with the file? Those questions are more likely to lead you to the module you're after. I believe Max's guess was that the file is compressed with bzip (the first two characters will be BZ, as you found). Try doing: >>> import bz2 >>> print bz2.decompress(data) Where data is a string containing the characters you have. (Although you say that compression is unlikely, the BZ characters would be a big co-incidence). =Tony.Meyer From jfouhy at paradise.net.nz Thu May 12 04:00:00 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 12 May 2005 14:00:00 +1200 (NZST) Subject: [Tutor] character format In-Reply-To: References: <8daabe5605051117262ff6ff64@mail.gmail.com> <1115859028.4282a85483b4b@www.paradise.net.nz> Message-ID: <1115863200.4282b8a016d05@www.paradise.net.nz> Quoting Max Noel : > You mean ?? Oh, it is perfectly printable. It's even on my > keyboard (as unshifted 2), along with ?, ?, ? and ?. Ah, American > cultural assumption... ^^ I was waiting for someone to call me on that ... As was pointed out, I'm not American. I guess the problem stems from an American cultural assumption, though, in that Americans (I think) developed the ASCII character set without any thought for other languages. Will a standard xterm display chr(130) as ? in linux for you, Max? Or under Mac OS X? Anyway, in Python3000 all strings will be unicode, so it won't matter then :-) -- John. From bgailer at alum.rpi.edu Thu May 12 04:48:22 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 11 May 2005 19:48:22 -0700 Subject: [Tutor] character format In-Reply-To: References: Message-ID: <6.1.2.0.0.20050511194754.03949fe0@pop.sbcglobal.yahoo.com> At 06:42 PM 5/11/2005, Tony Meyer wrote: > > You mean ?? Oh, it is perfectly printable. It's even on my > > keyboard (as unshifted 2), along with ?, ?, ? and ?. Ah, American > > cultural assumption... ^^ > > >From the email address, chances are that this was a New Zealand cultural >assumption. Ah, the French, lumping all English speakers under the American >banner . > >Anyway, the explanation was right, if the label wasn't. They are simply >hexidecimal representations of characters. Did you mean "hexadecimal"? >Denise: there are many uses for this - to know what you need to do, we need >to know what you are trying to do. Where are you finding these characters? >Are they in a file? If so, what type of file is it, and what do you want to >do with the file? Those questions are more likely to lead you to the module >you're after. > >I believe Max's guess was that the file is compressed with bzip (the first >two characters will be BZ, as you found). Try doing: > > >>> import bz2 > >>> print bz2.decompress(data) > >Where data is a string containing the characters you have. (Although you >say that compression is unlikely, the BZ characters would be a big >co-incidence). > >=Tony.Meyer > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/4475cb69/attachment.html From tameyer at ihug.co.nz Thu May 12 04:53:29 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Thu, 12 May 2005 14:53:29 +1200 Subject: [Tutor] character format In-Reply-To: Message-ID: [me, typo'ing] >> hexidecimal representations of characters. [Bob Gailer] > Did you mean "hexadecimal"? Sigh. Yes. I did a one character typo. Please forgive me. =Tony.Meyer From bvande at po-box.mcgill.ca Thu May 12 05:38:03 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 11 May 2005 23:38:03 -0400 Subject: [Tutor] dicts&lists vs objects In-Reply-To: <9a8f06705051112026d229267@mail.gmail.com> References: <9a8f06705051112026d229267@mail.gmail.com> Message-ID: <4282CF9B.4040107@po-box.mcgill.ca> Chris Somerlot said unto the world upon 2005-05-11 15:02: > I have been working on a scientific application for awhile, and > have been using dictionaries and lists to store data and attributes > of datasets. This is getting cumbersome as there are many, every > dict/list is a premutation of another, and I'm having trouble > following the code I've written. > > Is there a golden rule to knowing when to use objects instead of > dictionaries and lists? > Hi Chris, first, while I believe I understand what you mean in the last line, there is a mistaken assumption behind it -- lists and dictionaries *are* objects :-) I take you to mean "when should I use builtin objects like lists and dictionaries, and when should I use classes to define my own object types instead?" I'm still fairly early on in getting the hang of OOP design. But, I've found that experiencing confusion over the structure of my own none-OO code is a pretty reliable sign that converting the approach to OOP might be worth a serious thought :-) If you could say a bit more about your problem space, perhaps I, or someone more experienced, will be able to say something more specific to help. Best, Brian vdB From smichr at bigfoot.com Thu May 12 05:34:33 2005 From: smichr at bigfoot.com (Chris Smith) Date: Wed, 11 May 2005 22:34:33 -0500 Subject: [Tutor] character format In-Reply-To: Message-ID: On Wednesday, May 11, 2005, at 20:43 America/Chicago, tutor-request at python.org wrote: > I believe Max's guess was that the file is compressed with bzip (the > first > two characters will be BZ, as you found). Try doing: > >>>> import bz2 >>>> print bz2.decompress(data) > > Where data is a string containing the characters you have. (Although > you > say that compression is unlikely, the BZ characters would be a big > co-incidence). > That interactive mode is *very* helpful. If you import a module and then do a directory on it to see what it has for "tools" and then start playing with them, you can learn some interesting things without a lot of overhead: ### >>> import bz2 >>> dir(bz2) ['BZ2Compressor', 'BZ2Decompressor', 'BZ2File', '__author__', '__doc__', '__file__', '__name__', 'compress', 'decompress'] >>> bz2.compress('foo') "BZh91AY&SYI\xfe\xc4\xa5\x00\x00\x00\x01\x00\x01\x00\xa0\x00!\x00\x82,]\ xc9\x14\xe1BA'\xfb\x12\x94" >>> bz2.decompress(_) #underscore to reference last thing 'foo' ### Hmmm... /c From jeffrice at finity.org Thu May 12 06:39:47 2005 From: jeffrice at finity.org (Jeffrey Rice) Date: Wed, 11 May 2005 22:39:47 -0600 Subject: [Tutor] Pipe variable to external command Message-ID: <6.2.1.2.2.20050511223118.026b2e68@popfile> Hi, I am working on getting comfortable with Python, and am trying to rewrite some of my old (clumsy) bash scripts into python. I am having a little problem with how to pipe a variable's contents to an external command. Essentially, I have a variable that contains the contents of a variable that I want to feed to a series of external commands (clamav and spamassassin). EMAIL contains the full email message, and CLAMAV contains the path to the clamscan bin (and necessary flags). I have tested this on the command line and it works (so I know the command syntax is correct), but in my python script it is clear that nothing is getting piped to the scanner. CLAMAV_h= os.popen(CLAMAV, 'w') CLAMAV_h.write(EMAIL) CLAM_RESULT=CLAMAV_h.close() print CLAM_RESULT I can make this work by writing to a temp file and scanning that, but I would like to avoid having to write to and read from a temp file at every step. I expect I am making a very basic error, stemming from my tackling a (perhaps?) more advanced problem at this early stage. But one can only get so far with "Hello World".... Many thanks, Jeff * * * * * * * Jeffrey Rice || jeffrice at finity.org || www.finity.org From dyoo at hkn.eecs.berkeley.edu Thu May 12 07:50:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 22:50:02 -0700 (PDT) Subject: [Tutor] map() and lambda to change class instance attribute In-Reply-To: Message-ID: > On Wed, 11 May 2005, Danny Yoo wrote: > > > map(lambda x: x^2, [1, 2, 3]) > > > > [x^2 for x in [1, 2, 3]] > > then we're really saying something like this: > > > > [1, 2, 3] > > | | | > > | | | map() > > | | | > > V V V > > [1, 4, 9] > > You probably don't want to invoke a bitwise exclusive-or here! > > I think Danny meant: > > map(lambda x: x**2, [1, 2, 3]) > [x**2 for x in [1, 2, 3]] Right, what Terry said. Dear goodness, I'm getting really sloppy these days; I must test my examples. Thanks for catching that for me. From dyoo at hkn.eecs.berkeley.edu Thu May 12 08:16:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 11 May 2005 23:16:06 -0700 (PDT) Subject: [Tutor] Pipe variable to external command In-Reply-To: <6.2.1.2.2.20050511223118.026b2e68@popfile> Message-ID: On Wed, 11 May 2005, Jeffrey Rice wrote: > I am having a little problem with how to pipe a variable's contents to an > external command. Essentially, I have a variable that contains the > contents of a variable that I want to feed to a series of external commands > (clamav and spamassassin). Hi Jeffrey, Ok, let's take a look. > CLAMAV_h= os.popen(CLAMAV, 'w') > CLAMAV_h.write(EMAIL) > CLAM_RESULT=CLAMAV_h.close() > print CLAM_RESULT Ah, ok. The value of the 'close()' here isn't defined, so you probably won't get anything. Let me double check that: ###### >>> import os >>> f = os.popen('ls') >>> result = f.close() >>> type(result) ###### Yeah, no value. By the way, we can also look this up by reading the documentation on file-like objects: http://www.python.org/doc/lib/bltin-file-objects.html Anyway, so trying to get a result from close() is a no-go. But when we open up a process, we can get back both an "input" file and an "output file". os.popen() just gives us the output stream, since unidirectional communication is the common case. But there are variations of popen that can give us both: http://www.python.org/doc/lib/module-popen2.html You're probably looking for 'popen2', which gives us both streams. Here's an example with the word-counting Unix program 'wc': ###### >>> child_out, child_in = popen2.popen2("wc") >>> child_in.write("hello world\nthis is a test\ngoodbye!\n") >>> child_in.close() >>> result = child_out.read() >>> child_out.close() >>> result ' 3 7 36\n' ###### Three lines, seven words, and thirty-six characters. Sounds right. *grin* That being said, if you haven't used either popen2 or subprocess set, you may want to try subprocess first, as there are some subtleties to using popen2 that aren't obvious at first. (Some of these subtleties are documented in: http://www.python.org/doc/lib/popen2-flow-control.html) The 'subprocess' module is described here: http://www.python.org/doc/lib/module-subprocess.html and should be fairly easy to work with. I haven't yet installed Python 2.4 on my home machine, so I'll need to delegate to someone else on the Tutor list here for a subprocess example. *grin* If you have more questions, please feel free to ask! From dave at eddy.uni-duisburg.de Wed May 11 08:23:10 2005 From: dave at eddy.uni-duisburg.de (Ferry Dave =?iso-8859-1?q?J=E4ckel?=) Date: Wed, 11 May 2005 08:23:10 +0200 Subject: [Tutor] Talking to hardware with python In-Reply-To: <01a101c5545d$711b3f70$e54b8651@xp> References: <200505082148.15731.dave@eddy.uni-duisburg.de> <01a101c5545d$711b3f70$e54b8651@xp> Message-ID: <200505110823.17190.dave@eddy.uni-duisburg.de> Hi Alan, Am Montag, 9. Mai 2005 08:07 schrieb Alan Gauld: > The only advice I'd offer is to stick to a C interface rather > than C++ and provide the OO wrapper at the Python layer. But thats another layer. A c-interface, swig, and python-abstraction. As Python function calls are rather slow and I want to make full usage of this measurement device this may be slow. And there's more code to maintain. > C is > much easier to use than C++ and simpler to intregrate with > Python - which is itself written in C. I have found several examples for this chip and win32 (but with other firmware) in c and c++. I will evaluate both, I think. What kind of problems is to be expected when integrating c++ with python (vs. c with python)? > Also a C library is > more open in that it can be used by other projects who may > not have an OO language to map to C++. Ah yes, allways make your code reuseable for others. Another point for c. Thanks for your advices! Dave -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050511/726208c6/attachment.pgp From MichaelCole1234 at comcast.net Wed May 11 12:33:59 2005 From: MichaelCole1234 at comcast.net (Michael Cole) Date: Wed, 11 May 2005 04:33:59 -0600 Subject: [Tutor] total newbie Message-ID: <000e01c55614$f1e616d0$512e89a5@Bart> WARNING: TOTAL NEWBIE QUESTION BELOW Had to warn ya, I just finished reading a book on learning python for beginners and decided to write a small game program as an exercise. The game I wrote was breakout (in case you dont know it, its a very simple game where there is several rows of bricks in the upper portion of the screen and a paddle at the bottom, a ball bounces around destroying bricks...) I used pygame for all of the graphics, sprites, collision, etc... What I noticed while testing the program is that the ball moves fairly slowly, I tried incrementing the ball's speed (dx and dy) but it still seemed to move pretty slow no matter how much I increased its speed. I went ahead and played out the game, destroying bricks (sprites, 128 of them). As the number of remaining bricks decreased the ball's speed increased, dramatically. so i guess what I want to know is, is python normally this slow when dealing with such a small number of objects? or is this something particular about pygame's handling of sprites? and, if this is something intrinsic to python, can anything be done to speed it up? I realize python is an intrepeted language but this seems almost useless for any decent number of objects.... Thanks in advance. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050511/ccdf3afb/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu May 12 09:11:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 00:11:02 -0700 (PDT) Subject: [Tutor] total newbie [profiling example] In-Reply-To: <000e01c55614$f1e616d0$512e89a5@Bart> Message-ID: On Wed, 11 May 2005, Michael Cole wrote: > What I noticed while testing the program is that the ball moves fairly > slowly, I tried incrementing the ball's speed (dx and dy) but it still > seemed to move pretty slow no matter how much I increased its speed. I > went ahead and played out the game, destroying bricks (sprites, 128 of > them). As the number of remaining bricks decreased the ball's speed > increased, dramatically. Hi Michael, It's hard to say what's going on without reading code and running profiling tests. Do you mind posting the URL up somewhere? One of us can then review the code and see if we can help you pinpoint the performance issue. > dealing with such a small number of objects? or is this something > particular about pygame's handling of sprites? and, if this is something > intrinsic to python, can anything be done to speed it up? I realize > python is an intrepeted language but this seems almost useless for any > decent number of objects.... It may or may not have anything to do with Python itself: it's possible that there is a time sink somewhere that can be easily fixed, or perhaps there's something fundamentally wrong. But I really don't like to guess. *grin* Let us take a look at the code; we'll be in a better position to do some analysis if we have something we can measure. One of us will probably run the program through a "profiler": http://docs.python.org/lib/profile.html to identify the "hot" spots in the program, and then we can work from there. It looks like there are things in the pygame code repository that may also be relevant to profiling: http://www.pygame.org/pcr/profiler/ As an example of what we might do, say that someone comes up with the following program: ###### ## Adds two numbers together def add(x, y): while x != 0: x = x - 1 y = y + 1 return y ###### Ok, ok, this is a totally unrealistic example, but bear with me. *grin* It's obvious to us that there's a severe performance issue with the function above, but pretend for a moment that we had no clue that add() was written in such a silly way, and imagine that we were using this in the middle of a larger program, and wouldn't know what was going on. Let's make the artificial problem a little less artificial: ###### def add(x, y): while x != 0: x = x - 1 y = y + 1 return y def f(): return add(10**7, 10**7) def g(): print f(), f() if __name__ == '__main__': main() ###### Something like that. It's still artificial, but oh well. So we have a few functions that call each other, and let's pretend that it's not immmediately obvious that add() is broken. *grin* If someone comes to us and says "This program goes slow, and I don't know why", then what can we do? We can run a "profiler", which will give us a good chance at figuring out what's wrong: ###### >>> import profile >>> profile.run('g()') 20000000 20000000 7 function calls in 9.480 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 2 9.430 4.715 9.430 4.715 :1(add) 2 0.000 0.000 9.430 4.715 :1(f) 1 0.000 0.000 9.430 9.430 :1(g) 1 0.000 0.000 9.430 9.430 :1(?) 1 0.050 0.050 9.480 9.480 profile:0(g()) 0 0.000 0.000 profile:0(profiler) ###### Ok, so there's a big "blip" in the total time "tottime" that add() uses: out of the 9.480 CPU seconds that the whole program takes up, 9.43 of those seconds is in add()! So we are now more sure that add() implementation is evil. And if we switch it to something realistic: ###### >>> def add(x, y): ... return x + y ... >>> profile.run('g()') 20000000 20000000 7 function calls in 0.010 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 2 0.000 0.000 0.000 0.000 :1(add) 2 0.000 0.000 0.000 0.000 :1(f) 1 0.010 0.010 0.010 0.010 :1(g) 1 0.000 0.000 0.010 0.010 :1(?) 1 0.000 0.000 0.010 0.010 profile:0(g()) 0 0.000 0.000 profile:0(profiler) ###### then the numbers relax, and we can be happy. Whenever we have performance issues with our programs, we should use a profiler, since it cuts down on guessing why programs go slow. It's better to know that certain sections of programs go slow, so we can focus our attention like a laser. So try to profile the program first; if you need help, again, post a URL to your game, and I'm sure folks here will be happy to help profile and pinpoint performance issues for you. Best of wishes! From flamesrock at gmail.com Thu May 12 10:36:14 2005 From: flamesrock at gmail.com (Aaron Elbaz) Date: Thu, 12 May 2005 08:36:14 +0000 Subject: [Tutor] #NameError: global name is not defined Message-ID: <2c2812b60505120136755d67d2@mail.gmail.com> Hi, I'm having difficulty understanding why the following code doesn't work: getfr.py #import pymetar # #class wReport: # def __init__(self,metarcode="CYYC"): #weather for calgary INTL # self.METARCODE=metarcode # rf=pymetar.ReportFetcher(self.METARCODE) # rep=rf.FetchReport() # pr=rp.ParseReport(rep) # def getRep() # return pr.getFullReport #>>> import getfr #>>> w = getfr.wReport() #Traceback (most recent call last): # File "", line 1, in ? # File "getfr.py", line 8, in __init__ # pr=rp.ParseReport(rep) #NameError: global name 'rp' is not defined The goal of this simple script is to get a full weather report from pymetar in only two lines of code (for my own amusement.) I've tried using self.rp (.rf etc..) to no avail. Any ideas what I'm doing wrong? -thanks in advance From ray007 at bluemail.ch Thu May 12 10:43:53 2005 From: ray007 at bluemail.ch (ray007@bluemail.ch) Date: Thu, 12 May 2005 16:43:53 +0800 Subject: [Tutor] py2exe Message-ID: <4262FED5000B22F6@mssazhh-int.msg.bluewin.ch> Hi I was wondering if someone knows of a better way to make an exe file out of python code. I would like to have just one exe file that once you run no other windows will pop up other than your application. If you use py2exe this will open up a DOS prompt which is not the desired output. Does anyone know how I can achieve this. Something similar to delphi exes. I would appreciate your help and advice in this matter. Thanks Ray From project5 at redrival.net Thu May 12 10:59:15 2005 From: project5 at redrival.net (Andrei) Date: Thu, 12 May 2005 08:59:15 +0000 (UTC) Subject: [Tutor] dicts&lists vs objects References: <9a8f06705051112026d229267@mail.gmail.com> Message-ID: Chris Somerlot gmail.com> writes: > is a premutation of another, and I'm having trouble following the code > I've written. > Is there a golden rule to knowing when to use objects instead of dictionaries and lists? It all depends on the programmer, the project, etc. I'd say that the fact that you're having trouble following your code is an indication that it might be time to drop the procedural/inline approach for something more structured. Not that it's impossible to write unmaintainable OOP code by the way, far from it :). E.g. imagine having one huge big Application object with everything that was a function having become a method of this monolithic object. Not an improvement at all. Depending on what/how you write, I'd say that for code over 50 lines (say 1h of work) an OO approach at least deserves consideration and will often turn out to have some benefits (it's possible to mix OO and procedural code). If a project runs into thousands of lines of code, it virtually always makes sense to bring OO into the picture. Yours, Andrei From kent37 at tds.net Thu May 12 12:04:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 May 2005 06:04:58 -0400 Subject: [Tutor] #NameError: global name is not defined In-Reply-To: <2c2812b60505120136755d67d2@mail.gmail.com> References: <2c2812b60505120136755d67d2@mail.gmail.com> Message-ID: <42832A4A.8070808@tds.net> Aaron Elbaz wrote: > Hi, > > I'm having difficulty understanding why the following code doesn't work: > > > getfr.py > #import pymetar > # > #class wReport: > # def __init__(self,metarcode="CYYC"): #weather for calgary INTL > # self.METARCODE=metarcode > # rf=pymetar.ReportFetcher(self.METARCODE) > # rep=rf.FetchReport() > # pr=rp.ParseReport(rep) > # def getRep() > # return pr.getFullReport You never assign to rp so it is undefined, which is what the error message is telling you. Looking at the pymetar example you are missing the line rp=pymetar.ReportParser() Kent From jfouhy at paradise.net.nz Thu May 12 12:38:18 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 12 May 2005 22:38:18 +1200 (NZST) Subject: [Tutor] py2exe In-Reply-To: <4262FED5000B22F6@mssazhh-int.msg.bluewin.ch> References: <4262FED5000B22F6@mssazhh-int.msg.bluewin.ch> Message-ID: <1115894297.4283321a010ff@www.paradise.net.nz> Quoting "ray007 at bluemail.ch" : > I was wondering if someone knows of a better way to make an exe file > out of python code. I would like to have just one exe file that once you > run no other windows will pop up other than your application. If you use > py2exe this will open up a DOS prompt which is not the desired output. Does > anyone know how I can achieve this. Something similar to delphi exes. Change the 'console=' option in your setup.py to 'window=' :-) -- John. From jsmith at medplus.com Thu May 12 15:08:20 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu, 12 May 2005 09:08:20 -0400 Subject: [Tutor] dicts&lists vs objects Message-ID: Those are good observations and I think answers part of the question. I think the other part is that even in OO code, how do you know what to make an object and what to just store in an existing data type like a list or dictionary. Personally, I use the "if it walks like a duck" rule. In other words, if you are storing an ordered list of items which are logically to each other, use a list. If you are storing an un-ordered list of logically related items which you think of referencing by some other list, use a dictionary. Anything else is an object. Another way to look at it is that anytime you have two or more lists of things which you are trying to keep connected by some arbitrary variable to keep track of the index, you should be using an object. This happens frequently in scientific code: elements = ['al', 'ar', 'o'] boiling_points = [500, 400, 150] element = 0 for i in xrange(1,len(elements)): stuff with elements[i] and boiling points[i] could be a dictionary: boiling_points = ['al': 500, 'ar': 400, 'o': 150] for (element, bp) in elements.iteritems(): stuff with element and bp But add one more property and you need a class class Element(object): def __init__(self, name, boiling_point, melting_point): you get the picture Jeff Disclaimer: I'm new to Python and wrote this on the fly, so if there are any coding errors from a Python standpoint, then this isn't Python but pseudo code which happens to resemble Python :-) Disclaimer 2: I'm not a materials scientist so don't let my numbers cause problems for those of you who are! -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Andrei Sent: Thursday, May 12, 2005 4:59 AM To: tutor at python.org Subject: Re: [Tutor] dicts&lists vs objects Chris Somerlot gmail.com> writes: > is a premutation of another, and I'm having trouble following the code > I've written. Is there a golden rule to knowing when to use objects > instead of dictionaries and lists? It all depends on the programmer, the project, etc. I'd say that the fact that you're having trouble following your code is an indication that it might be time to drop the procedural/inline approach for something more structured. Not that it's impossible to write unmaintainable OOP code by the way, far from it :). E.g. imagine having one huge big Application object with everything that was a function having become a method of this monolithic object. Not an improvement at all. Depending on what/how you write, I'd say that for code over 50 lines (say 1h of work) an OO approach at least deserves consideration and will often turn out to have some benefits (it's possible to mix OO and procedural code). If a project runs into thousands of lines of code, it virtually always makes sense to bring OO into the picture. Yours, Andrei _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Thu May 12 15:24:21 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri, 13 May 2005 01:24:21 +1200 Subject: [Tutor] dicts&lists vs objects In-Reply-To: <9a8f06705051112026d229267@mail.gmail.com> References: <9a8f06705051112026d229267@mail.gmail.com> Message-ID: Is some form of SQL database feasible? It sounds more like what you need. Depends on what you're storing, and how much. Cheers, Liam Clarke On 5/12/05, Chris Somerlot wrote: > > I have been working on a scientific application for awhile, and have been > using dictionaries and lists to store data and attributes of datasets. This > is getting cumbersome as there are many, every dict/list is a premutation of > another, and I'm having trouble following the code I've written. > > Is there a golden rule to knowing when to use objects instead of > dictionaries and lists? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050513/f4fa9a16/attachment.htm From maxnoel_fr at yahoo.fr Thu May 12 16:23:46 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 12 May 2005 15:23:46 +0100 Subject: [Tutor] character format In-Reply-To: References: Message-ID: <30B50FD5-37E7-4171-A933-6BDA5C5C80E0@yahoo.fr> On May 12, 2005, at 02:42, Tony Meyer wrote: >> >> From the email address, chances are that this was a New Zealand >> cultural >> > assumption. Ah, the French, lumping all English speakers under the > American > banner . Touch?. :D -- Max ( What makes it even more unforgivable is that I'm living in the UK at the moment -- one would have thought that by now I'd have realized that all English speakers are not American. ^^ ) From maxnoel_fr at yahoo.fr Thu May 12 17:06:22 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 12 May 2005 16:06:22 +0100 Subject: [Tutor] character format In-Reply-To: <1115863200.4282b8a016d05@www.paradise.net.nz> References: <8daabe5605051117262ff6ff64@mail.gmail.com> <1115859028.4282a85483b4b@www.paradise.net.nz> <1115863200.4282b8a016d05@www.paradise.net.nz> Message-ID: <21ABA89E-F211-45B2-97EE-4016ACCF58FD@yahoo.fr> On May 12, 2005, at 03:00, jfouhy at paradise.net.nz wrote: > As was pointed out, I'm not American. I guess the problem stems > from an > American cultural assumption, though, in that Americans (I think) > developed the > ASCII character set without any thought for other languages. At that time, it was a reasonable decision. Written French can still be understood without accented characters. It's just a bit harder, since the only convention we have for this is to replace accented characters with their non-accented versions (e.g. ?, ? and ? become e), but rarely if ever causes any trouble. The Germans are better in that regard (? -> ae, ? -> ss...). The true problem comes from the lateness in standardizing extended ASCII (characters 128 to 255) -- which, I guess, does in some way stem from the ACA (as in "we already have what we need to write English, so we'll worry about that later"). Opening a text file that contains extended chars in an editor is usually followed by up to 5 minutes of "guess the encoding", as the very nature of text files makes it virtually impossible for an editor to do it automatically and reliably. Now, I only write Unicode text files (most real text editors support this), but notepad.exe, as far as I know, only writes Windows- encoded files, which themselves are different from DOS-encoded files (I still have some of those lying around on some of my hard drives, written with edit.exe or e.com)... It gets very messy, very quickly. > Will a standard xterm display chr(130) as ? in linux for you, Max? > Or under Mac > OS X? I just made a few tests. So far, it seems that it depends on the character encoding in use: - If it's Western Latin 1, yes, but cat'ing Unicode text files doesn't work properly (which is to be expected). - If it's Unicode, it then depends on the application in use (although most of them just fail). bash 2.05 and zsh 4.2.3 get in big trouble when I type accented characters. ksh seems a bit more tolerant, but backspace behavior becomes erratic. vim sprouts random garbage, and emacs beeps at me angrily. Unicode text files cat nicely, though. > Anyway, in Python3000 all strings will be unicode, so it won't > matter then :-) As should be evident from the above post, I'm *really* looking forward to that. ;) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From william.ohiggins at utoronto.ca Thu May 12 19:37:41 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Thu, 12 May 2005 13:37:41 -0400 Subject: [Tutor] *nix-specific Python Scripting Message-ID: <20050512173741.GA13537@sillyrabbi.dyndns.org> I am trying to learn Python by translating some of my Perl scripts. One thing that is eluding me is assigning the results of system calls to variables. Here's what I want to do in Perl: $isxrunning = `ps -C startx | grep "startx"`; if ($isxrunning =~ "startx") { do something; } else { do something else; } It is a simple check to see if the X server is running (this is inelegant, but it works - if you have a better way, I'd love to know about it, but I would like to be able to do things like this in Python - so I might better write scripts with it). My experiments have lead me to the os.exec* collection of methods, and they seem fine, but they don't (as far as I understand them, which isn't very far) allow me to string piped commands or complex collections of switches together in the way that Perl's backticks does. Don't get me wrong, I'm in this to find out how things of this ilk are done in *Python* (if I wanted to know how this was done in Perl, I'd be asking somewhere else), I'm not whining for features. Does Python have a means of doing what I want, or do I construct my command lines in pieces and hand them to os.execl one at a time? Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050512/1a9d4cce/attachment.pgp From zenten at gmail.com Thu May 12 16:27:20 2005 From: zenten at gmail.com (Zenten) Date: Thu, 12 May 2005 10:27:20 -0400 Subject: [Tutor] help with tabs and Tkinter Message-ID: Ok, I'm writing a program using tkinter, that has a bit of data entry in it. It would be useful to have a window with various tabs to select between different "pages" in my entry. However, I can't figure out how to do this part, after looking through documentation. Can anyone help? Joshua From dyoo at hkn.eecs.berkeley.edu Thu May 12 19:56:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 10:56:28 -0700 (PDT) Subject: [Tutor] Pipe variable to external command (fwd) Message-ID: ---------- Forwarded message ---------- Date: Thu, 12 May 2005 11:31:57 -0600 From: Jeffrey Rice To: Danny Yoo Subject: Re: [Tutor] Pipe variable to external command At 12:16 AM 5/12/2005, Danny Yoo wrote: >###### > >>> child_out, child_in = popen2.popen2("wc") > >>> child_in.write("hello world\nthis is a test\ngoodbye!\n") > >>> child_in.close() > >>> result = child_out.read() > >>> child_out.close() > >>> result >' 3 7 36\n' >###### Thanks for your help -- this is working, with a minor wrinkle I have not cleared up yet. I also need to read stderr, so I looked at the docs and it seems that popen2.popen3 is the tool. * * * * CLAMAV_out, CLAMAV_in, CLAMAV_err= popen2.popen3(CLAMAV) CLAMAV_in.write(WORKING) CLAMAV_in.close() CLAM_RESULT=CLAMAV_out.read() CLAMAV_out.close() CLAM_ERR=CLAMAV_err.read() CLAMAV_err.close() * * * * CLAM_RESULT gives the correct reply, and stderr is 1. But CLAM_ERR is empty. This seems like it should be simple -- what am I missing? Jeff * * * * * * * Jeffrey Rice || jeffrice at finity.org || www.finity.org From dyoo at hkn.eecs.berkeley.edu Thu May 12 20:06:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 11:06:57 -0700 (PDT) Subject: [Tutor] *nix-specific Python Scripting In-Reply-To: <20050512173741.GA13537@sillyrabbi.dyndns.org> Message-ID: On Thu, 12 May 2005, William O'Higgins wrote: > I am trying to learn Python by translating some of my Perl scripts. One > thing that is eluding me is assigning the results of system calls to > variables. Here's what I want to do in Perl: > > $isxrunning = `ps -C startx | grep "startx"`; > > if ($isxrunning =~ "startx") { > do something; > } else { > do something else; > } > It is a simple check to see if the X server is running (this > is inelegant, but it works - if you have a better way, I'd love to know > about it, but I would like to be able to do things like this in Python - > so I might better write scripts with it). Hi William, You may want to look at the 'subprocess' module, or the 'popen2' module. I wrote a quick-and-dirty example of this yesterday: http://mail.python.org/pipermail/tutor/2005-May/038343.html which should apply to your problem. > My experiments have lead me to the os.exec* collection of methods, and > they seem fine, os.exec*() is almost certainly not what you want. *grin* A call to an exec*() function doesn't just call out to an external program, but completely replaces the currently running Python program. Once we do an exec*, we don't get back to Python. (Actually, you can do things with the exec*() functions, but you'll probably end up doing too much work with fork() too if you take that route.) > Don't get me wrong, I'm in this to find out how things of this ilk are > done in *Python* (if I wanted to know how this was done in Perl, I'd be > asking somewhere else), I'm not whining for features. Don't worry; We're tutors and programmers first. We're not averse to seeing code in other languages, as long as the code snippets are tastefully short. *grin* Best of wishes! From dyoo at hkn.eecs.berkeley.edu Thu May 12 20:10:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 11:10:33 -0700 (PDT) Subject: [Tutor] help with tabs and Tkinter In-Reply-To: Message-ID: On Thu, 12 May 2005, Zenten wrote: > Ok, I'm writing a program using tkinter, that has a bit of data entry in > it. It would be useful to have a window with various tabs to select > between different "pages" in my entry. However, I can't figure out how > to do this part, after looking through documentation. Hi Joshua, There is an extension to Tkinter called the Python MegaWidgets (PMW) which you may want to look at. The PMW package includes a tabbed notebook widget that you might be able to use: http://pmw.sourceforge.net/doc/NoteBook.html More infomation on the Python MegaWidgets can be found here: http://pmw.sourceforge.net/ Best of wishes! From jeffrice at finity.org Thu May 12 20:17:20 2005 From: jeffrice at finity.org (Jeffrey Rice) Date: Thu, 12 May 2005 12:17:20 -0600 Subject: [Tutor] Pipe variable to external command (fwd) In-Reply-To: References: Message-ID: <6.2.1.2.2.20050512121241.02758b48@popfile> At 11:56 AM 5/12/2005, Danny Yoo wrote: >* * * * >CLAMAV_out, CLAMAV_in, CLAMAV_err= popen2.popen3(CLAMAV) >CLAMAV_in.write(WORKING) >CLAMAV_in.close() >CLAM_RESULT=CLAMAV_out.read() >CLAMAV_out.close() >CLAM_ERR=CLAMAV_err.read() >CLAMAV_err.close() >* * * * > >CLAM_RESULT gives the correct reply, and stderr is 1. But CLAM_ERR is >empty. This seems like it should be simple -- what am I missing? I think I am messing this up! What I actually need is the exitcode of the spawned command, which is why stderr did not contain the info I wanted. It seems there is a new problem: to get the exitcode of the spawned process, not the "shell" that contains it. I found this example on another list that seems to address this problem: http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/68786 As a work around, I end up calling popen3 like this: Open3.popen3 ("/some/command/to/run ; echo $? 1>&2") { ... } That ensures the exit code from /some/command/to/run will be the last line of the standard error stream from Open3.popen3. Then I can just pull that line off the output to get the return code. Is there a more elegant way to get the exitcode off the child process, or is this the "approved" method? Jeff * * * * * * * Jeffrey Rice || jeffrice at finity.org || www.finity.org From dyoo at hkn.eecs.berkeley.edu Thu May 12 20:24:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 11:24:15 -0700 (PDT) Subject: [Tutor] Pipe variable to external command (fwd) In-Reply-To: <6.2.1.2.2.20050512121241.02758b48@popfile> Message-ID: > http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/68786 > As a work around, I end up calling popen3 like this: > > Open3.popen3 ("/some/command/to/run ; echo $? 1>&2") { ... } > > That ensures the exit code from /some/command/to/run will be the last > line of the standard error stream from Open3.popen3. Then I can just > pull that line off the output to get the return code. Hi Jeffrey, Ah! Ok, you're looking for the error code too. > Is there a more elegant way to get the exitcode off the child process, > or is this the "approved" method? Yeah; check the Popen3 object in the 'popen2' module: it has a separate way of getting at the error code: http://www.python.org/doc/lib/popen3-objects.html For example: ###### >>> import popen2 >>> process = popen2.Popen3(['wc']) >>> process.tochild.write("hello\nworld") >>> process.tochild.close() >>> process.fromchild.read() ' 1 2 11\n' >>> process.fromchild.close() >>> process.wait() 0 ###### Hope this helps! From rschroev_nospam_ml at fastmail.fm Thu May 12 21:37:03 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 12 May 2005 21:37:03 +0200 Subject: [Tutor] *nix-specific Python Scripting In-Reply-To: <20050512173741.GA13537@sillyrabbi.dyndns.org> References: <20050512173741.GA13537@sillyrabbi.dyndns.org> Message-ID: William O'Higgins wrote: > It is a simple check to see if the X server is running (this is > inelegant, but it works - if you have a better way, I'd love to know > about it, but I would like to be able to do things like this in Python - > so I might better write scripts with it). Checking for startx doesn't work if the server is started via xdm (or kdm or gdm). Another solution would be to check for the DISPLAY environment variable, though that solution has problems of it's own. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From uselinux34 at yahoo.co.uk Thu May 12 21:57:36 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Thu, 12 May 2005 20:57:36 +0100 Subject: [Tutor] any help with this piece of code Message-ID: <4283B530.3030103@yahoo.co.uk> import os fileList = [] subDirectories = [] directories = [] directoryPath = raw_input( "Type in the path you want to start at: " ) for directory,subDirectory, files in os.walk( directoryPath ): directories.append( directory ) subDirectories.append( subDirectory ) fileList.append( files ) for Files in fileList: print Files # It works fine up until here fileToSearchFor = raw_input( "Type in the file name you want to search for: ") if fileToSearchFor in fileList: print "%s was found" % fileToSearchFor else: print "%s was not found" % fileToSearchFor Could someone explain to me why this pice of code doesn't work, in that it works fine up until where I have commented , but when I come to search the list for a file name, even though I know the filename is in that particular directory, and is present in the list returned by 'fileList.append( files )' it always reports that the file is not found. Incidentally if you try this code out, when prompted for the path to start at, don't select a large directory as it takes sometime to run. It may not be very useful I am just curious as to why the file name cannot be found in the list, what am I missing? Richard Gelling From william.ohiggins at utoronto.ca Thu May 12 22:08:44 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Thu, 12 May 2005 16:08:44 -0400 Subject: [Tutor] *nix-specific Python Scripting In-Reply-To: References: <20050512173741.GA13537@sillyrabbi.dyndns.org> Message-ID: <20050512200844.GA14439@sillyrabbi.dyndns.org> On Thu, May 12, 2005 at 09:37:03PM +0200, Roel Schroeven wrote: >William O'Higgins wrote: >> It is a simple check to see if the X server is running (this is >> inelegant, but it works - if you have a better way, I'd love to know >> about it, but I would like to be able to do things like this in Python - >> so I might better write scripts with it). > >Checking for startx doesn't work if the server is started via xdm (or >kdm or gdm). Another solution would be to check for the DISPLAY >environment variable, though that solution has problems of it's own. Absolutely true. However, in this context I can be assured that if X is running, it was started by startx. More importantly, the DISPLAY environment variable is not usually imported into the shell/process running a script - exporting ENV willy-nilly into sub-processes and spawned shells is, from a security standpoint, very, very bad. I could just as easily look for X itself, which is more foolproof, but I am only looking to stump a small sub-set of possible fools. The set of all fools is said to be unbounded, making proof against them non-trivial. Still, I appreciate the advice and suggestions. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050512/d122fab8/attachment.pgp From dyoo at hkn.eecs.berkeley.edu Thu May 12 22:15:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 13:15:39 -0700 (PDT) Subject: [Tutor] any help with this piece of code In-Reply-To: <4283B530.3030103@yahoo.co.uk> Message-ID: On Thu, 12 May 2005, Richard gelling wrote: > fileToSearchFor = raw_input( "Type in the file name you want to search > for: ") > > if fileToSearchFor in fileList: > print "%s was found" % fileToSearchFor > else: > print "%s was not found" % fileToSearchFor > > Could someone explain to me why this pice of code doesn't work, in that > it works fine up until where I have commented , but when I come to > search the list for a file name, even though I know the filename is in > that particular directory, and is present in the list returned by > 'fileList.append( files )' it always reports that the file is not found. Hi Richard, Ah. TypeError. *grin* At least, a conceptual one. The code above accumulates the fileList with the following: fileList.append( files ) But the problem is that your fileList is a list of lists of file names. What you really want to do is: fileList.extend( files ) to hold a flat list of file names in fileList. The extend() method of a list allows the list to absorb the elements of the other input list. Concretely, your fileList probably looks something like this: [['hello.txt'], ['notes.txt', 'blah.txt']] where you really want to have something like this instead: ['hello.txt', 'notes.txt', 'blah.txt'] Hope this helps! From 3dbernard at gmail.com Thu May 12 23:17:31 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 12 May 2005 17:17:31 -0400 Subject: [Tutor] Why use apply()? Message-ID: <61d0e2b405051214174387c385@mail.gmail.com> Just a generic question: why one would use apply()? In Learning Python, on page 357, there is an example of generating an instance using apply(): class A: def __init__( self, number ): self.number = number a = apply( A, 3 ) What is the benefit of doing this over simply creating an instance "the usual way": a = A( 3 ) Thanks Bernard From zamb at saudi.net.sa Thu May 12 23:18:29 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Fri, 13 May 2005 00:18:29 +0300 Subject: [Tutor] *nix-specific Python Scripting [Off Topic] In-Reply-To: <20050512173741.GA13537@sillyrabbi.dyndns.org> References: <20050512173741.GA13537@sillyrabbi.dyndns.org> Message-ID: <1115932709.31062.11.camel@localhost.localdomain> On Thu, 2005-05-12 at 13:37 -0400, William O'Higgins wrote: > I am trying to learn Python by translating some of my Perl scripts. One > thing that is eluding me is assigning the results of system calls to > variables. Here's what I want to do in Perl: > > $isxrunning = `ps -C startx | grep "startx"`; > > if ($isxrunning =~ "startx") { > do something; > } else { > do something else; > } > > It is a simple check to see if the X server is running (this is > inelegant, but it works - if you have a better way, I'd love to know > about it, but I would like to be able to do things like this in Python - > so I might better write scripts with it). > ... (This is off topic! Sorry.) Why using ?ps -C startx | grep "startx"?? Why not ?ps h -C startx?[1]? Even better, why not ?pidof startx?? As for another way to check for X, did you try checking for the lock file? (Usually in ?/tmp/.X0-lock?) Combined with checking the $DISPLAY environment variable, this is a much better and elegant solution in my not-so-experienced opinion. Notes: 1. This probably wont work with FreeBSD (and all other *BSD(s) in that matter), instead, try the ?--no-headers? option. See the manual page for ?ps?. Ziyad. From jeffrice at finity.org Thu May 12 23:22:11 2005 From: jeffrice at finity.org (Jeffrey Rice) Date: Thu, 12 May 2005 15:22:11 -0600 Subject: [Tutor] [unclassified] Re: Pipe variable to external command (fwd) In-Reply-To: References: <6.2.1.2.2.20050512121241.02758b48@popfile> Message-ID: <6.2.1.2.2.20050512144540.0297a808@popfile> At 12:24 PM 5/12/2005, Danny Yoo wrote: >###### > >>> import popen2 > >>> process = popen2.Popen3(['wc']) > >>> process.tochild.write("hello\nworld") > >>> process.tochild.close() > >>> process.fromchild.read() >' 1 2 11\n' > >>> process.fromchild.close() > >>> process.wait() >0 >###### This is all well and good if the child exits with 0, but things get a little funky if it doesn't. For example, modifying the model to have clamdscan exit with 0: ###### >>> import popen2 >>> process = popen2.Popen3(['clamdscan','ham.test']) >>> process.tochild.close() >>> process.fromchild.read() 'ham.test: OK\n\n----------- SCAN SUMMARY -----------\nInfected files: 0\nTime: 0.098 sec (0 m 0 s)\n' >>> process.fromchild.close() >>> process.wait() 0 ###### Now rewrite it to return an exit code of 1: ###### >>> import popen2 >>> process = popen2.Popen3(['clamdscan','eicar.test']) >>> process.tochild.write("hello\nworld") >>> process.tochild.close() >>> process.fromchild.read() 'eicar.test: Eicar-Test-Signature FOUND\n\n----------- SCAN SUMMARY -----------\nInfected files: 1\nTime: 0.043 sec (0 m 0 s)\n' >>> process.fromchild.close() >>> process.wait() 256 ###### Now for a exit code of 2: ###### >>> import popen2 >>> process = popen2.Popen3(['clamdscan','nonexistent.test']) >>> process.tochild.close() >>> process.fromchild.read() '\n----------- SCAN SUMMARY -----------\nInfected files: 0\nTime: 0.004 sec (0 m 0 s)\n' >>> process.fromchild.close() >>> process.wait() 512 ###### In my fiirst example, clamdscan should return 1 when the EICAR string is found -- process.wait() gets 256 instead. In the second, clamdscan returns 2 if an error occurs, such as trying to scan a non-existent file, but 512 is returned. No doubt there is a reason why the exit code is getting multiplied by 256... ??? My search has not enlightened me, however. Jeff * * * * * * * Jeffrey Rice || jeffrice at finity.org || www.finity.org From keridee at jayco.net Thu May 12 23:27:47 2005 From: keridee at jayco.net (Jacob S.) Date: Thu, 12 May 2005 16:27:47 -0500 Subject: [Tutor] #NameError: global name is not defined References: <2c2812b60505120136755d67d2@mail.gmail.com> Message-ID: <001301c55739$8a65ffe0$9e5428cf@JSLAPTOP> > Hi, > > I'm having difficulty understanding why the following code doesn't work: > > > getfr.py > #import pymetar > # > #class wReport: > # def __init__(self,metarcode="CYYC"): #weather for calgary INTL > # self.METARCODE=metarcode > # rf=pymetar.ReportFetcher(self.METARCODE) > # rep=rf.FetchReport() > # pr=rp.ParseReport(rep) > # def getRep() > # return pr.getFullReport > > #>>> import getfr > > #>>> w = getfr.wReport() > > #Traceback (most recent call last): > > # File "", line 1, in ? > > # File "getfr.py", line 8, in __init__ > > # pr=rp.ParseReport(rep) > > #NameError: global name 'rp' is not defined I would also suggest, along side Kent's suggestion, that you rewrite two things. 1) pr = rp.ParseReport(rep) as self.pr = rp.ParseReport(rep) 2) def getRep(): as def getRep(self): to make it a method of the class Obviously, this will not fix your problem, but it makes it neater and less error prone in the future. To fix your problem, I refered to Kent... I'm done, Jacob From albertito_g at hotmail.com Fri May 13 00:01:23 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 12 May 2005 22:01:23 +0000 Subject: [Tutor] Compare hours Message-ID: Hey everyone I have a question. I need to compare two dates and times but it has to be quick. (With quick I mean that the algorythm has to be simple in efficient Here is the deal: day="thursday" hour1="15:30" hour2="16:30" all of the above are strings I have to get the system date and time and check if they are between the strings and check that days are the same Can anyone send me an explained code cause I don't know how to work with dates and times in Python (Never needed it until now) Thanks Alberto From bgailer at alum.rpi.edu Fri May 13 00:18:39 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 12 May 2005 15:18:39 -0700 Subject: [Tutor] Why use apply()? In-Reply-To: <61d0e2b405051214174387c385@mail.gmail.com> References: <61d0e2b405051214174387c385@mail.gmail.com> Message-ID: <6.1.2.0.0.20050512151713.0370fad8@pop.sbcglobal.yahoo.com> At 02:17 PM 5/12/2005, Bernard Lebel wrote: >Just a generic question: why one would use apply()? > >In Learning Python, on page 357, there is an example of generating an >instance using apply(): > >class A: > def __init__( self, number ): > self.number = number > >a = apply( A, 3 ) >What is the benefit of doing this over simply creating an instance "the >usual way": >a = A( 3 ) No benefit. See 2.2 Non-essential Built-in Functions in the Python Library Reference. 'Use of apply() is not necessary since the ``extended call syntax,'' as used in the last example, is completely equivalent." Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050512/70e93985/attachment.htm From bgailer at alum.rpi.edu Fri May 13 00:19:38 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 12 May 2005 15:19:38 -0700 Subject: [Tutor] Compare hours In-Reply-To: References: Message-ID: <6.1.2.0.0.20050512151904.0369b3b0@pop.sbcglobal.yahoo.com> At 03:01 PM 5/12/2005, Alberto Troiano wrote: >Hey everyone > >I have a question. I need to compare two dates and times but it has to be >quick. (With quick I mean that the algorythm has to be simple in efficient > >Here is the deal: > >day="thursday" >hour1="15:30" >hour2="16:30" > >all of the above are strings >I have to get the system date and time and check if they are between the >strings and check that days are the same > >Can anyone send me an explained code cause I don't know how to work with >dates and times in Python (Never needed it until now) Take a look at the time module. Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050512/d6b50c26/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri May 13 01:10:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 12 May 2005 16:10:30 -0700 (PDT) Subject: [Tutor] [unclassified] Re: Pipe variable to external command (fwd) In-Reply-To: <6.2.1.2.2.20050512144540.0297a808@popfile> Message-ID: > In my first example, clamdscan should return 1 when the EICAR string is > found -- process.wait() gets 256 instead. In the second, clamdscan > returns 2 if an error occurs, such as trying to scan a non-existent > file, but 512 is returned. > > No doubt there is a reason why the exit code is getting multiplied by > 256... ??? My search has not enlightened me, however. The return value of wait() packs a few values in a single integer, so you may need to do some bit manipulation. The popen2 documentation talks about this: """ wait() Waits for and returns the status code of the child process. The status code encodes both the return code of the process and information about whether it exited using the exit() system call or died due to a signal. Functions to help interpret the status code are defined in the os module; see section 6.1.5 for the W*() family of functions. """ http://www.python.org/doc/lib/popen3-objects.html You can take a look near the bottom of: http://www.python.org/doc/lib/os-process.html#os-process for functions like os.WEXITSTATUS(), which should help you get the values that you're expecting. This is all definitely "not obvious" stuff, so please feel free to continue to ask questions. Best of wishes! From keridee at jayco.net Fri May 13 01:59:18 2005 From: keridee at jayco.net (Jacob S.) Date: Thu, 12 May 2005 18:59:18 -0500 Subject: [Tutor] Help with Challenge number 5 Message-ID: <001f01c5574e$a2b406e0$9e5428cf@JSLAPTOP> Is there anyone on the list right now who knows what to do with yes! pickle! on challenge number 5 -- Any hints appreciated. I've tried the most common combinations of yes and pickle in the url path, but to no avail. By the way, this means I solved challenge 4. TIA, Jacob From rschroev_nospam_ml at fastmail.fm Fri May 13 02:08:10 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 13 May 2005 02:08:10 +0200 Subject: [Tutor] Help with Challenge number 5 In-Reply-To: <001f01c5574e$a2b406e0$9e5428cf@JSLAPTOP> References: <001f01c5574e$a2b406e0$9e5428cf@JSLAPTOP> Message-ID: Jacob S. wrote: > Is there anyone on the list right now who knows what to do with > > yes! pickle! > > on challenge number 5 -- Any hints appreciated. > > I've tried the most common combinations of yes and pickle in the url path, > but to no avail. Have a look at the module index in the python docs. > By the way, this means I solved challenge 4. Congratulations! -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mishpaha at telus.net Thu May 12 20:08:19 2005 From: mishpaha at telus.net (Aaron) Date: Thu, 12 May 2005 18:08:19 +0000 Subject: [Tutor] help: threading + cron in python? Message-ID: <42839B93.8020305@telus.net> Lets say you have a threaded program. Is there any way to make it so that an operation occurs at a certain time every hour (eg) like the cron daemon? I'm afraid I don't really understanding threading enought to make this work.. From keridee at jayco.net Fri May 13 02:30:56 2005 From: keridee at jayco.net (Jacob S.) Date: Thu, 12 May 2005 19:30:56 -0500 Subject: [Tutor] Help with Challenge number 5 References: <001f01c5574e$a2b406e0$9e5428cf@JSLAPTOP> Message-ID: <003901c55753$12537a90$9e5428cf@JSLAPTOP> Okay, I've tried pickling, marshal, marshalling, serialization, and amazingly pi because I noticed that pickle was under the section 3.14 however, none of this worked, so, I hate to ask again but, could you go one step farther? Thanx, Jacob From maxnoel_fr at yahoo.fr Fri May 13 02:42:58 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 13 May 2005 01:42:58 +0100 Subject: [Tutor] Help with Challenge number 5 In-Reply-To: <003901c55753$12537a90$9e5428cf@JSLAPTOP> References: <001f01c5574e$a2b406e0$9e5428cf@JSLAPTOP> <003901c55753$12537a90$9e5428cf@JSLAPTOP> Message-ID: On May 13, 2005, at 01:30, Jacob S. wrote: > Okay, I've tried pickling, marshal, marshalling, serialization, and > amazingly pi because I noticed that pickle was under the section 3.14 > however, none of this worked, so, I hate to ask again but, could > you go one > step farther? > > Thanx, > Jacob > Have a look at the source code of the "peak hell" page. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Fri May 13 08:52:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 13 May 2005 07:52:05 +0100 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) References: Message-ID: <009c01c55788$46c2d6b0$91508651@xp> > now I always used map() to perform a looped call on a function that > would change the attribute value, as shown in Mark Lutz & David > Ascher's Learning Python: > > # Perform attribute value change on a single instance > def iterateInstances( oInstance ): > oInstance.value = myValue > > # Loop over list of instances > map( iterateInstances, aListOfInstances ) How bizarre. I'm astonished that Lutz/Ascher even show that as a means of changing an attribute. As Danny said, it's definitely an abuse of map, and there is no advantage whatsoever, as far as I can see. In fact I suspect that it's actually slower than an explicit loop (because of the extra list building). > However I was looking into lambdas in hope to eliminate the need to > define a function. And a loop also avoids the need for a function, and therefore for a function call, which is another reason the map should be slower. Its completely weird that a text book should even suggest that map be used for this! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ray007 at bluemail.ch Fri May 13 08:53:44 2005 From: ray007 at bluemail.ch (ray007@bluemail.ch) Date: Fri, 13 May 2005 14:53:44 +0800 Subject: [Tutor] py2exe In-Reply-To: <1115894297.4283321a010ff@www.paradise.net.nz> Message-ID: <4262FED5000B94E6@mssazhh-int.msg.bluewin.ch> Hi Thanks for this. But do you know how I can achieve a single exe file with the dist and build folders. Is it possible to run a single exe file without the other dependencies? Thanks for you help. ray >-- Original-Nachricht -- >Date: Thu, 12 May 2005 22:38:18 +1200 (NZST) >From: jfouhy at paradise.net.nz >To: tutor at python.org >Subject: Re: [Tutor] py2exe > > >Quoting "ray007 at bluemail.ch" : > >> I was wondering if someone knows of a better way to make an exe file >> out of python code. I would like to have just one exe file that once you >> run no other windows will pop up other than your application. If you use >> py2exe this will open up a DOS prompt which is not the desired output. >Does >> anyone know how I can achieve this. Something similar to delphi exes. > >Change the 'console=' option in your setup.py to 'window=' :-) > >-- >John. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From work at infomaniak.ch Fri May 13 09:58:18 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Fri, 13 May 2005 09:58:18 +0200 Subject: [Tutor] creation of a module Message-ID: <20050513075818.GB17427@obs.unige.ch> hi, 1) I'm trying to create my _first_ own module. I've decided to write each class into a separate file. /MyModule|-bunch.py |-a.py |-b.py `-c.py {a,b,c}.py contains respecetively classA,classB,classC more some unittest and bunch.py will contains some usefull function using the class{A,B,C} I'd like that when I import MyModule (`import MyModule')OB I'll see from it: MyModule.classA .classB .classC . . ... without seeing MyModule.{a,b,c} 2) does someone now how to do this: x=3 with a function like: assign('x',3) -- Cedric BRINER From joe at omc-international.com.au Fri May 13 09:17:06 2005 From: joe at omc-international.com.au (Joe Healy) Date: Fri, 13 May 2005 17:17:06 +1000 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <009c01c55788$46c2d6b0$91508651@xp> References: <009c01c55788$46c2d6b0$91508651@xp> Message-ID: <42845472.1020708@omc-international.com.au> Alan Gauld wrote: >>now I always used map() to perform a looped call on a function that >>would change the attribute value, as shown in Mark Lutz & David >>Ascher's Learning Python: >> >># Perform attribute value change on a single instance >>def iterateInstances( oInstance ): >> oInstance.value = myValue >> >># Loop over list of instances >>map( iterateInstances, aListOfInstances ) >> >> > >How bizarre. I'm astonished that Lutz/Ascher even show that as a means >of changing an attribute. As Danny said, it's definitely an abuse of >map, >and there is no advantage whatsoever, as far as I can see. In fact I >suspect that it's actually slower than an explicit loop (because of >the extra list building). > > I have just been looking at http://www.python.org/moin/PythonSpeed/PerformanceTips#loops and whilst the examples do not show anything like this, they describe the map function as a for moved into C code. Could be confusing. Does not mention anything about return a list. > > >>However I was looking into lambdas in hope to eliminate the need to >>define a function. >> >> > >And a loop also avoids the need for a function, and therefore for >a function call, which is another reason the map should be slower. > >Its completely weird that a text book should even suggest that map >be used for this! > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > -- ________________________________________________________ Joe Healy | Engineer OMC-International | 6 Paterson St | Abbotsford, VIC 3067 Melbourne | Australia www.omc-international.com.au Dedicated to safer and more efficient shipping. From pierre.barbier at cirad.fr Fri May 13 09:21:05 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 13 May 2005 09:21:05 +0200 Subject: [Tutor] help: threading + cron in python? In-Reply-To: <42839B93.8020305@telus.net> References: <42839B93.8020305@telus.net> Message-ID: <42845561.4010305@cirad.fr> Ok, there is an easy way :) You can write something like : from datetime import datetime import time def run_at( t, fct, fct_args = (), fct_words = {}): now = datetime.today() delta = (t-now).minutes time.sleep(delta) fct(*fct_args, **fct_kwords) Now you can just launch this function in a new thread :) It will wait the wanted time and launch the function at that moment ! Pierre Aaron a ?crit : > Lets say you have a threaded program. Is there any way to make it so > that an operation occurs at a certain time every hour (eg) like the cron > daemon? > > I'm afraid I don't really understanding threading enought to make this > work.. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Fri May 13 12:10:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 May 2005 06:10:02 -0400 Subject: [Tutor] creation of a module In-Reply-To: <20050513075818.GB17427@obs.unige.ch> References: <20050513075818.GB17427@obs.unige.ch> Message-ID: <42847CFA.7010707@tds.net> Cedric BRINER wrote: > hi, > > 1) > I'm trying to create my _first_ own module. I've decided to write each class into a separate file. > > /MyModule|-bunch.py > |-a.py > |-b.py > `-c.py You also need MyModule/__init__.py to signal to Python that MymModule is a package. (Actually you are creating a package containing several modules.) > > {a,b,c}.py contains respecetively classA,classB,classC more some unittest > and bunch.py will contains some usefull function using the class{A,B,C} > > I'd like that when I import MyModule (`import MyModule')OB > I'll see from it: > MyModule.classA > .classB > .classC > . > . > ... > without seeing MyModule.{a,b,c} In MyModule/__init__.py put from MyModule.a import classA from MyModule.b import classB from MyModule.c import classC This creates package-level attributes for the classes. > 2) does someone now how to do this: > x=3 > with a function like: > assign('x',3) Can you say why you want to do this? It is possible but generally it is better to use a dict: values = {} values['x'] = 3 Kent From jfouhy at paradise.net.nz Fri May 13 12:30:45 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 13 May 2005 22:30:45 +1200 (NZST) Subject: [Tutor] py2exe In-Reply-To: <4262FED5000B94E6@mssazhh-int.msg.bluewin.ch> References: <4262FED5000B94E6@mssazhh-int.msg.bluewin.ch> Message-ID: <1115980245.428481d55e8fa@www.paradise.net.nz> Quoting "ray007 at bluemail.ch" : > Thanks for this. But do you know how I can achieve a single exe file > with the dist and build folders. Is it possible to run a single exe file > without the other dependencies? There is another freezer here: http://starship.python.net/crew/atuining/cx_Freeze/ I don't have any experience with it, though, so I don't know if it will do what you want. Just as a note --- you only need to distribute the contents of the dist directory. Don't worry about the build directory or your source code. -- John. From servando at mac.com Fri May 13 13:19:05 2005 From: servando at mac.com (Servando Garcia) Date: Fri, 13 May 2005 06:19:05 -0500 Subject: [Tutor] URLLIB Message-ID: Hello list I am on challenge 5. I think I need to some how download a file. I have been trying like so X=urllib.URLopener(name,proxies={'http':'URL').distutils.copy_file('Some FileName') but with no luck. Servando Garcia John 3:16 For GOD so loved the world.......... -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 296 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050513/42a14830/attachment.bin From kent37 at tds.net Fri May 13 13:52:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 May 2005 07:52:20 -0400 Subject: [Tutor] URLLIB In-Reply-To: References: Message-ID: <428494F4.5090601@tds.net> Servando Garcia wrote: > Hello list > I am on challenge 5. I think I need to some how download a file. I have > been trying like so > > X=urllib.URLopener(name,proxies={'http':'URL').distutils.copy_file('SomeFileName') urlopener() returns a file-like object - something that behaves like an open file. Try x = urllib.urlopener(name) data = x.read() Kent From kent37 at tds.net Fri May 13 13:59:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 May 2005 07:59:24 -0400 Subject: [Tutor] py2exe In-Reply-To: <4262FED5000B94E6@mssazhh-int.msg.bluewin.ch> References: <4262FED5000B94E6@mssazhh-int.msg.bluewin.ch> Message-ID: <4284969C.3070007@tds.net> ray007 at bluemail.ch wrote: > Hi > > Thanks for this. But do you know how I can achieve a single exe file with > the dist and build folders. Is it possible to run a single exe file without > the other dependencies? The most common approach on Windows seems to be to use py2exe to create the executable and InnoSetup or NSIS to package an installer. This gives you a single-file distribution though the executable is more than one file. For more discussion search comp.lang.python for py2exe innosetup: http://groups-beta.google.com/group/comp.lang.python/search?hl=en&group=comp.lang.python&q=py2exe+innosetup&qt_g=1&searchnow=Search+this+group Kent From greg.lindstrom at novasyshealth.com Fri May 13 14:52:54 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Fri, 13 May 2005 07:52:54 -0500 Subject: [Tutor] Python Resources In-Reply-To: References: Message-ID: <4284A326.5070109@novasyshealth.com> Hello- I have been asked to write an article for the IEEE "IT Pro" magazine dealing with using Python in the medical field. The editors asked for about half the article dealing with using Python and the other half giving a short tutorial. They also asked for three "sidebars"; I'm going with Tim Peter's "Zen of Python" for one, a comparison of "Hello, World", in C, C++, Perl, and Java in the second, and for the third I would like to list some resources. I have the Python home page, "Dive Into Python", the Python Gems" page, but would like to ask what resources would any of you suggest? I'd like between 5 and 10, with a short description of each. The article emphasizes the simple syntax of Python and the friendliness of our community. It encourages anyone interested in learning to subscribe to this mailing list and ask questions (though I do caution them not to submit their homework simply to get a solution). I have asked two people to review the paper from a "Python" perspective to make sure I have not mis-represented the language (I'm sorry about the delays, Steve, but the paper is coming!). If any of you would like to review it, I would be happy to send you a copy, too. I have about a week before submission. Thanks for your help, --greg From albertito_g at hotmail.com Fri May 13 15:24:29 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 13 May 2005 13:24:29 +0000 Subject: [Tutor] Help with time module In-Reply-To: <4284A326.5070109@novasyshealth.com> Message-ID: Hey everyone I have two strings like this hour1="14:30" hour2="15:30" I want to compare them like this: if local_time between hour1 and hour2: print True else print False Can anyone tell me how to make that comparison to work??????? (I don't know how to take only the time in this format(Hour:Minutes)) Thanks in advanced Alberto From kent37 at tds.net Fri May 13 15:56:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 May 2005 09:56:17 -0400 Subject: [Tutor] Help with time module In-Reply-To: References: Message-ID: <4284B201.7040802@tds.net> Alberto Troiano wrote: > I have two strings like this > > hour1="14:30" > hour2="15:30" > > I want to compare them like this: > > if local_time between hour1 and hour2: > print True > else > print False > > Can anyone tell me how to make that comparison to work??????? (I don't know > how to take only the time in this format(Hour:Minutes)) time.strptime() can parse the time string to a time tuple, then you can pull out a tuple of (hours, minutes) and compare. >>> import time >>> time.strptime('10:23', '%H:%M') (1900, 1, 1, 10, 23, 0, 0, 1, -1) Here is a helper function that extracts (hours, minutes) from a provided string, or from the clock time if no string is given: >>> def getHoursMinutes(ts=None): ... if ts: ... t = time.strptime(ts, '%H:%M') ... else: ... t = time.localtime() ... return (t.tm_hour, t.tm_min) ... >>> getHoursMinutes() (9, 52) >>> getHoursMinutes('8:34') (8, 34) >>> hour1="14:30" >>> hour2="15:30" >>> getHoursMinutes(hour1) (14, 30) The values returned from getHoursMinutes() can be compared directly: >>> getHoursMinutes(hour1) <= getHoursMinutes() <= getHoursMinutes(hour2) False >>> hour1='8:56' >>> getHoursMinutes(hour1) <= getHoursMinutes() <= getHoursMinutes(hour2) True Kent From 3dbernard at gmail.com Fri May 13 16:39:20 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 13 May 2005 10:39:20 -0400 Subject: [Tutor] Why use apply()? In-Reply-To: <6.1.2.0.0.20050512151713.0370fad8@pop.sbcglobal.yahoo.com> References: <61d0e2b405051214174387c385@mail.gmail.com> <6.1.2.0.0.20050512151713.0370fad8@pop.sbcglobal.yahoo.com> Message-ID: <61d0e2b4050513073972a17a06@mail.gmail.com> All right, thank you. Bernard On 5/12/05, Bob Gailer wrote: > At 02:17 PM 5/12/2005, Bernard Lebel wrote: > > Just a generic question: why one would use apply()? > > In Learning Python, on page 357, there is an example of generating an > instance using apply(): > > class A: > def __init__( self, number ): > self.number = number > > a = apply( A, 3 ) > What is the benefit of doing this over simply creating an instance "the > usual way": > a = A( 3 ) > No benefit. See 2.2 Non-essential Built-in Functions in the Python Library > Reference. 'Use of apply() is not necessary since the ``extended call > syntax,'' as used in the last example, is completely equivalent." > > > Bob Gailer > mailto:bgailer at alum.rpi.edu > 510 558 3275 home > 720 938 2625 cell From 3dbernard at gmail.com Fri May 13 16:52:20 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 13 May 2005 10:52:20 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <009c01c55788$46c2d6b0$91508651@xp> References: <009c01c55788$46c2d6b0$91508651@xp> Message-ID: <61d0e2b40505130752582ce88@mail.gmail.com> The authors even go as far as saysing, on page 228 (first paragraph) that map() used that way has a performance benefit and is faster than a for loop. Cheers Bernard On 5/13/05, Alan Gauld wrote: > How bizarre. I'm astonished that Lutz/Ascher even show that as a means > of changing an attribute. As Danny said, it's definitely an abuse of > map, > and there is no advantage whatsoever, as far as I can see. In fact I > suspect that it's actually slower than an explicit loop (because of > the extra list building). > > > However I was looking into lambdas in hope to eliminate the need to > > define a function. > > And a loop also avoids the need for a function, and therefore for > a function call, which is another reason the map should be slower. > > Its completely weird that a text book should even suggest that map > be used for this! > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From albertito_g at hotmail.com Fri May 13 17:14:16 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 13 May 2005 15:14:16 +0000 Subject: [Tutor] Help with time module In-Reply-To: <4284B201.7040802@tds.net> Message-ID: Thank you so much Kent That's exactly what I was lookin for Regards Alberto
 Gaucho
>From: Kent Johnson >CC: tutor at python.org >Subject: Re: [Tutor] Help with time module >Date: Fri, 13 May 2005 09:56:17 -0400 > >Alberto Troiano wrote: > > I have two strings like this > > > > hour1="14:30" > > hour2="15:30" > > > > I want to compare them like this: > > > > if local_time between hour1 and hour2: > > print True > > else > > print False > > > > Can anyone tell me how to make that comparison to work??????? (I don't >know > > how to take only the time in this format(Hour:Minutes)) > >time.strptime() can parse the time string to a time tuple, then you can >pull out a tuple of (hours, >minutes) and compare. > > >>> import time > >>> time.strptime('10:23', '%H:%M') >(1900, 1, 1, 10, 23, 0, 0, 1, -1) > >Here is a helper function that extracts (hours, minutes) from a provided >string, or from the clock >time if no string is given: > > >>> def getHoursMinutes(ts=None): > ... if ts: > ... t = time.strptime(ts, '%H:%M') > ... else: > ... t = time.localtime() > ... return (t.tm_hour, t.tm_min) > ... > >>> getHoursMinutes() >(9, 52) > >>> getHoursMinutes('8:34') >(8, 34) > >>> hour1="14:30" > >>> hour2="15:30" > >>> getHoursMinutes(hour1) >(14, 30) > >The values returned from getHoursMinutes() can be compared directly: > > >>> getHoursMinutes(hour1) <= getHoursMinutes() <= >getHoursMinutes(hour2) >False > >>> hour1='8:56' > >>> getHoursMinutes(hour1) <= getHoursMinutes() <= >getHoursMinutes(hour2) >True > >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From johnp at milwaukielumber.com Fri May 13 17:17:19 2005 From: johnp at milwaukielumber.com (John Purser) Date: Fri, 13 May 2005 08:17:19 -0700 Subject: [Tutor] Python Resources In-Reply-To: <4284A326.5070109@novasyshealth.com> Message-ID: <200505131517.j4DFHJYT015316@email.morseintranet.com> Greg, Thanks for taking one for the team! How about some OS specific resources like the Active State (I think I have that right. At work so I can't check) stuff for windows/com and the debian-python mailing list that came up the other day. I even ran across some AS-400 python stuff a while back. Python is cross platform but there are platform specific issues and communities that can help with them. Just a thought. Thanks for being out there and making us look good. John Purser -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Greg Lindstrom Sent: Friday, May 13, 2005 05:53 To: tutor at python.org Subject: [Tutor] Python Resources Hello- I have been asked to write an article for the IEEE "IT Pro" magazine dealing with using Python in the medical field. The editors asked for about half the article dealing with using Python and the other half giving a short tutorial. They also asked for three "sidebars"; I'm going with Tim Peter's "Zen of Python" for one, a comparison of "Hello, World", in C, C++, Perl, and Java in the second, and for the third I would like to list some resources. I have the Python home page, "Dive Into Python", the Python Gems" page, but would like to ask what resources would any of you suggest? I'd like between 5 and 10, with a short description of each. The article emphasizes the simple syntax of Python and the friendliness of our community. It encourages anyone interested in learning to subscribe to this mailing list and ask questions (though I do caution them not to submit their homework simply to get a solution). I have asked two people to review the paper from a "Python" perspective to make sure I have not mis-represented the language (I'm sorry about the delays, Steve, but the paper is coming!). If any of you would like to review it, I would be happy to send you a copy, too. I have about a week before submission. Thanks for your help, --greg _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri May 13 17:19:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 May 2005 11:19:54 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <61d0e2b40505130752582ce88@mail.gmail.com> References: <009c01c55788$46c2d6b0$91508651@xp> <61d0e2b40505130752582ce88@mail.gmail.com> Message-ID: <4284C59A.4050108@tds.net> Bernard Lebel wrote: > The authors even go as far as saysing, on page 228 (first paragraph) > that map() used that way has a performance benefit and is faster than > a for loop. That may well be correct, at least in the case where the function passed to map is a builtin. Mapping a builtin to over a list is extremely fast. So write the code with a for loop so it is clear. When you identify a performance bottleneck you can try rewriting your loop using map or list comprehension, which is also fast. Until then it is premature optimization. For typical loops over a small number of items I can't imagine you would notice the difference. Kent From carroll at tjc.com Fri May 13 19:39:55 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 May 2005 10:39:55 -0700 (PDT) Subject: [Tutor] Perl to Python phrasebook Message-ID: A "Perl-to-Python phrasebook," showing a number of common tasks in Perl, and how to do the equivalent in Python, is at . I'll bet a lot of readers know about it already, but I just stumbled on it and thought that some readers might also find it useful. Terry From work at infomaniak.ch Fri May 13 21:27:16 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Fri, 13 May 2005 21:27:16 +0200 Subject: [Tutor] creation of a module In-Reply-To: <42847CFA.7010707@tds.net> References: <20050513075818.GB17427@obs.unige.ch> <42847CFA.7010707@tds.net> Message-ID: <20050513192716.GC17427@obs.unige.ch> > > hi, > > > > 1) > > I'm trying to create my _first_ own module. I've decided to write each class into a separate file. OB> > > > /MyModule|-bunch.py > > |-a.py > > |-b.py > > `-c.py > > You also need MyModule/__init__.py to signal to Python that MymModule is a package. (Actually you > are creating a package containing several modules.) thank you to enlight me.. :).. that I was creating a package containing many modules. Maybe I'm smarter than I thought. > > {a,b,c}.py contains respecetively classA,classB,classC more some unittest > > and bunch.py will contains some usefull function using the class{A,B,C} > > > > I'd like that when I import MyModule (`import MyModule')OB > > I'll see from it: > > MyModule.classA > > .classB > > .classC > > . > > . > > ... > > without seeing MyModule.{a,b,c} > > In MyModule/__init__.py put > from MyModule.a import classA > from MyModule.b import classB > from MyModule.c import classC I've done it. But is it normal that I'see also the filename MyModule.classA .classB .classC .a <---- not expected .b <--' .c <-' . . can I not import them ? > This creates package-level attributes for the classes. > > > 2) does someone now how to do this: > > x=3 > > with a function like: > > assign('x',3) > > Can you say why you want to do this? It is possible but generally it is better to use a dict: > values = {} > values['x'] = 3 > the idea was to automate the : from MyModule.a import classA from MyModule.b import classB from MyModule.c import classC with a loop lclassname=['classA', 'classB', 'classC'] #in the future I can even automate the creation of classname list for classname in lclassname: #filename='a', classname='classA' filename=classname.replace('class','').lower() #from filename import classname #can't do this module=__import__(filename, gloabls(), locals(), [classname]) classDefinition=getattr(module,classname) assign(classname,classDefinition) In this way, when I'll do an import FWobs I'll get: MyModule.classA .classB .classC . . thanks for your help ! -- Cedric BRINER From william.ohiggins at utoronto.ca Fri May 13 21:21:58 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Fri, 13 May 2005 15:21:58 -0400 Subject: [Tutor] Perl to Python phrasebook In-Reply-To: References: Message-ID: <20050513192158.GA20692@sillyrabbi.dyndns.org> On Fri, May 13, 2005 at 10:39:55AM -0700, Terry Carroll wrote: >A "Perl-to-Python phrasebook," showing a number of common tasks in Perl, >and how to do the equivalent in Python, is at >. > >I'll bet a lot of readers know about it already, but I just stumbled on it >and thought that some readers might also find it useful. That's excellent, thank you Terry! My hovercraft is no longer full of eels! -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050513/bc6b41f8/attachment.pgp From cgw501 at york.ac.uk Fri May 13 21:36:19 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 13 May 2005 20:36:19 +0100 Subject: [Tutor] Simple string processing problem Message-ID: Hi, i am a Biology student taking some early steps with programming. I'm currently trying to write a Python script to do some simple processing of a gene sequence file. A line in the file looks like: SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATCagctagtcgatagcgat Ther are many lines like this. What I want to do is read the file and remove the trailing lowercase letters and create a new file containing the remaining information. I have some ideas of how to do this (using the isLower() method of the string module. I was hoping someone could help me with the file handling. I was thinking I'd us .readlines() to get a list of the lines, I'm not sure how to delete the right letters or write to a new file. Sorry if this is trivially easy. Chris From 3dbernard at gmail.com Fri May 13 21:56:06 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 13 May 2005 15:56:06 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <4284C59A.4050108@tds.net> References: <009c01c55788$46c2d6b0$91508651@xp> <61d0e2b40505130752582ce88@mail.gmail.com> <4284C59A.4050108@tds.net> Message-ID: <61d0e2b40505131256607893a@mail.gmail.com> Hi Kent, So if I undestand you right, mapping a function with map() when it is a built-in function will/may be faster than a for loop, but if it's a custom function (ie. a def one), it will most likely be slower? Thanks Bernard On 5/13/05, Kent Johnson wrote: > Bernard Lebel wrote: > > The authors even go as far as saysing, on page 228 (first paragraph) > > that map() used that way has a performance benefit and is faster than > > a for loop. > > That may well be correct, at least in the case where the function passed to map is a builtin. > Mapping a builtin to over a list is extremely fast. So write the code with a for loop so it is > clear. When you identify a performance bottleneck you can try rewriting your loop using map or list > comprehension, which is also fast. Until then it is premature optimization. For typical loops over a > small number of items I can't imagine you would notice the difference. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From albertito_g at hotmail.com Fri May 13 22:03:48 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 13 May 2005 20:03:48 +0000 Subject: [Tutor] Linux variable to Python Message-ID: Hey Another problem Here is an example of what I want to do: I run over Linux shell the following command: [root at siseg root]# fec=cam`date +%Y%m%d%H%M%S`.jpg [root at siseg root]# echo $fec cam2005051255702.jpg [root at siseg root]# mv hola.txt grabacion/$fec To explain for those who doesn't know: The first line creates a variable named "fec" with the value cam(a Linux function returning year month day hour minute second).jpg The second show the value of "fec" The third moves hola.txt to the directory grabacion and puts the "fec" value as the new name for the file I need to do this from Python but I'm having problems with the Linux variable I don't get any errors when I execute the commands Here is what I'm doing import os >>>os.system("fec=cam`date +%Y%m%d%H%M%S`.jpg") 0 >>>os.system("echo $fec") 0 >>>os.system("mv hola.txt grabacion/$fec") 0 Then I check for the file and turns out that it moved hola.txt to grabacion with the same name I think that for some extrange way it is not accepting the linux variable I'm using Python 2.2.2 over Red Hat 9.0 Thanks in advanced Alberto From project5 at redrival.net Fri May 13 22:06:32 2005 From: project5 at redrival.net (Andrei) Date: Fri, 13 May 2005 22:06:32 +0200 Subject: [Tutor] Python Resources References: <4284A326.5070109@novasyshealth.com> Message-ID: Greg Lindstrom wrote on Fri, 13 May 2005 07:52:54 -0500: > would like to list some resources. I have the Python home page, "Dive > Into Python", the Python Gems" page, but would like to ask what > resources would any of you suggest? I'd like between 5 and 10, with a > short description of each. Not sure what the Python Gems is. I'd suggest the ActiveState Python Cookbook as a valuable resource (though it's not exactly intro material). The Daily Python Url is nice because it collects interesting posts in Python-related blogs. > subscribe to this mailing list and ask questions (though I do caution > them not to submit their homework simply to get a solution). I think people reading a magazine called "IT Pro" should be aware of such basic etiquette :). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From maxnoel_fr at yahoo.fr Fri May 13 22:17:27 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 13 May 2005 21:17:27 +0100 Subject: [Tutor] Simple string processing problem In-Reply-To: References: Message-ID: On May 13, 2005, at 20:36, cgw501 at york.ac.uk wrote: > Hi, > > i am a Biology student taking some early steps with programming. I'm > currently trying to write a Python script to do some simple > processing of a > gene sequence file. Welcome aboard! > A line in the file looks like: > SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATCagctagtcgatagcgat > > Ther are many lines like this. What I want to do is read the file and > remove the trailing lowercase letters and create a new file > containing the > remaining information. I have some ideas of how to do this (using the > isLower() method of the string module. I was hoping someone could > help me > with the file handling. I was thinking I'd us .readlines() to get a > list of > the lines, I'm not sure how to delete the right letters or write to > a new > file. Sorry if this is trivially easy. First of all, you shouldn't use readlines() unless you really need to have access to several lines at the same time. Loading the entire file in memory eats up a lot of memory and scales up poorly. Whenever possible, you should iterate over the file, like this: foo = open("foo.txt") for line in foo: # do stuff with line... foo.close() As for the rest of your problem, the strip() method of string objects is what you're looking for: >>> "SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATCagctagtcgatagcgat".strip ("atgc") 'SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATC' Combining those 2 pieces of advice should solve your problem. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri May 13 22:20:20 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri, 13 May 2005 21:20:20 +0100 Subject: [Tutor] Linux variable to Python In-Reply-To: References: Message-ID: <86D2DEFC-B059-4AC1-A8FD-9EEE026B7EC1@yahoo.fr> On May 13, 2005, at 21:03, Alberto Troiano wrote: >>>> os.system("fec=cam`date +%Y%m%d%H%M%S`.jpg") >>>> > 0 > >>>> os.system("echo $fec") >>>> > 0 > >>>> os.system("mv hola.txt grabacion/$fec") >>>> > 0 > > Then I check for the file and turns out that it moved hola.txt to > grabacion > with the same name > I think that for some extrange way it is not accepting the linux > variable > No, it's just that the os.system() function returns the return value of the executed process (that is, 0 if everything went okay). For what you want to do, one of the os.popen* functions is what you're looking for. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From missive at hotmail.com Fri May 13 22:48:41 2005 From: missive at hotmail.com (Lee Harr) Date: Sat, 14 May 2005 01:18:41 +0430 Subject: [Tutor] Linux variable to Python Message-ID: >import os >>>>os.system("fec=cam`date +%Y%m%d%H%M%S`.jpg") >0 >>>>os.system("echo $fec") >0 >>>>os.system("mv hola.txt grabacion/$fec") >0 Each system() call gets a fresh shell, and a fresh env ... >>>import os >>>os.environ['foo'] = 'bar' >>>os.system('echo $foo') bar 0 >>>os.system('foo=zzz') 0 >>>os.system('echo $foo') bar 0 >>>os.system('export foo=zzz') 0 >>>os.system('echo $foo') bar 0 >>>os.environ['foo'] 'bar' If you really need to work with environment variables use os.environ, but I have a feeling you do not really need that and it's going to be messy. How about this ... import datetime timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S') filename = 'cam%s.jpg' % timestamp os.rename('hola.txt', filename) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From cgw501 at york.ac.uk Fri May 13 22:59:58 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 13 May 2005 21:59:58 +0100 Subject: [Tutor] Simple string processing problem In-Reply-To: References: Message-ID: Thanks! Your help has made me realise the problem is more complex than I first though though...I've included a small sample of an actual file I need to process. The structure is the same as in the full versions though; some lowercase, some uppercase, then some more lowercase. One is that I need to remove the lines of asterisks. I think I can do this with .isalpha(). Here's what I've written: theAlignment = open('alignment.txt', 'r') strippedList = [] for line in theAlignment: if line.isalpha() strippedList.append(line.strip('atgc')) strippedFile = open ('stripped.txt', 'w') for i in strippedList: strippedFile.write(i) strippedFile.close() theAlignment.close() The other complication is that I need to retain the lowercase stuff at the start of each sequence (the sequences are aligned, so 'Scer' in the second block follows on from 'Scer' in the first etc.). Maybe the best thing to do would be to concatenate all the Scer, Spar, Smik and Sbay sequences bfore processing them? Also i need to get rid of '-' characters within the trailing lowercase, but keep the rest of them. So basically everything after the last capital letter only needs to go. I'd really appreciate any thoughts, but don't worry if you've got better things to do. Chris The file: Scer ACTAACAAGCAAAATGTTTTGTTTCTCCTTTT-AAAATAGTACTGCTGTTTCTCAAGCTG Spar actaacaagcaaaatgttttgtttctcctttt-aaaatagtactgctgtttctcaagctg Smik actaacaagcaaaatgtttcttttctcttttttgaaatagtactgctgcttctcaagctg Sbay actaacaagcaaaaactttttgttttatt----gaaatagtactgctgtctctcaagctg **** * ************** ** ******** *** ***** ******* * Scer GGGGTGCTCACCAATTTATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG Spar GGGGTGCTCACCAATTTATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG Smik GGGGTGCTCACCAATTCATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG Sbay GGGGTGCTCACCAATTCATCCCAATTGGTTTCGGTATCAAGAAATTGCAAATTAACTGTG * ********** ********* **** ********* * ** ***** ** **** Scer ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAaaggctttttt-ataa Spar ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAaaagctttttttataa Smik ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAgaagctttttctataa Sbay ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAgaagctttttctataa ******************************************** * ******* **** Scer actttttataatt----aacattaa-------agcaaaaacaacattgtaaagattaaca Spar actttttataata----aacatcaa-------agcaaaaacaacattgtaaagattaaca Smik actttttataatt----aacatcgacaaaaacgacaacaacaacattgtaaagattaaca Sbay actttttataacttagcaacaacaacaacaacaacatcaacaacattgtaaagattaaca *********** **** * ** ********************** On May 13 2005, Max Noel wrote: > > On May 13, 2005, at 20:36, cgw501 at york.ac.uk wrote: > > > Hi, > > > > i am a Biology student taking some early steps with programming. I'm > > currently trying to write a Python script to do some simple > > processing of a > > gene sequence file. > > Welcome aboard! > > > A line in the file looks like: > > SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATCagctagtcgatagcgat > > > > Ther are many lines like this. What I want to do is read the file and > > remove the trailing lowercase letters and create a new file > > containing the > > remaining information. I have some ideas of how to do this (using the > > isLower() method of the string module. I was hoping someone could > > help me > > with the file handling. I was thinking I'd us .readlines() to get a > > list of > > the lines, I'm not sure how to delete the right letters or write to > > a new > > file. Sorry if this is trivially easy. > > First of all, you shouldn't use readlines() unless you really > need to have access to several lines at the same time. Loading the > entire file in memory eats up a lot of memory and scales up poorly. > Whenever possible, you should iterate over the file, like this: > > > foo = open("foo.txt") > for line in foo: > # do stuff with line... > foo.close() > > > As for the rest of your problem, the strip() method of string > objects is what you're looking for: > > > >>> "SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATCagctagtcgatagcgat".strip > ("atgc") > 'SCER ATCGATCGTAGCTAGCTATGCTCAGCTCGATC' > > > Combining those 2 pieces of advice should solve your problem. > > From dyoo at hkn.eecs.berkeley.edu Fri May 13 23:00:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 May 2005 14:00:50 -0700 (PDT) Subject: [Tutor] Linux variable to Python In-Reply-To: Message-ID: On Fri, 13 May 2005, Alberto Troiano wrote: > Here is an example of what I want to do: > > I run over Linux shell the following command: > > [root at siseg root]# fec=cam`date +%Y%m%d%H%M%S`.jpg > [root at siseg root]# echo $fec > cam2005051255702.jpg > [root at siseg root]# mv hola.txt grabacion/$fec > > I need to do this from Python but I'm having problems with the Linux > variable Hi Alberto, [Tangent: are you running things using the Unix 'root' account? If so, you may want to consider using a regular user account unless you really know what you're doing. Running things as root should never be taken lightly.] You may want to consider using the 'datetime' module for this one. There are portability and security issues that you may not be considering whenever you "shell" out. If you use Python's Standard Libraries, you can avoid these issues. I think you can avoid using 'date' by taking advantage of datetime.datetime.strftime(): ###### >>> import datetime >>> datetime.datetime.today().strftime("%Y%m%d%H%M%S") '20050513135531' ###### This is portable on any system that supports the Python Standard Library. The problems you are running into with os.system() are related to those that other people have been asking about this week. It's sorta funny how these questions come in streaks. *grin* For more information on driving external processes with Python, you may want to look at the messages on "Pipe variable to external command" that Jeffrey was asking about yesterday: http://mail.python.org/pipermail/tutor/2005-May/038341.html http://mail.python.org/pipermail/tutor/2005-May/038343.html I hope this helps! From dyoo at hkn.eecs.berkeley.edu Sat May 14 00:25:25 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 May 2005 15:25:25 -0700 (PDT) Subject: [Tutor] Simple string processing problem In-Reply-To: Message-ID: On 13 May 2005 cgw501 at york.ac.uk wrote: > Your help has made me realise the problem is more complex than I first > though though...I've included a small sample of an actual file I need to > process. The structure is the same as in the full versions though; some > lowercase, some uppercase, then some more lowercase. One is that I need > to remove the lines of asterisks. Hello Chris, Since this does look like a biologically-driving example, you may want to make sure that no one else has already done this work for you. BioPython is a collections of programs written for bioinformatics work in Python: http://biopython.org/ and you may want to just double check to see if someone has already done the work in parsing that data. The input that you've show us suggests that you're dealing with ClustalW sequence alignment data. If so, you should be aware that a Biopython parser does exist in the 'Bio.Clustalw' module package: http://biopython.org/docs/api/public/Bio.Clustalw-module.html And if you are willing to look at BioPython, then take a look at section 11.6.2 of: http://www.pasteur.fr/recherche/unites/sis/formation/python/ch11s06.html for an example of parsing a CLUSTALW file with BioPython. If you're doing this from scratch to learn Python better, that's great. But if you're in a hurry, take advantage of the stuff that's out there. By the way, you may find the tutorial at: http://www.pasteur.fr/recherche/unites/sis/formation/python/index.html to be useful; it's a Python tutorial with a biological focus. Best of wishes! From albertito_g at hotmail.com Sat May 14 00:39:42 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 13 May 2005 22:39:42 +0000 Subject: [Tutor] Linux variable to Python In-Reply-To: Message-ID: And again I'm gonna say BINGO!!!!!!!!! It's like you were doing the same app as I am Thanks Alberto >From: Danny Yoo >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Linux variable to Python >Date: Fri, 13 May 2005 14:00:50 -0700 (PDT) > > > >On Fri, 13 May 2005, Alberto Troiano wrote: > > > Here is an example of what I want to do: > > > > I run over Linux shell the following command: > > > > [root at siseg root]# fec=cam`date +%Y%m%d%H%M%S`.jpg > > [root at siseg root]# echo $fec > > cam2005051255702.jpg > > [root at siseg root]# mv hola.txt grabacion/$fec > > > > I need to do this from Python but I'm having problems with the Linux > > variable > >Hi Alberto, > >[Tangent: are you running things using the Unix 'root' account? If so, >you may want to consider using a regular user account unless you really >know what you're doing. Running things as root should never be taken >lightly.] > > >You may want to consider using the 'datetime' module for this one. There >are portability and security issues that you may not be considering >whenever you "shell" out. If you use Python's Standard Libraries, you can >avoid these issues. > > >I think you can avoid using 'date' by taking advantage >of datetime.datetime.strftime(): > >###### > >>> import datetime > >>> datetime.datetime.today().strftime("%Y%m%d%H%M%S") >'20050513135531' >###### > >This is portable on any system that supports the Python Standard Library. > > >The problems you are running into with os.system() are related to those >that other people have been asking about this week. It's sorta funny how >these questions come in streaks. *grin* > >For more information on driving external processes with Python, you may >want to look at the messages on "Pipe variable to external command" that >Jeffrey was asking about yesterday: > > http://mail.python.org/pipermail/tutor/2005-May/038341.html > http://mail.python.org/pipermail/tutor/2005-May/038343.html > > > >I hope this helps! > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From william.ohiggins at utoronto.ca Sat May 14 02:30:56 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Fri, 13 May 2005 20:30:56 -0400 Subject: [Tutor] Testing for commandline args Message-ID: <20050514003056.GA23507@sillyrabbi.dyndns.org> I am writing a tiny commandline utility (re-writing it from Perl) and I want the behaviour to change based on the presence of arguments. The conditional in Perl looks like this: if (defined $ARGV[0]) { do stuff } else { do different stuff In Python I've nearly been successful, but something's wonky. Here's the code: if sys.argv[1]: do stuff else: do different stuff If I have arguments, the "different stuff" happens beautifully, thank you very much. If I don't have arguments I get this: if sys.argv[1]: IndexError: list index out of range] So I'm doing something wrong. I looked at getopt, but that seemed to be doing what I was already doing, except in a way I could not follow :-( Any tips would be appreciated, thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050513/51bc0d05/attachment.pgp From maxnoel_fr at yahoo.fr Sat May 14 02:39:43 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 14 May 2005 01:39:43 +0100 Subject: [Tutor] Testing for commandline args In-Reply-To: <20050514003056.GA23507@sillyrabbi.dyndns.org> References: <20050514003056.GA23507@sillyrabbi.dyndns.org> Message-ID: On May 14, 2005, at 01:30, William O'Higgins wrote: > if sys.argv[1]: > do stuff > else: > do different stuff > > If I have arguments, the "different stuff" happens beautifully, thank > you very much. If I don't have arguments I get this: > > if sys.argv[1]: > IndexError: list index out of range] > > So I'm doing something wrong. I looked at getopt, but that seemed > to be > doing what I was already doing, except in a way I could not follow :-( How about this? if len(sys.argv) > 1: # do stuff else: # do different stuff Also, I hear that optparse is much better than getopt. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Sat May 14 03:40:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 13 May 2005 18:40:30 -0700 (PDT) Subject: [Tutor] Testing for commandline args In-Reply-To: <20050514003056.GA23507@sillyrabbi.dyndns.org> Message-ID: > > If I have arguments, the "different stuff" happens beautifully, thank > you very much. If I don't have arguments I get this: > > if sys.argv[1]: > IndexError: list index out of range] > > So I'm doing something wrong. I looked at getopt, but that seemed to be > doing what I was already doing, except in a way I could not follow :-( Hi William, One difference between Python and Perl is their treatment of out-of-bound indices on lists. Python does not "autovivify" a list, nor does it automagically extend lists to make indices fit. So if there are no command line arguments, doing: sys.argv[1] will raise the IndexError exception that you're seeing. It is a significant difference between those two languages, so be careful. There are several ways of doing what you're doing. One solution is to check for list length, as Max suggests. Another is to take a "slice" of the argument list: if sys.argv[1:]: ... The expression: sys.argv[1:] produces a list of all but the first entry in sys.argv. And the condition check should work fine because empty lists are treated as False in Python. Best of wishes! From thomas.s.mark at gmail.com Sat May 14 08:04:41 2005 From: thomas.s.mark at gmail.com (Mark Thomas) Date: Sat, 14 May 2005 06:04:41 +0000 Subject: [Tutor] Simple string processing problem In-Reply-To: References: Message-ID: <7b9699030505132304d1857cf@mail.gmail.com> On 13 May 2005 21:59:58 +0100, cgw501 at york.ac.uk wrote: > The file: > > Scer ACTAACAAGCAAAATGTTTTGTTTCTCCTTTT-AAAATAGTACTGCTGTTTCTCAAGCTG > Spar actaacaagcaaaatgttttgtttctcctttt-aaaatagtactgctgtttctcaagctg > Smik actaacaagcaaaatgtttcttttctcttttttgaaatagtactgctgcttctcaagctg > Sbay actaacaagcaaaaactttttgttttatt----gaaatagtactgctgtctctcaagctg > **** * ************** ** ******** *** ***** ******* * > > Scer GGGGTGCTCACCAATTTATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG > Spar GGGGTGCTCACCAATTTATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG > Smik GGGGTGCTCACCAATTCATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG > Sbay GGGGTGCTCACCAATTCATCCCAATTGGTTTCGGTATCAAGAAATTGCAAATTAACTGTG > * ********** ********* **** ********* * ** ***** ** **** > > Scer ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAaaggctttttt-ataa > Spar ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAaaagctttttttataa > Smik ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAgaagctttttctataa > Sbay ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAAgaagctttttctataa > ******************************************** * ******* **** > > Scer actttttataatt----aacattaa-------agcaaaaacaacattgtaaagattaaca > Spar actttttataata----aacatcaa-------agcaaaaacaacattgtaaagattaaca > Smik actttttataatt----aacatcgacaaaaacgacaacaacaacattgtaaagattaaca > Sbay actttttataacttagcaacaacaacaacaacaacatcaacaacattgtaaagattaaca > *********** **** * ** ********************** How about some RE action. >>> import re >>> pat = re.compile('^(S[a-z]{3}\s*[A-Z]+).*$') >>> fr = file('dna','r') >>> for line in fr: ... m = pat.match(line) ... if m: ... print m.group(1) ... Scer ACTAACAAGCAAAATGTTTTGTTTCTCCTTTT Scer GGGGTGCTCACCAATTTATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG Spar GGGGTGCTCACCAATTTATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG Smik GGGGTGCTCACCAATTCATCCCAATTGGTTTCGGTATCAAGAAGTTGCAAATTAACTGTG Sbay GGGGTGCTCACCAATTCATCCCAATTGGTTTCGGTATCAAGAAATTGCAAATTAACTGTG Scer ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAA Spar ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAA Smik ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAA Sbay ACCACGTCCAATCTACCGATATTGCTGCTATGCAAAAATTATAA -- _ ( ) Mark Thomas ASCII ribbon campaign X www.theswamp.org - against HTML email / \ From william.ohiggins at utoronto.ca Sat May 14 17:13:57 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Sat, 14 May 2005 11:13:57 -0400 Subject: [Tutor] Lists of files Message-ID: <20050514151357.GA26425@sillyrabbi.dyndns.org> Here's the problem - I want a list (array) of the files in a directory, and then I want to iterate over the list testing for image-ness (with imghdr.what()) and put all the image filenames in a global list. What I've tried is this: files = glob.glob('*.*') for file in files: global pics pics = [] if imghdr.what(file): # so far so good - file is a list of files in the directory pics.append(file) # I this this is the problem - my list only has the last # alphabetical entry in it So there's two questions - is there a better way to create a list of files in a directory? And, how do I populate my list to get all of the filenames. I've also tried "pics + [file]", but that gave me an empty list. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050514/a4394620/attachment.pgp From 3dbernard at gmail.com Sat May 14 18:02:54 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sat, 14 May 2005 12:02:54 -0400 Subject: [Tutor] Lists of files In-Reply-To: <20050514151357.GA26425@sillyrabbi.dyndns.org> References: <20050514151357.GA26425@sillyrabbi.dyndns.org> Message-ID: <61d0e2b4050514090253a10825@mail.gmail.com> Hi William, First, check out the os and os.path modules. It has exactly what you need to handle files and directories. http://www.python.org/doc/2.4.1/lib/module-os.html More specifically: http://www.python.org/doc/2.4.1/lib/os-file-dir.html http://www.python.org/doc/2.4.1/lib/module-os.path.html import os # Get list of files in directory aFiles = os.listdir( ) # Create empty list to store image files aImgFiles = [] # Iterate list to collect image files for sFile in aFiles: # Split extension to see if it is an image type # This returns a list of two elements, check the last one to get the extension if os.path.splitext( sFile )[-1] == : aImgFiles.append( sFile ) You could also do that more quickly with list comprehension: aImgFiles = [ sFile for sFile in os.listdir( ) if os.path.splitext( sFile )[-1] == ] Cheers Bernard On 5/14/05, William O'Higgins wrote: > Here's the problem - I want a list (array) of the files in a directory, > and then I want to iterate over the list testing for image-ness (with > imghdr.what()) and put all the image filenames in a global list. > > What I've tried is this: > > files = glob.glob('*.*') > > for file in files: > global pics > pics = [] > if imghdr.what(file): > # so far so good - file is a list of files in the directory > pics.append(file) > # I this this is the problem - my list only has the last > # alphabetical entry in it > > So there's two questions - is there a better way to create a list of > files in a directory? And, how do I populate my list to get all of the > filenames. I've also tried "pics + [file]", but that gave me an empty > list. > -- > > yours, > > William > > > BodyID:4269787.2.n.logpart (stored separately) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From sigurd at 12move.de Sat May 14 20:17:03 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sat, 14 May 2005 20:17:03 +0200 Subject: [Tutor] Lists of files In-Reply-To: <20050514151357.GA26425@sillyrabbi.dyndns.org> (William O'Higgins's message of "Sat, 14 May 2005 11:13:57 -0400") References: <20050514151357.GA26425@sillyrabbi.dyndns.org> Message-ID: On 14 Mai 2005, william.ohiggins at utoronto.ca wrote: > Here's the problem - I want a list (array) of the files in a directory, > and then I want to iterate over the list testing for image-ness (with > imghdr.what()) and put all the image filenames in a global list. > > What I've tried is this: > > files = glob.glob('*.*') > > for file in files: > global pics > pics = [] > if imghdr.what(file): > # so far so good - file is a list of files in the directory > pics.append(file) > # I this this is the problem - my list only has the last > # alphabetical entry in it The problem here is that in every iteration you set the list pics to `[]'. If you wanted to solve the problem like above (not very nice; try to avoid globals if possible) you had to define `pics' outside the loop. Bernard gave you an answer how you could solve it with a simple list comprehension (just filter the output from os.listdir); it can also be written like that: filter(imghdr.what, os.listdir('.')) Just jump before to the directory you want to get searched with: os.chdir(path) If you want a more general solution which also allows to search recursively through a directory tree you could use something like that: def filter_files (root, filepred=lambda f: f, dirpred=lambda d: False): filtered= [] jn = os.path.join for path, dirs, files in os.walk(root, topdown=True): for d in dirs: if not dirpred(jn(path, d)): dirs.remove(d) filtered.extend([jn(path,f) for f in files if filepred(jn(path, f))]) return filtered The above takes two callback functions: filepred and dirpred. For every file filepred returns a true value that file gets appended to the list of returned files. `dirpred' allows you to recurse only in directories where that function returns a true value. So to have the same as above you write: filter_files('.', filepred=imghdr.what) and if you wanted to search a directory tree without e.g. the ./bin directory you could write: filter_files('.', filepred=imghdr.what, dirpred=lambda d: not d.endswith('bin')) HTH Karl -- Please do *not* send copies of replies to me. I read the list From flamesrock at gmail.com Sat May 14 21:09:48 2005 From: flamesrock at gmail.com (Aaron Elbaz) Date: Sat, 14 May 2005 13:09:48 -0600 Subject: [Tutor] help: space formatting for multiplication table Message-ID: <2c2812b605051412092b53da4e@mail.gmail.com> I've been racking my brain and am right now feeling nauseous from not being able to figure out such a simple problem. Here's the code: #r=10 #line=1 # #def spaces(r): # return r/10 # #while line-1 < r: # for i in range(r): # print str((i+1)*line) + ' '*spaces(r), # line=line+1 # print The idea is to print out a multiplication table on the command line with numbers lining up in the ones column. I want to eventually emulate programs like top with their spacing. But this code is mostly for my amusement. How would you make this work? -thanks From maxnoel_fr at yahoo.fr Sat May 14 21:21:43 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 14 May 2005 20:21:43 +0100 Subject: [Tutor] help: space formatting for multiplication table In-Reply-To: <2c2812b605051412092b53da4e@mail.gmail.com> References: <2c2812b605051412092b53da4e@mail.gmail.com> Message-ID: On May 14, 2005, at 20:09, Aaron Elbaz wrote: > The idea is to print out a multiplication table on the command line > with numbers lining up in the ones column. I want to eventually > emulate programs like top with their spacing. But this code is mostly > for my amusement. How would you make this work? > You may want to have a look at the string ljust() and rjust() methods. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From missive at hotmail.com Sun May 15 00:24:06 2005 From: missive at hotmail.com (Lee Harr) Date: Sun, 15 May 2005 02:54:06 +0430 Subject: [Tutor] help: space formatting for multiplication table Message-ID: >The idea is to print out a multiplication table on the command line >with numbers lining up in the ones column. I want to eventually >emulate programs like top with their spacing. But this code is mostly >for my amusement. How would you make this work? > Try print string formatting using % >>>print '%5d' % 12 12 >>>print '--%5d--' % 12 -- 12-- >>>print '--%5d--' % 112 -- 112-- >>>print '--%5d--' % 1123 -- 1123-- >>>print '--%5d--' % 11235 --11235-- >>>print '--%5d--' % 112356 --112356-- >>>print '--%05d--' % 112 --00112-- http://docs.python.org/lib/typesseq-strings.html _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From 3dbernard at gmail.com Sun May 15 00:28:31 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Sat, 14 May 2005 18:28:31 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <000701c558ca$dfe93d50$d2cd8751@xp> References: <009c01c55788$46c2d6b0$91508651@xp> <61d0e2b40505130752582ce88@mail.gmail.com> <4284C59A.4050108@tds.net> <61d0e2b40505131256607893a@mail.gmail.com> <000701c558ca$dfe93d50$d2cd8751@xp> Message-ID: <61d0e2b405051415284796fcfe@mail.gmail.com> Thanks Alan, that clears things up quite well. Bernard On 5/14/05, Alan Gauld wrote: > > So if I undestand you right, mapping a function with map() > > when it is a built-in function will/may be faster than a for > > loop, but if it's a custom function (ie. a def one), it will > > most likely be slower? > > That's right, a builtin function, including map itself will > be written in C and so be 'fast'. So we have the trade off > between a Python for loop calling a function or a C loop > which additionally has to build a list result. But in the > builtin case we have C code calling C code which is > much faster than Python code calling C code. > > So for a function written in Python there will be less > difference and the bulk of the time is likely to be > spent in the function calls but for builtins C to C > could give a significant benefit. > > Which is faster will depend on several other factors including > what the function returns and how easily that can be packaged > into a list. > > From my personal experience I wouldn't expect map to be > much faster than a for loop, if at all. But as Kent says > you can always profile it and test it if you really need > speed. The real issue is the map call is more obscure > than an explicit loop since map() is intended to build > a list not modify an existing list! > > Alan G. > From carroll at tjc.com Sun May 15 07:54:53 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 14 May 2005 22:54:53 -0700 (PDT) Subject: [Tutor] How to verify all things are equal to one another Message-ID: Suppose I have several variables, e.g.: a, b, c, d, e, f, g. I would like to be able to see if they're all the same, I don't care what the value is, as long as they're equal. If they're all equal to 0, or to "spam", or to ["cleese", "idle", "gilliam"], as long as they're the same. Is there a more pythonic way of doing this other than, if (a == b & a == c & a == d & a == e & a == f & a == g): do stuff For example, is there any kind of function: if allsame(a, b, c, d, e, f, g): do stuff I can roll my own, but I was just wondering if something already existed like this. From jfouhy at paradise.net.nz Sun May 15 12:19:36 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Sun, 15 May 2005 22:19:36 +1200 (NZST) Subject: [Tutor] How to verify all things are equal to one another In-Reply-To: References: Message-ID: <1116152376.42872238f0a5a@www.paradise.net.nz> Quoting Terry Carroll : > Suppose I have several variables, e.g.: a, b, c, d, e, f, g. > > I would like to be able to see if they're all the same, I don't care > what the value is, as long as they're equal. If they're all equal to 0, or > to "spam", or to ["cleese", "idle", "gilliam"], as long as they're the > same. Two suggestions --- First, you can actually do multiple equality testing the way your mathematics teacher would: if a == b == c == d == e == f == g: # do stuff (this grates against my instincts in some ways, since it breaks associativity (because it means 'a == b == c' is different from '(a == b) == c'), but it's in the language, so I guess it's the Right Way). You could also do this: # python2.3: use Set module if set([a,b,c,d,e,f,g]) == set([a]): # do stuff HTH. -- John. From maxnoel_fr at yahoo.fr Sun May 15 13:23:40 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun, 15 May 2005 12:23:40 +0100 Subject: [Tutor] How to verify all things are equal to one another In-Reply-To: References: Message-ID: On May 15, 2005, at 06:54, Terry Carroll wrote: > if (a == b & > a == c & > a == d & > a == e & > a == f & > a == g): > do stuff > Well, you can already try this: if a == b == c == d == e == f == g: do stuff -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Sun May 15 18:24:20 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 15 May 2005 17:24:20 +0100 Subject: [Tutor] How to verify all things are equal to one another References: Message-ID: <001401c5596a$8cd4f820$358c8651@xp> > Is there a more pythonic way of doing this other than, > > if (a == b & > a == c & > a == d & > a == e & > a == f & > a == g): > do stuff You don't want to use & coz its a bitwise comparison, so you should use 'and'.... if a == b and a == c and ... However you can also do the more intuitive: if a == b == c == d == e == f == g: do stuff Anther slightly mor flexible but much more obscure way uses comprehensions: if [item for item in [a,b,c,d,e,f,g] if item != a]: which returms an empty list(false0 if they are all equal. The comprehensions advantage is that you can keep the list separate from the check and add, remove items and it doesn't break working code, each hard coded test would need to be modified in the event of a change. Finally old assembler hackers will no doubt want to use xor: if not (a^b^c^d^e^f): do it :-) PS. The last works for primitive types but is not intended to be a serious suggestion!! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jeffrice at finity.org Sun May 15 20:41:37 2005 From: jeffrice at finity.org (Jeffrey Rice) Date: Sun, 15 May 2005 12:41:37 -0600 Subject: [Tutor] Pipe variable to external command (solved) In-Reply-To: <000201c558ca$dfd56730$d2cd8751@xp> References: <6.2.1.2.2.20050511223118.026b2e68@popfile> <000201c558ca$dfd56730$d2cd8751@xp> Message-ID: <6.2.1.2.2.20050515123238.025ae328@popfile> At 04:17 PM 5/13/2005, Alan Gauld wrote: >AS a general pont all uppercase usually means a consrtant in Python. >Variable names typically start lowercase and either use capital >letters to separate words likeThis, or use underscores like_this. > >Variables starting with an uppercase letter tend to indicate class >names - although thats not universally true, even in the standard >library! But the ALLUPPER thing for constants is pretty universal >so its worth adopting IMHO. Thanks for the style pointers. I will make these changes -- I realize how important consistency is, since I use other people's code as a learning tool with great frequency. >So what happens? Do you get any error messages? >What value is CLAM_RESULT showing? >What value are you expecting? (The actual return value from >popen/close is not clearly defined in general.) >Finally, although you close the pipe it may be worth trying >a flush() first just to clear the buffer. I have gotten this working, with much help (especially from Danny). Here is what the code I settled on looks like: ### working = email.message_from_file(open(emailfile)) clamav = popen2.Popen3(clamav_cmd,1) clamav.tochild.write(working.as_string()) clamav.tochild.close() clamav_result = clamav.fromchild.read().lstrip('stream: ') clamav.fromchild.close clamav_exit = os.WEXITSTATUS(clamav.wait()) ### This gives me a string (clamav_result) that contains the output from the scanner: either OK if it was clean, or the name of the virus detected. (it is prefixed with "stream: " to indicate that stdin was scanned, so I strip that off) clamav_exit contains the exit code, converted using WEXITSTATUS: either 0, 1, or 2 for OK, infected, or error respectively. This seems to be working out just fine, and gives me a lot more flexibility that the bash script I was using! (as a note, I am reading the email into an email object because I perform other actions, like adding headers. Otherwise, it would be simpler to have clamav read the file directly rather than the stream.) Thanks to everyone for your patience and advice! Jeff * * * * * * * Jeffrey Rice || jeffrice at finity.org || www.finity.org From dyoo at hkn.eecs.berkeley.edu Sun May 15 21:52:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 15 May 2005 12:52:06 -0700 (PDT) Subject: [Tutor] How to verify all things are equal to one another In-Reply-To: <1116152376.42872238f0a5a@www.paradise.net.nz> Message-ID: > > Suppose I have several variables, e.g.: a, b, c, d, e, f, g. > > > > I would like to be able to see if they're all the same, I don't care > > what the value is, as long as they're equal. If they're all equal to > > 0, or to "spam", or to ["cleese", "idle", "gilliam"], as long as > > they're the same. > > First, you can actually do multiple equality testing the way your > mathematics teacher would: > > if a == b == c == d == e == f == g: > # do stuff > > (this grates against my instincts in some ways, since it breaks > associativity (because it means 'a == b == c' is different from '(a == > b) == c'), but it's in the language, so I guess it's the Right Way). Chaining up equalities like that does feel weird to me too, but I think that's just because of my prior bad experiences with C. *grin* But Python's chained comparisons are especially nice when we're doing explicit bounds checking with the other comparison operators: low <= value < high rather than: (low <= value) and (value < high) There are a few more details about chained comparisons here: http://www.python.org/doc/ref/comparisons.html From dyoo at hkn.eecs.berkeley.edu Sun May 15 22:07:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 15 May 2005 13:07:56 -0700 (PDT) Subject: [Tutor] Why use apply()? In-Reply-To: <61d0e2b405051214174387c385@mail.gmail.com> Message-ID: On Thu, 12 May 2005, Bernard Lebel wrote: > Just a generic question: why one would use apply()? > > In Learning Python, on page 357, there is an example of generating an > instance using apply(): > > class A: > def __init__( self, number ): > self.number = number > > a = apply( A, 3 ) > > What is the benefit of doing this over simply creating an instance > "the usual way": > > a = A( 3 ) Hi Bernard, Just wanted to mention that Python allows us to define functions that take a variable number of arguments: ###### >>> max(1, 2, 3, 4, 5) 5 >>> def mymax(*things): ... biggest = things[0] ... for x in things: ... if x > biggest: ... biggest = x ... return biggest ... >>> mymax("this", "is", "a", "test") 'this' ###### So this 'mymax' function can take in an arbitrary number of arguments. This power comes with a slightly nonobvious problem: let's say that we had a list of things: ###### >>> words = """hello world this is a test of the emergency broadcast ... system""".split() ###### Can we call mymax() to get the maximum word in this list? We might try to brute-force this: mymax(words[0], words[1], words[2], ...) but there is a better approach: apply(mymax, words) In newer versions of Python, we have syntactic sugar to make it easier to say: "Apply this function with the elements of the input list": mymax(*words) So apply (and the * stuff) really come into play when we're doing functions with variable number of arguments. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon May 16 00:29:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 15 May 2005 15:29:03 -0700 (PDT) Subject: [Tutor] Pipe variable to external command (solved) In-Reply-To: <6.2.1.2.2.20050515123238.025ae328@popfile> Message-ID: > Here is what the code I settled on looks like: > > ### > working = email.message_from_file(open(emailfile)) > > clamav = popen2.Popen3(clamav_cmd,1) > clamav.tochild.write(working.as_string()) > clamav.tochild.close() > clamav_result = clamav.fromchild.read().lstrip('stream: ') > clamav.fromchild.close ^^^^^^^^^^^^^^^^^^^^^^ Hi Jeffrey, Careful: you may need parens there on your 'close' line. (clothesline? *grin*) As written, that last statement doesn't fire off the close() method. This might be suprising because some other languages make parens optional. But we need them in Python because Python makes it very easy to get function references: ###### >>> def calculatePi(): ... return 22/7 ... >>> calculatePi ###### Without parens, we just get the function reference. We still need to "call" that function value by using parens, which trigger the function to fire off: ###### >>> calculatePi() 3 ###### Otherwise, your program looks good! I'm glad that it's working for you now. Best of wishes! From jeffrice at finity.org Mon May 16 02:18:37 2005 From: jeffrice at finity.org (Jeffrey Rice) Date: Sun, 15 May 2005 18:18:37 -0600 Subject: [Tutor] Pipe variable to external command (solved) In-Reply-To: References: <6.2.1.2.2.20050515123238.025ae328@popfile> Message-ID: <6.2.1.2.2.20050515181520.0264dbf8@popfile> At 04:29 PM 5/15/2005, Danny Yoo wrote: > > clamav.fromchild.close > ^^^^^^^^^^^^^^^^^^^^^^ >Careful: you may need parens there on your 'close' line. (clothesline? >*grin*) > >As written, that last statement doesn't fire off the close() method. >This might be suprising because some other languages make parens optional. >But we need them in Python because Python makes it very easy to get >function references: The program appears to work fine as written, in fact, but apparently was not doing exactly what I thought. I assume the stream would be closed at the end of the program if I did not do it explicitly, but it is sloppy. Interesting that the following clawav.wait() statement seem to function fine even though the close statement lacked its parens. Jeff * * * * * * * Jeffrey Rice || jeffrice at finity.org || www.finity.org From kent37 at tds.net Mon May 16 12:09:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 May 2005 06:09:31 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <61d0e2b40505131256607893a@mail.gmail.com> References: <009c01c55788$46c2d6b0$91508651@xp> <61d0e2b40505130752582ce88@mail.gmail.com> <4284C59A.4050108@tds.net> <61d0e2b40505131256607893a@mail.gmail.com> Message-ID: <4288715B.2040305@tds.net> Bernard Lebel wrote: > Hi Kent, > > So if I undestand you right, mapping a function with map() when it is > a built-in function will/may be faster than a for loop, but if it's a > custom function (ie. a def one), it will most likely be slower? I guess I didn't proofread that last mail...what I meant is - Write the code for clarity first - If you find a performance bottleneck then test different solutions to see which is fastest for your actual data and usage. - Mapping a builtin function over a list is relatively fast in Python and it is worth trying if it meets your needs. - Calling a function is relatively expensive in Python so if using map() requires you to define a helper that may wipe out its advantage. - Testing is crucial! Guessing is only good for helping to come up with ideas to test. Here is a program that tests six ways to apply a function to elements of a list. The functions don't create new lists except as side effects since that was the original problem. They use map(), list comprehension and an explicit for loop to apply str() or a Python function returning str() to the elements of a list. (The list already contains strings so the actual function call should be fast.) #### import timeit data = [str(n) for n in range(100)] def strByMap(): map(str, data) def strByListComp(): [str(n) for n in data] def strByLoop(): for n in data: str(n) def func(x): return str(x) def funcByMap(): map(func, data) def funcByListComp(): [func(n) for n in data] def funcByLoop(): for n in data: func(n) def timeOne(fn): setup = "from __main__ import " + fn.__name__ stmt = '%s()' % (fn.__name__) t = timeit.Timer(stmt, setup) secs = min(t.repeat(number=1000)) print '%15s %s' % (fn.__name__, secs) for fn in [ strByMap, strByListComp, strByLoop, funcByMap, funcByListComp, funcByLoop ]: timeOne(fn) ### Here are the results on my computer: strByMap 0.0359623918682 strByListComp 0.0581065470611 strByLoop 0.0481150537289 funcByMap 0.0810943849009 funcByListComp 0.0891375859222 funcByLoop 0.0806144356336 So for this test, map is fastest when calling a builtin and explicit looping is fastest when calling a function. With the explicit loop you might be able to inline the function, in which case it would be much faster than either map or list comp. Modifying the program slightly so that each function actually creates a list changes the results dramatically: strByMap 0.0365733633744 strByListComp 0.0579948010152 strByLoop 0.0764722890758 funcByMap 0.0811885309446 funcByListComp 0.0883995032888 funcByLoop 0.10586876265 Now map() is fastest in both cases, though a for loop with inlined code beats map() with an external function. Kent > > > Thanks > Bernard > > > On 5/13/05, Kent Johnson wrote: > >>Bernard Lebel wrote: >> >>>The authors even go as far as saysing, on page 228 (first paragraph) >>>that map() used that way has a performance benefit and is faster than >>>a for loop. >> >>That may well be correct, at least in the case where the function passed to map is a builtin. >>Mapping a builtin to over a list is extremely fast. So write the code with a for loop so it is >>clear. When you identify a performance bottleneck you can try rewriting your loop using map or list >>comprehension, which is also fast. Until then it is premature optimization. For typical loops over a >>small number of items I can't imagine you would notice the difference. >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon May 16 13:46:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 May 2005 07:46:04 -0400 Subject: [Tutor] URLLIB In-Reply-To: References: <428494F4.5090601@tds.net> Message-ID: <428887FC.9040207@tds.net> Please post the code that gave you the error. Kent Servando Garcia wrote: > I tired that and here is the error I am currently getting: > > assert hasattr(proxies, 'has_key'), "proxies must be a mapping" > > I was trying this: > >>> X=urllib.URLopener(name,proxies={'http':'URL').distutils.copy_file('So >>> meFileName') > > > in hopes to solve the above error > > > > On May 13, 2005, at 6:52 AM, Kent Johnson wrote: > >> Servando Garcia wrote: >> >>> Hello list >>> I am on challenge 5. I think I need to some how download a file. I >>> have been trying like so >>> X=urllib.URLopener(name,proxies={'http':'URL').distutils.copy_file('So >>> meFileName') >> >> >> urlopener() returns a file-like object - something that behaves like >> an open file. Try >> x = urllib.urlopener(name) >> data = x.read() >> >> Kent >> >> > > From kent37 at tds.net Mon May 16 14:03:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 May 2005 08:03:25 -0400 Subject: [Tutor] Simple string processing problem In-Reply-To: References: Message-ID: <42888C0D.7050401@tds.net> cgw501 at york.ac.uk wrote: > Thanks! > > Your help has made me realise the problem is more complex than I first > though though...I've included a small sample of an actual file I need to > process. The structure is the same as in the full versions though; some > lowercase, some uppercase, then some more lowercase. One is that I need to > remove the lines of asterisks. I think I can do this with .isalpha(). > Here's what I've written: > > theAlignment = open('alignment.txt', 'r') > > strippedList = [] > for line in theAlignment: > if line.isalpha() > strippedList.append(line.strip('atgc')) > > strippedFile = open ('stripped.txt', 'w') > > for i in strippedList: > strippedFile.write(i) > > strippedFile.close() > theAlignment.close() You can read and write in the same loop and avoid creating the intermediate list. Also I think you will need to strip the trailing newline (otherwise it blocks stripping the lower case chars) and then add it back: theAlignment = open('alignment.txt', 'r') strippedFile = open ('stripped.txt', 'w') for line in theAlignment: if line.isalpha() strippedFile.write(line.strip('atgc\n')) strippedFile.write('\n') strippedFile.close() theAlignment.close() > > > The other complication is that I need to retain the lowercase stuff at the > start of each sequence (the sequences are aligned, so 'Scer' in the second > block follows on from 'Scer' in the first etc.). You can use line.rstrip('atgc') to just strip from the right side. Though in the data you have shown, you don't actually have any lines that start with lower case letters. For example, >>> 'Scer actttttataatt----aacattaa-------agcaaaaacaacattgtaaagattaaca'.strip('atgc') 'Scer actttttataatt----aacattaa-------' You might like to browse this page to see what else you can do with strings: http://docs.python.org/lib/string-methods.html Maybe the best thing to do > would be to concatenate all the Scer, Spar, Smik and Sbay sequences bfore > processing them? Also i need to get rid of '-' characters within the > trailing lowercase, but keep the rest of them. So basically everything > after the last capital letter only needs to go. > > I'd really appreciate any thoughts, but don't worry if you've got better > things to do. Don't worry about asking beginner questions, that's what this list is for :-) Kent From cpu.crazy at gmail.com Mon May 16 02:55:26 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 15 May 2005 18:55:26 -0600 Subject: [Tutor] YATENJoe Message-ID: <6.1.0.6.2.20050515183101.01f06988@pop.gmail.com> YATENJoe (Yet Another Text Editor, Named Joe) First off, If this isn't the right place to ask, tell me so. That way I won't make this mistake again :-) I want to make a text editor. I know that there are hundreds out there, but practice makes perfect, and I need the practice. My problem is that I have no idea how to make one. I've tried a little already by defining line functions: def line1(): l1 = raw_input("") def line2(): l2 = raw_input("") line1() line2() Of course, this only allows for 2 lines. What's the trick to an infinite number of lines? Event driven programming is a must, obviously. How can I use 'Ctrl' + 'Q' to quit while still being able to type: "Press 'Ctrl' + 'Q' to quit YATENJoe"? I'm still a newbie to python (actually OOP programming in general!) so I can't have a lot of complicated stuff thrown in my face. I'd like it to not be platform specific, but if it has to be OS bound to be simple, then that's fine. I thought of a function that would define a function for me. Is this possible? If it is how would I do it? If it possible, here's my idea: def makefunc(): # This is where it defines a function. If line1 = "full" then # make a new line adding 1 integer do separate it from the first. def l1(): l1 = raw_input("") line1 = "full" l1() makefunc() One other thing, is there a way to call a function that is inside a function? 'Cause makefunc().l1() doesn't work. Thanks in advance, JQ PS: FYI I use Windows XP Pro and Linux PPS. FYI 2: I'm still a newbie to Linux too :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050515/db458ec7/attachment.html From RPhillips at engineer.co.summit.oh.us Mon May 16 17:00:58 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Mon, 16 May 2005 11:00:58 -0400 Subject: [Tutor] Opinions about this GIS script Message-ID: I made a script that opens GIS shapefiles and turns them into python objects. I posted it at http://www.geocities.com/tiltbike/GIS/py_shape_files.zip The only one that's mine, really, is the PyShape.py script; the others are there for support/testing. It's my first real effort at 'shareable' python. Everything else I've done so far is either a quick-and-dirty for my own use, or a simple illustration for instructional purposes. The script produces expected results, but if anyone is so inclined, I'd appreciate review/evaluation/critique of the 'pythonism' of the script. Ron Phillips -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050516/68abc72c/attachment.htm From jonasmg at softhome.net Mon May 16 19:30:33 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Mon, 16 May 2005 18:30:33 +0100 Subject: [Tutor] Directory not empty :: Fast mode Message-ID: <4288D8B9.6010607@softhome.net> To knowing if a directory isn't empty, I use: dir_example = "/usr/foo/" if glob.glob(os.path.join(dir_example, "*")): ... But, as it has to expand all files, i'm supposed that it's a little slow to simply knowing if a directory is empty. Any improvement? From maxnoel_fr at yahoo.fr Mon May 16 19:57:47 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon, 16 May 2005 18:57:47 +0100 Subject: [Tutor] Directory not empty :: Fast mode In-Reply-To: <4288D8B9.6010607@softhome.net> References: <4288D8B9.6010607@softhome.net> Message-ID: On May 16, 2005, at 18:30, Jonas Melian wrote: > To knowing if a directory isn't empty, I use: > > dir_example = "/usr/foo/" > > if glob.glob(os.path.join(dir_example, "*")): > ... > > > But, as it has to expand all files, i'm supposed that it's a little > slow > to simply knowing if a directory is empty. > > Any improvement? > The os.listdir() function returns a list of all the elements (files and dirs, everything but . and ..) in a directory. So if it returns an empty list, your dir is empty. >>> import os >>> os.listdir("Prog") ['.DS_Store', 'archive', 'C-Cpp', 'docs', 'eclipse', 'gi21', 'Haskell', 'Java', 'matt', 'ObjC', 'Python'] -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From albertito_g at hotmail.com Mon May 16 21:35:49 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 16 May 2005 19:35:49 +0000 Subject: [Tutor] Tkinter questions Message-ID: Hey Tkinter question How can I change the background color of a label?????? How can I change the font-size and make it BOLD?????? Regards Alberto From william.ohiggins at utoronto.ca Mon May 16 21:50:37 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Mon, 16 May 2005 15:50:37 -0400 Subject: [Tutor] Lists of files In-Reply-To: <61d0e2b4050514090253a10825@mail.gmail.com> References: <20050514151357.GA26425@sillyrabbi.dyndns.org> <61d0e2b4050514090253a10825@mail.gmail.com> Message-ID: <20050516195037.GA5456@sillyrabbi.dyndns.org> Thanks to all who helped me with my questions regarding testing for commandline arguments and list assignment. I have finished my first Python program (included below). It is slightly more secure than the Perl program I rewrote, but also about a tenth of a second slower (0.6 seconds for Perl on average (100 trials) and 0.7 seconds for Python). Is that typical of Python programs? I like Python so far, and I'm not going to go crazy optimizing working code, but I am curious. Any pointers, suggestions, etc. are welcome. One last thing - is there an equivalent of the "use strict" and "use warnings" pragmas in Python? Thanks. -- yours, William #!/usr/bin/python import os, sys, random, imghdr # This is a little program I call via cron to change my desktop every # few minutes. With no arguments it goes to my directory of backdrop # images and picks a valid image at random. If I specify a path and a # file the program will put it up as the display. # I don't want to fill up my inbox with emails from cron telling me that # X isn't running, so I check first. xisrunning = os.popen("pidof /usr/bin/X11/X").read() def changebackdrop(): # The below command works for transparent Eterm or Urxvt terminals, # populating their backgrounds with the image they occlude. xli or # xsetroot can be called, but they don't work as desired for # transparent terminals. command = "/usr/bin/Esetroot" # If I was logging into X remotely, this would change. commandargs = " -display :0.0 " # This is where my backdrops live picdir = "/home/willyyam/misc/bmps/" if sys.argv[1:]: doit = command + commandargs + sys.argv[1] os.popen(doit, 'r') else: files = os.listdir(picdir) os.chdir(picdir) pics = [] for file in files: # This is a test for valid images - it includes rgb files, # which are not supported by my image software, but the # error thrown is not terrible - the image software knows # what it can and cannot run. if imghdr.what(file): pics.append(file) randpic = random.choice(pics) doit = command + commandargs + picdir + randpic os.popen(doit, 'r') if xisrunning: changebackdrop() else: exit -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050516/141e836e/attachment-0001.pgp From danie.viljoen at siemens.com Mon May 16 13:54:52 2005 From: danie.viljoen at siemens.com (Viljoen, Danie) Date: Mon, 16 May 2005 13:54:52 +0200 Subject: [Tutor] Objects in List Message-ID: <67333EF7FC5BBE4AA30723BAC4B53537023F1D42@mdrf002e.za001.siemens.net> Hi I'm new to python (have a java background). I'm trying to add object to a list, and afterwards manipulate the object again. How do a cast a object to another object My Code: class MyObject: """A simple VO class""" def setName(self, newName): self.name=newName def getName(self): return self.name def main(): list=[] #created object in container for i in range(10): myObject = MyObject() name = 'name:' + str(i) myObject.setName(name) list.append(myObject) #manipulate object in list for p in enumerate(range(10)): myObject=p print myObject.getName() if __name__ == '__main__': main() The ERROR: C:\development\python__>python list.py Traceback (most recent call last): File "list.py", line 25, in ? main() File "list.py", line 21, in main print myObject.getName() AttributeError: 'tuple' object has no attribute 'getName' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050516/9478a396/attachment.html From carroll at tjc.com Mon May 16 22:26:49 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 16 May 2005 13:26:49 -0700 (PDT) Subject: [Tutor] How to verify all things are equal to one another In-Reply-To: <001401c5596a$8cd4f820$358c8651@xp> Message-ID: Thanks to all who responded on this. The commonly suggested: > if a == b == c == d == e == f == g: > do stuff Is just what I needed. It never occurred to me that Python supported a construct like that. I would have though this would have evaulated a la: if ((((((a == b) == c) == d) == e) == f) == g): From dyoo at hkn.eecs.berkeley.edu Mon May 16 22:40:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 May 2005 13:40:19 -0700 (PDT) Subject: [Tutor] Objects in List In-Reply-To: <67333EF7FC5BBE4AA30723BAC4B53537023F1D42@mdrf002e.za001.siemens.net> Message-ID: Hi Danie, The enumerate() function takes a list of elements, and returns a list of (index, element) pairs. For example: ###### >>> names = ["wilma", "fred", "betty", "barney"] >>> for p in enumerate(names): ... print p ... (0, 'wilma') (1, 'fred') (2, 'betty') (3, 'barney') ###### Note that nothing stops us from doing an iteration directly across a list: there is no need to "enumerate" if we don't care about indices: ###### >>> for n in names: ... print n.capitalize() ... Wilma Fred Betty Barney ###### Let's look in the code that you have: > #manipulate object in list > for p in enumerate(range(10)): > myObject=p > print myObject.getName() This code is buggy because the enumeration is going across an arbitrary list of the integers between zero and ten. Python has no clue that there should be a relationship here with the code you had previously with the 'list' collection. You may want to iterate across the 'list' that you've constructed instead. ###### for object in list: print object.getName() ###### This has a similar effect to the following Java pseudocode: /*** Java pseudocode ***/ for (Iterator iter = list.iterator(); iter.hasNext(); ) { object = (MyObject) iter.next(); System.out.println(object.getName()); } /******/ except you don't have to worry about the type casting in Python. I hope this helps! From carroll at tjc.com Tue May 17 00:34:56 2005 From: carroll at tjc.com (Terry Carroll) Date: Mon, 16 May 2005 15:34:56 -0700 (PDT) Subject: [Tutor] Objects in List In-Reply-To: <67333EF7FC5BBE4AA30723BAC4B53537023F1D42@mdrf002e.za001.siemens.net> Message-ID: On Mon, 16 May 2005, Viljoen, Danie wrote: > My Code: > > class MyObject: > """A simple VO class""" > def setName(self, newName): > self.name=newName > > def getName(self): > return self.name > > def main(): > list=[] > #created object in container > for i in range(10): > myObject = MyObject() > name = 'name:' + str(i) > myObject.setName(name) > list.append(myObject) > > #manipulate object in list > for p in enumerate(range(10)): > myObject=p > print myObject.getName() I think what you're looking to do in this second loop is go through the list (of instances of MyObject) and print each instance's name. But your for loop doesn't reference list. (note: "list" is a defined word in Python, so it's best to use something else. I'll use "ObjectList" below, with conforming changes made to the earlier loop creating it, of course) #manipulate object in list for p in ObjectList: myObject=p print myObject.getName() Prints: name:0 name:1 name:2 name:3 name:4 name:5 name:6 name:7 name:8 name:9 > C:\development\python__>python list.py > Traceback (most recent call last): > File "list.py", line 25, in ? > main() > File "list.py", line 21, in main > print myObject.getName() > AttributeError: 'tuple' object has no attribute 'getName' Yeah, here's the breakdown of why this is occurring: > #manipulate object in list > for p in enumerate(range(10)): This is going to essentially generate feed the for loop with a series of tuples, with the values (0,0), (1,1) ... (9,9) [see Danny's message] . Each iteration of teh for loop will use one tuple as the value for p. > myObject=p Now, you've set the label mObject to point to a tuple, e.g., (0,0). > print myObject.getName() Now, you've asked to execute a method named getName in the tuple (0,0). A tuple doesn't have that method, so the call failes: > AttributeError: 'tuple' object has no attribute 'getName' By the way, normally, you wouldn't use getters and setters in Python in the way they dominate in Java. Instead, you'd just use an appropriately named attribute. It makes for simpler code later. Here'a a more pythonic approach: class MyObject: """A simple VO class""" def main(): ObjectList=[] #created object in container for i in range(10): myObject = MyObject() myObject.name = 'name:' + str(i) ObjectList.append(myObject) #manipulate object in list for p in ObjectList: print p.name if __name__ == '__main__': main() From jfouhy at paradise.net.nz Tue May 17 01:03:45 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 17 May 2005 11:03:45 +1200 (NZST) Subject: [Tutor] Tkinter questions In-Reply-To: References: Message-ID: <1116284625.428926d181ff2@www.paradise.net.nz> Quoting Alberto Troiano : > How can I change the background color of a label?????? > How can I change the font-size and make it BOLD?????? Check out Fredrik Lundh's _Introduction to Tkinter_: http://www.pythonware.com/library/tkinter/introduction/ In particular, the section on widget customization/styling: http://www.pythonware.com/library/tkinter/introduction/widget-styling.htm If you are using Pmw, you can also use Pmw.logicalfont() to change the font. (eg: tk = Tk() fixed = Pmw.logicalfont(name='Fixed', weight='bold') Label(tk, background='blue', font=fixed, text='Hello world!').pack() ) -- John. From terji78 at gmail.com Tue May 17 03:46:50 2005 From: terji78 at gmail.com (T Petersen) Date: Tue, 17 May 2005 03:46:50 +0200 Subject: [Tutor] using counters and timers in text based programs Message-ID: Hi, This is my first post here, and I'm new to programming (and therefore Python also:-)) I've made a almost functioning chess program which works in the shell. Now, I would like to add some type of counters, e.g. time used so far and/or move depth searched which should be updated continously. Is this possible in shell shell based programs? I could of course do a 'print' command for every calculation made, but this would make the chess board disappear, which I don't want, so...is this easy? regards From james2dope at yahoo.com Tue May 17 05:40:30 2005 From: james2dope at yahoo.com (james middendorff) Date: Mon, 16 May 2005 20:40:30 -0700 (PDT) Subject: [Tutor] help with my python app Message-ID: <20050517034030.52070.qmail@web31013.mail.mud.yahoo.com> Hello, I would like to be able to use the arrow keys to control a remote control car, which I can do but only one key at a time. I would like to press the up key, then while it is moving forward, press the left or right key to turn while it is moving forward? I am sure there are probably better ways to write the code, I am still learning all of this. Also if this indention is off I am including the file thanks #!/usr/bin/python import parallel import pygame from pygame.locals import * p=parallel.Parallel() p.setData(0) def main(): # Initialise screen pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("James' custom RC Car Application") # Fill background background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) # Display some text font = pygame.font.Font(None, 36) text = font.render("Which Way? ", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) # Blit everything to the screen screen.blit(background, (0, 0)) pygame.display.flip() # Event loop while 1: for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN: if event.key == K_UP: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("Forward", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(1) if event.key == K_DOWN: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("Reverse", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(2) if event.key == K_LEFT: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("LEFT", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(8) if event.key == K_RIGHT: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("RIGHT", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(4) elif event.type == KEYUP: if event.key == K_UP: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("Which Way? ", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(0) if event.key == K_DOWN: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("Which way? ", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(0) if event.key == K_LEFT: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("Which way? ", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(0) if event.key == K_RIGHT: background.fill((250, 250, 250)) font = pygame.font.Font(None, 36) text = font.render("Which way? ", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() screen.blit(background, (0, 0)) pygame.display.flip() p.setData(0) if __name__ == '__main__': main() "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- Yahoo! Mail Stay connected, organized, and protected. Take the tour: http://tour.mail.yahoo.com/mailtour.html -------------- next part -------------- A non-text attachment was scrubbed... Name: newesttest.py Type: text/x-python Size: 7004 bytes Desc: 643111960-newesttest.py Url : http://mail.python.org/pipermail/tutor/attachments/20050516/a93ff5a6/newesttest-0001.py From leec03273 at mac.com Tue May 17 06:26:26 2005 From: leec03273 at mac.com (Lee Cullens) Date: Tue, 17 May 2005 00:26:26 -0400 Subject: [Tutor] Python Interest Group Query Message-ID: <57146F1B-4098-4912-86FD-440388C72E0D@mac.com> Python Interest Group Query I'm aware of the Boston PIG, a smaller one in Amherst and have been told that there is possibly a PIG in Manchester, NH. Basically I'm trying to find out if there are any, or any interest in (or even any other Python users at all :~)) in a PIG in the northern NE corridor (Vermont, New Hampshire, Maine). I'm a recent Mac and Python convert working at some multimedia software development, and retired from a software engineering career. I live in western NH and back in the late 80's commuted to Boston and NY, so I'm not very keen on such anymore :~) Thank you, Lee C From alan.gauld at freenet.co.uk Tue May 17 09:20:06 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 17 May 2005 08:20:06 +0100 Subject: [Tutor] help with my python app References: <20050517034030.52070.qmail@web31013.mail.mud.yahoo.com> Message-ID: <007701c55ab0$daf52510$358c8651@xp> Hi James, I can't answer your question because I don't know anything about pygame, but your code would look a lot better if you wrote a function (handleKeyEvent() say?) to avoid repeating all that code. One of the big advantages of using functions - aside from saving typing effort - is that they make the code more readable by replacing a lot of detail with a short descriptive phrase(the functions name). The other advantage is that if the code has to be fixed you only change it in one place so there's less chance of you accidentaly missing out one of the event handlers. If the code is slightly diffeent each time - although from a quick look this doesn't seem to be the case here - you can parameterise the function so you can pass in either the changing values or some flag to indicate which variant you need. It's all part of helping us to see the wood instead of the trees... HTH Alan G. ----- Original Message ----- From: "james middendorff" To: Sent: Tuesday, May 17, 2005 4:40 AM Subject: [Tutor] help with my python app > Hello, I would like to be able to use the arrow keys > to control a remote control car, which I can do but > only one key at a time. I would like to press the up > key, then while it is moving forward, press the left > or right key to turn while it is moving forward? I am > sure there are probably better ways to write the code, > I am still learning all of this. Also if this > indention is off I am including the file > thanks > > #!/usr/bin/python > import parallel > import pygame > from pygame.locals import * > > p=parallel.Parallel() > p.setData(0) > > > > > > > > def main(): > # Initialise screen > pygame.init() > screen = pygame.display.set_mode((640, 480)) > pygame.display.set_caption("James' custom RC > Car Application") > > # Fill background > background = pygame.Surface(screen.get_size()) > background = background.convert() > background.fill((250, 250, 250)) > > # Display some text > font = pygame.font.Font(None, 36) > text = font.render("Which Way? ", 1, (10, 10, > 10)) > textpos = text.get_rect() > textpos.centerx = > background.get_rect().centerx > background.blit(text, textpos) > > # Blit everything to the screen > screen.blit(background, (0, 0)) > pygame.display.flip() > > # Event loop > while 1: > for event in pygame.event.get(): > if event.type == QUIT: > return > elif event.type == KEYDOWN: > if event.key == K_UP: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Forward", 1, (10, 10, > 10)) > textpos = text.get_rect() > textpos.centerx = > background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(1) > > > if event.key == K_DOWN: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("Reverse", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(2) > > > if event.key == K_LEFT: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("LEFT", 1, (10, 10, 10)) > textpos = > text.get_rect() > textpos.centerx = > background.get_rect().centerx > background.blit(text, > textpos) > > screen.blit(background, (0, 0)) > pygame.display.flip() > > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(8) > > > if event.key == K_RIGHT: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("RIGHT", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(4) > > > > elif event.type == KEYUP: > if event.key == K_UP: > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("Which Way? ", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(0) > > > if event.key == K_DOWN: > > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("Which way? ", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(0) > > > if event.key == K_LEFT: > > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("Which way? ", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(0) > > > if event.key == K_RIGHT: > > background.fill((250, 250, 250)) > font = > pygame.font.Font(None, 36) > text = > font.render("Which way? ", 1, (10, 10, 10)) > textpos = > text.get_rect() > > textpos.centerx = background.get_rect().centerx > > background.blit(text, textpos) > > screen.blit(background, (0, 0)) > > pygame.display.flip() > > screen.blit(background, (0, 0)) > > pygame.display.flip() > p.setData(0) > > if __name__ == '__main__': main() > > "I would kill everyone in this room > for a drop of sweet beer." > ----Homer Simpson---- > > > > Yahoo! Mail > Stay connected, organized, and protected. Take the tour: > http://tour.mail.yahoo.com/mailtour.html > ---------------------------------------------------------------------- ---------- > #!/usr/bin/python > import parallel > import pygame > from pygame.locals import * > > p=parallel.Parallel() > p.setData(0) > > > > > > > > def main(): > # Initialise screen > pygame.init() > screen = pygame.display.set_mode((640, 480)) > pygame.display.set_caption("James' custom RC Car Application") > > # Fill background > background = pygame.Surface(screen.get_size()) > background = background.convert() > background.fill((250, 250, 250)) > > # Display some text > font = pygame.font.Font(None, 36) > text = font.render("Which Way? ", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > > # Blit everything to the screen > screen.blit(background, (0, 0)) > pygame.display.flip() > > # Event loop > while 1: > for event in pygame.event.get(): > if event.type == QUIT: > return > elif event.type == KEYDOWN: > if event.key == K_UP: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Forward", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(1) > > > if event.key == K_DOWN: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Reverse", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(2) > > > if event.key == K_LEFT: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("LEFT", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(8) > > > if event.key == K_RIGHT: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("RIGHT", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(4) > > > > elif event.type == KEYUP: > if event.key == K_UP: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Which Way? ", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(0) > > > if event.key == K_DOWN: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Which way? ", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(0) > > > if event.key == K_LEFT: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Which way? ", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(0) > > if event.key == K_RIGHT: > background.fill((250, 250, 250)) > font = pygame.font.Font(None, 36) > text = font.render("Which way? ", 1, (10, 10, 10)) > textpos = text.get_rect() > textpos.centerx = background.get_rect().centerx > background.blit(text, textpos) > screen.blit(background, (0, 0)) > pygame.display.flip() > screen.blit(background, (0, 0)) > pygame.display.flip() > p.setData(0) > > if __name__ == '__main__': main() > From project5 at redrival.net Tue May 17 09:16:47 2005 From: project5 at redrival.net (Andrei) Date: Tue, 17 May 2005 07:16:47 +0000 (UTC) Subject: [Tutor] YATENJoe References: <6.1.0.6.2.20050515183101.01f06988@pop.gmail.com> Message-ID: Joseph Quigley gmail.com> writes: > I want to make a text editor. I know that there are hundreds out there, > but practice makes perfect, and I need the practice. My problem is > that I have no idea how to make one. I've tried a little already by > defining line functions:def line1(): l1 = > raw_input("") If you intend to make a text editor (something which allows the user to browse through the text and manipulate it at will) using just raw_input and print, I think you've set yourself an impossible task. For a console editor you should probably look at curses (http://www.amk.ca/python/howto/curses/) - which don't work on Windows, so you'll probably need this: http://adamv.com/dev/python/curses/ (but according to the site it's incomplete). It's probably better to select a GUI toolkit which has an editor widget and build your editor on that. Tkinter and wxPython both offer this, with wxPython including a wrapper of the excellent Scintilla control (it has syntax highlighting, word wrapping, support for non-monospaced fonts, etc.). You could even write a webbased editor using the text entry widget provided by browsers (crappy as it may be), even that would be better than hand-coding your own editor widget. > line2()Of course, this only allows for 2 lines. What's the trick to an > infinite number of lines? lines = [] while True: lines.append(raw_input('')) (But that offers no way to e.g. save and continue.) > YATENJoe"? I'm still a newbie to python (actually OOP programming in > general!) so I can't have a lot of complicated stuff thrown in my > face. Text editors are IMO not applications suitable for learning vanilla Python, or OOP for that matter. Text editors are used as example applications in the RAD IDE world (VB, Delphi and such) because in those environments a text editor is literally three clicks away (click on memo component, click on form, click on run). Vanilla Python has no GUI, so no memo component - hence my recommendation for Tkinter or wxPython. PythonCard and Boa provide an experience somewhat similar to commercial RAD IDE's if that's what you're looking for. > I thought of a function that would define a function for me. Is this > possible? If it is how would I do it? If it possible, here's my Having one function for each line is a bad idea whether you code it by hand or automatically (yes, it would be possible, but not something you should want to do). A line of text is a piece of *data* similar to the line before it and the line after it. A function implements certain behavior. Having the same behavior (raw_input) implemented separately for each line is an extremely wasteful way of programming. Use data containers (like lists) for storing data and use a single function for manipulating any item (line) in such a data structure. E.g. let's say you have 5 lines of text and you want to uppercase them all. Your way would be to create 5 separate functions (or 10000000 if there are more lines) for each of the lines and call each of those. A better way would be to have a single function and call that repeatedly telling it on which line to operate. I would suggest that you learn a bit more about Python's facilities before embarking on an ambitious project :) - you won't get very far without knowing how to use lists and dictionaries. Yours, Andrei From olli.rajala at gmail.com Tue May 17 09:21:40 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Tue, 17 May 2005 10:21:40 +0300 Subject: [Tutor] Save data 'over SSH' Message-ID: Hi guys (and gals too!) I'm writing a program where I would need to write the output finally to the computer I can access with SSH/SFTP/SCP. So, is there any 'pythonish' way to do it, or do I have to use os.system() or something similar? I can save it temporarily to the computer the program is running on, if that matters. Oh, the program is a cgi-script running on Apache2 and it's running on my own computer so if I need to install some additional modules, it is possible. Thanks in advance! -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From carroll at tjc.com Tue May 17 09:27:20 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 May 2005 00:27:20 -0700 (PDT) Subject: [Tutor] Linux variable to Python In-Reply-To: Message-ID: On Fri, 13 May 2005, Alberto Troiano wrote: > To explain for those who doesn't know: > The first line creates a variable named "fec" with the value cam(a Linux > function returning year month day hour minute second).jpg > The second show the value of "fec" > The third moves hola.txt to the directory grabacion and puts the "fec" value > as the new name for the file I do something similar in a pure python program: # get to temporary directory (_year, _mon, _day, _hour, _min, _sec, _none, _none, _none)=time.localtime() temp_dir = "D%4d-%02d-%02d-%02d%02d%02d" % (_year, _mon, _day, _hour, _min, _sec) os.mkdir(temp_dir) os.chdir(temp_dir) This creates a directory in the form DYYYY-MM-DD-HHMMSS (for example, at 6:10:08 PM on May 12, 2005, the directory is named D2005-05-12-181008), and then makes it the current directory. You could probably do the same with minimal tweaking. From project5 at redrival.net Tue May 17 09:40:52 2005 From: project5 at redrival.net (Andrei) Date: Tue, 17 May 2005 07:40:52 +0000 (UTC) Subject: [Tutor] Opinions about this GIS script References: Message-ID: Ron Phillips engineer.co.summit.oh.us> writes: > The script produces expected results, but if anyone is so inclined, I'd appreciate review/evaluation/critique of the 'pythonism' of the script. I haven't read it from A to Z, but it looks OK. Some minor things: - string formatting, e.g.: out+= 'Attribute: '+field+" => "+str(self.fileAttributes[field])+'\n' I'd prefer seeing a format string. "Attribute: %s => %d\n" % (field, self.fileAttributes[field]) - I'm guessing at types here, with file as string and attrib as integer. - lists of strings and ''.join instead of +, e.g.: I'd favor making 'out' a list of strings and building the result at the end, using "\n".join(out). - long functions/loops: there are two parse functions which don't fit on my screen. Perhaps they can be split in smaller parts. There's some duplicate code in the two large (and also the third smaller) parse functions, indicating that splitting in smaller pieces should be possible and would also remove the duplicate code. - There's a lot of "struct.unpack('>i',indexfile.read(4))[0]" and similar lines. A file class which would wrap this stuff and offer a nice interface with methods like ReadInt, ReadDouble would clear it up a bit. - "Private function" in the comment of __newdemo. I'd remove it, since the double underscore already documents this. Yours, Andrei From olli.rajala at gmail.com Tue May 17 09:52:39 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Tue, 17 May 2005 10:52:39 +0300 Subject: [Tutor] Removing lines in string-table Message-ID: Okay, I have a string table (don't recall the right word used in Python right now) and would like to remove every 'cell' that contains a string '_thumb.jpg'. There are 1-> digits before the string if that matters. I made a for-loop that does what I want to: for line in fileNames: if line[-10:] == '_thumb.jpg': fileNames.remove(line) But I really doubt that it's not the best way to do this. So, any comments are really appreciated. Back to coding... -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From work at infomaniak.ch Tue May 17 10:43:58 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Tue, 17 May 2005 10:43:58 +0200 Subject: [Tutor] creation of a module In-Reply-To: <000601c558ca$dfe4a970$d2cd8751@xp> References: <20050513075818.GB17427@obs.unige.ch> <42847CFA.7010707@tds.net> <20050513192716.GC17427@obs.unige.ch> <000601c558ca$dfe4a970$d2cd8751@xp> Message-ID: <20050517084358.GA12919@obs.unige.ch> Hi Alan > Hi Cedric, > > Reading through this I can't help but think you are going to > a lot of trouble to make things very complicated for yourself > - and for anyone else who has to work on your code. The > Python module system is very simple and helpful in tracking > down where the various things live. You can see by the > prefix name which package/file provides which service. > It appears that you are trying to hide that information? > > Is there a special reason why you are trying to introduce > this kind of obfuscation? > > > > > {a,b,c}.py contains respecetively classA,classB,classC more some > unittest > > > > and bunch.py will contains some usefull function using the > class{A,B,C} > > > > > > > > I'd like that when I import MyModule (`import MyModule')OB > > > > I'll see from it: > > > > MyModule.classA > > > > .classB > > > > .classC > > > > . > > > > . > > > > ... > > > > without seeing MyModule.{a,b,c} > > Why do you want to conceal the information about what lives inside > the package? How will users be able to debug the package? If you > hide a,b and c you will make it harder to do things like I thought that it will be more convenient. But as I can read from your email: it seems a really __not_so_good__ idea . > > >>> dir(MyModule) > >>> dir (MyModule.a) > > etc to explore the structure and find the code. never done such kind of things. > > > I've done it. But is it normal that I'see also the filename > > Actually you don;t see the filename you see the sub moduile names. > a.py becomes a module called a within your package. > > > the idea was to automate the : > > from MyModule.a import classA > > from MyModule.b import classB > > from MyModule.c import classC > > What is the advantage - apart from a minimal amount of typing? > You still need to maintain a list of the class/module mappings. no the idea was to give a prefix to all my files depending on the way I'd like to import them. In fact, my files are named class_foo.py and the class inside this file is named CFoo. > > with a loop > > > > lclassname=['classA', 'classB', 'classC'] > > #in the future I can even automate the creation of classname list > > for classname in lclassname: > > #filename='a', classname='classA' > > filename=classname.replace('class','').lower() > > Maybe you should use a dictionary as Kent suggested: > > classes = {'classA': 'a', > 'classB': 'b', > 'classC : 'c' > } > > filename = classes[classname] > > > #from filename import classname > > module=__import__(filename, gloabls(), locals(), [classname]) > > classDefinition=getattr(module,classname) > > assign(classname,classDefinition) > > > > But this is a lot of work to sabve a very small amount of typing and > could slow down your program initialisation significantly. > > > In this way, when I'll do an > > import FWobs > > I'll get: > > MyModule.classA > > .classB > > .classC > > . > > . > > It looks as if all you really want to do is avoid having the > sub-module names visible when you import the package. As I > explained above I think thats a fundamentally bad idea. Good, I'll follow your recommendation > If you do just want to export a single set of services from a > single import it would be much simpler to just put them all > in a single module! And then you can hide the exposed names > using the Python naming convention of prefixing with '_' > or ' __'. > > Of course if its a very large set of services a package > is better, but then you probably should expose the sub modules > too. NAmespaces are one of Pythons best features - they are > simple to use and very effective both in controlling program > structure and in aiding debugging, its probabnly best to use > them as intended rather than trying to force them to work > differently. > > All IMHO of course! :-) > > Alan G thanks for your time. Ced. -- Cedric BRINER From work at infomaniak.ch Tue May 17 10:47:45 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Tue, 17 May 2005 10:47:45 +0200 Subject: [Tutor] Testing for commandline args In-Reply-To: References: <20050514003056.GA23507@sillyrabbi.dyndns.org> Message-ID: <20050517084745.GB12919@obs.unige.ch> > Also, I hear that optparse is much better than getopt. this is a true pleasure to work with optparse. It was included in python2.3 and was primarly called python-optik Ced. -- Cedric BRINER From kent37 at tds.net Tue May 17 12:06:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 May 2005 06:06:04 -0400 Subject: [Tutor] Python Interest Group Query In-Reply-To: <57146F1B-4098-4912-86FD-440388C72E0D@mac.com> References: <57146F1B-4098-4912-86FD-440388C72E0D@mac.com> Message-ID: <4289C20C.6050301@tds.net> Lee Cullens wrote: > Python Interest Group Query > > I'm aware of the Boston PIG, a smaller one in Amherst and have been > told that there is possibly a PIG in Manchester, NH. > > Basically I'm trying to find out if there are any, or any interest in > (or even any other Python users at all :~)) in a PIG in the northern > NE corridor (Vermont, New Hampshire, Maine). > > I'm a recent Mac and Python convert working at some multimedia > software development, and retired from a software engineering > career. I live in western NH and back in the late 80's commuted to > Boston and NY, so I'm not very keen on such anymore :~) I am interested, I live in southern NH (Hollis). Kent From jgschenz at yahoo.com Wed May 18 12:05:47 2005 From: jgschenz at yahoo.com (J. Gabriel Schenz) Date: Wed, 18 May 2005 05:05:47 -0500 Subject: [Tutor] Tutor Digest, Vol 15, Issue 40 In-Reply-To: Message-ID: <20050517104914.EA48A1E4006@bag.python.org> >At 02:17 PM 5/12/2005, Bernard Lebel wrote: >>Just a generic question: why one would use apply()? >> >>In Learning Python, on page 357, there is an example of generating an >>instance using apply(): >> >>class A: >> def __init__( self, number ): >> self.number = number >> >>a = apply( A, 3 ) >>What is the benefit of doing this over simply creating an instance "the >>usual way": >>a = A( 3 ) > >No benefit. See 2.2 Non-essential Built-in Functions in the Python Library >Reference. 'Use of apply() is not necessary since the ``extended call >syntax,'' as used in the last example, is completely equivalent." > >Bob Gailer Now, I am new to Python as well, but it seems like apply might not be completely superfluous. I was thinking that if one were using a functional programming style, and had to apply a function determined at runtime to an argument, then one could use this apply to do so. Granted, you could also have a dictionary of functions and call the function required as determined at runtime, but this is stylistically different. If I am off base on this, I would appreciate someone explaining why. That way I can learn this elegant language better. Regards, Gabe From RPhillips at engineer.co.summit.oh.us Tue May 17 13:11:53 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Tue, 17 May 2005 07:11:53 -0400 Subject: [Tutor] Opinions about this GIS script Message-ID: Thank you, Andrei, that's just what I was hoping for -- I wondered about some of those issues, but was a little unsure how to approach a solution. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050517/2ec129e7/attachment.htm From kent37 at tds.net Tue May 17 14:06:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 May 2005 08:06:59 -0400 Subject: [Tutor] Tutor Digest, Vol 15, Issue 40 In-Reply-To: <20050517104914.EA48A1E4006@bag.python.org> References: <20050517104914.EA48A1E4006@bag.python.org> Message-ID: <4289DE63.7010807@tds.net> J. Gabriel Schenz wrote: > Now, I am new to Python as well, but it seems like apply might not be > completely superfluous. I was thinking that if one were using a functional > programming style, and had to apply a function determined at runtime to an > argument, then one could use this apply to do so. Granted, you could also > have a dictionary of functions and call the function required as determined > at runtime, but this is stylistically different. > > If I am off base on this, I would appreciate someone explaining why. That > way I can learn this elegant language better. apply() is superfluous. apply(function, args[, keywords]) is exactly equivalent to function(*args, [**keywords]). So however you are determining the function to use with apply, you can call it directly with the newer syntax. In each case, the variable 'function' will be bound to a function object. For example, >>> def foo(): ... print 'foo' ... >>> def bar(): ... print 'bar' ... >>> def pick(arg): ... if arg: ... return foo ... else: ... return bar ... >>> myFunc = pick(True) >>> apply(myFunc, ()) foo >>> myFunc() foo >>> myFunc = pick(False) >>> myFunc() bar Kent From albertito_g at hotmail.com Tue May 17 14:43:56 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 17 May 2005 12:43:56 +0000 Subject: [Tutor] Tkinter questions In-Reply-To: <1116284625.428926d181ff2@www.paradise.net.nz> Message-ID: Thanks for the reply I read the link and I think I've got all what I need (at least for now) Thanks again Regards Alberto >From: jfouhy at paradise.net.nz >To: Tutor Tutor >Subject: Re: [Tutor] Tkinter questions >Date: Tue, 17 May 2005 11:03:45 +1200 (NZST) > >Quoting Alberto Troiano : > > > How can I change the background color of a label?????? > > How can I change the font-size and make it BOLD?????? > >Check out Fredrik Lundh's _Introduction to Tkinter_: >http://www.pythonware.com/library/tkinter/introduction/ > >In particular, the section on widget customization/styling: >http://www.pythonware.com/library/tkinter/introduction/widget-styling.htm > >If you are using Pmw, you can also use Pmw.logicalfont() to change the >font. > >(eg: > >tk = Tk() >fixed = Pmw.logicalfont(name='Fixed', weight='bold') >Label(tk, background='blue', font=fixed, text='Hello world!').pack() > >) > >-- >John. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From python at venix.com Tue May 17 15:07:37 2005 From: python at venix.com (Lloyd Kvam) Date: Tue, 17 May 2005 09:07:37 -0400 Subject: [Tutor] Python Interest Group in New England Message-ID: <1116335257.6188.12.camel@laptop.venix.com> (From digest) > I'm aware of the Boston PIG, a smaller one in Amherst and have been > told that there is possibly a PIG in Manchester, NH. The Dartmouth Lake Sunapee Linux User Group http://dlslug.org/ also supports a python mail list. http://dlslug.org/mailing_lists.html The Python folks are scattered around the state. I'm in Lebanon, NH. Seven people in signed up for python.meetup in Lebanon, but we've never had more than 4 show up for a meeting. Sign up for the python-talk list and let us know you joined. http://www.gnhlug.org/ I think you'll find the local LUGs will welcome Python folks, even those using Macs and Windows. -- Lloyd Kvam Venix Corp From jsmith at medplus.com Tue May 17 15:35:26 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 17 May 2005 09:35:26 -0400 Subject: [Tutor] I know you will hate this but... Message-ID: I'm working on a Python development project which spans multiple people. We are all working on Windows and using the PyWin IDE. Our code is revision controlled using Perforce. Already we had one instance where the logical structure of a file was destroyed because indentation levels were changed along the way. I can't tell if it was done because PyWin IDE was setup differently or because Perforce munged things on a merge...that doesn't really matter. It seems problematic to me to try to enforce tool standards on people (IDE and editor settings) which may or may not take. My solution has been to require (as a coding standard) ending comments on control blocks longer than one line. At least this is something that could be caught at submit time with an automated review tool. I'd be interested in how anyone else has solved this problem...provided you've seen it. Thanks, Jeff P.S. An example of my solution would be: if some condition: do stuff and more stuff elif another condition: this is the elif clause with stuff to do else: and the else clause #endif some condition From albertito_g at hotmail.com Tue May 17 15:36:14 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 17 May 2005 13:36:14 +0000 Subject: [Tutor] Troubles with Python modules Message-ID: Hey I'm working on Python 2.2 over Linux REd Hat 9.0 and here is the code I have import os import sys import MySQLdb import datetime import time class conexion(object): def __init__(self): self.db = MySQLdb.connect(host="localhost", user="administrador", passwd="123456",db="seguridad") def consulta(self,query,args=None): try: self.cursor=self.db.cursor() self.sql=self.cursor.execute(query,args) except: self.cerrar() else: self.cerrar() def cerrar(self): self.db.close() def getpath(): global ruta global user global cam try: i=0 for arg in sys.argv: if i==1: ruta+=arg elif i==2: user=arg elif i==3: cam=arg else: pass i+=1 except: f=open("cotascamonerrors.log","a+") f.write("ERROR ------ No se pudo encontrar el path "+ruta+". Contacte al administrador.") f.close() def getHoursMinutes(ts=None): if ts: t = time.strptime(ts, '%H:%M') else: t = time.localtime() return (t.tm_hour, t.tm_min) global ruta global user global cam ruta="/var/www/html/home/" getpath() os.chdir(ruta) os.system("mkdir grabacion") days={1:"Lunes",2:"Martes",3:"Miercoles",4:"Jueves",5:"Viernes",6:"Sabado",7:"Domingo"} while 1: hoy=datetime.datetime.now() dia=days[hoy.isoweekday()] query="SELECT %s, Limite from camara where CodigoCamara=%s" args=(dia,cam) cur=conexion() cur.consulta(query,args) res=cur.cursor.fetchall() for i in res: horag=i[0] limite=i[1] horai1=horag[0:5] horaf1=horag[6:11] horai2=horag[12:17] horaf2=horag[18:23] if getHoursMinutes(horai1) <= getHoursMinutes() <= getHoursMinutes(horaf1): cur=conexion() query="SELECT count(*) from imagen where CodigoCamara=%s and Usuario=%s" args(cam,user) cur.consulta(query,args) j=cur.cursor.fetchall() for k in j: actual=k[0] if actual < limite: cur=conexion() grupo=datetime.datetime.today().strftime("%Y%m%d%H%M%S") try: os.system("cp webcam.jpg grabacion/cam"+grupo+".jpg") query="INSERT INTO imagen values (%s,%s,%s,NOW(),NOW(),%s) where CodigoCamara=%s and Usuario=%s" grupo1=datetime.datetime.today().strftime("%Y%m%d%H%M") ruta1=ruta+"/grabacion/cam"+grupo+".jpg" args(user,cam,ruta1,grupo1) cur.consulta(query,args) except: pass else: f=open("cotascamonerrors.log","a+") f.write("ERROR ------ El usuario "+user+" agoto su espacio de almacenamiento.") f.close() elif getHoursMinutes(horai2) <= getHoursMinutes() <= getHoursMinutes(horaf2): cur=conexion() query="SELECT count(*) from imagen where CodigoCamara=%s and Usuario=%s" args(cam,user) cur.consulta(query,args) j=cur.cursor.fetchall() for k in j: actual=k[0] if actual < limite: cur=conexion() grupo=datetime.datetime.today().strftime("%Y%m%d%H%M%S") try: os.system("cp webcam.jpg grabacion/cam"+grupo+".jpg") query="INSERT INTO imagen values (%s,%s,%s,NOW(),NOW(),%s)where CodigoCamara=%s and Usuario=%s" grupo1=datetime.datetime.today().strftime("%Y%m%d%H%M") ruta1=ruta+"/grabacion/cam"+grupo+".jpg" args(user,cam,ruta1,grupo1) cur.consulta(query,args) except: pass else: f=open("cotascamonerrors.log","a+") f.write("ERROR ------ El usuario "+user+" agoto su espacio de almacenamiento.") f.close() else: pass First I'd like to know if this code can be shorter or more efficient (if you have the time) Second the error is the following: Traceback (most recent call last): File "/root/cotascamon.py", line 4, in ? import datetime ImportError: No module named datetime I think this module is in Python 2.3. What can I do?????? Then I have installed Python 2.3.4 in the same Linux but I can't use it because it doesn't recognze the module MySQLdb Here is the error Traceback (most recent call last): File "/root/cotascamon.py", line 3, in ? import MySQLdb File "/usr/local/lib/python2.3/site-packages/MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: No module named _mysql I have cross modules Modules Python 2.2 ----------------- Python 2.3.4 MySQLdb YES NO datetime NO YES Heeeeeeeeeelp Thanks in advanced Alberto From maxnoel_fr at yahoo.fr Tue May 17 15:40:00 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 17 May 2005 14:40:00 +0100 Subject: [Tutor] Removing lines in string-table In-Reply-To: References: Message-ID: <380EEE54-0C2B-4D7F-BAB3-F9E5060B5B29@yahoo.fr> On May 17, 2005, at 08:52, Olli Rajala wrote: > Okay, > I have a string table (don't recall the right word used in Python > right now) It's called a list, or an array. > and would like to remove every 'cell' that contains a > string '_thumb.jpg'. There are 1-> digits before the string if that > matters. I made a for-loop that does what I want to: > > for line in fileNames: > if line[-10:] == '_thumb.jpg': > fileNames.remove(line) > > But I really doubt that it's not the best way to do this. So, any > comments are really appreciated. Looks like a job for a list comprehension: fileNames = [element for element in fileNames if not element.endswith ("_thumb.jpg")] -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From olli.rajala at gmail.com Tue May 17 15:48:40 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Tue, 17 May 2005 16:48:40 +0300 Subject: [Tutor] Removing lines in string-table In-Reply-To: <380EEE54-0C2B-4D7F-BAB3-F9E5060B5B29@yahoo.fr> References: <380EEE54-0C2B-4D7F-BAB3-F9E5060B5B29@yahoo.fr> Message-ID: > Looks like a job for a list comprehension: > > fileNames = [element for element in fileNames if not element.endswith > ("_thumb.jpg")] Thanks Max! It seem to work, but now I have to do some reading, because I have no idea why it works or what it really does. :) But thanks anyway. Yours, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From mhansen at cso.atmel.com Tue May 17 17:37:25 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 17 May 2005 09:37:25 -0600 Subject: [Tutor] Use Strict or Use Warnings was ( Lists of files) In-Reply-To: References: Message-ID: <428A0FB5.5040501@cso.atmel.com> > ------------------------------------------------------------------------ > > Subject: > Re: [Tutor] Lists of files > From: > William O'Higgins > Date: > Mon, 16 May 2005 15:50:37 -0400 > > [...] > > One last thing - is there an equivalent of the "use strict" and "use > warnings" pragmas in Python? Thanks. The closest thing I've found is PyChecker. It's kind of like perl -c hardtoreadperlscript.pl http://pychecker.sourceforge.net/ From smichr at bigfoot.com Tue May 17 17:41:04 2005 From: smichr at bigfoot.com (Chris Smith) Date: Tue, 17 May 2005 10:41:04 -0500 Subject: [Tutor] Removing lines in string-table In-Reply-To: Message-ID: <13DC162A-C6EA-11D9-9AA3-000393C0D100@bigfoot.com> On Tuesday, May 17, 2005, at 08:35 America/Chicago, tutor-request at python.org wrote: > I have a string table (don't recall the right word used in Python > right now) and would like to remove every 'cell' that contains a > string '_thumb.jpg'. There are 1-> digits before the string if that > matters. I made a for-loop that does what I want to: > > for line in fileNames: > if line[-10:] == '_thumb.jpg': > fileNames.remove(line) > > But I really doubt that it's not the best way to do this. So, any > comments are really appreciated. > The above will not work if two successive lines contain the target text. When you remove the one, its neighbor "slides over" to take the place of the one removed and then when you proceed to the "next" line you are actually skipping the one that slid over. This could be remedied with using indices to access the list, but perhaps a better approach is to use filter or a list comprehension to remove the target lines: ### def myfilter(x): return not x.endswith('_thumb.jpg') fileNames =filter(myfilter, fileNames) # OR fileNames =[x for x in fileNames if not x.endswith('_thumb.jpg')] ### /c From olli.rajala at gmail.com Tue May 17 18:19:30 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Tue, 17 May 2005 19:19:30 +0300 Subject: [Tutor] Removing lines in string-table In-Reply-To: <13DC162A-C6EA-11D9-9AA3-000393C0D100@bigfoot.com> References: <13DC162A-C6EA-11D9-9AA3-000393C0D100@bigfoot.com> Message-ID: My code: > > for line in fileNames: > > if line[-10:] == '_thumb.jpg': > > fileNames.remove(line) Chris wrote: > The above will not work if two successive lines contain the target > text. When you remove the one, its neighbor "slides over" to take the > place of the one removed and then when you proceed to the "next" line > you are actually skipping the one that slid over. Oh, yeah, that's right. I just didn't notice it... Thanks for correcting me! Actually it wouldn't have mattered (I think) because the list contains x.jpg and x_thumb.jpg which have been collected by os.listdir(). At least I suppose that it would be like [x.jpg, x_thumb.jpg, y.jpg, y_thumb.jpg] or am I completely wrong? But thanks for good suggestions, I replaced my code with the list comprehension method and it works now. Thanks! Yours, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From dyoo at hkn.eecs.berkeley.edu Tue May 17 18:20:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 May 2005 09:20:01 -0700 (PDT) Subject: [Tutor] Objects in List (fwd) Message-ID: > Hi Danny > > Thanks, it works - I must read the documentation more carefully! > > Would you mind if I knok on your door again with futher Python hick-ups? Hi Danie, It's probably a better idea to send your questions to Tutor. The reason is to allow the community to get involved. Also, I have the slight tendency to screw up and give mistaken advice sometimes, and I depend greatly on someone calling me on it and correcting my mistakes. *grin* So just from the sake of accountability and visibility, it's probably best to send questions to the group. Best of wishes! From sigurd at 12move.de Tue May 17 18:46:23 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue, 17 May 2005 18:46:23 +0200 Subject: [Tutor] Lists of files In-Reply-To: <20050516195037.GA5456@sillyrabbi.dyndns.org> (William O'Higgins's message of "Mon, 16 May 2005 15:50:37 -0400") References: <20050514151357.GA26425@sillyrabbi.dyndns.org> <61d0e2b4050514090253a10825@mail.gmail.com> <20050516195037.GA5456@sillyrabbi.dyndns.org> Message-ID: On 16 Mai 2005, william.ohiggins at utoronto.ca wrote: > Thanks to all who helped me with my questions regarding testing for > commandline arguments and list assignment. I have finished my first > Python program (included below). It is slightly more secure than the > Perl program I rewrote, but also about a tenth of a second slower (0.6 > seconds for Perl on average (100 trials) and 0.7 seconds for Python). 0.1 secs isn't much. It's not easy to see if such small differences are according to the program or some side-effects from the OS. Also the time till the interpreter/compiler starts will be significant if the total time is so short. > Is that typical of Python programs? I like Python so far, and I'm not > going to go crazy optimizing working code, but I am curious. It depends. > Any pointers, suggestions, etc. are welcome. I'll write some annotations how you *could* perhaps speed things a _little_ bit up. > One last thing - is there an equivalent of the "use strict" and "use > warnings" pragmas in Python? Thanks. No. There is no need for them IMO since Python doesn't allow such unsafe constructs as Perl a priori. > def changebackdrop(): [...] > command = "/usr/bin/Esetroot" > # If I was logging into X remotely, this would change. > commandargs = " -display :0.0 " I would write these tow as formal parameters (with default values) since they can change. > # This is where my backdrops live > picdir = "/home/willyyam/misc/bmps/" > > if sys.argv[1:]: > doit = command + commandargs + sys.argv[1] > os.popen(doit, 'r') Why you create the variable doit? Just write directly: os.popen(command + commandargs + sys.argv[1] > else: > files = os.listdir(picdir) No need for that variable. > os.chdir(picdir) > pics = [] No need for that variable. > for file in files: > # This is a test for valid images - it includes rgb files, > # which are not supported by my image software, but the > # error thrown is not terrible - the image software knows=20 > # what it can and cannot run. > if imghdr.what(file): > pics.append(file) > No need for that loop. > randpic = random.choice(pics) randpic = random.choice(filter(imghdr.what, os.listdir(picdir))) That's IMO easier to read and should be a bit faster. One problem I forgot to mention with that solution is: if there are not only files but also directories in that picdir you first have to filter the files since imghdr.what throws an exception if it gets a directory as argument. > doit = command + commandargs + picdir + randpic > os.popen(doit, 'r') The same as above. Or you create the variable `doit' but you write the `os.popen' only once (since after the if statement it will hold the right value for the command to execute. Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Tue May 17 18:58:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 May 2005 09:58:10 -0700 (PDT) Subject: [Tutor] Troubles with Python modules In-Reply-To: Message-ID: On Tue, 17 May 2005, Alberto Troiano wrote: > I'm working on Python 2.2 over Linux REd Hat 9.0 and here is the code I > have [code cut] > First I'd like to know if this code can be shorter or more efficient (if > you have the time) Yes. But let's look at the errors first. > Second the error is the following: > > Traceback (most recent call last): > File "/root/cotascamon.py", line 4, in ? > import datetime > ImportError: No module named datetime > > I think this module is in Python 2.3. What can I do?????? I'll assume for the moment that you are using your root account. Are you sure that your root account is using Python 2.3? It may be possible that the root account has a slightly more restricive PATH than normal user accounts, and that you might be picking up '/usr/bin/python'. > Then I have installed Python 2.3.4 in the same Linux but I can't use it > because it doesn't recognze the module MySQLdb > > Here is the error > > Traceback (most recent call last): > File "/root/cotascamon.py", line 3, in ? > import MySQLdb > File "/usr/local/lib/python2.3/site-packages/MySQLdb/__init__.py", line > 27, in ? > import _mysql > ImportError: No module named _mysql Different releases of Python will not automatically migrate the old third-party modules. You'll need to reinstall MySQLdb for Python 2.3. MySQLdb can be found here: http://sourceforge.net/projects/mysql-python Let's look at some of the code. > def consulta(self,query,args=None): > try: > self.cursor=self.db.cursor() > self.sql=self.cursor.execute(query,args) > except: > self.cerrar() > else: > self.cerrar() The consulta() function tries to make sure that the cerrar() method is called, no matter what. In this case, try/finally may do what you want: ###### try: ... finally: self.cerrar() ###### > def getpath(): > global ruta > global user > global cam > try: > i=0 > for arg in sys.argv: > if i==1: > ruta+=arg > elif i==2: > user=arg > elif i==3: > cam=arg > else: > pass > i+=1 > except: > f=open("cotascamonerrors.log","a+") > f.write("ERROR ------ No se pudo encontrar el path "+ruta+". > Contacte al administrador.") > f.close() This looks like it's trying to do argument parsing, storing state in global variables. You may want to see if you can avoid the globals, and instead just return those three values back to the caller. My nervousness with the globals comes from the requirement that getpath() has to assume that 'ruta' already has some sort of value already. So there's already a dependency that can be more clearly documented by making getpath() take in an initial base path argument: ###### def getpath(base_path): ... return (ruta, user, cam) ###### But the block above also feels a little awkward because it assumes that any exception that occurs has to be a path problem. That might not necessarily be the case. I'd strongly recommend letting the exception speak for itself. traceback.print_exc() can help: http://www.python.org/doc/lib/module-traceback.html ###### try: .... except: f = open("cotascamonerrors.log", "a+") traceback.print_exc(file=f) f.close() ###### Up to this point, though, things are pretty ok, with the nice helper functions with clear roles. The large block near the bottom, though, needs work. I'd recommend applying the same helper-function breakup to make the code's intent clearer. For example, here's SQL code that's repeated, a. It should be broken out: > try: > os.system("cp webcam.jpg grabacion/cam"+grupo+".jpg") > query="INSERT INTO imagen values (%s,%s,%s,NOW(),NOW(),%s) > where CodigoCamara=%s and Usuario=%s" > grupo1=datetime.datetime.today().strftime("%Y%m%d%H%M") > ruta1=ruta+"/grabacion/cam"+grupo+".jpg" > args(user,cam,ruta1,grupo1) > cur.consulta(query,args) > except: > pass Again, try not to obscure exceptions. If something bad happens, you really want the exception to tell you what happened: it is not fun to debug something when the error message is insufficiently helpful. Change the except block to log the error message. I do not understand what's happening with args() above: > args(user,cam,ruta1,grupo1) Do you mean: args = (user,cam,ruta1,grupo1) instead? Hope this helps! From project5 at redrival.net Tue May 17 19:06:46 2005 From: project5 at redrival.net (Andrei) Date: Tue, 17 May 2005 17:06:46 +0000 (UTC) Subject: [Tutor] I know you will hate this but... References: Message-ID: Smith, Jeff medplus.com> writes: > merge...that doesn't really matter. It seems problematic to me to try > to enforce tool standards on people (IDE and editor settings) which may > or may not take. It seems problematic to me to NOT enforce standard *settings* (e.g. 4 spaces per indentation level, no tabs). Any IDE can be used as long as the proper settings are configured. Inconsistent indentation styles are very annoying in other languages, but a fatal problem in Python. > My solution has been to require (as a coding standard) ending comments > on control blocks longer than one line. At least this is something that > could be caught at submit time with an automated review tool. Weird. Looks to me like the wrong solution (it would IMO be better to find out who committed the broken code and work from there to find the cause), but whatever works for you. > I'd be interested in how anyone else has solved this problem...provided > you've seen it. I haven't, but I use Subversion and haven't done team development in Python. But I don't think any half-decent VCS should go around modifying code on its own in *any* way, even if it's spaces. Although, now that I think about it, a VCS might have an option of ignoring leading/trailing whitespace when doing diffs, such an option could bite when merging Python code. Yours, Andrei From carroll at tjc.com Tue May 17 19:32:29 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 May 2005 10:32:29 -0700 (PDT) Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' Message-ID: I've often found it convenient to run a Python program I'm developing with the -i flag. I find it convenient to use as a post-mortem as it hits bugs, or to explore data structures. I've recently started using the construct if __name__ == "__main__": main() And found I can't do the -i thing effectively any more. What's a good equivalent approach? To use a trivial example, if I have the following program (t2.py): i = 0 k = 4/i print i, k I can do this: C:\>python -i t2.py Traceback (most recent call last): File "t2.py", line 2, in ? k = 4/i ZeroDivisionError: integer division or modulo by zero >>> i 0 >>> But if the program is like this: def main(): i = 0 k = 4/i print i, k if __name__ == "__main__": main() That won't work: C:\>python -i t1.py Traceback (most recent call last): File "t1.py", line 7, in ? main() File "t1.py", line 3, in main k = 4/i ZeroDivisionError: integer division or modulo by zero >>> i Traceback (most recent call last): File "", line 1, in ? NameError: name 'i' is not defined >>> I understand *why* it won't work; I'm just looking for a nice easy way to do the same sort of thing I used to do before I started using '''if __name__ == "__main__":''' From jsmith at medplus.com Tue May 17 20:03:29 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 17 May 2005 14:03:29 -0400 Subject: [Tutor] I know you will hate this but... Message-ID: From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Andrei >It seems problematic to me to NOT enforce standard *settings* (e.g. 4 spaces >per indentation level, no tabs). Any IDE can be used as long as the proper >settings are configured. Inconsistent indentation styles are very annoying in >other languages, but a fatal problem in Python. But there is no way to enforce standard settings. When new versions are installed or someone just makes a mistake the settings might change and you won't know until it's too late...possibly weeks later. >Weird. Looks to me like the wrong solution (it would IMO be better to find out >who committed the broken code and work from there to find the cause), but >whatever works for you. I agree I don't like it much either, but finding out who broke the code doesn't prevent the problem from happening again. My plan is to eventually produce a tool that will verify that this coding standard is met which allows us to recover the logical structure should this happen on an ongoing basis. >I haven't, but I use Subversion and haven't done team development in Python. >But I don't think any half-decent VCS should go around modifying code on its >own in *any* way, even if it's spaces. Although, now that I think about it, a >VCS might have an option of ignoring leading/trailing whitespace when doing >diffs, such an option could bite when merging Python code. Every CMS I've used modified code in some way. CVS, RCS, VSS, Perforce, and Subversion support the use of keywords. All of these tools, as well as Clearcase have merge tools to merge changes between branches in an automated way. At the core level, all these tools work by tearing apart the source and saving the diffs between revisions and then putting them back together again when a specific revision is requested. Sure you hope it's the same as it was in the beginning but there's always a chance for error. I don't know where the error was introduced in my case, It's either the PyWin settings or the Perforce merge tool. I have control over one but not the other. In either case, we need a system that can allow us to recover from this situation when it happens. Jeff From kent37 at tds.net Tue May 17 20:20:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 May 2005 14:20:13 -0400 Subject: [Tutor] I know you will hate this but... In-Reply-To: References: Message-ID: <428A35DD.2010906@tds.net> Smith, Jeff wrote: > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Andrei >>Weird. Looks to me like the wrong solution (it would IMO be better to find out >>who committed the broken code and work from there to find the cause), but >>whatever works for you. > > > I agree I don't like it much either, but finding out who broke the code > doesn't prevent the problem from happening again. My plan is to > eventually produce a tool that will verify that this coding standard is > met which allows us to recover the logical structure should this happen > on an ongoing basis. Take a look at the tabnanny module, it might help. Kent From albertito_g at hotmail.com Tue May 17 21:22:46 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 17 May 2005 19:22:46 +0000 Subject: [Tutor] Troubles with Python modules Message-ID: First of all, thanks for the corrections I'm assuming that Python 2.2 doesn't have datetime module then??????? Is there any way to install it??????? My version of Python 2.3.4 is an alternative installation so I know that when I type python with my root account its going to Python 2.2.2 (I'm using the root account) I changed the link though so when I say Python I enter Python 2.3.4 (works and checked) I'm sending the errors MySQLdb gives me when I try to install it. It's hola.txt file I'm doing python setup.py build and inside hola.txt you can see what it says I have installed Linux Red Hat with ALL packages Can I add datetime module to Python 2.2.2 ?????? If so how??????? Regards Alberto >From: Danny Yoo >To: Alberto Troiano >CC: Tutor >Subject: Re: [Tutor] Troubles with Python modules >Date: Tue, 17 May 2005 09:58:10 -0700 (PDT) > > > >On Tue, 17 May 2005, Alberto Troiano wrote: > > > I'm working on Python 2.2 over Linux REd Hat 9.0 and here is the code I > > have > >[code cut] > > > First I'd like to know if this code can be shorter or more efficient (if > > you have the time) > >Yes. But let's look at the errors first. > > > > > Second the error is the following: > > > > Traceback (most recent call last): > > File "/root/cotascamon.py", line 4, in ? > > import datetime > > ImportError: No module named datetime > > > > I think this module is in Python 2.3. What can I do?????? > >I'll assume for the moment that you are using your root account. Are you >sure that your root account is using Python 2.3? It may be possible that >the root account has a slightly more restricive PATH than normal user >accounts, and that you might be picking up '/usr/bin/python'. > > > > > Then I have installed Python 2.3.4 in the same Linux but I can't use it > > because it doesn't recognze the module MySQLdb > > > > Here is the error > > > > Traceback (most recent call last): > > File "/root/cotascamon.py", line 3, in ? > > import MySQLdb > > File "/usr/local/lib/python2.3/site-packages/MySQLdb/__init__.py", >line > > 27, in ? > > import _mysql > > ImportError: No module named _mysql > > >Different releases of Python will not automatically migrate the old >third-party modules. You'll need to reinstall MySQLdb for Python 2.3. >MySQLdb can be found here: > > http://sourceforge.net/projects/mysql-python > > > > >Let's look at some of the code. > > > > def consulta(self,query,args=None): > > try: > > self.cursor=self.db.cursor() > > self.sql=self.cursor.execute(query,args) > > except: > > self.cerrar() > > else: > > self.cerrar() > >The consulta() function tries to make sure that the cerrar() method is >called, no matter what. In this case, try/finally may do what you want: > >###### >try: > ... >finally: > self.cerrar() >###### > > > > > def getpath(): > > global ruta > > global user > > global cam > > try: > > i=0 > > for arg in sys.argv: > > if i==1: > > ruta+=arg > > elif i==2: > > user=arg > > elif i==3: > > cam=arg > > else: > > pass > > i+=1 > > except: > > f=open("cotascamonerrors.log","a+") > > f.write("ERROR ------ No se pudo encontrar el path "+ruta+". > > Contacte al administrador.") > > f.close() > >This looks like it's trying to do argument parsing, storing state in >global variables. You may want to see if you can avoid the globals, and >instead just return those three values back to the caller. > >My nervousness with the globals comes from the requirement that getpath() >has to assume that 'ruta' already has some sort of value already. So >there's already a dependency that can be more clearly documented by making >getpath() take in an initial base path argument: > >###### >def getpath(base_path): > ... > return (ruta, user, cam) >###### > > >But the block above also feels a little awkward because it assumes that >any exception that occurs has to be a path problem. That might not >necessarily be the case. I'd strongly recommend letting the exception >speak for itself. traceback.print_exc() can help: > > http://www.python.org/doc/lib/module-traceback.html > >###### >try: > .... >except: > f = open("cotascamonerrors.log", "a+") > traceback.print_exc(file=f) > f.close() >###### > > >Up to this point, though, things are pretty ok, with the nice helper >functions with clear roles. The large block near the bottom, though, >needs work. I'd recommend applying the same helper-function breakup to >make the code's intent clearer. > > >For example, here's SQL code that's repeated, a. It should be broken out: > > > try: > > os.system("cp webcam.jpg grabacion/cam"+grupo+".jpg") > > query="INSERT INTO imagen values >(%s,%s,%s,NOW(),NOW(),%s) > > where CodigoCamara=%s and Usuario=%s" > > grupo1=datetime.datetime.today().strftime("%Y%m%d%H%M") > > ruta1=ruta+"/grabacion/cam"+grupo+".jpg" > > args(user,cam,ruta1,grupo1) > > cur.consulta(query,args) > > except: > > pass > > >Again, try not to obscure exceptions. If something bad happens, you >really want the exception to tell you what happened: it is not fun to >debug something when the error message is insufficiently helpful. Change >the except block to log the error message. > > > >I do not understand what's happening with args() above: > > > args(user,cam,ruta1,grupo1) > >Do you mean: > > args = (user,cam,ruta1,grupo1) > >instead? > > >Hope this helps! > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: hola.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050517/dbac7393/hola-0001.txt From cpu.crazy at gmail.com Tue May 17 22:04:34 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Tue, 17 May 2005 14:04:34 -0600 Subject: [Tutor] YATENJoe In-Reply-To: References: Message-ID: <6.1.0.6.2.20050517135941.01ed5998@pop.gmail.com> >If you intend to make a text editor (something which allows the user to browse >through the text and manipulate it at will) using just raw_input and print, I >think you've set yourself an impossible task. For a console editor you should >probably look at curses (http://www.amk.ca/python/howto/curses/) - which don't >work on Windows, so you'll probably need this: >http://adamv.com/dev/python/curses/ (but according to the site it's >incomplete). Ok. >lines = [] >while True: > lines.append(raw_input('')) > >(But that offers no way to e.g. save and continue.) Ok again. >Text editors are IMO not applications suitable for learning vanilla Python, or >OOP for that matter. Text editors are used as example applications in the RAD >IDE world (VB, Delphi and such) because in those environments a text editor is >literally three clicks away (click on memo component, click on form, click on >run). Vanilla Python has no GUI, so no memo component - hence my >recommendation >for Tkinter or wxPython. PythonCard and Boa provide an experience somewhat >similar to commercial RAD IDE's if that's what you're looking for. I got my idea from looking at Nano, Vi, Joe and a few other UNIX text editors. Nano and Joe are console programs. That's why I thought I would try a console ed. in Python. >Having one function for each line is a bad idea whether you code it by hand or >automatically Ah. >A function implements certain behavior. Having the same behavior (raw_input) >implemented separately for each line is an extremely wasteful way of >programming. Is there a way of telling Python to make a new line after you press Enter (return)? >I would suggest that you learn a bit more about Python's facilities before >embarking on an ambitious project :) - you won't get very far without knowing >how to use lists and dictionaries. So that's one of the ways Dicts, and lists are used for? I never could fully grasp their use. Thanks, JQ ----------------------------------- Proud to be a true hacker (You may have a bad impression of the word "hacker". Do some homework, go to: http://catb.org/~esr/faqs/hacker-howto.html and become enlightened) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050517/7791455c/attachment.html From administrata at hotmail.com Tue May 17 22:12:18 2005 From: administrata at hotmail.com (. ,) Date: Tue, 17 May 2005 20:12:18 +0000 Subject: [Tutor] Problem with a while loop. Message-ID: Hi, I'm writing a program that is a program that flips a coin 100 times and then tells the number of heads and tails. ------------------------------------------------------------------------------------------------------------------------------------------- import random head = 0 tail = 0 coin = random.randrange(2) while (head + tail) < 100: if coin == 0: print "head" head += 1 elif coin == 1: print "tail" tail += 1 else: print "Error" raw_input("") ------------------------------------------------------------------------------------------------------------------------------------------- The problem is the program prints like.. tail tail tail . . . Help me! _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ From josh.goldie at mirant.com Tue May 17 22:22:58 2005 From: josh.goldie at mirant.com (Goldie, Josh) Date: Tue, 17 May 2005 16:22:58 -0400 Subject: [Tutor] Problem with a while loop. Message-ID: import random head = 0 tail = 0 while (head + tail) < 100: coin = random.randrange(2) <-- move this line inside the loop if coin == 0: -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of . , Sent: Tuesday, May 17, 2005 4:12 PM To: tutor at python.org Subject: [Tutor] Problem with a while loop. Hi, I'm writing a program that is a program that flips a coin 100 times and then tells the number of heads and tails. ------------------------------------------------------------------------ ------------------------------------------------------------------- import random head = 0 tail = 0 coin = random.randrange(2) while (head + tail) < 100: if coin == 0: print "head" head += 1 elif coin == 1: print "tail" tail += 1 else: print "Error" raw_input("") ------------------------------------------------------------------------ ------------------------------------------------------------------- The problem is the program prints like.. tail tail tail . . . Help me! _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue May 17 22:26:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 May 2005 13:26:09 -0700 (PDT) Subject: [Tutor] Troubles with Python modules In-Reply-To: Message-ID: On Tue, 17 May 2005, Alberto Troiano wrote: > I'm sending the errors MySQLdb gives me when I try to install it. It's > hola.txt file > I'm doing python setup.py build and inside hola.txt you can see what it says > I have installed Linux Red Hat with ALL packages Hi Alberto, [Side note: please avoid using the plaintive '??????' in your questions. it just reads in a way that feels like begging; you don't need to do that.] Red Hat's "Install All Packages" might not actually install all the packages you need --- I suspect that it might not include developer packages. According to the error messages: ###### gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.3 -c _mysql.c -o build/temp.linux-i686-2.3/_mysql.o -I'/usr/include/mysql' _mysql.c:41:19: mysql.h: No such file or directory ###### the necessary MySQL header files can't be found in '/usr/include/mysql'. You mentioned Red Hat 9, so you probably need to install something like the 'mysql-devel-3.23.54a-11.i386.rpm' file. Here is a link to a mirror with that file: ftp://ftp.linux.ncsu.edu/pub/redhat/linux/9/en/os/i386/RedHat/RPMS/mysql-devel-3.23.54a-11.i386.rpm > Can I add datetime module to Python 2.2.2? You may find: http://www.egenix.com/files/python/mxDateTime.html useful, although I can't confirm that it has the exact same API as the one in the Standard Library. From albertito_g at hotmail.com Tue May 17 22:41:53 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 17 May 2005 20:41:53 +0000 Subject: [Tutor] Troubles with Python modules In-Reply-To: Message-ID: Hey Danny Sorry about the question marks (MSN addiction :)) Didn't work and as I suspected it was already installed. What else can I do? Is there another built-in module that resemble datetime module? I had to use Python 2.2.2 because of MySQLdb but now I can't use datetime. As you see I'm in the middle of the wall and the sword thanks for any help you can give me Best Regards Alberto >From: Danny Yoo >To: Alberto Troiano >CC: Tutor >Subject: Re: [Tutor] Troubles with Python modules >Date: Tue, 17 May 2005 13:26:09 -0700 (PDT) > > >On Tue, 17 May 2005, Alberto Troiano wrote: > > > > I'm sending the errors MySQLdb gives me when I try to install it. It's > > hola.txt file > > I'm doing python setup.py build and inside hola.txt you can see what it >says > > I have installed Linux Red Hat with ALL packages > >Hi Alberto, > > >[Side note: please avoid using the plaintive '??????' in your questions. >it just reads in a way that feels like begging; you don't need to do >that.] > >Red Hat's "Install All Packages" might not actually install all the >packages you need --- I suspect that it might not include developer >packages. According to the error messages: > >###### >gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall >-Wstrict-prototypes >-fPIC -I/usr/local/include/python2.3 -c _mysql.c -o >build/temp.linux-i686-2.3/_mysql.o -I'/usr/include/mysql' >_mysql.c:41:19: mysql.h: No such file or directory >###### > >the necessary MySQL header files can't be found in '/usr/include/mysql'. >You mentioned Red Hat 9, so you probably need to install something like >the 'mysql-devel-3.23.54a-11.i386.rpm' file. Here is a link to a mirror >with that file: > >ftp://ftp.linux.ncsu.edu/pub/redhat/linux/9/en/os/i386/RedHat/RPMS/mysql-devel-3.23.54a-11.i386.rpm > > > > > Can I add datetime module to Python 2.2.2? > >You may find: > > http://www.egenix.com/files/python/mxDateTime.html > >useful, although I can't confirm that it has the exact same API as the one >in the Standard Library. > Gaucho From jsmith at medplus.com Tue May 17 23:00:33 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 17 May 2005 17:00:33 -0400 Subject: [Tutor] Perl equivalent of $#var Message-ID: Is there a more Pythonic way to get the Perl equivalent of $#var other than len(var) - 1 Thanks, Jeff From maxnoel_fr at yahoo.fr Tue May 17 23:28:54 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 17 May 2005 22:28:54 +0100 Subject: [Tutor] Perl equivalent of $#var In-Reply-To: References: Message-ID: <15AC19B5-383A-4D55-AE66-AC7380EA77C3@yahoo.fr> On May 17, 2005, at 22:00, Smith, Jeff wrote: > Is there a more Pythonic way to get the Perl equivalent of > $#var > other than > len(var) - 1 AFAIK, len(var) - 1 is the only way. Note, however, that the last element of a list (or of any ordered sequence) can be obtained with the shortcut var[-1]. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From albertito_g at hotmail.com Tue May 17 23:50:07 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 17 May 2005 21:50:07 +0000 Subject: [Tutor] Menu help Message-ID: Hey I know I posted so many things but it's because I have so much to do I used to program in VB 6 but I want to learn a programming so I can I master it. I want to make a menu (Tkinter) like the one of the image attached to this email I can do the menu and submenu but I can't do the third submenu Help me! Regards Alberto -------------- next part -------------- A non-text attachment was scrubbed... Name: Menu_example.JPG Type: image/pjpeg Size: 27707 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050517/6ff6e7f2/Menu_example-0001.bin From dyoo at hkn.eecs.berkeley.edu Tue May 17 23:56:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 May 2005 14:56:52 -0700 (PDT) Subject: [Tutor] Troubles with Python modules In-Reply-To: Message-ID: On Tue, 17 May 2005, Alberto Troiano wrote: > Sorry about the question marks (MSN addiction :)) > > Didn't work and as I suspected it was already installed. Hi Alberto, I'm still thinking that the MySQL development packages are either damaged or mixed up, since the error message says that it can't find MySQL's headers. Let's double check something. Can you do the following from your Unix shell? ###### $ rpm -qil mysql-devel $ ls -l /usr/include/mysql ###### Show us what comes out. From dyoo at hkn.eecs.berkeley.edu Wed May 18 00:00:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 17 May 2005 15:00:16 -0700 (PDT) Subject: [Tutor] Perl equivalent of $#var In-Reply-To: Message-ID: On Tue, 17 May 2005, Smith, Jeff wrote: > Is there a more Pythonic way to get the Perl equivalent of > $#var > other than > len(var) - 1 Hi Jeff, Just out of curiosity, where do you use Perl's $#var? Can you show us the context of its use? If we see context, it might help us find a Python idiom that fits the usage. Best of wishes! From albertito_g at hotmail.com Wed May 18 00:12:01 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 17 May 2005 22:12:01 +0000 Subject: [Tutor] Troubles with Python modules Message-ID: Here you go Each filenaem corresponds to the command Thanks in advanced Alberto >From: Danny Yoo >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Troubles with Python modules >Date: Tue, 17 May 2005 14:56:52 -0700 (PDT) > > > >On Tue, 17 May 2005, Alberto Troiano wrote: > > > Sorry about the question marks (MSN addiction :)) > > > > Didn't work and as I suspected it was already installed. > >Hi Alberto, > >I'm still thinking that the MySQL development packages are either damaged >or mixed up, since the error message says that it can't find MySQL's >headers. > >Let's double check something. Can you do the following from your Unix >shell? > >###### >$ rpm -qil mysql-devel >$ ls -l /usr/include/mysql >###### > >Show us what comes out. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: rpm.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050517/02e8e1cb/rpm.txt -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ls.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050517/02e8e1cb/ls.txt From jfouhy at paradise.net.nz Wed May 18 00:40:12 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 18 May 2005 10:40:12 +1200 (NZST) Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: References: Message-ID: <1116369611.428a72cc0445a@www.paradise.net.nz> Quoting Terry Carroll : > I've recently started using the construct > > if __name__ == "__main__": > main() > > And found I can't do the -i thing effectively any more. What's a good > equivalent approach? If main is a class, you could change to 'm = main()'; that would at least give you access to the class attributes. Another possibility is to look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 -- John. From jfouhy at paradise.net.nz Wed May 18 00:52:54 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 18 May 2005 10:52:54 +1200 (NZST) Subject: [Tutor] Tutor Digest, Vol 15, Issue 40 In-Reply-To: <4289DE63.7010807@tds.net> References: <20050517104914.EA48A1E4006@bag.python.org> <4289DE63.7010807@tds.net> Message-ID: <1116370374.428a75c6aad76@www.paradise.net.nz> Quoting Kent Johnson : > J. Gabriel Schenz wrote: > > Now, I am new to Python as well, but it seems like apply might not be > > completely superfluous. I was thinking that if one were using a functional > > programming style, and had to apply a function determined at runtime to an > > argument, then one could use this apply to do so. > apply() is superfluous. apply(function, args[, keywords]) is exactly > equivalent to function(*args, [**keywords]). Ooh. Functional programming is fun! >>> multers = [i.__mul__ for i in range(10)] >>> mulTable = [[f(i) for i in range(10)] for f in multers] >>> import pprint >>> pprint.pprint(mulTable) [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [0, 3, 6, 9, 12, 15, 18, 21, 24, 27], [0, 4, 8, 12, 16, 20, 24, 28, 32, 36], [0, 5, 10, 15, 20, 25, 30, 35, 40, 45], [0, 6, 12, 18, 24, 30, 36, 42, 48, 54], [0, 7, 14, 21, 28, 35, 42, 49, 56, 63], [0, 8, 16, 24, 32, 40, 48, 56, 64, 72], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81]] -- John. From denise.hartley at gmail.com Wed May 18 01:24:39 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 17 May 2005 16:24:39 -0700 Subject: [Tutor] hettingertools? Message-ID: <8daabe56050517162429807770@mail.gmail.com> This was a hint from a python challenge, but I can't find anything about it online: Anyone know? Thanks :) ~Denise From carroll at tjc.com Wed May 18 01:32:49 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 May 2005 16:32:49 -0700 (PDT) Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: <1116369611.428a72cc0445a@www.paradise.net.nz> Message-ID: On Wed, 18 May 2005 jfouhy at paradise.net.nz wrote: > If main is a class, you could change to 'm = main()'; that would at > least give you access to the class attributes. Interesting approach; I'm refering to where main() is a method, the usual python idiom. From carroll at tjc.com Wed May 18 01:35:42 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 May 2005 16:35:42 -0700 (PDT) Subject: [Tutor] hettingertools? In-Reply-To: <8daabe56050517162429807770@mail.gmail.com> Message-ID: On Tue, 17 May 2005, D. Hartley wrote: > This was a hint from a python challenge, but I can't find anything > about it online: Anyone know? Raymond Hettinger is a frequent contributor to Python. I don't know if that is part of it. From carroll at tjc.com Wed May 18 02:01:50 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 17 May 2005 17:01:50 -0700 (PDT) Subject: [Tutor] hettingertools? In-Reply-To: Message-ID: On Tue, 17 May 2005, Terry Carroll wrote: > On Tue, 17 May 2005, D. Hartley wrote: > > > This was a hint from a python challenge, but I can't find anything > > about it online: Anyone know? > > Raymond Hettinger is a frequent contributor to Python. I don't know if > that is part of it. And actually, I think he was behind itertools, come to think of it. You're obviously further along the challenges than I am. I'm on #9 now. My defense is that I'm not a programmer by occupation, so I do these in my Copious Spare Time in the evenings. From jfouhy at paradise.net.nz Wed May 18 02:21:07 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 18 May 2005 12:21:07 +1200 (NZST) Subject: [Tutor] hettingertools? In-Reply-To: References: Message-ID: <1116375667.428a8a73b7d95@www.paradise.net.nz> Quoting Terry Carroll : > On Tue, 17 May 2005, D. Hartley wrote: > > This was a hint from a python challenge, but I can't find anything > > about it online: Anyone know? > Raymond Hettinger is a frequent contributor to Python. I don't know if > that is part of it. If I had to guess, I would guess: itertools. (http://python.org/doc/2.3.5/whatsnew/node18.html) -- John. From kent37 at tds.net Wed May 18 05:01:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 May 2005 23:01:39 -0400 Subject: [Tutor] Tutor Digest, Vol 15, Issue 40 In-Reply-To: <1116370374.428a75c6aad76@www.paradise.net.nz> References: <20050517104914.EA48A1E4006@bag.python.org> <4289DE63.7010807@tds.net> <1116370374.428a75c6aad76@www.paradise.net.nz> Message-ID: <428AB013.5020305@tds.net> jfouhy at paradise.net.nz wrote: > Quoting Kent Johnson : > > >>J. Gabriel Schenz wrote: >> >>>Now, I am new to Python as well, but it seems like apply might not be >>>completely superfluous. I was thinking that if one were using a functional >>>programming style, and had to apply a function determined at runtime to an >>>argument, then one could use this apply to do so. >> >>apply() is superfluous. apply(function, args[, keywords]) is exactly >>equivalent to function(*args, [**keywords]). > > > Ooh. Functional programming is fun! > > >>>>multers = [i.__mul__ for i in range(10)] >>>>mulTable = [[f(i) for i in range(10)] for f in multers] or use mulTable = [[i*j for i in range(10)] for j in range(10)] if you prefer conciseness and readability :-) Kent From kent37 at tds.net Wed May 18 05:11:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 May 2005 23:11:21 -0400 Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: References: Message-ID: <428AB259.4060601@tds.net> Terry Carroll wrote: > I've often found it convenient to run a Python program I'm developing with > the -i flag. I find it convenient to use as a post-mortem as it hits bugs, > or to explore data structures. > > I've recently started using the construct > > if __name__ == "__main__": > main() I think this approach to debugging won't scale well and you are just seeing the tip of the iceberg. As your programs get more complex you will encapsulate more and more functionality into functions and classes and the variables they use will not in general be visible from the global scope. I often find that the information in the traceback and exception are enough to figure out the problem; if not, a few print statements can help. You will get better at this with experience. An alternative is to use a debugger such as pdb or the one built into IDLE. This recipe looks interesting - it dumps the values of the variables at the time of an uncaught exception. I haven't tried it but it looks like it could be useful when combined with the excepthook recipe John cited: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 Kent From erastley at charter.net Wed May 18 05:18:08 2005 From: erastley at charter.net (EUGENE ASTLEY) Date: Tue, 17 May 2005 20:18:08 -0700 Subject: [Tutor] game instructions Message-ID: <000001c55b58$3758e6f0$6501a8c0@D3K8PT61> Following the Tutorial by Michael Dawson and the previous web help from Liam Clark, I have a basic Othello Game up and running quite well. I now want to start the game with a set of instructions that stays on the screen until the user is ready to proceed. Since you are only allowed one screen, I am now confused as to how I can accomplish this. My program starts by defining global constants SCREEN_WIDTH = 1024 and SCREEN_HEIGHT=768 and THE_SCREEN = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) Then after writing all the classes, sprites etc I define main() as follows: def main(): my_screen = THE_SCREEN board_image=games.load_image("OthelloImage.jpg") my_screen.set_background(board_image) # then I create some board pieces etc and end with my_screen.mainloop() main() Thank you for any help. Gene -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050517/57f54ba0/attachment.htm From sadique_hannure at yahoo.com Wed May 18 06:18:09 2005 From: sadique_hannure at yahoo.com (Mahmad Sadique Hannure) Date: Tue, 17 May 2005 21:18:09 -0700 (PDT) Subject: [Tutor] help me on python + snack Message-ID: <20050518041809.26841.qmail@web90205.mail.scd.yahoo.com> Hello friends, I m currently working on sound stuff. I have installed all stuff related to Snack. My code for playing mp3 song is like this #!/usr/bin/python2.3 from Tkinter import * import tkSnack def main(): root = Tk() tkSnack.initializeSnack(root) mysound = tkSnack.Sound('xyz.mp3') #mysound.read() mysound.play() if __name__=='__main__': main() I works fine without any error but can't get any sound. So friend help me, I don't know whats wroung with my code. Help!!!!!!!!!!!!!!!!! Thank You. Regards, Mahmad Sadique. __________________________________ Do you Yahoo!? Make Yahoo! your home page http://www.yahoo.com/r/hs From project5 at redrival.net Wed May 18 08:45:22 2005 From: project5 at redrival.net (Andrei) Date: Wed, 18 May 2005 06:45:22 +0000 (UTC) Subject: [Tutor] YATENJoe References: <6.1.0.6.2.20050517135941.01ed5998@pop.gmail.com> Message-ID: Joseph Quigley gmail.com> writes: > Is there a way of telling Python to make a new line after you press Enter (return)? Return automatically ends the current input line (and therefore starts a new one) when you use raw_input. >> I would suggest that you learn a bit more about Python's facilities before >> embarking on an ambitious project :) - you won't get very far without knowing >> how to use lists and dictionaries. > So that's one of the ways Dicts, and lists are used for? I never could fully grasp their use. Perhaps you should have a look at "How to think like a computer scientist in Python" (http://www.ibiblio.org/obp/thinkCSpy/). Chapters 8 and 10 discuss Lists and Dictionaries http://www.ibiblio.org/obp/thinkCSpy/chap08.htm http://www.ibiblio.org/obp/thinkCSpy/chap10.htm , but I'd recommend you read all of it (or another Python tutorial). Yours, Andrei From project5 at redrival.net Wed May 18 09:04:01 2005 From: project5 at redrival.net (Andrei) Date: Wed, 18 May 2005 07:04:01 +0000 (UTC) Subject: [Tutor] I know you will hate this but... References: Message-ID: Smith, Jeff medplus.com> writes: > But there is no way to enforce standard settings. When new versions are > installed or someone just makes a mistake the settings might change and > you won't know until it's too late...possibly weeks later. Programs when updated tend to keep their settings, as they're usually written either in the registry or in the home folder. Perhaps PythonWin is different? I think of it as basic programmer's responsibility, but it's also possible to write an application to check the indentation settings and modify them, while leaving the rest alone, regardless of where they're stored. > >But I don't think any half-decent VCS should go around modifying code > on its > >own in *any* way, even if it's spaces. Although, now that I think about > Every CMS I've used modified code in some way. CVS, RCS, VSS, Perforce, > and Subversion support the use of keywords. All of these tools, as well Yes, but by using keywords (and at least for SVN telling it explicitly not to ignore them) you instruct it to modify the code, it doesn't do so on its own. > back together again when a specific revision is requested. Sure you > hope it's the same as it was in the beginning but there's always a > chance for error. Yep. But the fact that only the indentation changed, sounds fishy. I'd rather expect editor settings to be at fault than the VCS. If you do find out the cause, don't hesitate to drop another message to the list, I'm curious :). Yours, Andrei From klappnase at freenet.de Wed May 18 11:20:45 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 18 May 2005 11:20:45 +0200 Subject: [Tutor] help me on python + snack In-Reply-To: <20050518041809.26841.qmail@web90205.mail.scd.yahoo.com> References: <20050518041809.26841.qmail@web90205.mail.scd.yahoo.com> Message-ID: <20050518112045.3a3bc427.klappnase@freenet.de> On Tue, 17 May 2005 21:18:09 -0700 (PDT) Mahmad Sadique Hannure wrote: Hi Mahmad, > Hello friends, > I m currently working on sound stuff. I have installed > all stuff related to Snack. My code for playing mp3 > song is like this > > #!/usr/bin/python2.3 > > from Tkinter import * > import tkSnack > > def main(): > root = Tk() > tkSnack.initializeSnack(root) > mysound = tkSnack.Sound('xyz.mp3') I believe the last line is the problematic one. Try to change it into: mysound = tkSnack.Sound(file='xyz.mp3') > #mysound.read() > mysound.play() > if __name__=='__main__': > main() > I works fine without any error but can't get any > sound. > > So friend help me, I don't know whats wroung with my > code. > I hope this helps Michael From python at kapitalisten.no Wed May 18 14:46:43 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Wed, 18 May 2005 14:46:43 +0200 (CEST) Subject: [Tutor] Password Message-ID: <22427.193.71.38.142.1116420403.squirrel@mail.sporck.net> Hello. I am trying to make a loginbox for a program, and need to make a somewhat safe passwordroutine. Will this work? import md5 h = md5.new() h.update(password) h.hexdigest() The user enters a password first. These lines will create a string: '12c0faae657b3d068c0f19b71f5b43bc' This string will be stored in the file settings.txt Then, I will do the same where the password is entered in a GUI-box. Then I will do the same, and compare. If file.readline == h.hexdigest() the user will be accepted. Is this a good way to do this? And a second question. I have made a tkinter box with two entry-fields. Is there a way to make the letters in the second entrybox appear as **** as the user types his password? Is there some built in function in the Tkinter Entry that does this? Thanks in advance -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From jsmith at medplus.com Wed May 18 14:47:32 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 18 May 2005 08:47:32 -0400 Subject: [Tutor] Perl equivalent of $#var Message-ID: The most common usage is to get the last member of an array as with myarray[$#myarray] and I realize in Python, this can be done with myarray[-1] My current dilemma is that I've got a program that takes one argument and needs to be run multiple times with this argument being validated based on the previous one. So proper usage might be myprog red myprog blue myprog green where it would be wrong to do myprog red myprog green I have a list which gives the proper order colors = ['red', 'blue', 'green'] There are places where I need to know specifically if I am on the first or last sequence of runs so early on I get my current index: now = colors.index(sys.argv[1]) and then later I can compare if now == 0 or if now == len(colors) - 1 which is distinctly ugly and I would prefer if now == $#colors Keep in mind this is not an exact statement of the problem but I believe it captures the full context. Jeff -----Original Message----- From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] Sent: Tuesday, May 17, 2005 6:00 PM To: Smith, Jeff Cc: tutor at python.org Subject: Re: [Tutor] Perl equivalent of $#var On Tue, 17 May 2005, Smith, Jeff wrote: > Is there a more Pythonic way to get the Perl equivalent of > $#var > other than > len(var) - 1 Hi Jeff, Just out of curiosity, where do you use Perl's $#var? Can you show us the context of its use? If we see context, it might help us find a Python idiom that fits the usage. Best of wishes! From albertito_g at hotmail.com Wed May 18 14:59:18 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 18 May 2005 12:59:18 +0000 Subject: [Tutor] Password In-Reply-To: <22427.193.71.38.142.1116420403.squirrel@mail.sporck.net> Message-ID: Hey I think that is a good built-in way to protect your passwords, but then I don't know if a text file is the best way to store them. I think (in my opinion) I consider using a database to store tha info. There is a way to make the entry appears as *. txtPass=Entry(root,width=25,show="*") The show attribute accomplish what you want Regards Alberto >From: ?yvind >Reply-To: python at kapitalisten.no >To: tutor at python.org >Subject: [Tutor] Password >Date: Wed, 18 May 2005 14:46:43 +0200 (CEST) > >Hello. > >I am trying to make a loginbox for a program, and need to make a somewhat >safe passwordroutine. > >Will this work? > >import md5 >h = md5.new() >h.update(password) >h.hexdigest() > >The user enters a password first. These lines will create a string: >'12c0faae657b3d068c0f19b71f5b43bc' This string will be stored in the file >settings.txt > >Then, I will do the same where the password is entered in a GUI-box. Then >I will do the same, and compare. If file.readline == h.hexdigest() the >user will be accepted. Is this a good way to do this? > >And a second question. I have made a tkinter box with two entry-fields. Is >there a way to make the letters in the second entrybox appear as **** as >the user types his password? Is there some built in function in the >Tkinter Entry that does this? > >Thanks in advance > >-- >This email has been scanned for viruses & spam by Decna as - www.decna.no >Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From pieter.lust at katho.be Wed May 18 15:04:10 2005 From: pieter.lust at katho.be (Pieter Lust) Date: Wed, 18 May 2005 15:04:10 +0200 Subject: [Tutor] How to convert hex representation of char? (Challenge part 8) Message-ID: <428B3D4A.6040004@katho.be> Hello, I'm stuck on part 8 of the Python Challenge. To solve it, I want to feed 2 pieces of data to a Python module. I get those pieces by reading the webpage source, and then splitting it on "'", like this: import urllib pagesource = urllib.urlopen(site_address).read() parts = pagesource.split("'") onepart = parts[1] anotherpart = parts[3] onepart and anotherpart contain many hex representations of nonprintable characters, like '\x14'. But I can't manage to convert those to the actual nonprintable characters. Any hints on how to do this? Thanks, Pieter Lust From premshree.pillai at gmail.com Wed May 18 15:06:40 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 18 May 2005 18:36:40 +0530 Subject: [Tutor] Perl equivalent of $#var In-Reply-To: References: Message-ID: On 5/18/05, Smith, Jeff wrote: > Is there a more Pythonic way to get the Perl equivalent of > $#var > other than > len(var) - 1 By Pythonic, if you mean OO, you can do this: ['foo', 2, 'baz'].__len__() -- Premshree Pillai http://www.livejournal.com/users/premshree/ From cpu.crazy at gmail.com Wed May 18 15:19:44 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 18 May 2005 07:19:44 -0600 Subject: [Tutor] Finding word in file Message-ID: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> I'm making a program that opens a file and tries to find the word you specify. I can't get it to find the word! I also would like to know how I can get it to print 2 lines above and 2 lines below the line with the word specified. One more thing, the try: IOError won't work... I type the name of a nonexistent file and the except won't kick in and print my error message! Not to mention the program is killed. How can i fix that? Thanks, JQ Full Code: while True: file_name = raw_input("Enter the full file name: ") f = file(file_name, 'r') try: IOError except: print "File not found. Directories are not supported" while True: line = f.readline() if len(line) == 0: break find_word = raw_input("What word do you want to find (quit() to quit)?\n> ") if find_word in file_name: print f.readline(find_word) elif find_word == "quit()": break print line, f.close() close = raw_input("\n\nQuit program? (Y/N)> ") if ((close == "Y") or ("y" == close)): break else: print From 3dbernard at gmail.com Wed May 18 16:33:49 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 18 May 2005 10:33:49 -0400 Subject: [Tutor] Finding word in file In-Reply-To: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> References: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> Message-ID: <61d0e2b405051807337ad3499@mail.gmail.com> Hi Joseph, To answer your last question first, you should use the os.path.exsits() method to see if the path is valid: http://www.python.org/doc/2.4.1/lib/module-os.path.html As for finding a word in a text, I would suggest to write a basic text parser that would work on small files. def parseText(): # oFile: text file to test # myWord: word we are looking for # Get all lines into list aLines = oFile.readlines() # Perform list comprehension on lines to test if the word is found for sLine in aLines: # Parse the line (remove spaces), returns list aLine = sLine.split() # Iterate words and test to see if they match our word for sWord in aLines: # if it matches, append it to our list if sWord == myWord: aWords.append( sWord ) # Create empty list to store all instances of the word that we may find aWords = [] # Prompt user to know what word to search myWord = str( raw_input( 'what word to searh:' ) ) Note that I'm still new to Python, there might be more efficient ways to do that. For larger text files (in the order of thousands of lines), you may not use readlines() to build a list of the lines and insteand read one line after another with readline() or xreadline() and append to the list as you find the word. Cheers Bernard On 5/18/05, Joseph Quigley wrote: > I'm making a program that opens a file and tries to find the word you specify. > I can't get it to find the word! I also would like to know how I can get > it to print 2 lines above and 2 lines below the line with the word specified. > One more thing, the try: IOError won't work... I type the name of a > nonexistent file and the except won't kick in and print my error message! > Not to mention the program is killed. How can i fix that? > Thanks, > JQ > > Full Code: > > while True: > file_name = raw_input("Enter the full file name: ") > f = file(file_name, 'r') > try: > IOError > except: > print "File not found. Directories are not supported" > > while True: > line = f.readline() > if len(line) == 0: > break > find_word = raw_input("What word do you want to find (quit() to > quit)?\n> ") > if find_word in file_name: > print f.readline(find_word) > elif find_word == "quit()": > break > print line, > f.close() > > close = raw_input("\n\nQuit program? (Y/N)> ") > if ((close == "Y") or ("y" == close)): > break > else: > print > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From 3dbernard at gmail.com Wed May 18 16:35:27 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 18 May 2005 10:35:27 -0400 Subject: [Tutor] Finding word in file In-Reply-To: <61d0e2b405051807337ad3499@mail.gmail.com> References: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> <61d0e2b405051807337ad3499@mail.gmail.com> Message-ID: <61d0e2b405051807351b55f9a2@mail.gmail.com> Ooops, a part of my code was missing, sorry about that. Here is it again, complete. def parseText(): # oFile: text file to test # myWord: word we are looking for # Get all lines into list aLines = oFile.readlines() # Perform list comprehension on lines to test if the word is found for sLine in aLines: # Parse the line (remove spaces), returns list aLine = sLine.split() # Iterate words and test to see if they match our word for sWord in aLines: # if it matches, append it to our list if sWord == myWord: aWords.append( sWord ) # Create empty list to store all instances of the word that we may find aWords = [] # Prompt user to know what word to search myWord = str( raw_input( 'what word to searh:' ) ) # Call function parseText() # Check if list has at least one element if len( aWords ) < 1: print 'Word not found in file' else: print str( len( aWords ) ) + ' instances of our word found in file' Sorry again Bernard On 5/18/05, Bernard Lebel <3dbernard at gmail.com> wrote: > Hi Joseph, > > To answer your last question first, you should use the > os.path.exsits() method to see if the path is valid: > http://www.python.org/doc/2.4.1/lib/module-os.path.html > > As for finding a word in a text, I would suggest to write a basic text > parser that would work on small files. > > def parseText(): > > # oFile: text file to test > # myWord: word we are looking for > > # Get all lines into list > aLines = oFile.readlines() > > # Perform list comprehension on lines to test if the word is found > for sLine in aLines: > > # Parse the line (remove spaces), returns list > aLine = sLine.split() > > # Iterate words and test to see if they match our word > for sWord in aLines: > # if it matches, append it to our list > if sWord == myWord: aWords.append( sWord ) > > # Create empty list to store all instances of the word that we may find > aWords = [] > > # Prompt user to know what word to search > myWord = str( raw_input( 'what word to searh:' ) ) > > Note that I'm still new to Python, there might be more efficient ways > to do that. > > For larger text files (in the order of thousands of lines), you may > not use readlines() to build a list of the lines and insteand read one > line after another with readline() or xreadline() and append to the > list as you find the word. > > Cheers > Bernard > > > On 5/18/05, Joseph Quigley wrote: > > I'm making a program that opens a file and tries to find the word you specify. > > I can't get it to find the word! I also would like to know how I can get > > it to print 2 lines above and 2 lines below the line with the word specified. > > One more thing, the try: IOError won't work... I type the name of a > > nonexistent file and the except won't kick in and print my error message! > > Not to mention the program is killed. How can i fix that? > > Thanks, > > JQ > > > > Full Code: > > > > while True: > > file_name = raw_input("Enter the full file name: ") > > f = file(file_name, 'r') > > try: > > IOError > > except: > > print "File not found. Directories are not supported" > > > > while True: > > line = f.readline() > > if len(line) == 0: > > break > > find_word = raw_input("What word do you want to find (quit() to > > quit)?\n> ") > > if find_word in file_name: > > print f.readline(find_word) > > elif find_word == "quit()": > > break > > print line, > > f.close() > > > > close = raw_input("\n\nQuit program? (Y/N)> ") > > if ((close == "Y") or ("y" == close)): > > break > > else: > > print > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From project5 at redrival.net Wed May 18 18:30:36 2005 From: project5 at redrival.net (Andrei) Date: Wed, 18 May 2005 18:30:36 +0200 Subject: [Tutor] Password References: <22427.193.71.38.142.1116420403.squirrel@mail.sporck.net> Message-ID: <1xuojv92ic7fo$.q0hg6kaufc80$.dlg@40tude.net> ?yvind wrote on Wed, 18 May 2005 14:46:43 +0200 (CEST): > The user enters a password first. These lines will create a string: > '12c0faae657b3d068c0f19b71f5b43bc' This string will be stored in the file > settings.txt That's a very good way of preventing the user's password from being reconstructed. If that's all the safety you're looking for, then it's OK. If the password is intended to safeguard some really important data, it's not safe to store the password or the hash - you'll have to encrypt the data in such a way that it can't be decrypted without the password, even if the source code is available. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From carroll at tjc.com Wed May 18 19:07:13 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed, 18 May 2005 10:07:13 -0700 (PDT) Subject: [Tutor] How to convert hex representation of char? (Challenge part 8) In-Reply-To: <428B3D4A.6040004@katho.be> Message-ID: On Wed, 18 May 2005, Pieter Lust wrote: > onepart and anotherpart contain many hex representations of nonprintable > characters, like '\x14'. But I can't manage to convert those to the > actual nonprintable characters. Any hints on how to do this? The string including the \x14 escape should be usable as is. From bwinton at latte.ca Wed May 18 19:47:44 2005 From: bwinton at latte.ca (Blake Winton) Date: Wed, 18 May 2005 13:47:44 -0400 Subject: [Tutor] Perl equivalent of $#var In-Reply-To: Message-ID: <20050518173526.25C6450@short.latte.ca> > My current dilemma is that I've got a program that takes one argument > and needs to be run multiple times with this argument being validated > based on the previous one. So proper usage might be > myprog red > myprog blue > myprog green > where it would be wrong to do > myprog red > myprog green > I have a list which gives the proper order > colors = ['red', 'blue', 'green'] I've got to say, that's an odd setup you've got there. If it really needs to run in the proper order, why not just take no arguments, and put the whole program in a for color in colors: loop? Or take no arguments, store the last run in a file, and > if now == len(colors) - 1 > which is distinctly ugly and I would prefer > if now == $#colors Perhaps it would look nicer to you if you had: colors = ['red', 'blue', 'green'] LAST_COLOR = len(colors) - 1 [...] if now == LAST_COLOR: # Do something. Later, Blake. From alan.gauld at freenet.co.uk Wed May 18 20:46:15 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 18 May 2005 19:46:15 +0100 Subject: [Tutor] How to convert hex representation of char? (Challenge part 8) References: <428B3D4A.6040004@katho.be> Message-ID: <017201c55bd9$defd4be0$358c8651@xp> > onepart and anotherpart contain many hex representations of nonprintable > characters, like '\x14'. But I can't manage to convert those to the > actual nonprintable characters. Any hints on how to do this? '\x14' is the actual non printable charactewrs. If it were printable you would see its printed representation, because it isn't Pyhon showsw you the hex code as an escaped character but it is the character. You can get the numeric value using ord just as you would any other character: >>> print ord('\x14') 20 >>> print ord{'Q'} 81 so '\x14' is the character, it should just work... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauldHTH, From alan.gauld at freenet.co.uk Wed May 18 20:51:31 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 18 May 2005 19:51:31 +0100 Subject: [Tutor] Finding word in file References: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> Message-ID: <017901c55bda$9b5f4f40$358c8651@xp> > I'm making a program that opens a file and tries to find the word you specify. > I can't get it to find the word! What are you trying? You could simply read through the file line by line using the string search methods. Store the previous 2 lines then when found print the previous two lines, the current line and then read and print the next two lines. There are more sophisticated methods but that should do... > One more thing, the try: IOError won't work... I type the name of a > nonexistent file and the except won't kick in and print my error message! > while True: > file_name = raw_input("Enter the full file name: ") > f = file(file_name, 'r') > try: > IOError > except: > print "File not found. Directories are not supported" You need to catch the error not state it. try: f = file(....) except IOError: print 'file not....' If you do want to force an error to be raised you must use raise: try: raise IOError except IOError: print 'sure enough...' See my tutorial topic on errors for more info. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From michael.hall at critterpixstudios.com Wed May 18 21:15:12 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed, 18 May 2005 12:15:12 -0700 Subject: [Tutor] Python debugger under Tiger? Message-ID: Does anyone know of a Python debugger that will run under OSX 10.4? The Eric debugger was looked at, but it's highly unstable under Tiger. Thanks. -MH -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050518/f84ed492/attachment.htm From albertito_g at hotmail.com Thu May 19 00:02:16 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 18 May 2005 22:02:16 +0000 Subject: [Tutor] Troubles with Python modules Message-ID: I'm sending the commands you asked I'm still can't make it work and I don't know what else should I do I'll aprecciate any help Best Regards Alberto >From: Danny Yoo >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Troubles with Python modules >Date: Tue, 17 May 2005 14:56:52 -0700 (PDT) > > > >On Tue, 17 May 2005, Alberto Troiano wrote: > > > Sorry about the question marks (MSN addiction :)) > > > > Didn't work and as I suspected it was already installed. > >Hi Alberto, > >I'm still thinking that the MySQL development packages are either damaged >or mixed up, since the error message says that it can't find MySQL's >headers. > >Let's double check something. Can you do the following from your Unix >shell? > >###### >$ rpm -qil mysql-devel >$ ls -l /usr/include/mysql >###### > >Show us what comes out. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ls.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050518/e42ccb41/ls.txt -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: rpm.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050518/e42ccb41/rpm.txt From jfouhy at paradise.net.nz Thu May 19 00:10:57 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 19 May 2005 10:10:57 +1200 (NZST) Subject: [Tutor] Python debugger under Tiger? In-Reply-To: References: Message-ID: <1116454257.428bbd71486f7@www.paradise.net.nz> Quoting Mike Hall : > Does anyone know of a Python debugger that will run under OSX 10.4? > The Eric debugger was looked at, but it's highly unstable under > Tiger. Thanks. pdb should work :-) -- John. From missive at hotmail.com Thu May 19 00:27:59 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 19 May 2005 02:57:59 +0430 Subject: [Tutor] I know you will hate this but... Message-ID: >>Inconsistent indentation styles are very >>annoying in >>other languages, but a fatal problem in Python. > >But there is no way to enforce standard settings. When new versions are >installed or someone just makes a mistake the settings might change and >you won't know until it's too late...possibly weeks later. > I don't see how. If you diff between two versions where the indentation has been modified, you should get a massive diff which shows all of the changed lines. If you are using some tool that is hiding whitespace changes somehow, that is clearly not the tool to be using with python. I have used both cvs and svn with python and have never seen a problem like what you describe. That said, I have had problems importing other people's code in to my work environment -- usually when the code uses tabs instead of spaces, or has mixed tabs and spaces. I have my editor set up to use only spaces, covert tabs to spaces, and use 4 spaces per indent level. If I try to load code that used another indent style it can make a complete mess. My opinion is that tabs for indenting should just go away, and the 4-space indent should be mandatory. _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From michael.hall at critterpixstudios.com Thu May 19 00:54:18 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed, 18 May 2005 15:54:18 -0700 Subject: [Tutor] Python debugger under Tiger? In-Reply-To: <1116454257.428bbd71486f7@www.paradise.net.nz> References: <1116454257.428bbd71486f7@www.paradise.net.nz> Message-ID: I should of specified that I'm looking for an IDE with full debugging. Basically something like Xcode, but with Python support. On May 18, 2005, at 3:10 PM, jfouhy at paradise.net.nz wrote: > Quoting Mike Hall : > > >> Does anyone know of a Python debugger that will run under OSX 10.4? >> The Eric debugger was looked at, but it's highly unstable under >> Tiger. Thanks. >> > > pdb should work :-) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rha207 at worldnet.att.net Thu May 19 04:19:02 2005 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Wed, 18 May 2005 19:19:02 -0700 Subject: [Tutor] buttons, scrollbar, tkinter Message-ID: <000701c55c19$20228c40$e4384b0c@computer> Is there any way to change this to put in a column of buttons and it will scroll like it does now. I've tried but when I put in the buttons the scrollbar just grows with all the buttons and won't do anything. from Tkinter import * root = Tk() scrollbar = Scrollbar(root) scrollbar.pack(side=RIGHT, fill=Y) listbox = Listbox(root, yscrollcommand=scrollbar.set) for i in range(55): listbox.insert(END, str(i)) listbox.pack(side=LEFT, fill=BOTH) scrollbar.config(command=listbox.yview) Ron A From jfouhy at paradise.net.nz Thu May 19 02:19:15 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 19 May 2005 12:19:15 +1200 (NZST) Subject: [Tutor] buttons, scrollbar, tkinter In-Reply-To: <000701c55c19$20228c40$e4384b0c@computer> References: <000701c55c19$20228c40$e4384b0c@computer> Message-ID: <1116461955.428bdb8369222@www.paradise.net.nz> Quoting Ron Alvarado : > Is there any way to change this to put in a column of buttons and it > will scroll like it does now. I've tried but when I put in the buttons the > scrollbar just grows with all the buttons and won't do anything. I'm not exactly sure what you're after here ... You can't put buttons into a Listbox. A Listbox will only take strings. You can attach a scrollbar to a Frame and pack a bunch of buttons into that. But I find the easiest solution to making scrolling things is to get Pmw: http://pmw.sourceforge.net/ . A Pmw.ScrolledFrame will probably do what you want with very little effort on your part. -- John. From andre.roberge at gmail.com Thu May 19 03:48:49 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Wed, 18 May 2005 22:48:49 -0300 Subject: [Tutor] ANN: new release of RUR-PLE Message-ID: Version 0.8.6a is now available. This version is mostly a bug fix version. * unicode problem corrected (bug introduced in version 0.8.5) * linenumber information on syntax errors corrected * removed the URL browser capability * corrected typo and change explanation of next_to_a_beeper() in lessons * corrected name of robot in one lesson Addition: tower of Hanoi solution(.rur file) (with two typical .wld files) 8 queen puzzle solution (.rur file) Additional changes expected in version 0.8.6b Andr? From leec03273 at mac.com Thu May 19 05:12:23 2005 From: leec03273 at mac.com (Lee Cullens) Date: Wed, 18 May 2005 23:12:23 -0400 Subject: [Tutor] Python debugger under Tiger? In-Reply-To: References: <1116454257.428bbd71486f7@www.paradise.net.nz> Message-ID: <3EADA8CD-C14C-48C8-BF9E-78DFC411E852@mac.com> Mike, You may not be looking for a commercial IDE, but I am very happy with WingIDE and using it with Tiger. Lee C On May 18, 2005, at 6:54 PM, Mike Hall wrote: > I should of specified that I'm looking for an IDE with full > debugging. Basically something like Xcode, but with Python support. > > > On May 18, 2005, at 3:10 PM, jfouhy at paradise.net.nz wrote: > > >> Quoting Mike Hall : >> >> >> >>> Does anyone know of a Python debugger that will run under OSX 10.4? >>> The Eric debugger was looked at, but it's highly unstable under >>> Tiger. Thanks. >>> >>> >> >> pdb should work :-) >> >> -- >> John. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu May 19 08:55:30 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 19 May 2005 07:55:30 +0100 Subject: [Tutor] Python debugger under Tiger? References: Message-ID: <01bc01c55c3f$bf186830$358c8651@xp> > Does anyone know of a Python debugger that will run under OSX 10.4? > The Eric debugger was looked at, but it's highly unstable under > Tiger. Thanks. pdb should still work. Alan g From pieter.lust at katho.be Wed May 18 22:29:58 2005 From: pieter.lust at katho.be (Pieter Lust) Date: Wed, 18 May 2005 22:29:58 +0200 Subject: [Tutor] How to convert hex representation of char? (Challenge part 8) In-Reply-To: <017201c55bd9$defd4be0$358c8651@xp> References: <428B3D4A.6040004@katho.be> <017201c55bd9$defd4be0$358c8651@xp> Message-ID: Alan G wrote: > '\x14' is the actual non printable charactewrs. If it were printable > you > would see its printed representation, because it isn't Pyhon showsw > you > the hex code as an escaped character but it is the character. > Thanks for the input. I'm sorry, my question was not clear enough. The problem is that (to stick with the example) '\x14' is not the character 0x14, but a string of length 4. It consists of the characters backslash, 'x', '1' and '4'. (I verified the output of len()). What I want to do is make Python believe that that string of length 4 is actually a string of length 1 that contains character 0x14. Any help on how to achieve that is appreciated. Pieter Lust From kent37 at tds.net Thu May 19 11:52:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 May 2005 05:52:24 -0400 Subject: [Tutor] How to convert hex representation of char? (Challenge part 8) In-Reply-To: References: <428B3D4A.6040004@katho.be> <017201c55bd9$defd4be0$358c8651@xp> Message-ID: <428C61D8.8040507@tds.net> Pieter Lust wrote: > Alan G wrote: > > '\x14' is the actual non printable charactewrs. If it were printable > > you > > would see its printed representation, because it isn't Pyhon showsw > > you > > the hex code as an escaped character but it is the character. > > > > Thanks for the input. I'm sorry, my question was not clear enough. > > The problem is that (to stick with the example) '\x14' is not the > character 0x14, but a string of length 4. It consists of the characters > backslash, 'x', '1' and '4'. (I verified the output of len()). > What I want to do is make Python believe that that string of length 4 is > actually a string of length 1 that contains character 0x14. Any help on > how to achieve that is appreciated. One way is to paste the string into a program; when Python sees '\x14' it creates a string of length 1: >>> len('\x14') 1 Alternately you can use the 'string_escape' codec to convert the string: >>> s=r'\x14' >>> len(s) 4 >>> t=s.decode('string_escape') >>> t '\x14' >>> len(t) 1 Kent From pieter.lust at katho.be Thu May 19 13:20:58 2005 From: pieter.lust at katho.be (plust) Date: Thu, 19 May 2005 13:20:58 +0200 Subject: [Tutor] How to convert hex representation of char? (Challenge part 8) In-Reply-To: <428C61D8.8040507@tds.net> References: <428B3D4A.6040004@katho.be> <017201c55bd9$defd4be0$358c8651@xp> <428C61D8.8040507@tds.net> Message-ID: Kent Johnson wrote: > One way is to paste the string into a program; when Python sees '\x14' it creates a string of length 1: > > >>> len('\x14') > 1 > > Alternately you can use the 'string_escape' codec to convert the string: > >>> s=r'\x14' > >>> len(s) > 4 > >>> t=s.decode('string_escape') > >>> t > '\x14' > >>> len(t) > 1 > > Kent > Thanks! That solves my problem. Pieter Lust. From albertito_g at hotmail.com Thu May 19 14:48:15 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 19 May 2005 12:48:15 +0000 Subject: [Tutor] Troubles with Python modules In-Reply-To: Message-ID: Hey Is there any work around to accomplish what I want? I'm asking because I'm still with the same problem Regards Alberto >From: Danny Yoo >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Troubles with Python modules >Date: Tue, 17 May 2005 14:56:52 -0700 (PDT) > > > >On Tue, 17 May 2005, Alberto Troiano wrote: > > > Sorry about the question marks (MSN addiction :)) > > > > Didn't work and as I suspected it was already installed. > >Hi Alberto, > >I'm still thinking that the MySQL development packages are either damaged >or mixed up, since the error message says that it can't find MySQL's >headers. > >Let's double check something. Can you do the following from your Unix >shell? > >###### >$ rpm -qil mysql-devel >$ ls -l /usr/include/mysql >###### > >Show us what comes out. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From cpu.crazy at gmail.com Wed May 18 23:55:47 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 18 May 2005 15:55:47 -0600 Subject: [Tutor] Finding word in file In-Reply-To: <017901c55bda$9b5f4f40$358c8651@xp> References: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> <017901c55bda$9b5f4f40$358c8651@xp> Message-ID: <6.1.0.6.2.20050518155314.01f0ba00@pop.gmail.com> >What are you trying? >You could simply read through the file line by line using the string >search methods. Store the previous 2 lines then when found print the >previous two lines, the current line and then read and print the next >two lines. There are more sophisticated methods but that should do... How? Does your tutorial cover that (i don't remember it doing so)? >You need to catch the error not state it. OK >try: f = file(....) >except IOError: print 'file not....' Did that, IO Error handling works great now. Thanks JQ From mhansen at cso.atmel.com Thu May 19 16:09:48 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 19 May 2005 08:09:48 -0600 Subject: [Tutor] Python debugger under Tiger? In-Reply-To: References: Message-ID: <428C9E2C.3010703@cso.atmel.com> > Subject: > Re: [Tutor] Python debugger under Tiger? > From: > Mike Hall > Date: > Wed, 18 May 2005 15:54:18 -0700 > To: > jfouhy at paradise.net.nz > > To: > jfouhy at paradise.net.nz > CC: > tutor at python.org > > > I should of specified that I'm looking for an IDE with full debugging. > Basically something like Xcode, but with Python support. > > > On May 18, 2005, at 3:10 PM, jfouhy at paradise.net.nz wrote: > >> Quoting Mike Hall : >> >> >>> Does anyone know of a Python debugger that will run under OSX 10.4? >>> The Eric debugger was looked at, but it's highly unstable under >>> Tiger. Thanks. >>> >> >> pdb should work :-) >> >> -- >> John. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> It's too bad that Activestate doesn't have a version of Komodo that runs under OS X. They have Windows, Linux, and Solaris, but not OS X. I wonder if Eclipse using PyDev has visual debugging/stepping/watching that you are looking for? You might want to ask on the python mac mail list http://mail.python.org/mailman/listinfo/pythonmac-sig Mike From administrata at hotmail.com Thu May 19 16:50:16 2005 From: administrata at hotmail.com (. ,) Date: Thu, 19 May 2005 14:50:16 +0000 Subject: [Tutor] Whle Loop to run again. Message-ID: Hi, I want the program to run again when i input 'run' But, It doesn't... thanks. ------------------------------------------------------------------------------------------------------------------------------------------- import random raw_input("Flip a coin!") head = 0 tail = 0 run = "" while (head + tail) < 100: coin = random.randrange(2) if coin == 0: head += 1 elif coin == 1: tail += 1 elif run == "run": continue elif run == "ex1t": print ex1t break else: print "Error" print "\n", head, "heads,", tail, "tails out of 100." run = raw_input("\n'run' again or 'exit' ") ex1t = raw_input("\nPress the enter key to exit.") ------------------------------------------------------------------------------------------------------------------------------------------- _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From th1nk3r at server01.org Thu May 19 17:22:57 2005 From: th1nk3r at server01.org (Ricardo Catalinas Jimenez) Date: Thu, 19 May 2005 17:22:57 +0200 Subject: [Tutor] Whle Loop to run again. In-Reply-To: References: Message-ID: <20050519152257.GA3460@jehuty.server01.org> 0n Thu, May 19, 2005 at 02:50:16PM +0000, . , wrote: > Hi, > > I want the program to run again when i input 'run' But, It doesn't... > > thanks. > > ------------------------------------------------------------------------------------------------------------------------------------------- > import random > > raw_input("Flip a coin!") > > head = 0 > tail = 0 > run = "" > > while (head + tail) < 100: > coin = random.randrange(2) > if coin == 0: > head += 1 > > elif coin == 1: > tail += 1 > > elif run == "run": > continue > > elif run == "ex1t": > print ex1t > break > > else: > print "Error" > > print "\n", head, "heads,", tail, "tails out of 100." > > > > > run = raw_input("\n'run' again or 'exit' ") > > ex1t = raw_input("\nPress the enter key to exit.") --- code --- import random raw_input("Flip a coin!") head = 0 tail = 0 run = "" while True: while (head + tail) < 100: coin = random.randrange(2) if coin == 0: head += 1 elif coin == 1: tail += 1 print "\n", head, "heads,", tail, "tails out of 100." head, tail = 0, 0 run = raw_input("\n'run' again or 'exit' ") if run == "exit": break elif run == "run": continue else: print "Error" ex1t = raw_input("\nPress the enter key to exit.") --- end code --- Sorry, I changed your indentation by tabs characters. -- Ricardo Catalinas Jimenez Madrid, Spain. th1nk3r(at)server01(dot)org http://www.server01.org GnuPG Key fingerprint = 662C EBF7 9220 0F14 C644 F90B DC3E A163 7F8D CDAE From michael.hall at critterpixstudios.com Thu May 19 19:27:49 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu, 19 May 2005 10:27:49 -0700 Subject: [Tutor] Python debugger under Tiger? In-Reply-To: <3EADA8CD-C14C-48C8-BF9E-78DFC411E852@mac.com> References: <1116454257.428bbd71486f7@www.paradise.net.nz> <3EADA8CD-C14C-48C8-BF9E-78DFC411E852@mac.com> Message-ID: <0F1A4A9F-C455-4DFF-A153-4E89CC0EAE62@critterpixstudios.com> Great recommendation, thanks. -MH On May 18, 2005, at 8:12 PM, Lee Cullens wrote: > Mike, > > You may not be looking for a commercial IDE, but I am very happy with > WingIDE and using it with Tiger. > > Lee C > > > On May 18, 2005, at 6:54 PM, Mike Hall wrote: > > >> I should of specified that I'm looking for an IDE with full >> debugging. Basically something like Xcode, but with Python support. >> >> >> On May 18, 2005, at 3:10 PM, jfouhy at paradise.net.nz wrote: >> >> >> >>> Quoting Mike Hall : >>> >>> >>> >>> >>>> Does anyone know of a Python debugger that will run under OSX 10.4? >>>> The Eric debugger was looked at, but it's highly unstable under >>>> Tiger. Thanks. >>>> >>>> >>>> >>> >>> pdb should work :-) >>> >>> -- >>> John. >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050519/5b5a855e/attachment-0001.htm From alan.gauld at freenet.co.uk Thu May 19 19:27:29 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 19 May 2005 18:27:29 +0100 Subject: [Tutor] Finding word in file References: <6.1.0.6.2.20050517180706.01f02990@pop.gmail.com> <017901c55bda$9b5f4f40$358c8651@xp> <6.1.0.6.2.20050518155314.01f0ba00@pop.gmail.com> Message-ID: <01dc01c55c98$0cc15b70$358c8651@xp> > >What are you trying? > >You could simply read through the file line by line using the string > >search methods. Store the previous 2 lines then when found print the > >previous two lines, the current line and then read and print the next > >two lines. > > How? Does your tutorial cover that (i don't remember it doing so)? Two topics -- one on handling files the other on handling text. Alan G. From rha207 at worldnet.att.net Thu May 19 23:11:18 2005 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Thu, 19 May 2005 14:11:18 -0700 Subject: [Tutor] buttons, scrollbar, tkinter Message-ID: <000701c55cb7$4d11a620$f3384b0c@computer> I was trying to put buttons in, but now I know why it wouldn't work. I'm going to take a look at PMW. Thanks. Ron A From william.ohiggins at utoronto.ca Thu May 19 21:49:53 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Thu, 19 May 2005 15:49:53 -0400 Subject: [Tutor] dictionary values in strings Message-ID: <20050519194953.GA24831@sillyrabbi.dyndns.org> I am trying to discover the syntax for call on a dictionary of lists by key and index. The data structure looks like this: dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ 'key3':['li1'li2,'li3','']} The keys are passed to a function as arguments, and I want the value of the specified list index. This is what I *thought* it would look like: dol.key(argument)[0] # would return li1 when argument equals key1 But that's wrong. The error I get is this: AttributeError: 'dict' object has no attribute 'key' I don't know how to interpret that error (well, I know I screwed up, but ... :-) Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050519/78cdba4f/attachment.pgp From albertito_g at hotmail.com Thu May 19 22:04:17 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 19 May 2005 20:04:17 +0000 Subject: [Tutor] Disable menubar Message-ID: Hey everyone I've read about menubars and I decided to use the MenuBar from PMW instead of Tkinter's The reason is that I couldn't find an example to make a menu with cascade submenus and another cascade submenu inside the submenu and so on. Now I want to ask if somebody knows how to accomplish these with Menu from TKinter? On the other hand, every button on the menu opens a Toplevel, but I want to restrict the Toplevels to one of each kind. I was thinking in disable the menubutton but PMW only has disable_all and I only want to disable the opened Toplevel. Is there another way to accomplish this using Menu from TKinter or MenuBar from PMW or any other option? I'm sending a copy of the code of the menu (If you think you'll need all the code tell me because is kind of long and has many things that I haven't tried yet) Thanks in advanced Alberto def menuc(): balloon = Pmw.Balloon(root) menuBar = Pmw.MenuBar(root,hull_relief = 'raised',hull_borderwidth = 1,balloon = balloon) menuBar.pack(fill = 'x') menuBar.addmenu('Archivo', 'Salir') menuBar.addmenuitem('Archivo', 'command', 'Salir de la aplicacion',command = root.destroy,label = 'Salir') menuBar.addmenu('Parametros', 'Define ciudades y otros paramtros') menuBar.addmenuitem('Parametros', 'command', 'Agregar, modificar o eliminar ciudades',command=city,label='Ciudades') menuBar.addmenuitem('Parametros', 'separator') menuBar.addmenuitem('Parametros', 'command', 'Agregar, modificar o eliminar hospitales',command=hello,label='Hospitales') menuBar.addmenuitem('Parametros', 'command', 'Agregar, modificar o eliminar pacientes',command=hello,label='Pacientes') menuBar.addmenuitem('Parametros', 'separator') menuBar.addmenuitem('Parametros', 'command', 'Agregar, modificar o eliminar especialidades',command=hello,label='Especialidades') menuBar.addmenuitem('Parametros', 'command', 'Agregar, modificar o eliminar medicos',command=hello,label='Medicos') menuBar.addmenuitem('Parametros', 'separator') menuBar.addmenuitem('Parametros', 'command', 'Agregar, modificar o eliminar tecnicos',command=hello,label='Tecnicos') menuBar.addmenuitem('Parametros', 'separator') menuBar.addcascademenu('Parametros', 'Marcapasos','Marcas y modelos', traverseSpec = 'z', tearoff = 0) menuBar.addmenuitem('Marcapasos', 'command', 'Agregar, modificar o eliminar marcas',command=hello,label='Marcas') menuBar.addmenuitem('Marcapasos', 'command', 'Agregar, modificar o eliminar modelos',command=hello,label='Modelos') menuBar.addcascademenu('Parametros', 'Electrodos','Marcas y modelos', traverseSpec = 'z', tearoff = 0) menuBar.addmenuitem('Electrodos', 'command', 'Agregar, modificar o eliminar marcas',command=hello,label='Marcas') menuBar.addmenuitem('Electrodos', 'command', 'Agregar, modificar o eliminar modelos',command=hello,label='Modelos') menuBar.addmenu('Implantes', 'Programacion de implantes') menuBar.addmenuitem('Implantes', 'command', 'Agregar, modificar o eliminar implantes',command=hello,label='Nuevo') menuBar.addmenuitem('Implantes', 'command', 'Generar reportes',command=hello,label='Reporte') menuBar.addmenu('Reprogramaciones', 'Programacion de reprogramaciones') menuBar.addmenuitem('Reprogramaciones', 'command', 'Agregar, modificar o eliminar reprogramaciones',command=hello,label='Nuevo') menuBar.addmenuitem('Reprogramaciones', 'command', 'Generar reportes',command=hello,label='Reporte') From 3dbernard at gmail.com Thu May 19 22:33:20 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 May 2005 16:33:20 -0400 Subject: [Tutor] dictionary values in strings In-Reply-To: <20050519194953.GA24831@sillyrabbi.dyndns.org> References: <20050519194953.GA24831@sillyrabbi.dyndns.org> Message-ID: <61d0e2b405051913337d127463@mail.gmail.com> Indeed, dictionaries don't have a .key attribute. Instead, use: # Get list of values for 'key1' aList = dol[ 'key1' ] This would return the list of values you have assigned to 'key1' in the dictionary. Once you got that list, you can look in the list to find out the index of 'lil1' and return it: # Iterate list of values assigned to 'key1' for i in range( 0, len( dol[ 'key1' ] ) ): # Get list element using current iteration value sValue = dol[ 'key1' ][i] # If list element is 'lil1', print its list index if sValue == 'lil1': print 'lil1 has index : ' + str( i ) Cheers Bernard On 5/19/05, William O'Higgins wrote: > I am trying to discover the syntax for call on a dictionary of lists by > key and index. > > The data structure looks like this: > > dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ > 'key3':['li1'li2,'li3','']} > > The keys are passed to a function as arguments, and I want the value of > the specified list index. This is what I *thought* it would look like: > > dol.key(argument)[0] # would return li1 when argument equals key1 > > But that's wrong. The error I get is this: > AttributeError: 'dict' object has no attribute 'key' > > I don't know how to interpret that error (well, I know I screwed up, but > ... :-) Thanks. > -- > > yours, > > William > > > > BodyID:3456163.2.n.logpart (stored separately) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From maxnoel_fr at yahoo.fr Thu May 19 22:47:50 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 19 May 2005 21:47:50 +0100 Subject: [Tutor] dictionary values in strings In-Reply-To: <20050519194953.GA24831@sillyrabbi.dyndns.org> References: <20050519194953.GA24831@sillyrabbi.dyndns.org> Message-ID: <81F6DBE7-5764-49F2-B356-5F97798B6361@yahoo.fr> On May 19, 2005, at 20:49, William O'Higgins wrote: > I am trying to discover the syntax for call on a dictionary of > lists by > key and index. > > The data structure looks like this: > > dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ > 'key3':['li1'li2,'li3','']} > > The keys are passed to a function as arguments, and I want the > value of > the specified list index. This is what I *thought* it would look > like: > > dol.key(argument)[0] # would return li1 when argument equals key1 > > But that's wrong. The error I get is this: > AttributeError: 'dict' object has no attribute 'key' > > I don't know how to interpret that error (well, I know I screwed > up, but > ... :-) Thanks. As the error message implies, dictionaries don't have a key attribute. They do, however, have a keys() method: >>> a = {'foo': 1, 'bar': 2} >>> a.keys() ['foo', 'bar'] And they also have the has_key() method, which can be used to test for the presence of a key in a dict: >>> a.has_key('foo') True >>> a.has_key('baz') False What you are looking for can be achieved like this: >>> dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ ... 'key3':['li1', 'li2','li3','']} >>> dol['key1'][0] 'li1' Hope that helps, -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Thu May 19 22:52:56 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 19 May 2005 21:52:56 +0100 Subject: [Tutor] Whle Loop to run again. References: Message-ID: <020601c55cb4$bbe54280$358c8651@xp> > I want the program to run again when i input 'run' But, It doesn't... You need another loop, or to ask for input inside the loop. If you always want 100 iterations then prompt for another hundred structure it like: run = raw_input('run or exit? ') while run = 'run': for n in range(100): coin = random.randrange(2) if coin == 1: heads += 1 else coin == 2: tails += 1 run = raw_input('run or exit? ') But if you want to check after every coin toss (as your if/elif chain code seems to suggest) but with a maximum of 100 iterations, try it this way: heads,tails = 0,0 while heads+tails < 100: coin = random.randrange(2) if coin == 1: heads += 1 else coin == 2: tails += 1 run = raw_input('run or exit? ') if run = 'run': continue else: break HTH, Alan G. From chelan.farsight at gmail.com Thu May 19 23:18:38 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Thu, 19 May 2005 15:18:38 -0600 Subject: [Tutor] diving into py question Message-ID: <661da26c05051914185a7aa41d@mail.gmail.com> I am using the online book Dive Into Python. I ran the first program given and have run into an error on line 7 at the colon. Now I imagine that there is probably a corrections page at the site, but I am interested in knowing why it won't work as much as what I need to do to correct it. Any help would be appreciated. The script follows: def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string.""" return ";".join(["%s=%s" % (k, v) for k, v in params.items()]) if_name_ == "_main_": myParams = {"server":"mpilgrim", \ "database":"master", \ "uid":"sa", \ "pwd":"secret" \ } print buildConnectionString(myParams) From maxnoel_fr at yahoo.fr Thu May 19 23:24:18 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 19 May 2005 22:24:18 +0100 Subject: [Tutor] diving into py question In-Reply-To: <661da26c05051914185a7aa41d@mail.gmail.com> References: <661da26c05051914185a7aa41d@mail.gmail.com> Message-ID: <4B676AF4-FE0B-412A-90C7-4BC0FA47BA57@yahoo.fr> On May 19, 2005, at 22:18, Chelan Farsight wrote: > I am using the online book Dive Into Python. > I ran the first program given and have run into an error on line 7 at > the colon. Now I imagine that there is probably a corrections page at > the site, but I am interested in knowing why it won't work as much as > what I need to do to correct it. Any help would be appreciated. The > script follows: > > > if_name_ == "_main_": The number of underscores is incorrect. "Magic" names in Python start and end with two underscores. The line should be changed to: if __name__ == "__main__": Hope that helps, -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From 3dbernard at gmail.com Thu May 19 23:33:55 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 May 2005 17:33:55 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <4288715B.2040305@tds.net> References: <009c01c55788$46c2d6b0$91508651@xp> <61d0e2b40505130752582ce88@mail.gmail.com> <4284C59A.4050108@tds.net> <61d0e2b40505131256607893a@mail.gmail.com> <4288715B.2040305@tds.net> Message-ID: <61d0e2b40505191433445b1842@mail.gmail.com> Well, that was a nice explanation. Thanks once again Kent! Bernard On 5/16/05, Kent Johnson wrote: > Bernard Lebel wrote: > > Hi Kent, > > > > So if I undestand you right, mapping a function with map() when it is > > a built-in function will/may be faster than a for loop, but if it's a > > custom function (ie. a def one), it will most likely be slower? > > I guess I didn't proofread that last mail...what I meant is > > - Write the code for clarity first > - If you find a performance bottleneck then test different solutions to see which is fastest for > your actual data and usage. > - Mapping a builtin function over a list is relatively fast in Python and it is worth trying if it > meets your needs. > - Calling a function is relatively expensive in Python so if using map() requires you to define a > helper that may wipe out its advantage. > - Testing is crucial! Guessing is only good for helping to come up with ideas to test. > > Here is a program that tests six ways to apply a function to elements of a list. The functions don't > create new lists except as side effects since that was the original problem. They use map(), list > comprehension and an explicit for loop to apply str() or a Python function returning str() to the > elements of a list. (The list already contains strings so the actual function call should be fast.) > > #### > > import timeit > > data = [str(n) for n in range(100)] > > def strByMap(): > map(str, data) > > def strByListComp(): > [str(n) for n in data] > > def strByLoop(): > for n in data: > str(n) > > > def func(x): > return str(x) > > > def funcByMap(): > map(func, data) > > def funcByListComp(): > [func(n) for n in data] > > def funcByLoop(): > for n in data: > func(n) > > > def timeOne(fn): > setup = "from __main__ import " + fn.__name__ > stmt = '%s()' % (fn.__name__) > > t = timeit.Timer(stmt, setup) > secs = min(t.repeat(number=1000)) > print '%15s %s' % (fn.__name__, secs) > > for fn in [ strByMap, strByListComp, strByLoop, funcByMap, funcByListComp, funcByLoop ]: > timeOne(fn) > > ### > > Here are the results on my computer: > > strByMap 0.0359623918682 > strByListComp 0.0581065470611 > strByLoop 0.0481150537289 > funcByMap 0.0810943849009 > funcByListComp 0.0891375859222 > funcByLoop 0.0806144356336 > > So for this test, map is fastest when calling a builtin and explicit looping is fastest when calling > a function. With the explicit loop you might be able to inline the function, in which case it would > be much faster than either map or list comp. > > Modifying the program slightly so that each function actually creates a list changes the results > dramatically: > strByMap 0.0365733633744 > strByListComp 0.0579948010152 > strByLoop 0.0764722890758 > funcByMap 0.0811885309446 > funcByListComp 0.0883995032888 > funcByLoop 0.10586876265 > > Now map() is fastest in both cases, though a for loop with inlined code beats map() with an external > function. > > Kent > > > > > > Thanks > > Bernard > > > > > > On 5/13/05, Kent Johnson wrote: > > > >>Bernard Lebel wrote: > >> > >>>The authors even go as far as saysing, on page 228 (first paragraph) > >>>that map() used that way has a performance benefit and is faster than > >>>a for loop. > >> > >>That may well be correct, at least in the case where the function passed to map is a builtin. > >>Mapping a builtin to over a list is extremely fast. So write the code with a for loop so it is > >>clear. When you identify a performance bottleneck you can try rewriting your loop using map or list > >>comprehension, which is also fast. Until then it is premature optimization. For typical loops over a > >>small number of items I can't imagine you would notice the difference. > >> > >>Kent > >> > >>_______________________________________________ > >>Tutor maillist - Tutor at python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From chelan.farsight at gmail.com Thu May 19 23:46:36 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Thu, 19 May 2005 15:46:36 -0600 Subject: [Tutor] diving into py question In-Reply-To: <4B676AF4-FE0B-412A-90C7-4BC0FA47BA57@yahoo.fr> References: <661da26c05051914185a7aa41d@mail.gmail.com> <4B676AF4-FE0B-412A-90C7-4BC0FA47BA57@yahoo.fr> Message-ID: <661da26c0505191446635f6c1d@mail.gmail.com> Thanks! You were right about the double underscore, however, I am still getting the error on line 7...hrmm any other ideas? On 5/19/05, Max Noel wrote: > > On May 19, 2005, at 22:18, Chelan Farsight wrote: > > > I am using the online book Dive Into Python. > > I ran the first program given and have run into an error on line 7 at > > the colon. Now I imagine that there is probably a corrections page at > > the site, but I am interested in knowing why it won't work as much as > > what I need to do to correct it. Any help would be appreciated. The > > script follows: > > > > > > if_name_ == "_main_": > > The number of underscores is incorrect. "Magic" names in Python > start and end with two underscores. The line should be changed to: > > > if __name__ == "__main__": > > > Hope that helps, > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From maxnoel_fr at yahoo.fr Fri May 20 00:05:16 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 19 May 2005 23:05:16 +0100 Subject: [Tutor] diving into py question In-Reply-To: <661da26c0505191446635f6c1d@mail.gmail.com> References: <661da26c05051914185a7aa41d@mail.gmail.com> <4B676AF4-FE0B-412A-90C7-4BC0FA47BA57@yahoo.fr> <661da26c0505191446635f6c1d@mail.gmail.com> Message-ID: On May 19, 2005, at 22:46, Chelan Farsight wrote: > Thanks! > You were right about the double underscore, however, I am still > getting the error on line 7...hrmm > any other ideas? > In your original code, the space between if and __main__ is also missing. This may be the source of the error. Lacking that, could you send us the exact error message, please? Just copy/paste whatever the interpreter throws at you; error messages are very useful to us. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From carroll at tjc.com Fri May 20 00:05:48 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 May 2005 15:05:48 -0700 (PDT) Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: <428AB259.4060601@tds.net> Message-ID: On Wed, 18 May 2005 jfouhy at paradise.net.nz wrote: > Another possibility is to look at this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 On Tue, 17 May 2005, Kent Johnson wrote: > I think this approach to debugging won't scale well and you are just > seeing the tip of the iceberg.... [and more helpful stuff, snipped.] Thanks to you both. I think I may need to step up my "development environment" beyond emacs and a command line. From jonasmg at softhome.net Fri May 20 00:28:46 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Thu, 19 May 2005 23:28:46 +0100 Subject: [Tutor] kernel serie Message-ID: <428D131E.3010000@softhome.net> I want get the kernel serie, so 2.x only (2.6 or 2.4) info_kernel = platform.release() # get the kernel version info_kernel = '.'.join(info_kernel.split('.',2)[:2]) is there any way of get it in one line only? Thanks in advance! From carroll at tjc.com Fri May 20 00:17:08 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 May 2005 15:17:08 -0700 (PDT) Subject: [Tutor] Finding which list entry is being used, in a for loop (was: using -i flag with '''if __name__ == "__main__":''' In-Reply-To: <428AB259.4060601@tds.net> Message-ID: On Tue, 17 May 2005, Kent Johnson wrote: > I often find that the information in the traceback and exception are > enough to figure out the problem; if not, a few print statements can > help. You will get better at this with experience. Here's an example where traceback and print statements doesn't help, and it's really nice to have access to the variables... Suppose I have a long list of lists (by "long," I mean, too long to display on one screen and visually examine easily), and am iterating over the inner lists. (Forget whether there might be more efficient ways; this is just for illustration.) In most languages, you'd take this unpythonic approach: for i in range(0,len(mylist)): for j in range(0, len(mylist[i])): # stuff dependent on mylist[i][j] I could put in "print i,j, mylist[i][j]" statements in here, and pretty easily zero in on the exceptional data. But a pythonic approach, and the one I find easiest, is: for innerlist in mylist: for item in innerlist: # stuff dependent on item Now, I can only put in "print item", and finding that in the nested list is like a needle in a haystack. That's what I like about the -i option... I can use Python expressions to iterate through the list lookingfor stuff. Is there any way, in the second construct, to have the traceback (or equivalent info) include where in "innerlist" "item" came from, and where in "mylist" "innerlist" came from? From maxnoel_fr at yahoo.fr Fri May 20 00:25:14 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 19 May 2005 23:25:14 +0100 Subject: [Tutor] kernel serie In-Reply-To: <428D131E.3010000@softhome.net> References: <428D131E.3010000@softhome.net> Message-ID: On May 19, 2005, at 23:28, Jonas Melian wrote: > I want get the kernel serie, so 2.x only (2.6 or 2.4) > > info_kernel = platform.release() # get the kernel version > info_kernel = '.'.join(info_kernel.split('.',2)[:2]) > > is there any way of get it in one line only? Based on your code, that'd be: info_kernel = '.'.join(platform.release().split('.',2)) The [:2] is unnecessary, as you're limiting the number of splits to 2, so the resulting list from split() can't have more than 3 elements. Also, note that this code will likely cause the program to crash on any system that isn't Linux. On my box (OS X 10.4.1), for example, sys.platform returns 'darwin'. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri May 20 00:31:30 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 19 May 2005 23:31:30 +0100 Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: References: Message-ID: <277E8115-A7F6-47CF-8291-F51B88550BA5@yahoo.fr> On May 19, 2005, at 23:05, Terry Carroll wrote: > Thanks to you both. I think I may need to step up my "development > environment" beyond emacs and a command line. Actually, if you're having problems with debugging your problem, what you should step up is your approach to debugging/testing. Unit tests (the unittest module, which is itself derived from the Java JUnit framework) are an instance of BestThingEver, especially if you're using the OO paradigm. They basically allow you to prove the correctness of each part of your program. And trust me, the time you take to write them is by far lower than the time they save you tracking and correcting bugs if you don't. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From albertito_g at hotmail.com Fri May 20 00:47:59 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 19 May 2005 22:47:59 +0000 Subject: [Tutor] Disable menubar In-Reply-To: <1116540949.428d1015f2953@www.paradise.net.nz> Message-ID: YES!!!! That's what I was looking for and I will replace it. I don't like to much the MenuBar from Pmw its different and it does not have all the menu attributes that windows menu have (or maybe I don't know how to use it well :D) About disabling the button it would be nice to know if that can be done , although I made some work around and I managed to restrict the Toplevels. If anybody wants to know how I can post the code Thanks in advanced Alberto >From: jfouhy at paradise.net.nz >To: Alberto Troiano >Subject: Re: [Tutor] Disable menubar >Date: Fri, 20 May 2005 10:15:49 +1200 (NZST) > >Quoting Alberto Troiano : > > > The reason is that I couldn't find an example to make a menu with > > cascade submenus and another cascade submenu inside the submenu and so >on. > > Now I want to ask if somebody knows how to accomplish these with Menu > > from TKinter? > >Here is some code: > > >>> from Tkinter import * > >>> tk = Tk() > >>> m = Menu(tk) > >>> m2 = Menu(m, tearoff=False) > >>> m.add_cascade(label='foo', menu=m2) > >>> m3 = Menu(m2, tearoff=False) > >>> m2.add_cascade(label='bar', menu=m3) > >>> m3.add_command(label='One') > >>> m3.add_command(label='Two') > >>> tk.config(menu=m) > >Is this what you are after? Check the attachment for what it produces. > >You could add more menus, eg: > > >>> m4 = Menu(m3, tearoff=False) > >>> m3.add_cascade(label='baz', menu=m4) > >>> m4.add_command(label='Three') > >>> m4.add_command(label='Four') > >I think using Tkinter.Menu is better than Pmw, because Tkinter.Menu will >use >native menu widgets (which means your menu will look the same as other >menus in >other apps), whereas I think Pmw may do its own thing. > >-- >John. ><< menu.jpg >> Gaucho From carroll at tjc.com Fri May 20 00:59:09 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 19 May 2005 15:59:09 -0700 (PDT) Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: <277E8115-A7F6-47CF-8291-F51B88550BA5@yahoo.fr> Message-ID: On Thu, 19 May 2005, Max Noel wrote: > On May 19, 2005, at 23:05, Terry Carroll wrote: > > > Thanks to you both. I think I may need to step up my "development > > environment" beyond emacs and a command line. > > Actually, if you're having problems with debugging your problem, > what you should step up is your approach to debugging/testing. That's a fair point. However, most of the programming I'm doing right now is the Python Challenge! Not really programs I'm going to keep around and maintain. But I think my lesson here is to have two programming modes: one where I'm writing programs known to be throwaways (like these Python Challenge ones), where I don't do unit-testing and also don't use that "__name__ == "__main__" construct (what's the point of that in a throwaway, anyway?); and one where I'm writing a keeper, where I build tests. Thanks! From jfouhy at paradise.net.nz Fri May 20 01:09:21 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 20 May 2005 11:09:21 +1200 (NZST) Subject: [Tutor] Disable menubar In-Reply-To: References: Message-ID: <1116544161.428d1ca138fff@www.paradise.net.nz> Quoting Alberto Troiano : > About disabling the button it would be nice to know if that can be done > , although I made some work around and I managed to restrict the > Toplevels. You can disable buttons and menu items with the state option. Setting state=DISABLED will grey-out a Button or menu item. (you need to use the entryconfig method of the menu) You can reenable the object by setting state=NORMAL. -- John. From 3dbernard at gmail.com Fri May 20 01:33:51 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 May 2005 19:33:51 -0400 Subject: [Tutor] map() and lambda to change class instance attribute (fwd) In-Reply-To: <1116540347.428d0dbb37c5f@www.paradise.net.nz> References: <009c01c55788$46c2d6b0$91508651@xp> <61d0e2b40505130752582ce88@mail.gmail.com> <4284C59A.4050108@tds.net> <61d0e2b40505131256607893a@mail.gmail.com> <4288715B.2040305@tds.net> <61d0e2b40505191433445b1842@mail.gmail.com> <1116540347.428d0dbb37c5f@www.paradise.net.nz> Message-ID: <61d0e2b4050519163331e56f2@mail.gmail.com> That is very interesting John. Thanks! Bernard On 5/19/05, jfouhy at paradise.net.nz wrote: > Quoting Bernard Lebel <3dbernard at gmail.com>: > > > Well, that was a nice explanation. Thanks once again Kent! > > There is a nice (not too technical) essay on the running speeds of different > looping constructs on python.org: > > http://www.python.org/doc/essays/list2str.html > > Just FYI :-) > > -- > John. > From kent37 at tds.net Fri May 20 02:22:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 May 2005 20:22:58 -0400 Subject: [Tutor] Finding which list entry is being used, in a for loop In-Reply-To: References: Message-ID: <428D2DE2.8000507@tds.net> Terry Carroll wrote: > On Tue, 17 May 2005, Kent Johnson wrote: > > >>I often find that the information in the traceback and exception are >>enough to figure out the problem; if not, a few print statements can >>help. You will get better at this with experience. > > > Here's an example where traceback and print statements doesn't help, and > it's really nice to have access to the variables... > > Suppose I have a long list of lists (by "long," I mean, too long to > display on one screen and visually examine easily), and am iterating over > the inner lists. (Forget whether there might be more > efficient ways; > this is just for illustration.) > > In most languages, you'd take this unpythonic approach: > > for i in range(0,len(mylist)): > for j in range(0, len(mylist[i])): > # stuff dependent on mylist[i][j] > > I could put in "print i,j, mylist[i][j]" statements in here, and pretty > easily zero in on the exceptional data. > > But a pythonic approach, and the one I find easiest, is: > > for innerlist in mylist: > for item in innerlist: > # stuff dependent on item > > Now, I can only put in "print item", and finding that in the nested list > is like a needle in a haystack. That's what I like about the -i > option... I can use Python expressions to iterate through the list > lookingfor stuff. > > Is there any way, in the second construct, to have the traceback (or > equivalent info) include where in "innerlist" "item" came from, and where > in "mylist" "innerlist" came from? OK, you have prompted me to play around with the recipe I cited earlier. Here is a version that looks promising to me. I have this in Python24\Lib\site-packages\debug_helper.py: ### import sys, traceback def print_exc_plus_hook(type, value, tb): """ Print the usual traceback information, followed by a listing of all the local variables in the current frame. Based on this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215 """ if not tb or issubclass(type, SyntaxError): sys.__excepthook__(type, value, tb) return traceback.print_exception(type, value, tb) while 1: if not tb.tb_next: break tb = tb.tb_next frame = tb.tb_frame # Try to filter out top-level command line errors if frame.f_locals.has_key('__builtins__'): return print >> sys.stderr print >> sys.stderr, "Frame %s in %s at line %s" % (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno) for key, value in frame.f_locals.items(): print >> sys.stderr, "\t%20s = " % key, #We have to be careful not to cause a new error in our error #printer! Calling repr() on an unknown object could cause an #error we don't want. try: print >> sys.stderr, repr(value) except: print >> sys.stderr, "" def install_excepthook(): sys.excepthook = print_exc_plus_hook ### Then I created a file Python24\Lib\site-packages\sitecustomize.py containing these few lines: # Install an exception handler that prints the current stack frame from debug_helper import install_excepthook install_excepthook() ### Now when I get an exception the usual stack trace prints plus the values of the local variables. (I took out the printing of the variables in the higher stack frames, that seems like overkill to me. So in your example, when an exception occurs, you would get a printout with the values of innerlist and item which are both variables in the local scope. If you want more, you could temporarily change the list to for i, innerlist in enumerate(mylist): for j, item in enumerate(innerlist): # stuff dependent on item then you will get the indices as well. I'm going to try this out and see I find it helpful... Kent From alan.gauld at freenet.co.uk Fri May 20 09:14:24 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 20 May 2005 08:14:24 +0100 Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' References: Message-ID: <024c01c55d0b$8de20330$358c8651@xp> > > I think this approach to debugging won't scale well and you are just > > seeing the tip of the iceberg.... [and more helpful stuff, snipped.] > > Thanks to you both. I think I may need to step up my "development > environment" beyond emacs and a command line. I don't see why. The very biggest systems I've ever worked on were built using an editor and command line. Emacs in particular is extra-ordinarily powerful, especially in its integration with the interpreter and debugger. Modern IDEs offer a few extra features over emacs but generally they lose out in terms of raw editing power. I missed the original part of the post that prompted your decision, but the quoted comment above suggests a new aopproach to debugging, not necessarily a new debugger... Alan G. From meesters at uni-mainz.de Fri May 20 10:22:34 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Fri, 20 May 2005 10:22:34 +0200 Subject: [Tutor] "classmethods" Message-ID: <59bccc99d82d973cc3855bb0ef978ff9@uni-mainz.de> Hi I've asked a similar question before, but still I have to admit that I didn't find a solution with this particular problem here: Imaging you have a class with a certain __init__ function like: class MyClass: def __init__(parameter1, parameter2=default,*args,**kwargs): #handle all input And a member function like: def fromFile(cls,path): adict = {} alist = [] #... #some part to read a file and to process data Now, how do I create an instance of MyClass when calling: x = MyClass.fromfile(path) ? When I have a line return parameter1,parameter2,...,d in fromFile, a tuple is returned, which is not quite what I want. Is there a way to make fromFile a true classmethod? Any hint would be greatly appreciated. Regards, Christian From jonasmg at softhome.net Fri May 20 11:43:25 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Fri, 20 May 2005 10:43:25 +0100 Subject: [Tutor] Comparing a string Message-ID: <428DB13D.3040306@softhome.net> I'm tryin compare a string with a value with style of pattern-matching. string = 'i686' if string == glob.glob(i?86): This is fails because glob() is for listing files in a directory that match a Unix ls-pattern how make it? Thanks! From kent37 at tds.net Fri May 20 11:56:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 May 2005 05:56:49 -0400 Subject: [Tutor] using -i flag with '''if __name__ == "__main__":''' In-Reply-To: <024c01c55d0b$8de20330$358c8651@xp> References: <024c01c55d0b$8de20330$358c8651@xp> Message-ID: <428DB461.2040902@tds.net> Alan G wrote: >>>I think this approach to debugging won't scale well and you are > > just > >>>seeing the tip of the iceberg.... [and more helpful stuff, > > snipped.] > >>Thanks to you both. I think I may need to step up my "development >>environment" beyond emacs and a command line. > > > I don't see why. The very biggest systems I've ever worked on were > built using an editor and command line. Emacs in particular is > extra-ordinarily powerful, especially in its integration with > the interpreter and debugger. Modern IDEs offer a few extra > features over emacs but generally they lose out in terms of > raw editing power. > > I missed the original part of the post that prompted your decision, > but the quoted comment above suggests a new aopproach to debugging, > not necessarily a new debugger... Good catch Alan. Most of my Python coding is done entirely in TextPad... Kent From kent37 at tds.net Fri May 20 12:02:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 May 2005 06:02:01 -0400 Subject: [Tutor] "classmethods" In-Reply-To: <59bccc99d82d973cc3855bb0ef978ff9@uni-mainz.de> References: <59bccc99d82d973cc3855bb0ef978ff9@uni-mainz.de> Message-ID: <428DB599.4000204@tds.net> Christian Meesters wrote: > Hi > > I've asked a similar question before, but still I have to admit that I > didn't find a solution with this particular problem here: > > Imaging you have a class with a certain __init__ function like: > class MyClass: > def __init__(parameter1, parameter2=default,*args,**kwargs): > #handle all input > > And a member function like: > def fromFile(cls,path): > adict = {} > alist = [] > #... > #some part to read a file and to process data > > Now, how do I create an instance of MyClass when calling: x = > MyClass.fromfile(path) ? When I have a line > > return parameter1,parameter2,...,d > > in fromFile, a tuple is returned, which is not quite what I want. Is > there a way to make fromFile a true classmethod? I think you want a static method, which does not take the class as an argument. The return value should be the new instance, not the constructor arguments. (You are expecting some magic that is not part of Python.) Try this: def fromFile(path): adict = {} alist = [] #... #some part to read a file and to process data return MyClass(parameter1,parameter2,...,d) fromFile = staticmethod(fromFile) then client code will look like this: aClass = MyClass.fromFile('a/file/path') Kent From jfouhy at paradise.net.nz Fri May 20 12:50:49 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 20 May 2005 22:50:49 +1200 (NZST) Subject: [Tutor] Comparing a string In-Reply-To: <428DB13D.3040306@softhome.net> References: <428DB13D.3040306@softhome.net> Message-ID: <1116586249.428dc1096f1cb@www.paradise.net.nz> Quoting Jonas Melian : > I'm tryin compare a string with a value with style of pattern-matching. > > string = 'i686' > > if string == glob.glob(i?86): This is a task for regular expressions! Have a look at the re module. (and feel free to ask for more help if you're having trouble with it) -- John. From administrata at hotmail.com Fri May 20 13:56:18 2005 From: administrata at hotmail.com (. ,) Date: Fri, 20 May 2005 11:56:18 +0000 Subject: [Tutor] RPG game. Message-ID: I'm trying to make an RPG game which is only consisted of texts. But, it doesn't work! thanks. ------------------------------------------------------------------------------------------------------------------------------------------- import random print \ """Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and Archer ") mob = 300 hit = 0 hp = 100 run = "" while True: while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if (hp < 0): print "\nYour", wp, "has died by the monster(", mob, "hp)" break elif wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk - random.randrage(5) print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" run = raw_input("\n\nrun or exit ") if run == "exit": break elif run == "run": continue else: raw_input("\nError") break ------------------------------------------------------------------------------------------------------------------------------------------- _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From chelan.farsight at gmail.com Fri May 20 15:07:09 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Fri, 20 May 2005 07:07:09 -0600 Subject: [Tutor] diving into py question In-Reply-To: References: <661da26c05051914185a7aa41d@mail.gmail.com> <4B676AF4-FE0B-412A-90C7-4BC0FA47BA57@yahoo.fr> <661da26c0505191446635f6c1d@mail.gmail.com> Message-ID: <661da26c050520060759e8df09@mail.gmail.com> It worked! Thanks so much for the help. I spose its just difficult to read some of this. Not sure why that is the case for me, but I will be paying much closer attention from now on. Again thank you. Chelan On 5/19/05, Max Noel wrote: > > On May 19, 2005, at 22:46, Chelan Farsight wrote: > > > Thanks! > > You were right about the double underscore, however, I am still > > getting the error on line 7...hrmm > > any other ideas? > > > > In your original code, the space between if and __main__ is also > missing. This may be the source of the error. > Lacking that, could you send us the exact error message, please? > Just copy/paste whatever the interpreter throws at you; error > messages are very useful to us. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > From jeffpeery at yahoo.com Fri May 20 15:12:19 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri, 20 May 2005 06:12:19 -0700 (PDT) Subject: [Tutor] printing documents Message-ID: <20050520131219.65478.qmail@web30508.mail.mud.yahoo.com> hello, I am writing a program to store name/contact/business transaction information. I would like the ability to print out a form for each client with all this stored information. Can somone point me in the write direction for printing documents. How do I go about setting up a printable page with all the variables I have for each client? thanks Also I would like to take the information I input and store it as an images. Essentially take the above mentioned document (the one I want to print out a hard copy) and save it as an image so I can view it later. Any ideas? I'm operating on windows and I'm using wxpython. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050520/f56d51e7/attachment.html From albertito_g at hotmail.com Fri May 20 15:23:14 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 20 May 2005 13:23:14 +0000 Subject: [Tutor] Disable menubar In-Reply-To: <7e5ba92205051916002a3aa947@mail.gmail.com> Message-ID: Thank you very much for your help Now it's all clear Thanks again and best regards Alberto >From: "Michael P. Reilly" >Reply-To: "Michael P. Reilly" >To: Alberto Troiano >Subject: Re: [Tutor] Disable menubar >Date: Thu, 19 May 2005 19:00:11 -0400 > >On 5/19/05, Alberto Troiano wrote: > > > > Hey everyone > > > > I've read about menubars and I decided to use the MenuBar from PMW >instead > > of Tkinter's > > > > The reason is that I couldn't find an example to make a menu with >cascade > > submenus and another cascade submenu inside the submenu and so on. > > > > Now I want to ask if somebody knows how to accomplish these with Menu >from > > TKinter? > > > > On the other hand, every button on the menu opens a Toplevel, but I want > > to > > restrict the Toplevels to one of each kind. I was thinking in disable >the > > menubutton but PMW only has disable_all and I only want to disable the > > opened Toplevel. Is there another way to accomplish this using Menu from > > TKinter or MenuBar from PMW or any other option? > > > > I'm sending a copy of the code of the menu (If you think you'll need all > > the > > code tell me because is kind of long and has many things that I haven't > > tried yet) > > > > Thanks in advanced > > > > Alberto > > > >Hi Alberto, > >I believe I recreated what you are trying to do (except the tip balloons >that come with PMW but those can be added with bind events). I've added >some >example code that, I hope, does everything your code was doing. I also made >the "Implantes" menu disabled to show you how that is handled. It can be >done on the fly as well. > >-Arcege >-- >There's so many different worlds, >So many different suns. >And we have just one world, >But we live in different ones. ><< alberto.py >> Gaucho From askoose at sandia.gov Fri May 20 16:32:42 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Fri, 20 May 2005 08:32:42 -0600 Subject: [Tutor] RPG game. Message-ID: Could you post the error message? Ara Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza - Dante Alighieri You were not made to live like brutes, but to pursue virtue and knowledge -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of . , Sent: Friday, May 20, 2005 5:56 AM To: tutor at python.org Subject: [Tutor] RPG game. I'm trying to make an RPG game which is only consisted of texts. But, it doesn't work! thanks. ------------------------------------------------------------------------ ------------------------------------------------------------------- import random print \ """Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and Archer ") mob = 300 hit = 0 hp = 100 run = "" while True: while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if (hp < 0): print "\nYour", wp, "has died by the monster(", mob, "hp)" break elif wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk - random.randrage(5) print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" run = raw_input("\n\nrun or exit ") if run == "exit": break elif run == "run": continue else: raw_input("\nError") break ------------------------------------------------------------------------ ------------------------------------------------------------------- _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From albertito_g at hotmail.com Fri May 20 16:45:08 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 20 May 2005 14:45:08 +0000 Subject: [Tutor] RPG game. In-Reply-To: Message-ID: Hey You must set dmg to a value before using it The error is that the variable dmg hasn't been asigned yet >wp = raw_input("\n\nSelect between warrior and Archer ") > >mob = 300 >hit = 0 >hp = 100 >run = "" > >while True: > while (mob > 0): > hit += 1 > mob = mob - dmg #HERE before doing this and before the while you should type dmg=0 or the value you like Best Regards Alberto >From: "Kooser, Ara S" >To: ". ," , tutor at python.org >Subject: Re: [Tutor] RPG game. >Date: Fri, 20 May 2005 08:32:42 -0600 > >Could you post the error message? > >Ara > > > > > > >Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza >- Dante Alighieri > >You were not made to live like brutes, but to pursue virtue and >knowledge > > >-----Original Message----- >From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On >Behalf Of . , >Sent: Friday, May 20, 2005 5:56 AM >To: tutor at python.org >Subject: [Tutor] RPG game. > > >I'm trying to make an RPG game which is only consisted of texts. But, it > >doesn't work! > >thanks. > >------------------------------------------------------------------------ >------------------------------------------------------------------- >import random > >print \ > """Warrior - damage: 10~60 > Archer - damage: 0~100 > HP of Player: 100 > HP of the monster: 300""" > >wp = raw_input("\n\nSelect between warrior and Archer ") > >mob = 300 >hit = 0 >hp = 100 >run = "" > >while True: > while (mob > 0): > hit += 1 > mob = mob - dmg > hp = hp - atk > > if (hp < 0): > print "\nYour", wp, "has died by the monster(", mob, "hp)" > break > > elif wp == "warrior": > dmg = random.randrange(50) + 10 > atk = random.randrange(10) > > elif wp == "archer": > dmg = random.randrange(100) > atk - random.randrage(5) > > print "\n", hit, "hits" > print "HP of", wp,":", hp,"/100" > print "HP of the monster:", mob,"/300" > > print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" > > run = raw_input("\n\nrun or exit ") > > if run == "exit": > break > > elif run == "run": > continue > else: > raw_input("\nError") > break >------------------------------------------------------------------------ >------------------------------------------------------------------- > >_________________________________________________________________ >Don't just search. Find. Check out the new MSN Search! >http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From administrata at hotmail.com Fri May 20 16:46:41 2005 From: administrata at hotmail.com (. ,) Date: Fri, 20 May 2005 14:46:41 +0000 Subject: [Tutor] RPG game. In-Reply-To: Message-ID: I can't see the error message because the program ends fast. >From: "Kooser, Ara S" >To: ". ," ,tutor at python.org >Subject: RE: [Tutor] RPG game. >Date: Fri, 20 May 2005 08:32:42 -0600 > >Could you post the error message? > >Ara > > > > > > >Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza >- Dante Alighieri > >You were not made to live like brutes, but to pursue virtue and >knowledge > > >-----Original Message----- >From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On >Behalf Of . , >Sent: Friday, May 20, 2005 5:56 AM >To: tutor at python.org >Subject: [Tutor] RPG game. > > >I'm trying to make an RPG game which is only consisted of texts. But, it > >doesn't work! > >thanks. > >------------------------------------------------------------------------ >------------------------------------------------------------------- >import random > >print \ > """Warrior - damage: 10~60 > Archer - damage: 0~100 > HP of Player: 100 > HP of the monster: 300""" > >wp = raw_input("\n\nSelect between warrior and Archer ") > >mob = 300 >hit = 0 >hp = 100 >run = "" > >while True: > while (mob > 0): > hit += 1 > mob = mob - dmg > hp = hp - atk > > if (hp < 0): > print "\nYour", wp, "has died by the monster(", mob, "hp)" > break > > elif wp == "warrior": > dmg = random.randrange(50) + 10 > atk = random.randrange(10) > > elif wp == "archer": > dmg = random.randrange(100) > atk - random.randrage(5) > > print "\n", hit, "hits" > print "HP of", wp,":", hp,"/100" > print "HP of the monster:", mob,"/300" > > print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" > > run = raw_input("\n\nrun or exit ") > > if run == "exit": > break > > elif run == "run": > continue > else: > raw_input("\nError") > break >------------------------------------------------------------------------ >------------------------------------------------------------------- > >_________________________________________________________________ >Don't just search. Find. Check out the new MSN Search! >http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From administrata at hotmail.com Fri May 20 17:41:29 2005 From: administrata at hotmail.com (. ,) Date: Fri, 20 May 2005 15:41:29 +0000 Subject: [Tutor] RPG game. In-Reply-To: Message-ID: It works fine but, at the end of the program total damage has to be shown. Only single damage is shown. How can i change it? ------------------------------------------------------------------------------------------------------------------------------------------- import random print \ """ Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and archer: ") mob = 300 hit = 0 hp = 100 dmg = 0 atk = 0 run = "" while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk = random.randrange(5) else: print "\nError" print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" #HERE raw_input("") ------------------------------------------------------------------------------------------------------------------------------------------- And I tired to add a while loop to make the program able to run again. But, it doesn't work.. ------------------------------------------------------------------------------------------------------------------------------------------- import random print \ """ Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and archer: ") mob = 300 hit = 0 hp = 100 dmg = 0 atk = 0 run = "" while True: while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk = random.randrange(5) else: print "\nError" print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" run = raw_input("\n\nrun or exit ") #This Part if run == "exit": break elif run == "run": continue else: raw_input("\nError") break ------------------------------------------------------------------------------------------------------------------------------------------- _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From william.ohiggins at utoronto.ca Fri May 20 20:38:47 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Fri, 20 May 2005 14:38:47 -0400 Subject: [Tutor] dictionary values in strings In-Reply-To: <81F6DBE7-5764-49F2-B356-5F97798B6361@yahoo.fr> References: <20050519194953.GA24831@sillyrabbi.dyndns.org> <81F6DBE7-5764-49F2-B356-5F97798B6361@yahoo.fr> Message-ID: <20050520183847.GA30941@sillyrabbi.dyndns.org> On Thu, May 19, 2005 at 09:47:50PM +0100, Max Noel wrote: > >On May 19, 2005, at 20:49, William O'Higgins wrote: > >>I am trying to discover the syntax for call on a dictionary of >>lists by >>key and index. >> >>The data structure looks like this: >> >>dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ >>'key3':['li1'li2,'li3','']} >> >>The keys are passed to a function as arguments, and I want the >>value of >>the specified list index. This is what I *thought* it would look >>like: >> >>dol.key(argument)[0] # would return li1 when argument equals key1 > What you are looking for can be achieved like this: > >>>> dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\ >... 'key3':['li1', 'li2','li3','']} >>>> dol['key1'][0] >'li1' Ah, of course, it makes sense that an associative array, referenced one array at a time, would use array notation. Ah, crap, I'm speaking Perl again. Make that "it makes sense that a linked list, referenced one list at a time, would use list notation". Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050520/193a6910/attachment.pgp From william.ohiggins at utoronto.ca Fri May 20 20:45:01 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Fri, 20 May 2005 14:45:01 -0400 Subject: [Tutor] creating files on open() Message-ID: <20050520184501.GB30941@sillyrabbi.dyndns.org> When I am open()-ing a file, I sort of expect that if the file doesn't exist that it would be created, but it doesn't, it whines about it instead. So, how do I create a file with Python? I've looked all over, but I'm obviously missing something. Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050520/272e196a/attachment.pgp From kent37 at tds.net Fri May 20 20:59:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 May 2005 14:59:23 -0400 Subject: [Tutor] creating files on open() In-Reply-To: <20050520184501.GB30941@sillyrabbi.dyndns.org> References: <20050520184501.GB30941@sillyrabbi.dyndns.org> Message-ID: <428E338B.6010409@tds.net> William O'Higgins wrote: > When I am open()-ing a file, I sort of expect that if the file doesn't > exist that it would be created, but it doesn't, it whines about it > instead. So, how do I create a file with Python? I've looked all over, > but I'm obviously missing something. Thanks. Opening a file for writing will create it: f = open('myfile.txt', 'w') Kent From william.ohiggins at utoronto.ca Fri May 20 21:10:43 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Fri, 20 May 2005 15:10:43 -0400 Subject: [Tutor] creating files on open() In-Reply-To: <3511dc7505052011487593f926@mail.gmail.com> References: <20050520184501.GB30941@sillyrabbi.dyndns.org> <3511dc7505052011487593f926@mail.gmail.com> Message-ID: <20050520191043.GA31136@sillyrabbi.dyndns.org> On Fri, May 20, 2005 at 01:48:19PM -0500, Kristian Zoerhoff wrote: >On 5/20/05, William O'Higgins wrote: >> When I am open()-ing a file, I sort of expect that if the file doesn't >> exist that it would be created, but it doesn't, it whines about it >> instead. So, how do I create a file with Python? I've looked all over, >> but I'm obviously missing something. Thanks. > >How are you opening the file? It will be created if you open in write >or append mode (w or a), but not in read-only (r) mode. Fascinating. I was opening the file read-write (r+) and it didn't work. Are there only the few file-access methods (read (r), write (w), append (a) and read-write (r+))? Sometimes I like to prepend or to clobber or to address in binary mode - are these things possible, or do I have to seek() to prepend and delete to clobber? Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050520/a85eacf1/attachment.pgp From kristian.zoerhoff at gmail.com Fri May 20 21:34:08 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Fri, 20 May 2005 14:34:08 -0500 Subject: [Tutor] creating files on open() In-Reply-To: <20050520191043.GA31136@sillyrabbi.dyndns.org> References: <20050520184501.GB30941@sillyrabbi.dyndns.org> <3511dc7505052011487593f926@mail.gmail.com> <20050520191043.GA31136@sillyrabbi.dyndns.org> Message-ID: <3511dc7505052012346cf97042@mail.gmail.com> On 5/20/05, William O'Higgins wrote: > > Fascinating. I was opening the file read-write (r+) and it didn't work. > Are there only the few file-access methods (read (r), write (w), append > (a) and read-write (r+))? Sometimes I like to prepend or to clobber or > to address in binary mode - are these things possible, or do I have to > seek() to prepend and delete to clobber? Thanks. If you're intending to clobber, I'd open in write binary (wb) mode. I don't think I've ever used r+, as using w or wb should still give you read-write access. -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From albertito_g at hotmail.com Fri May 20 21:51:15 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 20 May 2005 19:51:15 +0000 Subject: [Tutor] Crossfire problem Message-ID: Hey everyone I have a very big problem with two versions of Python (2.2.2 and 2.3.4) over Linux Red Hat 9.0 I'll try to be as explicit as I can In the version 2.2.2 I have the module MySQLdb running but not the datetime module. In the version 2.3.4 I have the module datetime running but not the MySQLdb module. I need both modules running in the same version. I have tried to install MySQLdb for Python 2.3.4 but no luck and I read several documents telling me the steps to follow (in fact I posted yesterday the errors I got) and still no luck. These are the commands I need from datetime module. Is there another way to get this info???? hoy=datetime.datetime.now() # Today's date and time as a tuple dia=days[hoy.isoweekday()] # Today's dayweek as integer from 0 to 6 grupo=datetime.datetime.today().strftime("%Y%m%d%H%M%S") # string today's date and time I was looking for the datetime module so I can copy it to the libraries of Python 2.3.4. About this first I couldn't find the datetime.py in the version I'm using over Windows and second where should be located the libraries in Linux????? Thank you very much in advanced Alberto From administrata at hotmail.com Fri May 20 22:36:06 2005 From: administrata at hotmail.com (. ,) Date: Fri, 20 May 2005 20:36:06 +0000 Subject: [Tutor] Need some advice. Message-ID: It works fine but, at the end of the program total damage has to be shown. Only single damage is shown. How can i change it? ------------------------------------------------------------------------------------------------------------------------------------------- import random print \ """ Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and archer: ") mob = 300 hit = 0 hp = 100 dmg = 0 atk = 0 run = "" while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk = random.randrange(5) else: print "\nError" print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" #HERE raw_input("") ------------------------------------------------------------------------------------------------------------------------------------------- And I tired to add a while loop to make the program able to run again. But, it doesn't work.. ------------------------------------------------------------------------------------------------------------------------------------------- import random print \ """ Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and archer: ") mob = 300 hit = 0 hp = 100 dmg = 0 atk = 0 run = "" while True: while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk = random.randrange(5) else: print "\nError" print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" run = raw_input("\n\nrun or exit ") #This Part if run == "exit": break elif run == "run": continue else: raw_input("\nError") break ------------------------------------------------------------------------------------------------------------------------------------------- _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From denise.hartley at gmail.com Fri May 20 23:00:00 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 20 May 2005 14:00:00 -0700 Subject: [Tutor] Is anyone still working on the Python Riddles? #12 Message-ID: <8daabe5605052014004a491bf3@mail.gmail.com> Hello everyone! I know the thread has died down to nothing, but I was wondering, is anyone still working on the python challenges? I managed to get to #12 (!!) and feel like I'm learning a lot, especially about PIL. I'm stuck on this one now, tho, and it seems like everyone in the forum got the beginning part before they started asking questions, because they're way ahead of me! That usually seems to be the case for me. If I can get the initial file or find the sequence or puzzle or whatever, I can usually at least figure out things to try on it. It's getting to the riddle that is the hard part for me. I know this one is another image manipulation exercise (or at least partly so), but am not sure what elements are merged/shuffled in that I need to work with. I tried splitting RGB but that wasn't it (I keep hoping that will solve one of these upcoming riddles, since it's a trick I figured out on my own, but it hasnt come up yet, ha ha). The forums sounded like there were lots of 'hints' (something about five objects?), but I plugged a bunch of things into the url looking for hints and found nothing but 404's. If anyone is still working on these (or got past 12), do you have any pointers? Thanks! ~Denise From kent37 at tds.net Sat May 21 00:06:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 May 2005 18:06:40 -0400 Subject: [Tutor] Crossfire problem In-Reply-To: References: Message-ID: <428E5F70.1010707@tds.net> Alberto Troiano wrote: > These are the commands I need from datetime module. Is there another way to > get this info???? > > hoy=datetime.datetime.now() # Today's date and time as a tuple > dia=days[hoy.isoweekday()] # Today's dayweek as integer from 0 to 6 > grupo=datetime.datetime.today().strftime("%Y%m%d%H%M%S") # string today's > date and time These functions are all available in the time module which is older than datetime: >>> import time >>> hoy = time.localtime() >>> hoy (2005, 5, 20, 18, 1, 56, 4, 140, 1) >>> hoy.tm_wday 4 >>> time.strftime("%Y%m%d%H%M%S") '20050520180243' > I was looking for the datetime module so I can copy it to the libraries of > Python 2.3.4. Google 'python datetime 2.2' for some alternatives. Kent From rschroev_nospam_ml at fastmail.fm Sat May 21 00:11:23 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 21 May 2005 00:11:23 +0200 Subject: [Tutor] Is anyone still working on the Python Riddles? #12 In-Reply-To: <8daabe5605052014004a491bf3@mail.gmail.com> References: <8daabe5605052014004a491bf3@mail.gmail.com> Message-ID: D. Hartley wrote: > Hello everyone! > > I know the thread has died down to nothing, but I was wondering, is > anyone still working on the python challenges? I managed to get to #12 > (!!) and feel like I'm learning a lot, especially about PIL. > > I'm stuck on this one now, tho, and it seems like everyone in the > forum got the beginning part before they started asking questions, > because they're way ahead of me! That usually seems to be the case for > me. If I can get the initial file or find the sequence or puzzle or > whatever, I can usually at least figure out things to try on it. It's > getting to the riddle that is the hard part for me. > > I know this one is another image manipulation exercise (or at least > partly so), but am not sure what elements are merged/shuffled in that > I need to work with. I tried splitting RGB but that wasn't it (I keep > hoping that will solve one of these upcoming riddles, since it's a > trick I figured out on my own, but it hasnt come up yet, ha ha). The > forums sounded like there were lots of 'hints' (something about five > objects?), but I plugged a bunch of things into the url looking for > hints and found nothing but 404's. > > If anyone is still working on these (or got past 12), do you have any pointers? Well I'm stuck too now, but not on level 12 anymore. I certainly know the feeling; I've been stuck on 12 for quite some time too. Level 12 initially looks similar to level 11, but appearances lie. Instead look at the filename of the picture: evil1.jpg. What's that number doing there? None of the previous levels had it. Well, once there's a number, you might as well play with it. For example, try to increment it. (also note the number of piles of cards in evil1.jpg, and the numbers written on the back of the cards). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From carroll at tjc.com Sat May 21 00:18:24 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 20 May 2005 15:18:24 -0700 (PDT) Subject: [Tutor] OT (humor): amusing TV listing Message-ID: While I admit this is off-topic for the Tutor list, I know that a lot of us who are refugees from Perl would find this TV listing and accompanying warning amusing: http://www.xcom2002.com/doh/index.php?s=04113018oth From albertito_g at hotmail.com Sat May 21 00:29:54 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Fri, 20 May 2005 22:29:54 +0000 Subject: [Tutor] Crossfire problem In-Reply-To: <428E5F70.1010707@tds.net> Message-ID: Thank you very much Kent That solved my entire problem Best Regards Alberto >From: Kent Johnson >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Crossfire problem >Date: Fri, 20 May 2005 18:06:40 -0400 > >Alberto Troiano wrote: > > These are the commands I need from datetime module. Is there another way >to > > get this info???? > > > > hoy=datetime.datetime.now() # Today's date and time as a tuple > > dia=days[hoy.isoweekday()] # Today's dayweek as integer from 0 to 6 > > grupo=datetime.datetime.today().strftime("%Y%m%d%H%M%S") # string >today's > > date and time > >These functions are all available in the time module which is older than >datetime: > >>> import time > >>> hoy = time.localtime() > >>> hoy >(2005, 5, 20, 18, 1, 56, 4, 140, 1) > >>> hoy.tm_wday >4 > >>> time.strftime("%Y%m%d%H%M%S") >'20050520180243' > > > I was looking for the datetime module so I can copy it to the libraries >of > > Python 2.3.4. > >Google 'python datetime 2.2' for some alternatives. > >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Sat May 21 00:54:42 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 20 May 2005 23:54:42 +0100 Subject: [Tutor] "classmethods" References: <59bccc99d82d973cc3855bb0ef978ff9@uni-mainz.de> Message-ID: <026b01c55d8e$e9561840$358c8651@xp> > Now, how do I create an instance of MyClass when calling: x = MyClass.fromfile(path) ? Why not use an instance method and just do: x = MyClass().fromFile(path) provided fromPath() returns self there should be no problem. That is, MyClass looks like: class MyClass: def __init__(self): pass def fromFile(self, fname): f = open(fname,'r') self.attribute = f.readline().strip() self.attribute1 = f.readline().strip() self.attribute2 = f.readline().strip() f.close() return self > return parameter1,parameter2,...,d Instead of returning them you store them in the object. Or am I missing something? It is possible to write true class methods but I'm not sure this is the best place to use them. Alan G. From alan.gauld at freenet.co.uk Sat May 21 00:58:03 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 20 May 2005 23:58:03 +0100 Subject: [Tutor] Comparing a string References: <428DB13D.3040306@softhome.net> Message-ID: <027001c55d8f$613050b0$358c8651@xp> > I'm tryin compare a string with a value with style of pattern-matching. > > string = 'i686' > > if string == glob.glob(i?86): Use regular expressions and turn it around: import re s = 'i686' ex = re.compile('i?86') if ex.match(s): print 'they match!' Is that what you mean? Alan G. From alan.gauld at freenet.co.uk Sat May 21 01:37:02 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 21 May 2005 00:37:02 +0100 Subject: [Tutor] printing documents References: <20050520131219.65478.qmail@web30508.mail.mud.yahoo.com> Message-ID: <028601c55d94$d36baf80$358c8651@xp> > I am writing a program to store name/contact/business transaction > information. I would like the ability to print out a form for each > client with all this stored information. Can somone point me in the > write direction for printing documents. I usually just create html files. PDF would work too but is less programmer friendly in native form. > Also I would like to take the information I input and store it as > an images. Essentially take the above mentioned document In that case I'd go with a PDF file which does both jobs in one and batch printing can be done from Acrobat using: http://www.reportlab.org/rl_toolkit.html to create the PDF and the /p flag in acrobat. Alan G. From alan.gauld at freenet.co.uk Sat May 21 01:41:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 21 May 2005 00:41:38 +0100 Subject: [Tutor] creating files on open() References: <20050520184501.GB30941@sillyrabbi.dyndns.org><3511dc7505052011487593f926@mail.gmail.com><20050520191043.GA31136@sillyrabbi.dyndns.org> <3511dc7505052012346cf97042@mail.gmail.com> Message-ID: <02b901c55d95$77bca850$358c8651@xp> > to address in binary mode - are these things possible, or do I have to > seek() to prepend and delete to clobber? Thanks. Using seek() will not prepend it will overwrite! To prepend you will have to write out your preamble then append the existing data to that. There is no random access mechanism in Python other than seek() You can't create fixed length records and navigate through them as you can in some other languages. (you can of course use format strings to fake this but its messier than true random record access) Alan G. From singingxduck at gmail.com Sat May 21 05:03:57 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 20 May 2005 23:03:57 -0400 Subject: [Tutor] Python in HTML Message-ID: <428EA51D.1040707@gmail.com> Hello all, I've been trying to use javascript for coding something on a webpage, and I've just about given up on understanding the intricacies of why a given script will work now and not in 5 minutes, and why any bit of code longer than 5 lines doesn't behave as documented. Therefore, I thought it would be a smart idea if I could figure out how to somehow replace the javascript in the html with python. However, everything I've seen online seems to require installing something on the server, which I don't have access to. Any and all suggestions are appreciated. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3190 bytes Desc: S/MIME Cryptographic Signature Url : http://mail.python.org/pipermail/tutor/attachments/20050520/e2eed1eb/smime.bin From cyresse at gmail.com Sat May 21 05:15:09 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat, 21 May 2005 15:15:09 +1200 Subject: [Tutor] Python in HTML In-Reply-To: <428EA51D.1040707@gmail.com> References: <428EA51D.1040707@gmail.com> Message-ID: Hi Orri, I've pondered that too, and you're out of luck, I think. There is a Javascript/XUL/XBL/XPCOM interface in Mozilla browsers, it's quite low level and messy, and there's an XPCOM/Python interface also, but it's quite beta and hard to use. You can use Python like PHP or Perl, but it does need to be installed server side. For client-side execution, Javascript is the best way to go. If you want, send me your script that's not working, and I'll see if I can help, Javascript is a nasty beast at times. I also know some limited XPCOM stuff, if it would help any. Regards, Liam Clarke On 5/21/05, Orri Ganel wrote: > > Hello all, > > I've been trying to use javascript for coding something on a webpage, > and I've just about given up on understanding the intricacies of why a > given script will work now and not in 5 minutes, and why any bit of code > longer than 5 lines doesn't behave as documented. Therefore, I thought > it would be a smart idea if I could figure out how to somehow replace > the javascript in the html with python. However, everything I've seen > online seems to require installing something on the server, which I > don't have access to. Any and all suggestions are appreciated. > > Thanks in advance, > Orri > > -- > Email: singingxduck AT gmail DOT com > AIM: singingxduck > Programming Python for the fun of it. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050521/48083c43/attachment.html From meesters at uni-mainz.de Sat May 21 08:36:15 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Sat, 21 May 2005 08:36:15 +0200 Subject: [Tutor] "classmethods" In-Reply-To: <026b01c55d8e$e9561840$358c8651@xp> References: <59bccc99d82d973cc3855bb0ef978ff9@uni-mainz.de> <026b01c55d8e$e9561840$358c8651@xp> Message-ID: <959c8fcf8fbe3f82482aa8bd2fc14901@uni-mainz.de> Hi Thanks Kent and Alan for your input. Kent's example is working like a charm. It's just that I didn't find the time to give any feedback until now. Have a nice weekend! Christian From administrata at hotmail.com Sat May 21 11:58:15 2005 From: administrata at hotmail.com (. ,) Date: Sat, 21 May 2005 09:58:15 +0000 Subject: [Tutor] Running RPG game again. Message-ID: Hi, I'm trying to make the RPG game to be able to run again. But, when I type "run", nothing happens. thanks. ------------------------------------------------------------------------------------------------------------------------------------------- import random print \ """ Warrior - damage: 10~60 Archer - damage: 0~100 HP of Player: 100 HP of the monster: 300""" wp = raw_input("\n\nSelect between warrior and archer: ") mob = 300 hit = 0 hp = 100 dmg = 0 atk = 0 run = "" while True: while (mob > 0): hit += 1 mob = mob - dmg hp = hp - atk if wp == "warrior": dmg = random.randrange(50) + 10 atk = random.randrange(10) elif wp == "archer": dmg = random.randrange(100) atk = random.randrange(5) else: print "\nError" print "\n", hit, "hits" print "HP of", wp,":", hp,"/100" print "HP of the monster:", mob,"/300" print "\nYou defeated the monster by", hit,"hits,", dmg,"damage" run = raw_input("\nrun or exit ") if run == "run": continue else: break ------------------------------------------------------------------------------------------------------------------------------------------- _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From olli.rajala at gmail.com Sat May 21 12:17:04 2005 From: olli.rajala at gmail.com (Olli Rajala) Date: Sat, 21 May 2005 13:17:04 +0300 Subject: [Tutor] CGI-script and multilingual output (HTTP_ACCEPT_LANGUAGE) Message-ID: Well, I'm thinking about providing my site (at least some part of it) both in Finnish and English and would like to do it right. So, I decided that maybe I should try to use HTTP_ACCEPT_LANGUAGE, or am I completely wrong? I have some questions about it, though. I can access it through os.environ['HTTP_ACCEPT_LANGUAGE'] but have no idea how I should parse it. I mean, for example from my Firefox the output is like this 'fi,en;q=0.5' and because I'm not very good programmer, I don't know what would be the best way to check if surfer wants it in Finnish or in English. I could do something like this. languages = os.environ['HTTP_ACCEPT_LANGUAGE'].split(',') for temp in languages: if temp[:2] == 'fi' or temp[0:2] == 'en' language = temp[:2] break But I just doubt that it isn't the best or the right way to do it. I tried some Googling, but because don't know the proper terms, it wasn't very successful. So, any ideas would be very welcome! Yours, -- Olli Rajala <>< Tampere, Finland http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From kent37 at tds.net Sat May 21 12:29:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 May 2005 06:29:20 -0400 Subject: [Tutor] "classmethods" In-Reply-To: <428DB599.4000204@tds.net> References: <59bccc99d82d973cc3855bb0ef978ff9@uni-mainz.de> <428DB599.4000204@tds.net> Message-ID: <428F0D80.9010203@tds.net> Kent Johnson wrote: > Try this: > > def fromFile(path): > adict = {} > alist = [] > #... > #some part to read a file and to process data > return MyClass(parameter1,parameter2,...,d) > fromFile = staticmethod(fromFile) > > then client code will look like this: > aClass = MyClass.fromFile('a/file/path') A few more notes: - There is no need to make fromFile a staticmethod of MyClass, it could also be a module level function. Writing it as a staticmethod puts it in the namespace of MyClass which may be handy. - If you intend to subclass MyClass, the subclass constructors have compatible signatures and you want to be able to create subclasses with the same factory, a classmethod might work better. >>> class A(object): ... def __init__(self, val): ... self.val = val ... def show(self): ... print 'A.val:', self.val ... def factory(cls, val): ... return cls(val) ... factory = classmethod(factory) ... >>> a=A.factory(3) # calls A.factory(A, 3) >>> a.show() A.val: 3 >>> >>> class B(A): ... def show(self): ... print 'B.val:', self.val ... >>> b=B.factory(22) # calls A.factory(B, 22) >>> b.show() B.val: 22 - Finally, if you are using Python 2.4, you may prefer the decorator syntax for defining classmethods and staticmethods: class A(object): ... @classmethod def factory(cls, val): return cls(val) Kent From hashimoto.m at gmail.com Sat May 21 12:45:19 2005 From: hashimoto.m at gmail.com (Mitsuo Hashimoto) Date: Sat, 21 May 2005 19:45:19 +0900 Subject: [Tutor] difference between [[], [], []] and 3*[[]] Message-ID: <7c000468050521034543739ad2@mail.gmail.com> Hello, What's the difference between "[[], [], []]" and "3*[[]]" ? >>> a,b,c = [[], [], []] >>> id(a) 20609520 >>> id(b) 20722000 >>> id(c) 20721712 These ID is mutually different. But, >>> a,b,c = 3*[[]] >>> id(a) 20455728 >>> id(b) 20455728 >>> id(c) 20455728 >>> These are the same. On the other hand, >>> 3*[[]] [[], [], []] "[[], [], []]" is equal to "3*[[]]" or not ? After all, what should I do if I want to initialize a lot of lists ? For example a = [], b = [], c = [],...., z = [] Thanks in advance, Mitsuo From c.m.booth at durham.ac.uk Sat May 21 13:23:25 2005 From: c.m.booth at durham.ac.uk (Craig Booth) Date: Sat, 21 May 2005 12:23:25 +0100 (BST) Subject: [Tutor] Retrieving Webpage Source, a Problem with 'onclick' Message-ID: Hi, I am trying to loop over all of the links in a given webpage and retrieve the source of each of the child pages in turn. My problem is that the links are in the following form: [begin html] link1 link2 link3 link4 [end html] So clicking the links appears to call the Javascript function gS to dynamically create pages. I can't figure out how to get urllib/urllib2 to work here as the URL of each of these links is http://www.thehomepage.com/#. I have tried to get mechanize to click each link, once again it doesn't send the onclick request and just goes to http://www.thehomepage.com/# This blog (http://blog.tomtebo.org/programming/lagen.nu_tech_2.html) strongly suggests that the easiest way to do this is to use IE and COM automation (which is fine as I am working on a windows PC) so I have tried importing win32com.client and actually getting IE to click the link: [begin code] ie = Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.Navigate('http://www.thehomepage.com') #it takes a little while for page to load if ie.Busy: sleep(2) #Print page title print ie.LocationName test=ie.Document.links ie.Navigate(ie.Document.links(30)) [end code] Which should just click the 30th link on the page. As with the other methods this takes me to http://www.thehomepage/# and doesn't call the Javascript. If somebody who has more experience in these matters could suggest a course of action I would be grateful. I'm more than happy to use any method (urllib, mechanize, IE & COM as tried so far) just so long as it works :) Thanks in advance, Craig. From alan.gauld at freenet.co.uk Sat May 21 14:09:34 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 21 May 2005 13:09:34 +0100 Subject: [Tutor] Python in HTML References: <428EA51D.1040707@gmail.com> Message-ID: <02f101c55dfd$f3cbdca0$358c8651@xp> > it would be a smart idea if I could figure out how to somehow replace > the javascript in the html with python. However, everything I've seen > online seems to require installing something on the server, which I The problem lies not on the server but on the client. JavaScript support is embedded in every popular browser so it just works, but none of them know about python. Even if they did it would require the user to have Python installed, which you can't assume. It is possible to embed python in web pages on Windows and IE, using ActiveX scripting (Now called WSH) and the winall package includes a script to activate it. However that will still require the end users to have Python installed and the WSH feature for Python turned on - quite unlikely outside a closed user community. So sadly its back to JavaScript I'm afraid. OTOH I didn't find JavaScript to be too terrible, what kind of problems are you having? PS I couldn't reply to the original message because it had beebn digitally signed. Please don't do that when posting to public mailing lists folks! (Well, not if you want a reply!) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jonasmg at softhome.net Sat May 21 14:38:57 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sat, 21 May 2005 13:38:57 +0100 Subject: [Tutor] Exceptions for checking root, files Message-ID: <428F2BE1.3040603@softhome.net> Hi, I never haven't worked with exceptions, and I'm a little confused. In my programs I always build a function to check things as: - The user that runned the script is root - All the files and directories with whom I am going to work exist - etc else the program exits. Does this checks can be runned from an exception? P.S.: I did read http://www.python.org/doc/current/tut/node10.html From servando at mac.com Sat May 21 15:37:59 2005 From: servando at mac.com (Servando Garcia) Date: Sat, 21 May 2005 08:37:59 -0500 Subject: [Tutor] main() Message-ID: <698292aa961ad52ba8277c0a46f1a9da@mac.com> if __name__ == '__main__': what is the meaning and importance of this code line. I have been able to glean some information. When you call a script __name__ is set to the "Name" of the script called. example: python Hope.py __name__ = Hope but why would I want to do this if __name__ == '__main__': here a code snippet that I am trying to work through # # MAIN # if __name__ == '__main__': import sys filename = sys.argv[1] f = open(filename) generate(semantic(parse(scan(f)))) f.close() I feel that if I am calling the script Hope.py than the above code should never get to run because __name__ is equal to "Hope" so why even write it. From kent37 at tds.net Sat May 21 16:01:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 May 2005 10:01:14 -0400 Subject: [Tutor] difference between [[], [], []] and 3*[[]] In-Reply-To: <7c000468050521034543739ad2@mail.gmail.com> References: <7c000468050521034543739ad2@mail.gmail.com> Message-ID: <428F3F2A.3050906@tds.net> Mitsuo Hashimoto wrote: > Hello, > > What's the difference between "[[], [], []]" and "3*[[]]" ? [[], [], []] makes a list containing references to three different lists. 3*[[]] makes a list with three references to the *same* list. This can cause surprising behavior: >>> l=3*[[]] >>> l [[], [], []] >>> l[0].append(1) >>> l [[1], [1], [1]] Because each list in l is the same, changing one changes them all. This is probably not what you want. > After all, what should I do if I want to initialize a lot of lists ? > For example a = [], b = [], c = [],...., z = [] Why do you want to do this? Often using a dict is a good solution to this type of question. For example: >>> import string >>> d={} >>> for c in string.ascii_lowercase: ... d[c] = [] ... >>> d {'a': [], 'c': [], 'b': [], 'e': [], 'd': [], 'g': [], 'f': [], 'i': [], 'h': [], 'k': [], 'j': [], 'm': [], 'l': [], 'o': [], 'n': [], 'q': [], 'p': [], 's': [], 'r': [], 'u': [], 't': [], 'w': [], 'v': [], 'y': [], 'x': [], 'z': []} >>> Kent From kent37 at tds.net Sat May 21 16:05:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 May 2005 10:05:17 -0400 Subject: [Tutor] Retrieving Webpage Source, a Problem with 'onclick' In-Reply-To: References: Message-ID: <428F401D.2080405@tds.net> You may be interested in Pamie: http://pamie.sourceforge.net/ Kent Craig Booth wrote: > Hi, > > I am trying to loop over all of the links in a given webpage and > retrieve the source of each of the child pages in turn. > > My problem is that the links are in the following form: > > [begin html] > link1 > link2 > link3 > link4 > [end html] > > So clicking the links appears to call the Javascript function gS to > dynamically create pages. > > I can't figure out how to get urllib/urllib2 to work here as the URL of > each of these links is http://www.thehomepage.com/#. > > I have tried to get mechanize to click each link, once again it doesn't > send the onclick request and just goes to http://www.thehomepage.com/# > > This blog (http://blog.tomtebo.org/programming/lagen.nu_tech_2.html) > strongly suggests that the easiest way to do this is to use IE and COM > automation (which is fine as I am working on a windows PC) so I have tried > importing win32com.client and actually getting IE to click the link: > > [begin code] > > ie = Dispatch("InternetExplorer.Application") > ie.Visible = 1 > ie.Navigate('http://www.thehomepage.com') > > #it takes a little while for page to load > if ie.Busy: > sleep(2) > > #Print page title > print ie.LocationName > > test=ie.Document.links > ie.Navigate(ie.Document.links(30)) > > [end code] > > Which should just click the 30th link on the page. As with the other > methods this takes me to http://www.thehomepage/# and doesn't call the > Javascript. > > If somebody who has more experience in these matters could suggest a > course of action I would be grateful. I'm more than happy to use any > method (urllib, mechanize, IE & COM as tried so far) just so long as it > works :) > > Thanks in advance, > Craig. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From amonroe at columbus.rr.com Sat May 21 16:55:41 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 21 May 2005 10:55:41 -0400 Subject: [Tutor] Running RPG game again. In-Reply-To: References: Message-ID: <281213010536.20050521105541@columbus.rr.com> > I'm trying to make the RPG game to be able to run again. > But, when I type "run", nothing happens. It's because your continue statement on line 45 loops around to line 19 (I double checked in the debugger). Then it checks if the monster is still alive (AGAIN) on line 20, but the monster is already dead, so the whole inner while loop is skipped and the program will jump straight to line 43 again. You might want to change your outermost while loop to something like this: iloveplaying=1 while iloveplaying: (move all the variable setup inside the main while loop that way the monster is reborn every time you play) while (mob>0): (do all the fighting stuff here as normal) run = raw_input("\nrun or exit ") if run != "run": iloveplaying=0 Alan From administrata at hotmail.com Sat May 21 19:10:31 2005 From: administrata at hotmail.com (. ,) Date: Sat, 21 May 2005 17:10:31 +0000 Subject: [Tutor] Debugger? Message-ID: Hi, I see so many errors when i execute my programs. Where can i get debugger for python? or How can i debug a prgram? Thanks. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From jonasmg at softhome.net Sat May 21 19:43:11 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sat, 21 May 2005 18:43:11 +0100 Subject: [Tutor] Checking and showing all errors before of exit Message-ID: <428F732F.50003@softhome.net> Is there any way of checking all possible errors, show you all error messages, and then exit. If i use :: sys.exit("error message") :: it only shows this error message before of exit. Thanks in advance! From rschroev_nospam_ml at fastmail.fm Sat May 21 19:48:38 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 21 May 2005 19:48:38 +0200 Subject: [Tutor] main() In-Reply-To: <698292aa961ad52ba8277c0a46f1a9da@mac.com> References: <698292aa961ad52ba8277c0a46f1a9da@mac.com> Message-ID: Servando Garcia wrote: > > if __name__ == '__main__': > > what is the meaning and importance of this code line. I have been > able to glean some information. When you call a script __name__ is set > to the "Name" of the script called. example: python Hope.py > __name__ = Hope When Hope.py is a module imported into another script, then __name__ equals the name of the module as you say. Like this: ### HopeModule.py print __name__ ### Hope.py import HopeModule That will print 'HopeModule' if you run python Hope.py But if the scrip itself is run, __name__ will equal '__main__': ### Hope.py print __name__ Now python Hope.py prints '__main__', contrary to what you said. Did you try it? If your installation does otherwise, it seems there is something wrong. > but why would I want to do this if __name__ == '__main__': From the above it follows that code following if __name__ == '__main__': gets executed when the script itself is run, but not when it is import edas a module by another script. > here a code snippet that I am trying to work through > > # > # MAIN > # > > if __name__ == '__main__': > import sys > filename = sys.argv[1] > f = open(filename) > generate(semantic(parse(scan(f)))) > f.close() > > I feel that if I am calling the script Hope.py than the above code > should never get to run because __name__ is equal to "Hope" so why even > write it. Did you try that? The code should really be executed. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From alan.gauld at freenet.co.uk Sat May 21 22:15:25 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 21 May 2005 21:15:25 +0100 Subject: [Tutor] main() References: <698292aa961ad52ba8277c0a46f1a9da@mac.com> Message-ID: <001901c55e41$d33d1cd0$bfad8651@xp> > able to glean some information. When you call a script __name__ is set > to the "Name" of the script called. example: python Hope.py > __name__ = Hope Actually no. When you *import* a file its name is set to the file name(or more acurately the module name) When you run a file from the command line like python Hope.py then __name__ is set to __main__ > but why would I want to do this if __name__ == '__main__': So this line lets you create code that is executed when the file is run from the command line but not when the file is imported. Alan G. From alan.gauld at freenet.co.uk Sat May 21 22:19:28 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 21 May 2005 21:19:28 +0100 Subject: [Tutor] Debugger? References: Message-ID: <001e01c55e42$641b9970$bfad8651@xp> > I see so many errors when i execute my programs. > > Where can i get debugger for python? or How can i debug a prgram? import pdb gets you the standard python debugger. But IDLE and Pythonwin etc have their own builtin graphical debuggers too. But if you are getting a lot of errors the debugger is the wrong place to look. DEbuggers are for deep diagnostics when the simple things fail and usually only used on a single obscure fault at a time. To deal with lots of errors use the >>> prompt to try things out before committing them to a file. THen import the "finished" file and try exercising the functions classes one by one from the >>> prompt. Finally insert print statements at suitable points, and only after doing all of that try the debugger. The best debugger of all is the one between your ears! Alan G. From singingxduck at gmail.com Sat May 21 23:22:44 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sat, 21 May 2005 17:22:44 -0400 Subject: [Tutor] Python in HTML In-Reply-To: <02f101c55dfd$f3cbdca0$358c8651@xp> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> Message-ID: <428FA6A4.70209@gmail.com> Alan G wrote: > The problem lies not on the server but on the client. > JavaScript support is embedded in every popular browser so it just > works, but none of them know about python. Even if they did it would > require the user to have Python installed, which you can't assume. > > It is possible to embed python in web pages on Windows and IE, using > ActiveX scripting (Now called WSH) and the winall package includes a > script to activate it. However that will still require the end users > to have Python installed and the WSH feature for Python turned on > - quite unlikely outside a closed user community. > > So sadly its back to JavaScript I'm afraid. OTOH I didn't find > JavaScript > to be too terrible, what kind of problems are you having? > > PS > I couldn't reply to the original message because it had beebn > digitally signed. Please don't do that when posting to public mailing > lists folks! (Well, not if you want a reply!) > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Well, my problems in particular have been getting a bit of code to work at all, and when working, get it to behave as it should. It's really a trivial bit of code. All it does is control the behavior of a 'darkplayer' - a javscript mp3 player - for an online journal. The specific bit of code I'm having trouble with is the part that selects a random song from the playlist. To make sure every song is selected at least once, i tried to copy the playlist and have it choose songs from the copy, removing each song as it is played, and refilling the copy when it is empty. The code follows (apologies in advance for tabbing issues as it was edited in notepad):


-- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From cyresse at gmail.com Sat May 21 23:27:11 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun, 22 May 2005 09:27:11 +1200 Subject: [Tutor] Retrieving Webpage Source, a Problem with 'onclick' In-Reply-To: <428F401D.2080405@tds.net> References: <428F401D.2080405@tds.net> Message-ID: Wow, I was going to give a rundown of how to use COM, but use that PAMIE instead to do it, it's way easier. If you do want to use COM & win32all instead, just bear in mind that the way to simulate an OnClick is to use taken from the blog you quoted) - ie.Document.frames(1).Document.forms(0).all.item(\"buttonSok\").click() But yeah, use PAMIE instead. Regards, Liam Clarke PS Cheers for the link also Kent. On 5/22/05, Kent Johnson wrote: > > You may be interested in Pamie: > http://pamie.sourceforge.net/ > > Kent > > Craig Booth wrote: > > Hi, > > > > I am trying to loop over all of the links in a given webpage and > > retrieve the source of each of the child pages in turn. > > > > My problem is that the links are in the following form: > > > > [begin html] > > link1 > > link2 > > link3 > > link4 > > [end html] > > > > So clicking the links appears to call the Javascript function gS to > > dynamically create pages. > > > > I can't figure out how to get urllib/urllib2 to work here as the URL of > > each of these links is http://www.thehomepage.com/#. > > > > I have tried to get mechanize to click each link, once again it doesn't > > send the onclick request and just goes to http://www.thehomepage.com/# > > > > This blog (http://blog.tomtebo.org/programming/lagen.nu_tech_2.html) > > strongly suggests that the easiest way to do this is to use IE and COM > > automation (which is fine as I am working on a windows PC) so I have > tried > > importing win32com.client and actually getting IE to click the link: > > > > [begin code] > > > > ie = Dispatch("InternetExplorer.Application") > > ie.Visible = 1 > > ie.Navigate('http://www.thehomepage.com') > > > > #it takes a little while for page to load > > if ie.Busy: > > sleep(2) > > > > #Print page title > > print ie.LocationName > > > > test=ie.Document.links > > ie.Navigate(ie.Document.links(30)) > > > > [end code] > > > > Which should just click the 30th link on the page. As with the other > > methods this takes me to http://www.thehomepage/# and doesn't call the > > Javascript. > > > > If somebody who has more experience in these matters could suggest a > > course of action I would be grateful. I'm more than happy to use any > > method (urllib, mechanize, IE & COM as tried so far) just so long as it > > works :) > > > > Thanks in advance, > > Craig. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050522/81288e64/attachment.htm From administrata at hotmail.com Sun May 22 00:31:09 2005 From: administrata at hotmail.com (. ,) Date: Sat, 21 May 2005 22:31:09 +0000 Subject: [Tutor] While loop exercise Message-ID: Hi, I just finished the chapter which includes while loop, if-else-elif structure and randrange(). Can anyone suggest me 3 exercises to remind of the chapter? Exercises shouldn't be too difficult because i'm newbie! Looking forward to writing some programs! Thanks. _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From alan.gauld at freenet.co.uk Sun May 22 00:50:57 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 21 May 2005 23:50:57 +0100 Subject: [Tutor] Python in HTML References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> Message-ID: <000401c55e57$8ddcf140$0db78851@xp> > specific bit of code I'm having trouble with is the part that selects a > random song from the playlist. To make sure every song is selected at > least once, i tried to copy the playlist and have it choose songs from > the copy, removing each song as it is played, and refilling the copy > when it is empty. OK, so what happened? Did you start just making the copy and playing the songs from the copy? Did that work OK? Does the random number generation work - I assume you tested that by just writing out the sequence of numbers first? And finally when you use the random numbvers to select songs does it pick the songs as you expect? I still don't know what we are looking for as a problem? But writing code in Javaript is like any other language, except the debugging environment of poorer! You start doing the easy things and build on features one by one, fixing as you go. As soon as you get a feature working put it in a function. It keeps the working code and experimental stuff separate! Alan G. From singingxduck at gmail.com Sun May 22 02:07:22 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sat, 21 May 2005 20:07:22 -0400 Subject: [Tutor] Python in HTML In-Reply-To: <000401c55e57$8ddcf140$0db78851@xp> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> Message-ID: <428FCD3A.6080309@gmail.com> Alan G wrote: >OK, so what happened? >Did you start just making the copy and playing the songs from the >copy? >Did that work OK? > >Does the random number generation work - I assume you tested that by >just writing out the sequence of numbers first? > >And finally when you use the random numbvers to select songs does it >pick the songs as you expect? > >I still don't know what we are looking for as a problem? > >But writing code in Javaript is like any other language, except >the debugging environment of poorer! You start doing the easy things >and build on features one by one, fixing as you go. As soon as you >get a feature working put it in a function. It keeps the working code >and experimental stuff separate! > >Alan G. > Well, like I said, the darkplayer is on an online journal, which means that the only output possible is modifying the option strings of songs as they are played or something similar. I do know that the random number generator works, and the songs played always match the option selected. However, this was before adding the bit about copying the songs and playing from the copy. The last fully functional version (without the 'play all songs once' feature) is as follows:


-- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From ejp at zomething.com Sun May 22 07:24:05 2005 From: ejp at zomething.com (EJP) Date: Sat, 21 May 2005 21:24:05 -0800 Subject: [Tutor] Python in HTML In-Reply-To: <428FCD3A.6080309@gmail.com> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> Message-ID: <20050521212405.1692394451.ejp@zomething.com> > Well, like I said, the darkplayer is on an online journal, which means > that the only output possible is modifying the option strings of songs > as they are played or something similar. I do know that the random > number generator works, and the songs played always match the option > selected. However, this was before adding the bit about copying the > songs and playing from the copy. The last fully functional version > (without the 'play all songs once' feature) is as follows: > > codeBase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 > type=application/x-oleobject height=0 standby="Loading Microsoft > Windows > Media Player components..." width=0 > classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95> > It's a bit off list topic, but I am interested to know how much functionality you have been successful to get going. I tried something very similar with Quicktime and Javascript, but seemed to wind up at a dead-end. My (premature?) conclusion was that once the audio player object was loaded, I could not reset certain parameters _in_that_object_ such as I would need to have it play an arbitrary file (url). My javascript was successful in changing the page parameters, as verified with DOM and print statements, but there seemed nothing to trigger the audio player to recognize those new parameters. IMO the great thing about Javascript is that you have a whole gui & application tied to it, so you can do a lot with very little code (sheer candy!); but the downside follows, that there you are utilizing a complex, fixed framework which constrains what you can do (bitter aftertaste)... and, of course, the development environment is not quite Pythonic. I hope you can get your Javascript - Windows Media Player interface to work. Unfortunately, I do not know how Python could be used within that interface... Good luck! Eric Pederson http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From cyresse at gmail.com Sun May 22 07:34:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun, 22 May 2005 17:34:00 +1200 Subject: [Tutor] Python in HTML In-Reply-To: <20050521212405.1692394451.ejp@zomething.com> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <20050521212405.1692394451.ejp@zomething.com> Message-ID: Well Orri, I found one bug, but I don't know if this'll fix it, it's in your copy playlist bit though. > for (var index = 0; index < songs.length; playable++) >{ >playable[index] = songs[index]; >} >} I believe you want to increment index, not playable. Um, man, that's what I hate about Javascript, it fails silently. I've never met a Javascript console... /me ponders Firefox plugin. Good luck, Liam Clarke On 5/22/05, EJP wrote: > > > > Well, like I said, the darkplayer is on an online journal, which means > > that the only output possible is modifying the option strings of songs > > as they are played or something similar. I do know that the random > > number generator works, and the songs played always match the option > > selected. However, this was before adding the bit about copying the > > songs and playing from the copy. The last fully functional version > > (without the 'play all songs once' feature) is as follows: > > > > > codeBase= > http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 > > type=application/x-oleobject height=0 standby="Loading Microsoft > > Windows > > Media Player components..." width=0 > > classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95> > > > > > It's a bit off list topic, but I am interested to know how much > functionality you have been successful to get going. I tried something very > similar with Quicktime and Javascript, but seemed to wind up at a dead-end. > My (premature?) conclusion was that once the audio player object was loaded, > I could not reset certain parameters _in_that_object_ such as I would need > to have it play an arbitrary file (url). > > My javascript was successful in changing the page parameters, as verified > with DOM and print statements, but there seemed nothing to trigger the audio > player to recognize those new parameters. > > IMO the great thing about Javascript is that you have a whole gui & > application tied to it, so you can do a lot with very little code (sheer > candy!); but the downside follows, that there you are utilizing a complex, > fixed framework which constrains what you can do (bitter aftertaste)... and, > of course, the development environment is not quite Pythonic. > > > I hope you can get your Javascript - Windows Media Player interface to > work. Unfortunately, I do not know how Python could be used within that > interface... > > Good luck! > > > > > Eric Pederson > http://www.songzilla.blogspot.com > > > ::::::::::::::::::::::::::::::::::: > domainNot="@something.com " > domainIs=domainNot.replace("s","z") > ePrefix="".join([chr(ord(x)+1) for x in "do"]) > mailMeAt=ePrefix+domainIs > ::::::::::::::::::::::::::::::::::: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050522/423a6fdd/attachment.html From cyresse at gmail.com Sun May 22 07:36:21 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun, 22 May 2005 17:36:21 +1200 Subject: [Tutor] Python in HTML In-Reply-To: References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <20050521212405.1692394451.ejp@zomething.com> Message-ID: Oops, I'm lazy - https://addons.mozilla.org/extensions/moreinfo.php?application=firefox&category=Developer%20Tools&numpg=10&id=216 There's a Javascript debugger. On 5/22/05, Liam Clarke wrote: > > Well Orri, > > I found one bug, but I don't know if this'll fix it, it's in your copy > playlist bit though. > > > for (var index = 0; index < songs.length; playable++) > >{ > >playable[index] = songs[index]; > >} > >} > > I believe you want to increment index, not playable. > > Um, man, that's what I hate about Javascript, it fails silently. I've > never met a Javascript console... > > /me ponders Firefox plugin. > > Good luck, > > Liam Clarke > On 5/22/05, EJP wrote: > > > > > > > Well, like I said, the darkplayer is on an online journal, which means > > > that the only output possible is modifying the option strings of songs > > > as they are played or something similar. I do know that the random > > > number generator works, and the songs played always match the option > > > selected. However, this was before adding the bit about copying the > > > songs and playing from the copy. The last fully functional version > > > (without the 'play all songs once' feature) is as follows: > > > > > > > > codeBase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 > > > type=application/x-oleobject height=0 standby="Loading Microsoft > > > Windows > > > Media Player components..." width=0 > > > classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95> > > > > > > > > > It's a bit off list topic, but I am interested to know how much > > functionality you have been successful to get going. I tried something very > > similar with Quicktime and Javascript, but seemed to wind up at a dead-end. > > My (premature?) conclusion was that once the audio player object was loaded, > > I could not reset certain parameters _in_that_object_ such as I would need > > to have it play an arbitrary file (url). > > > > My javascript was successful in changing the page parameters, as > > verified with DOM and print statements, but there seemed nothing to trigger > > the audio player to recognize those new parameters. > > > > IMO the great thing about Javascript is that you have a whole gui & > > application tied to it, so you can do a lot with very little code (sheer > > candy!); but the downside follows, that there you are utilizing a complex, > > fixed framework which constrains what you can do (bitter aftertaste)... and, > > of course, the development environment is not quite Pythonic. > > > > > > I hope you can get your Javascript - Windows Media Player interface to > > work. Unfortunately, I do not know how Python could be used within that > > interface... > > > > Good luck! > > > > > > > > > > Eric Pederson > > http://www.songzilla.blogspot.com > > > > > > ::::::::::::::::::::::::::::::::::: > > domainNot="@ something.com " > > domainIs=domainNot.replace("s","z") > > ePrefix="".join([chr(ord(x)+1) for x in "do"]) > > mailMeAt=ePrefix+domainIs > > ::::::::::::::::::::::::::::::::::: > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050522/84e1d2e1/attachment.htm From alan.gauld at freenet.co.uk Sun May 22 10:09:09 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 22 May 2005 09:09:09 +0100 Subject: [Tutor] Python in HTML References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> Message-ID: <000901c55ea5$889d4470$0db78851@xp> HI Orri, > >OK, so what happened? You still aren't telling us what happens. Its very hard to find a fault in a program when you have no idea what the problem is. The code is very likely doing what you have asked it to do, so when we read it it will seem to 'work' at a superficial level. Without a clear explanation of the problem you force the tutors to read every line closely, and speaking personally, I don't have enough free time for that, I need to know what I'm looking for. > Well, like I said, the darkplayer is on an online journal, which means > that the only output possible is modifying the option strings of songs > as they are played or something similar. I do know that the random > number generator works, and the songs played always match the option > selected. So you got a version working that played the sings in random order? Or did you write separate programs, one that demonstrated the random generator working and another that played songs with diffrerent options? > However, this was before adding the bit about copying the > songs and playing from the copy. So if you forget about playing the songs can you copy the songs and generate a random selection from the copy? Alan G. From ajikoe at gmail.com Sun May 22 13:06:12 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 22 May 2005 13:06:12 +0200 Subject: [Tutor] installing python 2.4.1 over 2.4 Message-ID: Hello, I have python 2.4. I would like to install python 2.4.1, Should I uninstall python 2.4, or just install 2.4.1? Does it effect my ide such as pydev and komodo ? Sincerely Yours, pujo From kent37 at tds.net Sun May 22 15:06:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 May 2005 09:06:50 -0400 Subject: [Tutor] Python in HTML In-Reply-To: References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <20050521212405.1692394451.ejp@zomething.com> Message-ID: <429083EA.5090805@tds.net> Liam Clarke wrote: > Um, man, that's what I hate about Javascript, it fails silently. I've > never met a Javascript console... > > /me ponders Firefox plugin. Firefox has a JavaScript console that can be helpful... Kent From cyresse at gmail.com Sun May 22 15:28:08 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 23 May 2005 01:28:08 +1200 Subject: [Tutor] Python in HTML In-Reply-To: <429083EA.5090805@tds.net> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <20050521212405.1692394451.ejp@zomething.com> <429083EA.5090805@tds.net> Message-ID: Yeah, I just found it. Embarrassed... document inspector is kinda cool too. On 5/23/05, Kent Johnson wrote: > > Liam Clarke wrote: > > Um, man, that's what I hate about Javascript, it fails silently. I've > > never met a Javascript console... > > > > /me ponders Firefox plugin. > > Firefox has a JavaScript console that can be helpful... > > Kent > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050523/3291b53b/attachment.html From singingxduck at gmail.com Sun May 22 15:59:05 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sun, 22 May 2005 09:59:05 -0400 Subject: [Tutor] Python in HTML In-Reply-To: <20050521212405.1692394451.ejp@zomething.com> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <20050521212405.1692394451.ejp@zomething.com> Message-ID: <42909029.4050702@gmail.com> EJP wrote: >>Well, like I said, the darkplayer is on an online journal, which means >>that the only output possible is modifying the option strings of songs >>as they are played or something similar. I do know that the random >>number generator works, and the songs played always match the option >>selected. However, this was before adding the bit about copying the >>songs and playing from the copy. The last fully functional version >>(without the 'play all songs once' feature) is as follows: >> >>>codeBase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 >>type=application/x-oleobject height=0 standby="Loading Microsoft >>Windows >>Media Player components..." width=0 >>classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95> >> >> >> > > >It's a bit off list topic, but I am interested to know how much functionality you have been successful to get going. I tried something very similar with Quicktime and Javascript, but seemed to wind up at a dead-end. My (premature?) conclusion was that once the audio player object was loaded, I could not reset certain parameters _in_that_object_ such as I would need to have it play an arbitrary file (url). > >My javascript was successful in changing the page parameters, as verified with DOM and print statements, but there seemed nothing to trigger the audio player to recognize those new parameters. > >IMO the great thing about Javascript is that you have a whole gui & application tied to it, so you can do a lot with very little code (sheer candy!); but the downside follows, that there you are utilizing a complex, fixed framework which constrains what you can do (bitter aftertaste)... and, of course, the development environment is not quite Pythonic. > > >I hope you can get your Javascript - Windows Media Player interface to work. Unfortunately, I do not know how Python could be used within that interface... > >Good luck! > > > > >Eric Pederson >http://www.songzilla.blogspot.com > > >::::::::::::::::::::::::::::::::::: >domainNot="@something.com" >domainIs=domainNot.replace("s","z") >ePrefix="".join([chr(ord(x)+1) for x in "do"]) >mailMeAt=ePrefix+domainIs >::::::::::::::::::::::::::::::::::: > > > > Well, since my method of 'resetting parameters' is to use buttons, whose purpose is defined in the script, I'm not entirely sure that I'm really changing anything. With the script I sent out, it worked in the sense that, every time the 'random' button was pressed, a song was selected randomly from the song list (meaning not every song was played before a song was re-played) and played. However, as soon as the song ends, in order to select a new song, random must be pressed again. Of course, it is possible at any time to select a song from the menu and hit play, just hit play to re-play the current song, pause the song, or stop it using the play, pause, and stop buttons. As for the interface with Windows Media Player, that is handled entirely within "http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701", whatever it may be. Less complicated versions of the darkplayer than mine can be found on many average journals at www.xanga.com. It is only when i started fooling around with it that it started to behave oddly. I added the random button without much trouble, and changed the random number generator as well, but i can't seem to be able to get this to work. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Sun May 22 16:04:26 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sun, 22 May 2005 10:04:26 -0400 Subject: [Tutor] Python in HTML In-Reply-To: <000901c55ea5$889d4470$0db78851@xp> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <000901c55ea5$889d4470$0db78851@xp> Message-ID: <4290916A.5000602@gmail.com> Alan G wrote: >HI Orri, > > > >>>OK, so what happened? >>> >>> > >You still aren't telling us what happens. Its very hard to find >a fault in a program when you have no idea what the problem is. >The code is very likely doing what you have asked it to do, >so when we read it it will seem to 'work' at a superficial level. > >Without a clear explanation of the problem you force the tutors >to read every line closely, and speaking personally, I don't have >enough free time for that, I need to know what I'm looking for. > > > >>Well, like I said, the darkplayer is on an online journal, which >> >> >means > > >>that the only output possible is modifying the option strings of >> >> >songs > > >>as they are played or something similar. I do know that the random >>number generator works, and the songs played always match the option >>selected. >> >> > >So you got a version working that played the sings in random order? >Or did you write separate programs, one that demonstrated the random >generator working and another that played songs with diffrerent >options? > > > >>However, this was before adding the bit about copying the >>songs and playing from the copy. >> >> > >So if you forget about playing the songs can you copy the songs and >generate a random selection from the copy? > >Alan G. > > > > Well, the language being Javascript, I unfortunately don't know what happened, because there are no IDE's for Javascript; it just fails silently, as Liam put it. The last working copy I had was one in which there was a random number generator selecting random songs directly from the song list, meaning that songs were re-played before every song had been played once. Since this sciprt goes into a 'javascript module' in a webjournal, the opportunity to write separate scripts is limited. It also doesn't help that there are no Javascript IDE's available. As far as I know, the problem lies within some small syntax error. Or, it may be a completely different problem. Due to the lack of output when Javascript crashes, I just don't know. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Sun May 22 16:06:48 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sun, 22 May 2005 10:06:48 -0400 Subject: [Tutor] Python in HTML In-Reply-To: <429083EA.5090805@tds.net> References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <20050521212405.1692394451.ejp@zomething.com> <429083EA.5090805@tds.net> Message-ID: <429091F8.7030709@gmail.com> Kent Johnson wrote: > Liam Clarke wrote: > >> Um, man, that's what I hate about Javascript, it fails silently. I've >> never met a Javascript console... >> >> /me ponders Firefox plugin. > > > Firefox has a JavaScript console that can be helpful... > > Kent Many thanks. I was not aware of this. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3190 bytes Desc: S/MIME Cryptographic Signature Url : http://mail.python.org/pipermail/tutor/attachments/20050522/9a266611/smime-0001.bin From alan.gauld at freenet.co.uk Sun May 22 17:10:58 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 22 May 2005 16:10:58 +0100 Subject: [Tutor] Python in HTML References: <428EA51D.1040707@gmail.com> <02f101c55dfd$f3cbdca0$358c8651@xp> <428FA6A4.70209@gmail.com> <000401c55e57$8ddcf140$0db78851@xp> <428FCD3A.6080309@gmail.com> <000901c55ea5$889d4470$0db78851@xp> <4290916A.5000602@gmail.com> Message-ID: <004101c55ee0$75df2250$0db78851@xp> > >You still aren't telling us what happens. Its very hard to find > >a fault in a program when you have no idea what the problem is. > Well, the language being Javascript, I unfortunately don't know what > happened, because there are no IDE's for Javascript; it just fails > silently, as Liam put it. OK, unlock that silence by using lots of print statements (or document.write() in Javascript terms). Check the value of the strings you are using, the current index etc by printing them on the web page. Stub out the calls to the player until you are sure you are passing the correct values in. > there was a random number generator selecting random songs directly from > the song list, meaning that songs were re-played before every song had > been played once. So it sounds like an error in the copy mechanism... Liam(?) already pointed out one possible cause, but the key to working in any language is to break the program into bite size pieces and get them working bit by bit. Sometimes that means taking out a bit that was working before. > also doesn't help that there are no Javascript IDE's available. As far > as I know, the problem lies within some small syntax error. Actually there are a few JavaScript IDEs around, Microsoft do one for example. > be a completely different problem. Due to the lack of output when > Javascript crashes, I just don't know. There is a JavaScript console that you can display and it sometimes gives you some clues too. But the best bet is lots of write() statements IMHO. Also the fact its one big file shouldn't be a problem. Provided you make liberal use of functions to encapsulate the functionality and keep those together in the head of the html then the amount of code scattered through the html should be manageable. Alan G. From project5 at redrival.net Sun May 22 19:33:08 2005 From: project5 at redrival.net (Andrei) Date: Sun, 22 May 2005 17:33:08 +0000 (UTC) Subject: [Tutor] While loop exercise References: Message-ID: . , hotmail.com> writes: > I just finished the chapter which includes while loop, if-else-elif > structure and randrange(). > > Can anyone suggest me 3 exercises to remind of the chapter? The standard exercise which includes all three would be a number guessing game where the computer picks a number and the user guesses it (the opposite is also possible, but then randrange is not useful). A while loop is standard in *any* program that can be executed more than once. E.g. asking someone for a string is a single line of code, but asking for an unlimited number of strings directly requires a while loop. > Looking forward to writing some programs! At this stage there aren't many really useful application you can make, but you should use your fantasy. Pick a subject you know something about and make a simple application for it. I think there are lots of suitable subjects in maths, physics and children's games, but you can find suitable subjects in lots of other fields too. Other possible small programs using while and if (randrange is a bit exotic and not that useful): - let the user input names and dates of birth. Calculate membership fee to a club based on whether the person is a child, an adult or a senior citizen. - a quadradic formula solver (would have to check whether the determinant < 0) - a hangman game - a free fall calculator (given an object that is dropped from a certain height, calculate a table with its position as a function of time) - a quiz program about some topic you like (could even use randrange in this one to pick questions) - a program which combines some of the programs above - e.g. allow the user to play either number guessing or hangman. - a hotel booking application which allows making reservations for one or 2-person rooms and applies a discount if the reservation is on a day between monday and thursday. Yours, Andrei From nf6q at sbcglobal.net Sun May 22 19:42:09 2005 From: nf6q at sbcglobal.net (nf6q) Date: Sun, 22 May 2005 10:42:09 -0700 Subject: [Tutor] FS: Python Books Message-ID: <4290C471.8020004@sbcglobal.net> Hello Everyone. The following Python Books are in excess to my needs. I prefer to sell as one lot. XML Processing with Python by Sean McGrath. Web Programming in Python by Thiruvathukal,Christopher,Shafaee Programming Python by Mark Lutz The Quick Python Book. All books are in excellent condition and those that have a CD have them. All four books for $65.00 including shipping via USPS Media Mail to CONUS. PayPal prefer. thanks -- fernando From jonasmg at softhome.net Sun May 22 22:07:11 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sun, 22 May 2005 21:07:11 +0100 Subject: [Tutor] looking for a pattern in a lot of files Message-ID: <4290E66F.6050903@softhome.net> I've to looking for a pattern ('locale for') in a lot of files (/dir/*_[A-Z][A-Z]) it's goes ok any improvement about this code? how print the actual file? could i add an exception? by if there aren't files for line in fileinput.input(glob.glob(os.path.join (dir_locales, "*_[A-Z][A-Z]"))): if re.search("locale for", line): print line From singingxduck at gmail.com Sun May 22 22:54:01 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sun, 22 May 2005 16:54:01 -0400 Subject: [Tutor] Python in HTML Message-ID: <4290F169.3020202@gmail.com> Thanks to all who helped. It looks like I figured out what the problem was, with the use of mozilla's DOM inspector, js debugger, and JSIDE (a javascript ide) that I downloaded after googling "javascript ide" (it appears to be quite good). In any case, the whole issue was checking whether or not playable was empty. I used a single = instead of 2:


-- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From maxnoel_fr at yahoo.fr Mon May 23 00:28:57 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun, 22 May 2005 23:28:57 +0100 Subject: [Tutor] looking for a pattern in a lot of files In-Reply-To: <4290E66F.6050903@softhome.net> References: <4290E66F.6050903@softhome.net> Message-ID: On May 22, 2005, at 21:07, Jonas Melian wrote: > for line in fileinput.input(glob.glob(os.path.join > (dir_locales, "*_[A-Z][A-Z]"))): > if re.search("locale for", line): > print line If you're only looking for the occurrence of a string and not a regex pattern, you don't have to use regular expressions: if "locale for" in line: print line Works just as well, and is faster. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From shidai.liu at gmail.com Mon May 23 01:21:13 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Mon, 23 May 2005 00:21:13 +0100 Subject: [Tutor] [HELP]win32 shutdown, restart, logoff Message-ID: <33194d730505221621596a44b2@mail.gmail.com> Hi all, Any one know how to make a shutdown, restart, logoff call in windows os like 98, 2000 and xp? Implemented in python, can use python win32 extensions. But not os.system('rundll/shutodwn ...'). Thanks for your help. -- With best wishes! Shidai -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050523/c8eb8169/attachment.html From hashimoto.m at gmail.com Mon May 23 01:55:35 2005 From: hashimoto.m at gmail.com (Mitsuo Hashimoto) Date: Mon, 23 May 2005 08:55:35 +0900 Subject: [Tutor] difference between [[], [], []] and 3*[[]] In-Reply-To: <428F3F2A.3050906@tds.net> References: <7c000468050521034543739ad2@mail.gmail.com> <428F3F2A.3050906@tds.net> Message-ID: <7c0004680505221655853c4ad@mail.gmail.com> 2005/5/21, Kent Johnson : > 3*[[]] makes a list with three references to the *same* list. This can cause surprising behavior: > > >>> l=3*[[]] > >>> l > [[], [], []] > >>> l[0].append(1) > >>> l > [[1], [1], [1]] I see. > Often using a dict is a good solution to this type of question. I didn't notice a dict. Thank you, Mitsuo From cpu.crazy at gmail.com Mon May 23 01:54:56 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 22 May 2005 17:54:56 -0600 Subject: [Tutor] __init__.py Message-ID: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> I've seen many (python) "plugins" (some located in site-packages [windows here]) with the name __init__.py. What's their use? class foo: def __init__: print "this starts first" def foo1(): print "this comes later. Init initializes the chain of functions in this class Now, i've never used a program (i can't seem to grasp all the self, and other things in OOP yet) with __init__ but I know what __init__ does in a class, not as a file name. I'm asking this out of curiosity, not for help. JQ From jfouhy at paradise.net.nz Mon May 23 02:09:26 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 23 May 2005 12:09:26 +1200 (NZST) Subject: [Tutor] [HELP]win32 shutdown, restart, logoff In-Reply-To: <33194d730505221621596a44b2@mail.gmail.com> References: <33194d730505221621596a44b2@mail.gmail.com> Message-ID: <1116806966.42911f366aa3d@www.paradise.net.nz> Quoting Shidai Liu : > Any one know how to make a shutdown, restart, logoff call in windows os > like 98, 2000 and xp? Try this: win32api.InitiateSystemShutdown(None, 'Kaboom!', 2000, False, False) Parameters: 1. Computer to shutdown (None for lcoalhost) 2. Message to display. 3. Time in ms to display message (0 for no message). 4. Kill programs (False to allow user a chance to save their work). 5. Reboot or shutdown. If you are doing win32 programming, I strongly recommend Mark Hammond's book! (since that's where I got this information) Note that I have not tested this (in particular, it is possible I have the orientation of the two boolean parameters wrong). -- John. From shidai.liu at gmail.com Mon May 23 02:43:46 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Mon, 23 May 2005 01:43:46 +0100 Subject: [Tutor] [HELP]win32 shutdown, restart, logoff In-Reply-To: <1116806966.42911f366aa3d@www.paradise.net.nz> References: <33194d730505221621596a44b2@mail.gmail.com> <1116806966.42911f366aa3d@www.paradise.net.nz> Message-ID: <33194d73050522174322ff1b1f@mail.gmail.com> On 5/23/05, jfouhy at paradise.net.nz wrote: > > Quoting Shidai Liu : > > > Any one know how to make a shutdown, restart, logoff call in windows os > > like 98, 2000 and xp? > > Try this: win32api.InitiateSystemShutdown(None, 'Kaboom!', 2000, False, > False) > > Parameters: > 1. Computer to shutdown (None for lcoalhost) > 2. Message to display. > 3. Time in ms to display message (0 for no message). > 4. Kill programs (False to allow user a chance to save their work). > 5. Reboot or shutdown. > > If you are doing win32 programming, I strongly recommend Mark Hammond's > book! > (since that's where I got this information) > > Note that I have not tested this (in particular, it is possible I have the > orientation of the two boolean parameters wrong). Thanks John. I have the local machine's administration privilege. But my machine is logged in a local network which disables shutdown, restart functions (Group policy?). When I run the command as you point out, I got the following messages (5, 'InitiateSystemShutdown', 'Access is denied.') I have noticed for some software which require restart, it can restart properly. Does that mean software restart is possbile? If yes, any idea? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050523/f17e313a/attachment.htm From shidai.liu at gmail.com Mon May 23 02:46:46 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Mon, 23 May 2005 01:46:46 +0100 Subject: [Tutor] __init__.py In-Reply-To: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> References: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> Message-ID: <33194d73050522174677870911@mail.gmail.com> On 5/23/05, Joseph Quigley wrote: > > I've seen many (python) "plugins" (some located in site-packages [windows > here]) with the name __init__.py. > What's their use? > class foo: > def __init__: > print "this starts first" > def foo1(): > print "this comes later. Init initializes the chain of functions in this > class > > Now, i've never used a program (i can't seem to grasp all the self, and > other things in OOP yet) with __init__ but I know what __init__ does in a > class, not as a file name. > I'm asking this out of curiosity, not for help. > JQ __init__.py will be executed when a package is imported. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050523/bcd2ce64/attachment.html From tameyer at ihug.co.nz Mon May 23 02:51:23 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon, 23 May 2005 12:51:23 +1200 Subject: [Tutor] [HELP]win32 shutdown, restart, logoff In-Reply-To: Message-ID: > I have the local machine's administration privilege. [...] > When I run the command as you point out, I got the following > messages > > (5, 'InitiateSystemShutdown', 'Access is denied.') The process itself needs to have the privilege. This message has complete instructions: =Tony.Meyer From cpu.crazy at gmail.com Mon May 23 02:56:33 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Sun, 22 May 2005 18:56:33 -0600 Subject: [Tutor] __init__.py In-Reply-To: <33194d73050522174677870911@mail.gmail.com> References: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> <33194d73050522174677870911@mail.gmail.com> Message-ID: <6.1.0.6.2.20050522185539.01ef0ab8@pop.gmail.com> >__init__.py will be executed when a package is imported. Oh. So it will (for instance) compile .py to .pyc after the installation is finished. Nice. Thanks, JQ From leec03273 at mac.com Mon May 23 03:08:42 2005 From: leec03273 at mac.com (Lee Cullens) Date: Sun, 22 May 2005 21:08:42 -0400 Subject: [Tutor] __init__.py In-Reply-To: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> References: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> Message-ID: <94FB987A-2055-4F02-8B7C-35DDA3044C0B@mac.com> Joseph, I'm relatively new to Python, but I might be able to help with your question. First, think of the convention "self" (or sometimes "me" in other languages) as a reference to a specific instance derived from a class. When you reference an inherited class method of an instance, the specific instance address is automatically passed as the first argument. There is nothing special about the label "self" by itself (you could use instance_ref for example), but it is a convention that makes your code more easily understood. If I've used any inappropriate Python terminology, maybe someone will correct such :~) Now your real question. In my limited Python experience so far the module (file) __init__.py is used with module packages (multiple directories involved). Let's say you want to use "import dir1.dir2.mod" because you have structured you package something like: dir0/ dir1/ __init__.py dir2/ __init__.py mod.py another_mod.py dir3/ __init__.py yet_another_mod.py Two things here: 1) The container directory (dir0) needs to be added to your module search path, unless it's the directory of the importing module. 2) Each directory named in the package import statement must contain a file called __init__.py These may be empty files (used by Python in the package initialization phase) and are not meant to be executed directly. However you could use such to create a data file, connect to a database, etc. Package imports can be used to simplify your PYTHONPATH/.pth search path settings. If you have cross-directory imports, you might make such relative to a common root directly. We'll let the experts take it from there. Lee C On May 22, 2005, at 7:54 PM, Joseph Quigley wrote: > I've seen many (python) "plugins" (some located in site-packages > [windows > here]) with the name __init__.py. > What's their use? > class foo: > def __init__: > print "this starts first" > def foo1(): > print "this comes later. Init initializes the chain of > functions in this > class > > Now, i've never used a program (i can't seem to grasp all the self, > and > other things in OOP yet) with __init__ but I know what __init__ > does in a > class, not as a file name. > I'm asking this out of curiosity, not for help. > JQ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Mon May 23 04:25:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 May 2005 22:25:30 -0400 Subject: [Tutor] looking for a pattern in a lot of files In-Reply-To: <4290E66F.6050903@softhome.net> References: <4290E66F.6050903@softhome.net> Message-ID: <42913F1A.8080502@tds.net> Jonas Melian wrote: > any improvement about this code? > how print the actual file? You can print the file name and line number using fileinput.filename() and fileinput.filelineno() > could i add an exception? by if there aren't files Set a flag if you print anything, check it at the end of the loop Kent > > > for line in fileinput.input(glob.glob(os.path.join > (dir_locales, "*_[A-Z][A-Z]"))): > if re.search("locale for", line): > print line > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon May 23 04:33:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 May 2005 22:33:54 -0400 Subject: [Tutor] Checking and showing all errors before of exit In-Reply-To: <428F732F.50003@softhome.net> References: <428F732F.50003@softhome.net> Message-ID: <42914112.80407@tds.net> Jonas Melian wrote: > Is there any way of checking all possible errors, show you all error > messages, and then exit. > > If i use :: sys.exit("error message") :: it only shows this error > message before of exit. I don't understand your question. Can you give an example of what you would like to do? Kent From kent37 at tds.net Mon May 23 04:35:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 May 2005 22:35:22 -0400 Subject: [Tutor] installing python 2.4.1 over 2.4 In-Reply-To: References: Message-ID: <4291416A.4090401@tds.net> The 2.4.1 installer will install over you existing 2.4 install. I don't think it will affect the ides. Kent Pujo Aji wrote: > Hello, > > I have python 2.4. > I would like to install python 2.4.1, Should I uninstall python 2.4, > or just install 2.4.1? > > Does it effect my ide such as pydev and komodo ? > > Sincerely Yours, > pujo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Mon May 23 09:14:07 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 23 May 2005 08:14:07 +0100 Subject: [Tutor] __init__.py References: <6.1.0.6.2.20050522175045.01fa7648@pop.gmail.com> Message-ID: <00a301c55f67$02be66f0$0db78851@xp> HI Joseph, > I've seen many (python) "plugins" (some located in site-packages [windows > here]) with the name __init__.py. init.py is the file that controls the behaviour of python packages - that is collections of modules used as a single entity. Read the python docs for the fine detail, but essentially the init file often imports functions or classes that the package designer wants to appear as top level(in the package as opposed to being in a sub module). Also initialisation of package variables such as constants can be done there. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jonasmg at softhome.net Mon May 23 10:59:47 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Mon, 23 May 2005 09:59:47 +0100 Subject: [Tutor] Checking and showing all errors before of exit In-Reply-To: <42914112.80407@tds.net> References: <428F732F.50003@softhome.net> <42914112.80407@tds.net> Message-ID: <42919B83.80909@softhome.net> Kent Johnson wrote: > >>Is there any way of checking all possible errors, show you all error >>messages, and then exit. > > I don't understand your question. Can you give an example of what you would like to do? > The idea was check all exceptions before of exit. I made it :) flag_error = False for x in [dir_lo, dir_k, dir_x]: try: os.listdir(x) except OSError, err_o: flag_error = True print "Error! %s: %r" % (err_o.strerror, err_o.filename) if flag_error: sys.exit() Now, I have a dudes: 1) Is it necessary use .exit() with some value (as 1) for indicate that has been an error? 2) With .listdir() the exception can checks if the directory exist, but how check if there are files in that directory too? Thanks in advance! From kent37 at tds.net Mon May 23 12:05:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 May 2005 06:05:45 -0400 Subject: [Tutor] Checking and showing all errors before of exit In-Reply-To: <42919B83.80909@softhome.net> References: <428F732F.50003@softhome.net> <42914112.80407@tds.net> <42919B83.80909@softhome.net> Message-ID: <4291AAF9.9090002@tds.net> Jonas Melian wrote: > Kent Johnson wrote: > >>>Is there any way of checking all possible errors, show you all error >>>messages, and then exit. >> >>I don't understand your question. Can you give an example of what you would like to do? >> > > The idea was check all exceptions before of exit. I made it :) > > flag_error = False > for x in [dir_lo, dir_k, dir_x]: > try: > os.listdir(x) > except OSError, err_o: > flag_error = True > print "Error! %s: %r" % (err_o.strerror, err_o.filename) > > if flag_error: > sys.exit() > > Now, I have a dudes: > > 1) Is it necessary use .exit() with some value (as 1) for indicate that > has been an error? The argument to sys.exit() is the exit status of your program. exit() is the same as exit(0). If you want to signal to other programs that you exited with an error then use a different value. > > 2) With .listdir() the exception can checks if the directory exist, but > how check if there are files in that directory too? Look at the result of the call to listdir(), e.g. if len(os.listdir(x)) == 0: flag_error = True print "Error: Empty directory" Kent From rik at rikwade.com Mon May 23 13:48:12 2005 From: rik at rikwade.com (Rik Wade) Date: Mon, 23 May 2005 23:48:12 +1200 Subject: [Tutor] Davlib and HTTP Authentication Message-ID: <7CBB246D-C86F-4ADB-9F2D-E96BE735E5DE@rikwade.com> Would anyone on the list with some knowledge of working with davlib.py (http://www.lyra.org/greg/python/) be able to advise regarding use of the library with a Dav server (apache2 with mod_dav) that is configured to require HTTP Basic Authentication? Specifically, I have calls for davlib.put, which look like: mydav.put(myurl,mydata,None,None,{"Authorization":"Basic %s"%auth}) where davlib.put is defined as: def put(self, url, contents, content_type=None, content_enc=None, extra_hdrs={ }): The put functions work fine, as do some other basic Dav functions which are defined in a similar manner . However, I would like to manipulate the properties of files on the server. The "user" function defined in davlib is: def setprops(self, url, *xmlprops, **props): which doesn't appear to permit the addition of extra_hdrs as before in order to carry out HTTP Basic Authentication. There is, however, a proppatch function defined as: def proppatch(self, url, body, extra_hdrs={ }): which does not have some of the XML parsing and formatting that occurs in setprops. I am wondering whether I should be implementing my own setprops function, perhaps inheriting and extending from the davlib class, whether I should be writing my own setprops function from scratch, or whether I should just use the proppatch function. Davlib.py isn't very well documented. So in generic terms, the question is "I am using a library but the function doesn't appear to do what I need it to, what's the best way to proceed?". Many thanks, -- rik -------------- next part -------------- A non-text attachment was scrubbed... Name: PGP.sig Type: application/pgp-signature Size: 194 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20050523/19293e78/PGP.pgp From feziwe at sanbi.ac.za Mon May 23 17:54:05 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Mon, 23 May 2005 17:54:05 +0200 Subject: [Tutor] clock.py Message-ID: <4291FC9D.4010703@sanbi.ac.za> clock.py,problem is to get the last two digits to be random.her's what i tried from time import time,ctime prev_time = "" while(1): the_time = ctime() if (prev_time != the_time): print "The time is :",ctime(time()) prev_time = the_time guess = 0 number = 1-60 while guess != number: guess = input ("Guess the last two digits:") if guess > number: print "Too high" elif guess < number: print "Too low" print "Just right" From nick at javacat.f2s.com Mon May 23 18:36:05 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon, 23 May 2005 17:36:05 +0100 Subject: [Tutor] clock.py In-Reply-To: <4291FC9D.4010703@sanbi.ac.za> References: <4291FC9D.4010703@sanbi.ac.za> Message-ID: <42920675.2050801@javacat.f2s.com> Feziwe Mpondo wrote: >clock.py,problem is to get the last two digits to be random.her's what i >tried >from time import time,ctime >prev_time = "" >while(1): > the_time = ctime() > if (prev_time != the_time): > print "The time is :",ctime(time()) >prev_time = the_time >guess = 0 >number = 1-60 >while guess != number: > guess = input ("Guess the last two digits:") > if guess > number: > print "Too high" > elif guess < number: > print "Too low" >print "Just right" >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Hi Feziwe, you might want to look at the random module to generate 'guess' ramdon.randrange() more specifically. Nick . From luke.jordan at gmail.com Mon May 23 22:30:33 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Mon, 23 May 2005 15:30:33 -0500 Subject: [Tutor] Filtering Spreadsheet Data Message-ID: Hi All, I have several frighteningly cumbersome reports to review at my new job. I would like to write a python program to help me with my analysis. The goal of the program is to filter out information that doesn't meet certain requirements and print relevant results back to a legible report that I can do detailed research and analysis on. The reports come to me in Excel format. I have a solid understanding of basic programming. Any guidance/advice/starting points would be greatly appreciated. Thanks! Luke From jeffpeery at yahoo.com Tue May 24 00:00:25 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon, 23 May 2005 15:00:25 -0700 (PDT) Subject: [Tutor] passing variables between frames? Message-ID: <20050523220025.16041.qmail@web30513.mail.mud.yahoo.com> Hello, I am having trouble with passing variables between frames (Frame1 and Dialog1). I'm using wxpython to write an application. when I run my application the parent frame appears and within the parent frame I can assign values to variables. I then have a button that launches a child dialog. I want to access the values from the parent frame in the dialog. for example say I had a listbox in the parent frame and I choose the first entry 'a' from the list. I then launch the child dialog and I want to put the value of the selection from the list box into a text field - when I lauch the child dialog a text field appears with the value '0'. From within Frame1 I can use the getselection() function to get the listbox selection. although in the child dialog I tried to use Frame1.listBox.getselection() to get the selection from Frame1. this doesn't work. not sure what to do here? any ideas? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050523/d9de8dd6/attachment.htm From albertito_g at hotmail.com Tue May 24 00:06:40 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 23 May 2005 22:06:40 +0000 Subject: [Tutor] Calendar Combo Box Message-ID: Hey everyone Is there a built-in calendar combo box as in Visual Basic? Can anyone point me in the right direction? Thanks in advanced Alberto From kent37 at tds.net Tue May 24 00:32:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 May 2005 18:32:50 -0400 Subject: [Tutor] passing variables between frames? In-Reply-To: <20050523220025.16041.qmail@web30513.mail.mud.yahoo.com> References: <20050523220025.16041.qmail@web30513.mail.mud.yahoo.com> Message-ID: <42925A12.9000305@tds.net> Jeff Peery wrote: > Hello, I am having trouble with passing variables between frames (Frame1 > and Dialog1). I'm using wxpython to write an application. when I run my > application the parent frame appears and within the parent frame I can > assign values to variables. I then have a button that launches a child > dialog. I want to access the values from the parent frame in the > dialog. for example say I had a listbox in the parent frame and I > choose the first entry 'a' from the list. I then launch the child > dialog and I want to put the value of the selection from the list box > into a text field - when I lauch the child dialog a text field appears > with the value '0'. From within Frame1 I can use the getselection() > function to get the listbox selection. although in the child dialog I > tried to use Frame1.listBox.getselection() to get the selection from > Frame1. this doesn't work. not sure what to do here? any ideas? thanks. It's hard to know specifically what is broken without seeing code or error messages. My guess is that the variable Frame1 is not in scope in the dialog box code. But I would suggest a different approach... - Make the dialog box code independent of the values of variables in Frame1. Generally for me this means packaging up the dialog box in a function or class that is passed the values it needs to use and returns some result to the user. A very simple example is a dialog box that presents an error message; you could make a function showError(msg) that doesn't know anything about its caller. - In the event handler for the button in Frame1, gather the values needed by the dialog, launch it, get the result and handle it. This style keeps your dialog code independent of the rest of the program. An immediate benefit is that you can write a simple test driver that exercises the dialog without having to create any infrastructure. (This is the way I create most dialog boxes. I run it standalone until I am happy with its appearance and function, then I integrate it into the rest of the app.) Another long-term benefit is the dialogs are reusable; you may not see a need for this but in the long run some of them will probably have more than one use. HTH, Kent From zmerch at 30below.com Tue May 24 00:46:28 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Mon, 23 May 2005 18:46:28 -0400 Subject: [Tutor] better resolution on time.sleep()? Message-ID: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> I'm running an application that has a polling loop to check a serial port for certain signals, and on my laptop I can get about 6700 samples per second, which (of course) consumes 100% CPU; which may impact battery life. BTW, I'm running Python 2.2.2 on my laptop... not had a need to upgrade yet. I really only need between 500 and 1000 samples per second, but as the smallest sleep available normally is time.sleep(.01) -- which brings my samples/sec to a nice 100; but I need it a little faster. I found this: http://freshmeat.net/projects/rtsched/ which is supposed to bring real-time scheduling to Python (which the docs say is dangerous if used incorrectly) and also implementations of msleep/usleep/nanosleep. I downloaded it, compiled it, installed it, and popped in an import rtsched at the top and rtsched.msleep(1) where the time.sleep(.01) used to go... and now I get around 50 samples per second. I tried the usleep(1) and nanosleep(1) and the same thing happens. The rtsched implementation *is* working, as I can put in rtsched.msleep(100) and my samples/sec drops to 10. I'm guessing there's so much overhead to calling rtsched that it's b0rking up the works. :-/ Anyone know of: 1) a working millisleep/microsleep implementation for python 2.2+? -or- 2) will upgrading to a newer version of Python get me what I need? [[ I looked thru the "New in 2.4" dox and nothing I needed was listed...]] I've googled (off and on for more than a few days) and searched the archives, and came up empty so far... This isn't life or death by any means... My laptop known for long battery life, so everything should be OK as is, but why grind the CPU if it's not necessary, eh? ;-) Just a niggling little thing that's been on the back of my mind... [[ Oh, I found a reference to wxwindows that might have something that could work, but I was hoping for a little less overkill... my app barely uses ncurses. ]] Thanks! Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- SysAdmin, Iceberg Computers zmerch at 30below.com Hi! I am a .signature virus. Copy me into your .signature to join in! From jfouhy at paradise.net.nz Tue May 24 00:59:57 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 24 May 2005 10:59:57 +1200 (NZST) Subject: [Tutor] better resolution on time.sleep()? In-Reply-To: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> References: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> Message-ID: <1116889197.4292606d40498@www.paradise.net.nz> Quoting Roger Merchberger : > I really only need between 500 and 1000 samples per second, but as the > smallest sleep available normally is time.sleep(.01) -- which brings my > samples/sec to a nice 100; but I need it a little faster. Where did you find that out? > 2) will upgrading to a newer version of Python get me what I need? > [[ I looked thru the "New in 2.4" dox and nothing I needed was > listed...]] I just did some experimenting ... I am running ActiveState Python 2.4.1 under Windows XP / cygwin. >>> def check(): ... now = time.clock() ... for i in xrange(10000): ... time.sleep(0.001) ... print time.clock() - now ... >>> check() 11.2695306247 >>> def check(): ... now = time.clock() ... for i in xrange(100000): ... time.sleep(0.0001) ... print time.clock() - now ... >>> check() 2.77601985727 >>> check() 8.70900742972 The first test is fairly consistent with time.sleep(0.001) doing what you expect. The second is a bit puzzling to me, though... -- John. From list at ohtogo.com Tue May 24 01:05:49 2005 From: list at ohtogo.com (Trey Beck) Date: Mon, 23 May 2005 17:05:49 -0600 Subject: [Tutor] Simple password generation Message-ID: <46BC6635-2DB3-4A12-9D5F-B4E0A3628C12@ohtogo.com> Hi. First post. I'm trying to (more or less) copy the functionality of quepasa (http://quepasa.sourceforge.net), a simple password generation script that builds passwords from a combination of a passphrase and another string (like a domain name). If you enter the same passphrase and string, you should get the same password (in case you forget...). I've added a bit so that if neither a passphrase nor a string is entered, the function returns a random (or somewhat random) eight- character string. Am i on the right track here? (I'm brand new to sha and so forth.) Criticisms? Thx! Trey --- import sha, re, base64, string from random import choice def QuePasa (salt='', passphrase='', length=8): salted = passphrase + salt newpasswd = '' if (salted): hash = sha.new(salted).digest() # for now, strip non-alphanumeric characters newpasswd = re.sub(r'\W', '', base64.encodestring(hash)) [:length] else: chars = string.letters + string.digits for i in range(length): newpasswd = newpasswd + choice(chars) return newpasswd if __name__ == "__main__": sites = ['thissite.com','thatsite.com', 'theothersite.com',''] passphrase = 'all your base are belong to us' for i in range(10): for site in sites: print "%s : %s" % (site, QuePasa(passphrase, site)) From zmerch at 30below.com Tue May 24 01:56:14 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Mon, 23 May 2005 19:56:14 -0400 Subject: [Tutor] better resolution on time.sleep()? In-Reply-To: <1116889197.4292606d40498@www.paradise.net.nz> References: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> Message-ID: <5.1.0.14.2.20050523193433.03a32d18@mail.30below.com> Rumor has it that jfouhy at paradise.net.nz may have mentioned these words: >Quoting Roger Merchberger : > > > I really only need between 500 and 1000 samples per second, but as the > > smallest sleep available normally is time.sleep(.01) -- which brings my > > samples/sec to a nice 100; but I need it a little faster. > >Where did you find that out? Imperical testing -- I put in values smaller than .01, yet never got more than 100 samples per second. ;-) I then googled around and I saw a few other people found the same thing; but with no resolutions. I *can* post some ugly code if necessary... >I just did some experimenting ... I am running ActiveState Python 2.4.1 under >Windows XP / cygwin. I'm running under Linux From Scratch, book 4.0, kernel 2.4.29. [code snippage] >The first test is fairly consistent with time.sleep(0.001) doing what you >expect. The second is a bit puzzling to me, though... Yea, seems to be a bit of weirdness there... Hrm.... Anyway, maybe I'll go snag 2.4.x and see what that does for me... Laterz, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | Anarchy doesn't scale well. -- Me zmerch at 30below.com. | SysAdmin, Iceberg Computers From john at fouhy.net Mon May 23 23:01:59 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 24 May 2005 09:01:59 +1200 Subject: [Tutor] Filtering Spreadsheet Data In-Reply-To: References: Message-ID: <429244C7.8010206@fouhy.net> Luke Jordan wrote: > I have several frighteningly cumbersome reports to review at my new > job. I would like to write a python program to help me with my > analysis. The goal of the program is to filter out information that > doesn't meet certain requirements and print relevant results back to > a legible report that I can do detailed research and analysis on. The > reports come to me in Excel format. pyExcelerator seems to work well for parsing Excel spreadsheets. (it basically gives you a dictionary for each worksheet) Google should find it for you. (you could also use COM ... but that's a bit more effort) -- John. From zmerch at 30below.com Tue May 24 07:52:04 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Tue, 24 May 2005 01:52:04 -0400 Subject: [Tutor] better resolution on time.sleep()? In-Reply-To: <5.1.0.14.2.20050523193433.03a32d18@mail.30below.com> References: <1116889197.4292606d40498@www.paradise.net.nz> <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> Message-ID: <5.1.0.14.2.20050524014511.03958300@mail.30below.com> Rumor has it that Roger Merchberger may have mentioned these words: Yea, yea, I'm replying my own message.... you'll see why later! ;-) >Rumor has it that jfouhy at paradise.net.nz may have mentioned these words: > >I just did some experimenting ... I am running ActiveState Python 2.4.1 > under > >Windows XP / cygwin. > >I'm running under Linux From Scratch, book 4.0, kernel 2.4.29. I downloaded and compiled Python 2.4.1 this evening, and the granularity of sleep hasn't changed on my system... maybe it's a kernel limitation? Hrm... Despite my pitiful C knowledge, I found a code snippet I modified to make a command-line "msleep" command which sleeps for 1 millisecond & exits, and called that with an os.system('msleep') call. The best I could get then is around 32 samples for second, so that seemed "marginally less efficient" calling my msleep command thru the OS compared to the "realtime usleep" function I downloaded earlier to run on Python 2.2.2. The realtime package wouldn't compile with Python 2.4.1 (not that it did me much good before... ;-). =-=-= I'm downloading the source to wxPython now, there is a wx.usleep function in there. As I mentioned, it seems a bit'o'overkill to me, but what the heck, in for a penny, in for a pound, eh? ;^> I'll let y'all know how it turns out... Laterz, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | Anarchy doesn't scale well. -- Me zmerch at 30below.com. | SysAdmin, Iceberg Computers From alan.gauld at freenet.co.uk Tue May 24 08:54:45 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 24 May 2005 07:54:45 +0100 Subject: [Tutor] passing variables between frames? References: <20050523220025.16041.qmail@web30513.mail.mud.yahoo.com> Message-ID: <010201c5602d$786ad7f0$0db78851@xp> > want to access the values from the parent frame in the dialog. > for example say I had a listbox in the parent frame and I choose > the first entry 'a' from the list. I then launch the child > dialog and I want to put the value of the selection from the > list box into a text field - when I lauch the child dialog > a text field appears with the value '0'. From within Frame1 > I can use the getselection() function to get the listbox > selection. although in the child dialog I tried to use > Frame1.listBox.getselection() to get the selection from Frame1. > this doesn't work. not sure what to do here? any ideas? thanks. The dialog should be subclassed and you can add a parameter to the constructor. When you create the dialog pass in Frame1 as the value of your new parameter. Within the constructor assign the parameter to an attribute of the object, self.parent say. Within the event handlers in the dialog you can now reference Frame1 as self.parent. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue May 24 09:00:47 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 24 May 2005 08:00:47 +0100 Subject: [Tutor] better resolution on time.sleep()? References: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> Message-ID: <010b01c5602e$502fd000$0db78851@xp> > I'm running an application that has a polling loop to check a serial port > for certain signals, and on my laptop I can get about 6700 samples per > second, which (of course) consumes 100% CPU; which may impact battery life. Consuming 100% CPU won't make much difference, the CPU is running all the time anyway (when its not asleep). What will consume batteries much faster is if you are accessing hardware such as disk or modem or other power hungry devices. > Anyone know of: > > 1) a working millisleep/microsleep implementation for python 2.2+? I've never tried in Python but can you use select()? I've used it in C for short duration intervals. Just a thought. Alan G From jeannot18 at hotmail.com Tue May 24 11:10:31 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 24 May 2005 09:10:31 +0000 Subject: [Tutor] ASCII characters Message-ID: I need to print all the ASCII characters within a string, how would I delimit for example to print the first 100 only? Many thanks JC From kent37 at tds.net Tue May 24 11:46:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 05:46:25 -0400 Subject: [Tutor] ASCII characters In-Reply-To: References: Message-ID: <4292F7F1.80808@tds.net> John Carmona wrote: > I need to print all the ASCII characters within a string, how would I > delimit for example to print the first 100 only? Many thanks A string is a sequence and supports sequence operations including slices. So s[:100] gives the first 100 chars of a string. You might be interested in the textwrap modulue. Kent From shidai.liu at gmail.com Tue May 24 13:56:04 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Tue, 24 May 2005 12:56:04 +0100 Subject: [Tutor] [HELP]win32 shutdown, restart, logoff In-Reply-To: References: Message-ID: <33194d7305052404564e5292c3@mail.gmail.com> On 5/23/05, Tony Meyer wrote: > > > I have the local machine's administration privilege. > [...] > > When I run the command as you point out, I got the following > > messages > > > > (5, 'InitiateSystemShutdown', 'Access is denied.') > > The process itself needs to have the privilege. This message has complete > instructions: > > > > =Tony.Meyer > > Thanks for the link. But I still get 'Access is denied'. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050524/de1e70c4/attachment.html From albertito_g at hotmail.com Tue May 24 15:16:26 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 24 May 2005 13:16:26 +0000 Subject: [Tutor] Python Date picker Message-ID: Hey everyone I've been searching (with no luck by the way) for a date picker combo or something like it What I need to do is validate a date field (better if it's already done) and I want to know if anyone knows about a code to do that (a made code, don't mean you to do my work). I was hoping to find a calendar combo box as in Visual Basic DropDown Calendar Thanks in advanced Alberto From mhansen at cso.atmel.com Tue May 24 15:22:11 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue, 24 May 2005 07:22:11 -0600 Subject: [Tutor] Filtering Spreadsheet Data In-Reply-To: References: Message-ID: <42932A83.90409@cso.atmel.com> > Subject: > [Tutor] Filtering Spreadsheet Data > From: > Luke Jordan > Date: > Mon, 23 May 2005 15:30:33 -0500 > To: > tutor at python.org > > To: > tutor at python.org > > > Hi All, > > I have several frighteningly cumbersome reports to review at my new > job. I would like to write a python program to help me with my > analysis. The goal of the program is to filter out information that > doesn't meet certain requirements and print relevant results back to > a legible report that I can do detailed research and analysis on. The > reports come to me in Excel format. > > I have a solid understanding of basic programming. > > Any guidance/advice/starting points would be greatly appreciated. > > Thanks! > > Luke > Excel has some nice database-like queries itself. Take a look at Advanced Filter in Help. You can essentially query a worksheet and even send the results to a different worksheet. I'd imagine that once you got the query working, you could automate it using VBA or Python. Mike From maxnoel_fr at yahoo.fr Tue May 24 15:30:11 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 24 May 2005 14:30:11 +0100 Subject: [Tutor] Filtering Spreadsheet Data In-Reply-To: <42932A83.90409@cso.atmel.com> References: <42932A83.90409@cso.atmel.com> Message-ID: <598912EE-21DF-4257-A366-776528BA6D0A@yahoo.fr> On May 24, 2005, at 14:22, Mike Hansen wrote: > Excel has some nice database-like queries itself. Take a look at > Advanced Filter > in Help. You can essentially query a worksheet and even send the > results to a > different worksheet. I'd imagine that once you got the query > working, you could > automate it using VBA or Python. > > Mike If you want to do it in Python, the easiest way is to export the spreadsheet as CSV in Excel, then use the csv module to do your processing. If needed, convert back to XLS afterward. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From cpu.crazy at gmail.com Tue May 24 03:49:37 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 23 May 2005 19:49:37 -0600 Subject: [Tutor] Python won't play wav file Message-ID: <6.1.0.6.2.20050523194809.01ed3070@pop.gmail.com> I can't get: import wave as w def manipulate(): manipulate = raw_input("Type 'help' for help\nManipulate>> ") if manipulate == "play": w.tell() elif manipulate == "back()": main_menu() def open(): while True: file_name = raw_input("Open: ") if file_name == "back()": break try: w.open(file_name, 'r') except IOError: print "Non-existant file." w.open(file_name, 'r') manipulate() def main_menu(): main_menu = raw_input("Type 'help' for help\n>> ") if main_menu == "open": open() elif main_menu == "help": import help help.main() main_menu() ... to play a .wav music file. I tried w.play() but got an error that module has no attribute 'play'. What do I use to get it to play? Thanks, JQ From jonasmg at softhome.net Tue May 24 16:02:01 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Tue, 24 May 2005 15:02:01 +0100 Subject: [Tutor] Sorting a directory Message-ID: <429333D9.4020603@softhome.net> Hi all, I have to working with the files lines in this directory: ::: dir_locales = "/usr/share/i18n/locales/" for line in fileinput.input(glob.glob(os.path.join\ (dir_locales, "*_[A-Z][A-Z]"))): ... ::: The problem is that the directory otuput is: aa_DJ aa_ER aa_ET af_ZA ... and i would sort this files by the 2 last letters, so: aa_DJ so_DJ aa_ER byn_ER gez_ER ti_ER tig_ER ... I have not foun a lot of info about sort Thanks! From kent37 at tds.net Tue May 24 16:18:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 10:18:55 -0400 Subject: [Tutor] Sorting a directory In-Reply-To: <429333D9.4020603@softhome.net> References: <429333D9.4020603@softhome.net> Message-ID: <429337CF.5060408@tds.net> Jonas Melian wrote: > Hi all, > > I have to working with the files lines in this directory: > > ::: > dir_locales = "/usr/share/i18n/locales/" > > for line in fileinput.input(glob.glob(os.path.join\ > (dir_locales, "*_[A-Z][A-Z]"))): > ... > > ::: > > The problem is that the directory otuput is: > aa_DJ > aa_ER > aa_ET > af_ZA > ... > > and i would sort this files by the 2 last letters, so: > aa_DJ > so_DJ > aa_ER > byn_ER > gez_ER > ti_ER > tig_ER > ... > > I have not foun a lot of info about sort The sort() method of a mutable sequence is very powerful. Docs for it are here: http://docs.python.org/lib/typesseq-mutable.html The key= parameter of sort() allows you to provide a function which, given a member of the sequence being sorted, returns the sort key for that item. In your case you can define a simple helper function that returns the last two characters of a string: def lastTwoChars(s): return s[-2:] then sort like this: dir_locales = "/usr/share/i18n/locales/" files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]")) files.sort(key=lastTwoChars) # Note: NOT key=lastTwoChars() for line in fileinput.input(files): ... Kent From jonasmg at softhome.net Tue May 24 17:02:17 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Tue, 24 May 2005 16:02:17 +0100 Subject: [Tutor] Sorting a directory In-Reply-To: <429337CF.5060408@tds.net> References: <429333D9.4020603@softhome.net> <429337CF.5060408@tds.net> Message-ID: <429341F9.2060409@softhome.net> Kent Johnson wrote: >>and i would sort this files by the 2 last letters, so: > > The sort() method of a mutable sequence is very powerful. Docs for it are here: > http://docs.python.org/lib/typesseq-mutable.html > > The key= parameter of sort() allows you to provide a function which, given a member of the sequence > being sorted, returns the sort key for that item. In your case you can define a simple helper > function that returns the last two characters of a string: > > def lastTwoChars(s): > return s[-2:] > > then sort like this: > > dir_locales = "/usr/share/i18n/locales/" > > files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]")) > files.sort(key=lastTwoChars) # Note: NOT key=lastTwoChars() > > for line in fileinput.input(files): > ... > Thanks for this information. I get: :: files.sort(key=lastTwoChars) TypeError: sort() takes no keyword arguments :: Could it be by the Python version? I have Python 2.3.5 From kent37 at tds.net Tue May 24 17:00:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 11:00:27 -0400 Subject: [Tutor] Sorting a directory In-Reply-To: <429341F9.2060409@softhome.net> References: <429333D9.4020603@softhome.net> <429337CF.5060408@tds.net> <429341F9.2060409@softhome.net> Message-ID: <4293418B.4020202@tds.net> Jonas Melian wrote: > Kent Johnson wrote: >>files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]")) >>files.sort(key=lastTwoChars) # Note: NOT key=lastTwoChars() > > I get: > :: > files.sort(key=lastTwoChars) > TypeError: sort() takes no keyword arguments > :: > > Could it be by the Python version? I have Python 2.3.5 Yes, the key= parameter is new in Python 2.4. For Python 2.3 you can define a comparison function, e.g. def cmpLastTwoChars(a, b): return cmp(a[-2:], b[-2:]) files.sort(cmpLastTwoChars) Kent From jeffpeery at yahoo.com Tue May 24 17:28:39 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 24 May 2005 08:28:39 -0700 (PDT) Subject: [Tutor] passing variables between frames? In-Reply-To: 6667 Message-ID: <20050524152839.97880.qmail@web30510.mail.mud.yahoo.com> ok, thanks. that makes sense; however I do not know how to pass a variable from my parent frame to the dialog. I have tried this before unsuccessfully. could you provide a quick example of how to pass a variable to a dialog from a frame. I am not sure how this works. thanks. Jeff Kent Johnson wrote: Jeff Peery wrote: > Hello, I am having trouble with passing variables between frames (Frame1 > and Dialog1). I'm using wxpython to write an application. when I run my > application the parent frame appears and within the parent frame I can > assign values to variables. I then have a button that launches a child > dialog. I want to access the values from the parent frame in the > dialog. for example say I had a listbox in the parent frame and I > choose the first entry 'a' from the list. I then launch the child > dialog and I want to put the value of the selection from the list box > into a text field - when I lauch the child dialog a text field appears > with the value '0'. From within Frame1 I can use the getselection() > function to get the listbox selection. although in the child dialog I > tried to use Frame1.listBox.getselection() to get the selection from > Frame1. this doesn't work. not sure what to do here? any ideas? thanks. It's hard to know specifically what is broken without seeing code or error messages. My guess is that the variable Frame1 is not in scope in the dialog box code. But I would suggest a different approach... - Make the dialog box code independent of the values of variables in Frame1. Generally for me this means packaging up the dialog box in a function or class that is passed the values it needs to use and returns some result to the user. A very simple example is a dialog box that presents an error message; you could make a function showError(msg) that doesn't know anything about its caller. - In the event handler for the button in Frame1, gather the values needed by the dialog, launch it, get the result and handle it. This style keeps your dialog code independent of the rest of the program. An immediate benefit is that you can write a simple test driver that exercises the dialog without having to create any infrastructure. (This is the way I create most dialog boxes. I run it standalone until I am happy with its appearance and function, then I integrate it into the rest of the app.) Another long-term benefit is the dialogs are reusable; you may not see a need for this but in the long run some of them will probably have more than one use. HTH, Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050524/7037d559/attachment-0001.html From ajikoe at gmail.com Tue May 24 17:39:32 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 24 May 2005 17:39:32 +0200 Subject: [Tutor] Sorting a directory In-Reply-To: <4293418B.4020202@tds.net> References: <429333D9.4020603@softhome.net> <429337CF.5060408@tds.net> <429341F9.2060409@softhome.net> <4293418B.4020202@tds.net> Message-ID: you can sort listsource based on listkey For example: you have listsource = ['c','b','a'] and listkey = [2,3,1] # this will be used to sort listsource. def sortbasedlist(sources,keys): #combine (key,sources) Kombin = [(keys[i],sources[i]) for i in range(len(sources))] Kombin.sort() return [source for (key,source) in Kombin] main program: print sortbasedlist(listsource,listkey) # this will result ('a','c','b') And for your problem you can do something like this: # suppose files already found and can be considered as source filesKey = [x[-2:] for x in files] Result = sortbasedlist(files,filesKey) good luck. pujo On 5/24/05, Kent Johnson wrote: > Jonas Melian wrote: > > Kent Johnson wrote: > >>files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]")) > >>files.sort(key=lastTwoChars) # Note: NOT key=lastTwoChars() > > > > I get: > > :: > > files.sort(key=lastTwoChars) > > TypeError: sort() takes no keyword arguments > > :: > > > > Could it be by the Python version? I have Python 2.3.5 > > Yes, the key= parameter is new in Python 2.4. For Python 2.3 you can define a comparison function, e.g. > > def cmpLastTwoChars(a, b): > return cmp(a[-2:], b[-2:]) > > files.sort(cmpLastTwoChars) > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From william.ohiggins at utoronto.ca Tue May 24 18:21:55 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Tue, 24 May 2005 12:21:55 -0400 Subject: [Tutor] strip is deprecated, so what do I use? Message-ID: <20050524162155.GA6251@sillyrabbi.dyndns.org> As the subject says, I was looking for an analog to chomp, and found strip() and friends (rstrip() and lstrip()), but they are deprecated. I'm happy to forgo their use in preparation for 3.0 (I figure we're going to live the rest of our lives in the future, we might as well be ready) but I need an alternative syntax today, and I haven't been able to see what I should use instead. Anyone have a suggestion? -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050524/5a27a412/attachment.pgp From william.ohiggins at utoronto.ca Tue May 24 18:25:00 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Tue, 24 May 2005 12:25:00 -0400 Subject: [Tutor] Wizards in Tkinter Message-ID: <20050524162500.GB6251@sillyrabbi.dyndns.org> I am writing a small application that takes a user through a set of steps - like a wizard. What I need is an idea how I can start with a window, have the use click "Next" and get another window. My understanding is that it is undesirable to have more than one mainloop per program. Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050524/a446cf4d/attachment.pgp From jeannot18 at hotmail.com Tue May 24 19:00:44 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Tue, 24 May 2005 17:00:44 +0000 Subject: [Tutor] ASCII characters In-Reply-To: <4292F7F1.80808@tds.net> Message-ID: Thanks Kent for the reply, I am actually having trouble to find the solution of the following exercise: ## Write a for loop that prints the ASCII code of each character in a string name S.## I am ok with the for loop, put I don't know how get to print the ASCII code of each character with a string (I also know how to use the String). Many thanks JC From william.ohiggins at utoronto.ca Tue May 24 19:31:48 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Tue, 24 May 2005 13:31:48 -0400 Subject: [Tutor] strip is deprecated, so what do I use? In-Reply-To: <7e5ba92205052410164ce80d87@mail.gmail.com> References: <20050524162155.GA6251@sillyrabbi.dyndns.org> <7e5ba92205052410164ce80d87@mail.gmail.com> Message-ID: <20050524173148.GA6783@sillyrabbi.dyndns.org> On Tue, May 24, 2005 at 01:16:21PM -0400, Michael P. Reilly wrote: > On 5/24/05, William O'Higgins <[1]william.ohiggins at utoronto.ca> wrote: > > As the subject says, I was looking for an analog to chomp, and found > strip() and friends (rstrip() and lstrip()), but they are deprecated. > I'm happy to forgo their use in preparation for 3.0 (I figure we're > going to live the rest of our lives in the future, we might as well be > ready) but I need an alternative syntax today, and I haven't been able > to see what I should use instead. Anyone have a suggestion? > > William, > > These were all changed to object-oriented syntax on the string value > itself. > Old way string.strip(' abcd ') > New way ' abcd '.strip() > > It may take a little getting used to, but the functionality is the same > and it is more in keeping with how we should be treating the built-in data > values as objects just like we do with class instances. Perfect, and it make a lot of sense. Heck, I find this much more readable in terms of nested calls. Thank you. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050524/8cd4426a/attachment.pgp From kent37 at tds.net Tue May 24 19:46:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 13:46:36 -0400 Subject: [Tutor] ASCII characters In-Reply-To: References: Message-ID: <4293687C.5000308@tds.net> John Carmona wrote: > Thanks Kent for the reply, I am actually having trouble to find the > solution of the following exercise: > > ## Write a for loop that prints the ASCII code of each character in a > string name S.## > > I am ok with the for loop, put I don't know how get to print the ASCII > code of each character with a string (I also know how to use the String). You need the ord() function and maybe hex() also: >>> ord('s') 115 >>> hex(ord('s')) '0x73' Kent From denise.hartley at gmail.com Tue May 24 20:09:29 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 24 May 2005 11:09:29 -0700 Subject: [Tutor] ASCII characters In-Reply-To: <4293687C.5000308@tds.net> References: <4293687C.5000308@tds.net> Message-ID: <8daabe560505241109763dd81@mail.gmail.com> I have a question: what is the "opposite" of hex()? (i.e., like ord and chr). If I have '0x73', how can I get back to 115 or s? Thanks! ~Denise > You need the ord() function and maybe hex() also: > >>> ord('s') > 115 > >>> hex(ord('s')) > '0x73' > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue May 24 20:27:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 14:27:10 -0400 Subject: [Tutor] ASCII characters In-Reply-To: <8daabe560505241109763dd81@mail.gmail.com> References: <4293687C.5000308@tds.net> <8daabe560505241109763dd81@mail.gmail.com> Message-ID: <429371FE.9040908@tds.net> D. Hartley wrote: > I have a question: what is the "opposite" of hex()? (i.e., like ord > and chr). If I have > > '0x73', how can I get back to 115 or s? I don't know a really clean way to do this because '0x73' is not a legal input value for int(). The simplest way is to use eval(): >>> eval('0x73') 115 but eval() is a security hole so if you are not 100% sure of where your data is coming from then this is probably a better solution (it strips off the '0x' then tells int() to convert base 16): >>> int('0x73'[2:], 16) 115 To go from the string '115' to the integer 115 you can use int() directly: >>> int('115') 115 To get back to a string use chr(): >>> chr(115) 's' All of these functions are documented here: http://docs.python.org/lib/built-in-funcs.html Kent From dyoo at hkn.eecs.berkeley.edu Tue May 24 20:40:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 24 May 2005 11:40:06 -0700 (PDT) Subject: [Tutor] ASCII characters In-Reply-To: <429371FE.9040908@tds.net> Message-ID: On Tue, 24 May 2005, Kent Johnson wrote: > D. Hartley wrote: > > I have a question: what is the "opposite" of hex()? (i.e., like ord > > and chr). If I have > > > > '0x73', how can I get back to 115 or s? > > I don't know a really clean way to do this because '0x73' is not a legal > input value for int(). int() needs a little bit more hinting in this case: it can take in a seceond parameter whose value is the "base". For example: ###### >>> int('001010101001', 2) 681 >>> int('0x73', 16) 115 ###### Bets of wishes! From missive at hotmail.com Tue May 24 23:06:34 2005 From: missive at hotmail.com (Lee Harr) Date: Wed, 25 May 2005 01:36:34 +0430 Subject: [Tutor] Python won't play wav file Message-ID: >I can't get: > >import wave as w > >... to play a .wav music file. I tried w.play() but got an error that >module has no attribute 'play'. >What do I use to get it to play? Strangely... I do not believe the wave module is meant to actually _play_ a wav file. It looks to me like it is only intended to read and parse the file for meta information. You could try passing the name of the file to another program via os.system, or you could use pygame. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kent37 at tds.net Tue May 24 23:16:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 17:16:18 -0400 Subject: [Tutor] Python won't play wav file In-Reply-To: References: Message-ID: <429399A2.8050500@tds.net> Lee Harr wrote: >>I can't get: >> >>import wave as w >> > > > >>... to play a .wav music file. I tried w.play() but got an error that >>module has no attribute 'play'. >>What do I use to get it to play? > > > > Strangely... I do not believe the wave module is meant to actually > _play_ a wav file. It looks to me like it is only intended to read and > parse the file for meta information. If you are on windows try the winsound module. Kent From maxnoel_fr at yahoo.fr Tue May 24 23:18:29 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 24 May 2005 22:18:29 +0100 Subject: [Tutor] Python won't play wav file In-Reply-To: <6.1.0.6.2.20050523194809.01ed3070@pop.gmail.com> References: <6.1.0.6.2.20050523194809.01ed3070@pop.gmail.com> Message-ID: On May 24, 2005, at 02:49, Joseph Quigley wrote: > ... to play a .wav music file. I tried w.play() but got an error that > module has no attribute 'play'. > What do I use to get it to play? > Thanks, The wave module is meant to read, write and manipulate (transform, filter, whatever) WAV files, not to play them. Playing a sound is a highly OS-specific function; PyGame is a cross-platform library that enables this, among other things. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From denise.hartley at gmail.com Tue May 24 23:22:19 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 24 May 2005 14:22:19 -0700 Subject: [Tutor] Anyone doing the riddles? Message-ID: <8daabe5605052414226d92f8ce@mail.gmail.com> Hello all! I was just thinking: if there are people on here who are still doing the python riddles (or are interested in talking about them), I could start an off-tutor thread so that we could chat about them without clogging up the tutor mailing list for others? If you are interested, drop me an email! (and what riddle are you on? I just started 13!) ~Denise :) From missive at hotmail.com Tue May 24 23:22:53 2005 From: missive at hotmail.com (Lee Harr) Date: Wed, 25 May 2005 01:52:53 +0430 Subject: [Tutor] Python Date picker Message-ID: >What I need to do is validate a date field (better if it's already done) >and >I want to know if anyone knows about a code to do that (a made code, don't >mean you to do my work). I was hoping to find a calendar combo box as in >Visual Basic DropDown Calendar For which GUI system? py-qt has DateEdit py-kde has KDateWidget or KDateTable pygtk has gtk.Calendar _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From albertito_g at hotmail.com Tue May 24 23:50:48 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 24 May 2005 21:50:48 +0000 Subject: [Tutor] Python Date picker In-Reply-To: Message-ID: Completeley forgot, :D I'm working over Windows, Python 2.3., GUI Tkinter Thanks in advanced Alberto
 Gaucho
>From: "Lee Harr" >To: tutor at python.org >Subject: Re: [Tutor] Python Date picker >Date: Wed, 25 May 2005 01:52:53 +0430 > > >What I need to do is validate a date field (better if it's already done) > >and > >I want to know if anyone knows about a code to do that (a made code, >don't > >mean you to do my work). I was hoping to find a calendar combo box as in > >Visual Basic DropDown Calendar > > >For which GUI system? > >py-qt has DateEdit > >py-kde has KDateWidget or KDateTable > >pygtk has gtk.Calendar > >_________________________________________________________________ >Express yourself instantly with MSN Messenger! Download today it's FREE! >http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From denise.hartley at gmail.com Tue May 24 23:59:28 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 24 May 2005 14:59:28 -0700 Subject: [Tutor] xml Message-ID: <8daabe560505241459ec99687@mail.gmail.com> And just in case anyone *isnt* working on the riddles....: anyone have a pointer to a *SIMPLE* intro to xml as used in python? I looked in the library and there are about 11 xml-related modules. Perhaps something.... 'remote'..... ;) From maxnoel_fr at yahoo.fr Wed May 25 00:02:17 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 24 May 2005 23:02:17 +0100 Subject: [Tutor] Fwd: xml References: <3B74502B-E0FD-4894-B6F7-AC9BB2AB3925@yahoo.fr> Message-ID: <9FD1E7BF-D1DD-48A3-A046-9807EEF87A60@yahoo.fr> (meh, forgot to click "reply-all" again) Begin forwarded message: > From: Max Noel > Date: May 24, 2005 23:01:39 BDT > To: "D. Hartley" > Subject: Re: [Tutor] xml > > > > On May 24, 2005, at 22:59, D. Hartley wrote: > > >> anyone have a pointer to a *SIMPLE* intro to xml as used in python? I >> looked in the library and there are about 11 xml-related modules. >> > > The most elegant way to use XML in Python is to use the > elementtree module (http://effbot.org/zone/element-index.htm). It's > pure goodness. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, > panting and sweating as you run through my corridors... How can you > challenge a perfect, immortal machine?" > > -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jfouhy at paradise.net.nz Wed May 25 00:11:08 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 25 May 2005 10:11:08 +1200 (NZST) Subject: [Tutor] Wizards in Tkinter In-Reply-To: <20050524162500.GB6251@sillyrabbi.dyndns.org> References: <20050524162500.GB6251@sillyrabbi.dyndns.org> Message-ID: <1116972668.4293a67c0f6c6@www.paradise.net.nz> Quoting William O'Higgins : > I am writing a small application that takes a user through a set of > steps - like a wizard. What I need is an idea how I can start with a > window, have the use click "Next" and get another window. My > understanding is that it is undesirable to have more than one mainloop > per program. Thanks. If you want more than one window, you use Tkinter.Toplevel. But I think this is not what you want here. A few options spring to mind.. You could build multiple frames, but only pack the one you are interested in. eg: from Tkinter import * tk = Tk() page1 = Frame(tk) Label(page1, text='This is page 1 of the wizard').pack() page1.pack(side=TOP) page2 = Frame(tk) Label(page2, text='This is page 2 of the wizard.').pack() page3 = Frame(tk) Label(page3, text='This is page 3. It has an entry widget too!').pack() Entry(page3).pack() pages = [page1, page2, page3] current = page1 def move(dirn): global current idx = pages.index(current) + dirn if not 0 <= idx < len(pages): return current.pack_forget() current = pages[idx] current.pack(side=TOP) def next(): move(+1) def prev(): move(-1) Button(tk, text='Next', command=next).pack(side=BOTTOM) Button(tk, text='Previous', command=prev).pack(side=BOTTOM) ------------------ Another option is to use Pmw.Notebook without the tabs (and with next/previous buttons to change pages). This could be a bit easier (and it will do stuff like making the wizard stay the same size). Thirdly, a google search turned up this: http://www.freshports.org/devel/wizard/ HTH. -- John. From jfouhy at paradise.net.nz Wed May 25 00:12:13 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 25 May 2005 10:12:13 +1200 (NZST) Subject: [Tutor] xml In-Reply-To: <8daabe560505241459ec99687@mail.gmail.com> References: <8daabe560505241459ec99687@mail.gmail.com> Message-ID: <1116972733.4293a6bd7ec99@www.paradise.net.nz> Quoting "D. Hartley" : > anyone have a pointer to a *SIMPLE* intro to xml as used in python? I > looked in the library and there are about 11 xml-related modules. > > Perhaps something.... 'remote'..... ;) Use ElementTree! (google for it) -- John. From alan.gauld at freenet.co.uk Wed May 25 00:22:14 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 24 May 2005 23:22:14 +0100 Subject: [Tutor] Python won't play wav file References: <6.1.0.6.2.20050523194809.01ed3070@pop.gmail.com> Message-ID: <015701c560af$09b61b80$0db78851@xp> Joseph, I don't know if this will help or not, but some observations: > def manipulate(): > manipulate = raw_input("Type 'help' for help\nManipulate>> ") > if manipulate == "play": > w.tell() > elif manipulate == "back()": > main_menu() You expect the user to type 'play' or 'back()' One response is a command the other a pseudo function call complete with parentheses. Thats not a very consistent user experience. Also by calling main_menu from inside manipulate you are effectively using recursion as a loop. Thats OK if the number of loops is small but if this program were used over a long preiod you will eventually run out of menory. Its usually better to return a value and have a main control loop somewhere that calls the functions. For example have your main_menu function display the prompt, sanity check the input and return a valifd response from the user. Then have a single if/elif tree dispatch the appropriate function that returns success or failure. Wrap the menu and if/elif tree inside a loop that exits on error or command. That way ypur program can run indefinitely without risk of memory overflow. def main_menu(): .... return choice while True: choice = main_menu() if choice == 'foo': foo() elif chooice == 'bar': bar() # etc... elif choice == 'exit' break else: break > ... to play a .wav music file. I tried w.play() but got an error that > module has no attribute 'play'. Have you used dir(w) to see what it does offer? Even better what does the documentation say? Have you tried help(w)? HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed May 25 00:28:49 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 24 May 2005 23:28:49 +0100 Subject: [Tutor] Wizards in Tkinter References: <20050524162500.GB6251@sillyrabbi.dyndns.org> Message-ID: <017e01c560af$f510a820$0db78851@xp> Your mail came as an attachment so no quoted text, but basically there are two approaches to your problem of a Wizard. In Tkinter you normally use a Frame as your main window. You can pack another Frame inside that frame with your content. When you press next simply unpack frame 1 and pack frame 2. Repeat for as many frames as your Wizard requires. (This makes going back easy too...) A second approach is to use TopLevel widgets which are normally used for modeless dialog boxes. These effctively have their own mainloop running in parallel wit the main window but in a controlled way. But creating lors of TopLevel "dialogs" is IMHO resource hungry and harder work than using multiple frames. The Frame approach also has the advantage that you can, to a degree data drive the wizard by putting references to the Frames in a dictionary or list and stepping through the sequence. That way you can easily change the sequence, reuse frames over again within the same wizard etc etc. Hope that made sense, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed May 25 00:33:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 18:33:27 -0400 Subject: [Tutor] xml In-Reply-To: <8daabe560505241459ec99687@mail.gmail.com> References: <8daabe560505241459ec99687@mail.gmail.com> Message-ID: <4293ABB7.20904@tds.net> D. Hartley wrote: > And just in case anyone *isnt* working on the riddles....: > > anyone have a pointer to a *SIMPLE* intro to xml as used in python? I > looked in the library and there are about 11 xml-related modules. ElementTree is my choice too. It is simple and easy to use though a bit bare-bones. It has a C implementation that is very fast and can cope with very large files (e.g. 25MB). For a broader perspective and many examples, check out Uche Ogbuji's articles on xml.com. He has written several survey articles of available tools. http://www.xml.com/pub/au/84 In truth, I haven't found a Python XML library that IMO comes close to dom4j in power and ease of use. It's one of the reasons I still use Jython. lxml looks promising but it is not available on Windows so I haven't tried it. http://www.dom4j.org http://codespeak.net/lxml/ Kent From denise.hartley at gmail.com Wed May 25 00:40:50 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 24 May 2005 15:40:50 -0700 Subject: [Tutor] xml In-Reply-To: <1116972733.4293a6bd7ec99@www.paradise.net.nz> References: <8daabe560505241459ec99687@mail.gmail.com> <1116972733.4293a6bd7ec99@www.paradise.net.nz> Message-ID: <8daabe5605052415401fa5c57b@mail.gmail.com> I looked at the page for ElementTree that Max sent out, but I can't understand what it's even talking about. Looking through the python modules it seems like I need xmlrpclib - I created a serverproxy instance, which I want to use to talk to a server - to send it information (in this case, a name), and return to me its response. I can follow the documentation far enough to create a ServerProxy instance, but then don't know what to do with it (it starts talking about the reserved system member, and so on). I don't want to have to know everything about xml (yet), I just want to be able to use a phonebook which processes information in xml (forgive my probably erroneous wording of things). It said: "The returned instance is a proxy object with methods that can be used to invoke corresponding RPC calls on the remote server. If the remote server supports the introspection API, the proxy can also be used to query the remote server for the methods it supports (service discovery) and fetch other server-associated metadata." - and that sounds like what I want. Perhaps I am wrong? Also, when I read the ElementTree page, it talked about element instances and adding "code to load SML files as trees of Element objects, and save them back again" - as often happens to me (and, I hope to other beginners), this explanation does not even tell me if it does the same thing, or anything remotely related to what I am looking for. Is anyone familiar with xmlrpclib, or knows of documentation that is easier to follow than that in the library about how to use its methods? Also, re: using passwords and usernames in urls, I saw in this library the following: "Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: http://user:pass at host:port/path. The user:pass portion will be base64-encoded as an HTTP `Authorization' header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password." I read that the user:pass was an undocumented feature of, I think, urllib (I may be wrong on this one), and as such, I was wondering if anyone knew how to format the url so it automatically passed in the username/password, like: http://myname:mypass/www.mysite.com does not work - but I dont know a "host" or "port" .... ? Any ideas/suggestions/pointers would be appreciated! (sorry if I dont understand some of the pointers you have already sent! some of the documentation is not always user-friendly for beginners!) Thanks again, Denise On 5/24/05, jfouhy at paradise.net.nz wrote: > Quoting "D. Hartley" : > > > anyone have a pointer to a *SIMPLE* intro to xml as used in python? I > > looked in the library and there are about 11 xml-related modules. > > > > Perhaps something.... 'remote'..... ;) > > Use ElementTree! > > (google for it) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tktucker at gmail.com Wed May 25 01:08:04 2005 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 24 May 2005 19:08:04 -0400 Subject: [Tutor] Pickling in plain English Message-ID: <2a278ffe05052416082efc0301@mail.gmail.com> I am having trouble understanding the c|Pickle modules. What does serializing and de-serializing objects mean? I have read the below urls and I "think" I understand the process, but I can't visualize the beneifts. Can someone kindly explain pickling in lamens terms? Thanks, Tom http://effbot.org/librarybook/cpickle.htm http://www.python.org/doc/2.3.5/lib/module-cPickle.html From jfouhy at paradise.net.nz Wed May 25 01:32:50 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 25 May 2005 11:32:50 +1200 (NZST) Subject: [Tutor] Pickling in plain English In-Reply-To: <2a278ffe05052416082efc0301@mail.gmail.com> References: <2a278ffe05052416082efc0301@mail.gmail.com> Message-ID: <1116977570.4293b9a28e665@www.paradise.net.nz> Quoting Tom Tucker : > I am having trouble understanding the c|Pickle modules. What does > serializing and de-serializing objects mean? I have read the below > urls and I "think" I understand the process, but I can't visualize the > beneifts. Can someone kindly explain pickling in lamens terms? It's actually astonishingly simple, once you get the hang of it. example: >>> arr = [1, 3, 5, 7] >>> dct = {'foo':1, 'bar':2, 'baz':3} >>> st = "re: your mail" >>> >>> import pickle >>> f = file('dump', 'wb') >>> pickle.dump((arr, dct, st), f) >>> f.close() >>> ^Z [new instance of python] >>> import pickle >>> f = file('dump', 'r') >>> res = pickle.load(f) >>> res ([1, 3, 5, 7], {'bar': 2, 'foo': 1, 'baz': 3}, 're: your mail') [and you can look at the file 'dump' on your HDD, if you want to] Basically, pickle allows you to write any python object to disk and the load it back again with very little effort. This is important if you want your program to be able to save state between instances. You can pickle more complex objects; the only restriction is that pickle.load must be able to find the module where the classes are defined. [there are some other restrictions, but you can do a lot without worrying about them] Does this help? -- John. From dyoo at hkn.eecs.berkeley.edu Wed May 25 01:36:27 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 24 May 2005 16:36:27 -0700 (PDT) Subject: [Tutor] xml In-Reply-To: <8daabe5605052415401fa5c57b@mail.gmail.com> Message-ID: On Tue, 24 May 2005, D. Hartley wrote: > I looked at the page for ElementTree that Max sent out, but I can't > understand what it's even talking about. Hello Denise, ElementTree is a third-party module by the Effbot for handling some of the drudgery that is XML parsing: http://effbot.org/zone/element.htm it makes XML documents look like a bunch of nested lists. Let's work through a small example with it; that may help to clear some confusion. If we have something like a small HTML document: ###### >>> testtext = """ ... hello world. foo! ... """ ###### then we can use ElementTree to get a data structure out of this string: ####### >>> from elementtree import ElementTree >>> tree = ElementTree.fromstring(testtext) ####### 'tree' here is our root node, and the tree itself has a single child, the 'body' of the text, which we can get at by just indexing it: ###### >>> len(tree) 1 >>> tree[0] >>> tree[0].text 'hello world. ' ###### The body has some text, as well as a child (that italicized node): ###### >>> tree[0][0] >>> tree[0][0].text 'foo!' ###### One reason why this whole parsing thing is nice is because we can ask the tree things like: "Give me all the italicized nodes, anywhere in the document." ###### >>> for italicNode in tree.findall('.//i'): ... print italicNode.text ... foo! ###### No need to worry about regular expressions at all. *grin* We can also start mutating the tree and add more things. For example, let's add a "goodbye world" at the tail end of the body. ###### >>> tree[0].tail >>> tree[0].tail = "goodbye!" >>> >>> ElementTree.tostring(tree) 'hello world. foo!\ngoodbye!' ###### Does this make sense? > Looking through the python modules it seems like I need xmlrpclib - I > created a serverproxy instance, which I want to use to talk to a server Out of curiosity, which server? xmlrpclib is customized to talk to servers that speak the 'xmlrpc' protocol: http://www.xmlrpc.com/ so it might or might not be appropriate to use it, depending on what you're trying to connect to. From tomcloyd at bestmindhealth.com Wed May 25 03:08:43 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Tue, 24 May 2005 18:08:43 -0700 Subject: [Tutor] Pickling in plain English In-Reply-To: <1116977570.4293b9a28e665@www.paradise.net.nz> References: <2a278ffe05052416082efc0301@mail.gmail.com> <1116977570.4293b9a28e665@www.paradise.net.nz> Message-ID: I just want to take a moment to express my deep appreciation for this List. As one who is learning Python as amateur, in my spare moments, and already getting it to do good work for me, these clear, beautifully worked descriptions of basic aspects of Python are simply an ongoing delight for me - and singularly useful to my study of Python. To those of you who give your time, thought, and experience here to those of us who need it, thank you so very much. Tom Cloyd On Tue, 24 May 2005 16:32:50 -0700, wrote: > Quoting Tom Tucker : > >> I am having trouble understanding the c|Pickle modules. What does >> serializing and de-serializing objects mean? I have read the below >> urls and I "think" I understand the process, but I can't visualize the >> beneifts. Can someone kindly explain pickling in lamens terms? > > It's actually astonishingly simple, once you get the hang of it. > > example: > >>>> arr = [1, 3, 5, 7] >>>> dct = {'foo':1, 'bar':2, 'baz':3} >>>> st = "re: your mail" >>>> >>>> import pickle >>>> f = file('dump', 'wb') >>>> pickle.dump((arr, dct, st), f) >>>> f.close() >>>> ^Z > > [new instance of python] > >>>> import pickle >>>> f = file('dump', 'r') >>>> res = pickle.load(f) >>>> res > ([1, 3, 5, 7], {'bar': 2, 'foo': 1, 'baz': 3}, 're: your mail') > > [and you can look at the file 'dump' on your HDD, if you want to] > > Basically, pickle allows you to write any python object to disk and the > load it > back again with very little effort. This is important if you want your > program > to be able to save state between instances. > > You can pickle more complex objects; the only restriction is that > pickle.load > must be able to find the module where the classes are defined. > > [there are some other restrictions, but you can do a lot without > worrying about > them] > > Does this help? > -- ====================================================== Tom Cloyd Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From tktucker at gmail.com Wed May 25 03:25:30 2005 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 24 May 2005 21:25:30 -0400 Subject: [Tutor] Pickling in plain English In-Reply-To: References: <2a278ffe05052416082efc0301@mail.gmail.com> <1116977570.4293b9a28e665@www.paradise.net.nz> Message-ID: <2a278ffe05052418255305ab80@mail.gmail.com> John, Thanks that did help. Like usual, I was making it harder than necessary. Tom, I concur! Well put! On 5/24/05, Tom Cloyd wrote: > I just want to take a moment to express my deep appreciation for this > List. As one who is learning Python as amateur, in my spare moments, and > already getting it to do good work for me, these clear, beautifully worked > descriptions of basic aspects of Python are simply an ongoing delight for > me - and singularly useful to my study of Python. To those of you who give > your time, thought, and experience here to those of us who need it, thank > you so very much. > > Tom Cloyd > > On Tue, 24 May 2005 16:32:50 -0700, wrote: > > > Quoting Tom Tucker : > > > >> I am having trouble understanding the c|Pickle modules. What does > >> serializing and de-serializing objects mean? I have read the below > >> urls and I "think" I understand the process, but I can't visualize the > >> beneifts. Can someone kindly explain pickling in lamens terms? > > > > It's actually astonishingly simple, once you get the hang of it. > > > > example: > > > >>>> arr = [1, 3, 5, 7] > >>>> dct = {'foo':1, 'bar':2, 'baz':3} > >>>> st = "re: your mail" > >>>> > >>>> import pickle > >>>> f = file('dump', 'wb') > >>>> pickle.dump((arr, dct, st), f) > >>>> f.close() > >>>> ^Z > > > > [new instance of python] > > > >>>> import pickle > >>>> f = file('dump', 'r') > >>>> res = pickle.load(f) > >>>> res > > ([1, 3, 5, 7], {'bar': 2, 'foo': 1, 'baz': 3}, 're: your mail') > > > > [and you can look at the file 'dump' on your HDD, if you want to] > > > > Basically, pickle allows you to write any python object to disk and the > > load it > > back again with very little effort. This is important if you want your > > program > > to be able to save state between instances. > > > > You can pickle more complex objects; the only restriction is that > > pickle.load > > must be able to find the module where the classes are defined. > > > > [there are some other restrictions, but you can do a lot without > > worrying about > > them] > > > > Does this help? > > > > > > -- > > ====================================================== > Tom Cloyd > Bellingham, Washington, U.S.A: (360) 920-1226 > << BestMindHealth.com >> > ====================================================== > > Using Opera's revolutionary e-mail client (program): > http://www.opera.com/mail/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed May 25 04:48:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 May 2005 22:48:27 -0400 Subject: [Tutor] passing variables between frames? In-Reply-To: <20050524152839.97880.qmail@web30510.mail.mud.yahoo.com> References: <20050524152839.97880.qmail@web30510.mail.mud.yahoo.com> Message-ID: <4293E77B.8080906@tds.net> Jeff Peery wrote: > ok, thanks. that makes sense; however I do not know how to pass a > variable from my parent frame to the dialog. I have tried this before > unsuccessfully. could you provide a quick example of how to pass a > variable to a dialog from a frame. I am not sure how this works. thanks Can you post your (maybe broken) dialog code with a placeholder for the variable you want? Kent From tktucker at gmail.com Wed May 25 04:56:34 2005 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 24 May 2005 22:56:34 -0400 Subject: [Tutor] Covert numbers to hex fails Message-ID: <2a278ffe050524195655a0a6c0@mail.gmail.com> Good evening! I am trying to pass a number variable and have it converted to hex. Any recommendations on how to achieve this? Thank you. FAILS ---------- >>> value = 1234567890 >>> hexoutput = hex('%d' % (value)) Traceback (most recent call last): File "", line 1, in ? TypeError: hex() argument can't be converted to hex >>> WORKS ------------- >>> hexoutput = hex(1234567890) >>> print hexoutput 0x499602d2 >>> From jeffpeery at yahoo.com Wed May 25 05:00:23 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 24 May 2005 20:00:23 -0700 (PDT) Subject: [Tutor] passing variables between frames? In-Reply-To: 6667 Message-ID: <20050525030023.5592.qmail@web30505.mail.mud.yahoo.com> actually I got it to work! thanks for the help. Jeff Kent Johnson wrote: Jeff Peery wrote: > ok, thanks. that makes sense; however I do not know how to pass a > variable from my parent frame to the dialog. I have tried this before > unsuccessfully. could you provide a quick example of how to pass a > variable to a dialog from a frame. I am not sure how this works. thanks Can you post your (maybe broken) dialog code with a placeholder for the variable you want? Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050524/51148466/attachment-0001.html From tameyer at ihug.co.nz Wed May 25 05:09:10 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Wed, 25 May 2005 15:09:10 +1200 Subject: [Tutor] Covert numbers to hex fails In-Reply-To: Message-ID: > FAILS > ---------- > >>> value = 1234567890 > >>> hexoutput = hex('%d' % (value)) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: hex() argument can't be converted to hex Just don't convert the number to a string, e.g: >>> value = 1234567890 >>> hexoutput = hex(value) >>> hexoutput '0x499602d2' =Tony.Meyer From tktucker at gmail.com Wed May 25 05:14:18 2005 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 24 May 2005 23:14:18 -0400 Subject: [Tutor] Covert numbers to hex fails In-Reply-To: References: Message-ID: <2a278ffe05052420149e8d442@mail.gmail.com> Thanks! I see the mistake. On 5/24/05, Tony Meyer wrote: > > FAILS > > ---------- > > >>> value = 1234567890 > > >>> hexoutput = hex('%d' % (value)) > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: hex() argument can't be converted to hex > > Just don't convert the number to a string, e.g: > > >>> value = 1234567890 > >>> hexoutput = hex(value) > >>> hexoutput > '0x499602d2' > > =Tony.Meyer > > From zamb at saudi.net.sa Wed May 25 05:25:49 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Wed, 25 May 2005 06:25:49 +0300 Subject: [Tutor] Covert numbers to hex fails In-Reply-To: <2a278ffe050524195655a0a6c0@mail.gmail.com> References: <2a278ffe050524195655a0a6c0@mail.gmail.com> Message-ID: <1116991549.12034.3.camel@localhost.localdomain> On Tue, 2005-05-24 at 22:56 -0400, Tom Tucker wrote: > Good evening! I am trying to pass a number variable and have it > converted to hex. Any recommendations on how to achieve this? Thank > you. > > FAILS > ---------- > >>> value = 1234567890 > >>> hexoutput = hex('%d' % (value)) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: hex() argument can't be converted to hex > >>> > > > > WORKS > ------------- > >>> hexoutput = hex(1234567890) > >>> print hexoutput > 0x499602d2 > >>> Try one of those: '%x' % value # Will output the hex value without the leading 0x hex(value) # Leading 0x will be printed Ziyad. From alan.gauld at freenet.co.uk Wed May 25 09:18:17 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 25 May 2005 08:18:17 +0100 Subject: [Tutor] xml References: <8daabe560505241459ec99687@mail.gmail.com><1116972733.4293a6bd7ec99@www.paradise.net.nz> <8daabe5605052415401fa5c57b@mail.gmail.com> Message-ID: <01bb01c560f9$ec8c7b80$0db78851@xp> Hi Denise, Sounds like you need a tutor on the basics of the web rather than one on the Python aspects. It seems you are not familiar with the web terminology and therefore can't understand the explanations in the Python docs. I'll try to help with a few specifics here but you probably need to google for a web tutor somewhere. > modules it seems like I need xmlrpclib - I created a serverproxy > instance, which I want to use to talk to a server - to send it > information (in this case, a name), and return to me its response. I don't think you need this if you only want to use XML as a local storage medium. (Although a database is probably a better idea for that!) XNL serves several purposes but the one for which it was designed is as a platform independane data transport. So the expected use is for sending data between two different types of box - Windows and Linux say... Thats when you need servers and proxies and RPC (Remote Procedure Calls) etc. > (forgive my probably erroneous wording of things). It > said: "The returned instance is a proxy object with methods > that can be used to invoke corresponding RPC calls on the > remote server. So basically this thing is creating an object on your system that can talk to an object on another box somewhere (including on your own system of course!). This saves you the trouble of writing networking code, you just send messages to the local proxy object and it relays them to the remote object. But for your address book you don;t need this unless you intend to make the address list available over the network. > discovery) and fetch other server-associated metadata." > - and that sounds like what I want. Perhaps I am wrong? You might want to do that but the meta-data it refers to is data about data - for example the schema definition file that defines what your XML file looks like is an example of meta data. > Also, when I read the ElementTree page, it talked about element > instances instances of XML elements. An XML element being, basically, a single ... segment of your file. So you might have an address element with nested street and city elements. > and adding "code to load SML files as trees of Element And the above address elements form a tree structure. > objects, and save them back again" - as often happens to me (and, I > hope to other beginners), this explanation does not even tell me if it > does the same thing, or anything remotely related to what I am looking > for. When you start using a new technology its important to spend the time understanding the terminology of that tehnology, because the documentation will invariably assume you already know that. > "Both the HTTP and HTTPS transports support the URL syntax extension > for HTTP Basic Authentication: http://user:pass at host:port/path. The > http://myname:mypass/www.mysite.com > > does not work - but I dont know a "host" or "port" .... ? You missed an @ sign for a start! :-) The host is the IP address part: www.mysite.com ports are optional and by default http uses port 80. But you can specify a different port and this can be useful for building a test site prior to going live, so you might specify that as www.mysite.com:8080 to use port 8080 instead of port 80. In most cases you don't need to worry about that. Finally the path is the bit after the slash and looks like a file path, but is relative to the home directory of the web site and may have html references added on to the end. > documentation is not always user-friendly for beginners!) It assumes you are a beginner to the library but not to XML and XML tutors generally assume you are new to XML not to http or HTML. So you need to start at the beginning of web technology and read your way up the tree. HTH, Alan G. From alan.gauld at freenet.co.uk Wed May 25 09:22:20 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 25 May 2005 08:22:20 +0100 Subject: [Tutor] Covert numbers to hex fails References: <2a278ffe050524195655a0a6c0@mail.gmail.com> Message-ID: <01c201c560fa$7d56faf0$0db78851@xp> > Good evening! I am trying to pass a number variable and have it > converted to hex. Any recommendations on how to achieve this? You appear to have answered your own question below. What exactly is the problem? FAILS ---------- >>> value = 1234567890 >>> hexoutput = hex('%d' % (value)) WORKS ------------- >>> hexoutput = hex(1234567890) Are you trying to insert a hex representation of the number into a string for printing? If so the easiest way is using string format characters: >>> print "In hex: %d = %X" % (42,42) In hex: 42 = 2A HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rschroev_nospam_ml at fastmail.fm Wed May 25 09:55:31 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 25 May 2005 09:55:31 +0200 Subject: [Tutor] xml In-Reply-To: <8daabe560505241459ec99687@mail.gmail.com> References: <8daabe560505241459ec99687@mail.gmail.com> Message-ID: D. Hartley wrote: > And just in case anyone *isnt* working on the riddles....: > > anyone have a pointer to a *SIMPLE* intro to xml as used in python? I > looked in the library and there are about 11 xml-related modules. > > Perhaps something.... 'remote'..... ;) The 'remote' is the key indeed. What you need is xmlrpclib (as you already discovered). It uses XML, but that's only behind the scenes, you shouldn't have to deal with it yourself. The system.listMethods() an system.methodHelp() functions in the module should prove useful. And the 'Example of Client Usage' in the library reference, of course. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From jonasmg at softhome.net Wed May 25 12:31:42 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Wed, 25 May 2005 11:31:42 +0100 Subject: [Tutor] Exceptions and its error messages Message-ID: <4294540E.30902@softhome.net> Hi, How to know all the exceptions that there are? (i.e. OSError, ImportError) And all error messages of each exception? (i.e. err_o.strerror, err_o.filename) Thanks in advance! From jonasmg at softhome.net Wed May 25 13:09:34 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Wed, 25 May 2005 12:09:34 +0100 Subject: [Tutor] Data base in XML Message-ID: <42945CEE.1080907@softhome.net> Hi all, I'm going to build a little data base in XML, with information about localization for each country. Then, I'm in dude of using xml.sax (built in python) or elementtree. Which do you recommend to me? And is it necessary build a DTD or Schema file? Thanks in advance! From jfouhy at paradise.net.nz Wed May 25 13:17:00 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 25 May 2005 23:17:00 +1200 (NZST) Subject: [Tutor] Exceptions and its error messages In-Reply-To: <4294540E.30902@softhome.net> References: <4294540E.30902@softhome.net> Message-ID: <1117019820.42945eacde835@www.paradise.net.nz> Quoting Jonas Melian : > How to know all the exceptions that there are? (i.e. OSError, > ImportError) Check the Python library reference (on python.org); section 2.4: Built-in exceptions. Of course, you can subclass Exception to build your own! -- John. From kent37 at tds.net Wed May 25 13:32:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 May 2005 07:32:47 -0400 Subject: [Tutor] Exceptions and its error messages In-Reply-To: <4294540E.30902@softhome.net> References: <4294540E.30902@softhome.net> Message-ID: <4294625F.4040602@tds.net> Jonas Melian wrote: > How to know all the exceptions that there are? (i.e. OSError, ImportError) The built-in exceptions are documented here: http://docs.python.org/lib/module-exceptions.html Some library modules define their own exceptions such as socket.error so the above is not a complete list of exceptions defined in the standard distribution, just the ones that are built-in. And of course third-party modules and your own code can define new exceptions so I would say it's not possible to know *all* the exceptions that there are. > And all error messages of each exception? (i.e. err_o.strerror, > err_o.filename) I don't understand this part of the question; what is err_o? Kent From kent37 at tds.net Wed May 25 13:35:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 May 2005 07:35:41 -0400 Subject: [Tutor] Data base in XML In-Reply-To: <42945CEE.1080907@softhome.net> References: <42945CEE.1080907@softhome.net> Message-ID: <4294630D.2050004@tds.net> Jonas Melian wrote: > Hi all, > > I'm going to build a little data base in XML, with information about > localization for each country. Why XML? You could use pickle or CSV or a real database... > Then, I'm in dude of using xml.sax (built in python) or elementtree. > Which do you recommend to me? elementtree > And is it necessary build a DTD or Schema file? No. These are helpful if you want to validate your data but not required. Kent From jonasmg at softhome.net Wed May 25 14:03:58 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Wed, 25 May 2005 13:03:58 +0100 Subject: [Tutor] Exceptions and its error messages In-Reply-To: <4294625F.4040602@tds.net> References: <4294540E.30902@softhome.net> <4294625F.4040602@tds.net> Message-ID: <429469AE.40106@softhome.net> Kent Johnson wrote: > Jonas Melian wrote: >> How to know all the exceptions that there are? (i.e. OSError, ImportError) > > Some library modules define their own exceptions such as socket.error so > the above is not a complete > list of exceptions defined in the standard distribution, just the ones > that are built-in. > > And of course third-party modules and your own code can define new > exceptions so I would say it's > not possible to know *all* the exceptions that there are. > >> And all error messages of each exception? (i.e. err_o.strerror, >> err_o.filename) > > I don't understand this part of the question; what is err_o? > I use i.e. with OSError exception the next error messages: err_o.strerror, err_o.filename :: try: (os.listdir(x)) except OSError, err_o: print "Error! %s: %r" % (err_o.strerror, err_o.filename) :: But how knowing all error messages from some module? Is there any way of knowing from python interactive line? :: >>> import [module] >>> help(exceptions) :: From jonasmg at softhome.net Wed May 25 14:13:44 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Wed, 25 May 2005 13:13:44 +0100 Subject: [Tutor] Data base in XML In-Reply-To: <4294630D.2050004@tds.net> References: <42945CEE.1080907@softhome.net> <4294630D.2050004@tds.net> Message-ID: <42946BF8.2010109@softhome.net> Kent Johnson wrote: >>I'm going to build a little data base in XML, with information about >>localization for each country. > > Why XML? You could use pickle or CSV or a real database... > I have choosed XML because it's designed as a universal data exchange format. From python at venix.com Wed May 25 14:14:11 2005 From: python at venix.com (Lloyd Kvam) Date: Wed, 25 May 2005 08:14:11 -0400 Subject: [Tutor] brief description of URL's Message-ID: <1117023252.5298.34.camel@laptop.venix.com> A sample URL http://www.mysite.com/path-to/file?arg1=stuff&arg2=morestuff http: scheme of URL (specifies protocol or processing) //www.mysite.com is the host. the name of the computer That host computer could be offering many services, web sites, email, time, etc. Each service is given a number which is how you can specify the service you want to use. These numbers are ports. http 'listens' at port 80 smtp (email delivery) listens at port 25 pop (retrieving email from mailbox) is at port 110 https (SSL) is at port 443 If you want your software to connect to a different port number, that can be specified after the host. So if the www.mysite.com computer were running a Zope server that listened at port 8080, the URL to connect to Zope would be http://www.mysite.com:8080 A user name and password can precede the computer name. A @ is used to separate the computer name part from the user identification. http://myname:mypass at www.mysite.com The rules for URLs are specified here http://www.ietf.org/rfc/rfc1738.txt Google can help you find more. IANA now provides the registry for URL schemes along with pointers to documentation. http://www.iana.org/assignments/uri-schemes -- Lloyd Kvam Venix Corp From kent37 at tds.net Wed May 25 14:49:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 May 2005 08:49:33 -0400 Subject: [Tutor] Exceptions and its error messages In-Reply-To: <429469AE.40106@softhome.net> References: <4294540E.30902@softhome.net> <4294625F.4040602@tds.net> <429469AE.40106@softhome.net> Message-ID: <4294745D.8020507@tds.net> Jonas Melian wrote: > I use i.e. with OSError exception the next error messages: > err_o.strerror, err_o.filename > > :: > try: > (os.listdir(x)) > except OSError, err_o: > print "Error! %s: %r" % (err_o.strerror, err_o.filename) > :: > > But how knowing all error messages from some module? > Is there any way of knowing from python interactive line? If you want to print a useful message in your own exception handler, you have a couple of options. One is to use str(err_o): >>> import os >>> try: ... os.listdir('foo') ... except OSError, e: ... pass ... >>> e >>> dir(e) ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args', 'errno', 'filename', 'strerror'] >>> e.errno 3 >>> e.filename 'foo/*.*' >>> str(e) "[Errno 3] The system cannot find the path specified: 'foo/*.*'" >>> try: ... import foo ... except ImportError, e1: ... pass ... >>> e1 Notice that an ImportError does not have errno and filename attributes: >>> dir(e1) ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] but str() still gives a useful message: >>> str(e1) 'No module named foo' The traceback module is very helpful: >>> import traceback >>> traceback.format_exception_only(e.__class__, e) ["WindowsError: [Errno 3] The system cannot find the path specified: 'foo/*.*'\n"] >>> traceback.format_exception_only(e1.__class__, e1) ['ImportError: No module named foo\n'] traceback.print_exc() will print the exception and stack trace the same as you would get if the exception was not caught. So a useful exception handler is except SomeError: import traceback trackback.print_exc() If you want finer control you could try e.g. import sys, traceback typ, value, tb = sys.exc_info() print '\n'.join(traceback.format_exception_only(typ, value)) HTH, Kent From RPhillips at engineer.co.summit.oh.us Wed May 25 15:03:27 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Wed, 25 May 2005 09:03:27 -0400 Subject: [Tutor] Am I making this harder than it needs to be? Message-ID: short version: I need a way to get max and min E and N out of [(E0,N0),(E1,N1)...(En,Nn)] without reordering the list long version: I would like a list of geographic coordinates (Easting, Northing) to maintain a "bounding box" [(minEasting,minNorthing),(maxEasting,maxNorthing)] attribute. I did it like this: class geoCoordinateList(UserList): def __init__(self): UserList.__init__(self) self.boundingBox = geoBox(minEN=geoCoordinate(), maxEN=geoCoordinate()) def append(self, geoCoord): self.extend([geoCoord]) self.boundingBox.challenge(geoCoord)#bumps the max and min if necessary but I'd have to override almost all the UserList methods, unless there's a way to call boundingBox.challenge() on any change to the list. The other way I thought would be to make a getBB method, like: def getBB(self): new=geoBox() for gC in self: new.challenge(gC)#bumps the corners if needed self.boundingBox=new return(new) but that seems like a lot of churning if nothing has changed. I suspect there's some slick, readable way to do this, and when I see it I'll say "Doh!" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050525/e0f53d6b/attachment.htm From ajikoe at gmail.com Wed May 25 15:47:56 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 25 May 2005 15:47:56 +0200 Subject: [Tutor] Am I making this harder than it needs to be? In-Reply-To: References: Message-ID: try this code: L = [(1,11),(2,22)] print max(L) print min(L) I don't know if that what you want. good luck pujo On 5/25/05, Ron Phillips wrote: > > short version: I need a way to get max and min E and N out of > [(E0,N0),(E1,N1)...(En,Nn)] without reordering the list > > long version: > > I would like a list of geographic coordinates (Easting, Northing) to > maintain a "bounding box" > [(minEasting,minNorthing),(maxEasting,maxNorthing)] > attribute. > > I did it like this: > > class geoCoordinateList(UserList): > def __init__(self): > UserList.__init__(self) > self.boundingBox = geoBox(minEN=geoCoordinate(), > maxEN=geoCoordinate()) > > def append(self, geoCoord): > self.extend([geoCoord]) > self.boundingBox.challenge(geoCoord)#bumps the max and min if > necessary > > but I'd have to override almost all the UserList methods, unless there's a > way to call boundingBox.challenge() on any change to the list. > > The other way I thought would be to make a getBB method, like: > > def getBB(self): > new=geoBox() > for gC in self: > new.challenge(gC)#bumps the corners if needed > self.boundingBox=new > return(new) > > but that seems like a lot of churning if nothing has changed. > > I suspect there's some slick, readable way to do this, and when I see it > I'll say "Doh!" > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From cpu.crazy at gmail.com Wed May 25 15:12:56 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 25 May 2005 07:12:56 -0600 Subject: [Tutor] Python won't play .wav file In-Reply-To: References: Message-ID: <6.1.0.6.2.20050525070737.01f3c038@pop.gmail.com> Hi, I'm replying to you both... At 03:16 PM 5/24/2005, you wrote: >Strangely... I do not believe the wave module is meant to actually >_play_ a wav file. It looks to me like it is only intended to read and >parse the file for meta information. > >You could try passing the name of the file to another program >via os.system, or you could use pygame. Ok.... drat. I was hoping that it would play the files. >------------------------------ >Lee Harr wrote: > >If you are on windows try the winsound module. And if I'm on Linux or programing for Mac? Thanks guys, JQ From tktucker at gmail.com Wed May 25 16:04:55 2005 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 25 May 2005 10:04:55 -0400 Subject: [Tutor] Covert numbers to hex fails In-Reply-To: <01c201c560fa$7d56faf0$0db78851@xp> References: <2a278ffe050524195655a0a6c0@mail.gmail.com> <01c201c560fa$7d56faf0$0db78851@xp> Message-ID: <2a278ffe05052507046babb57e@mail.gmail.com> Alan, Thanks! Your response was helpful. I was trying to pass a number variable to the hex object. The output associated with this would be referenced in the hexoutput variable. I guess this is as simple as.... hexoutput = "%X" % (value) Thanks again for the help, Tom On 5/25/05, Alan G wrote: > > > Good evening! I am trying to pass a number variable and have it > > converted to hex. Any recommendations on how to achieve this? > > You appear to have answered your own question below. > What exactly is the problem? > > FAILS > ---------- > >>> value = 1234567890 > >>> hexoutput = hex('%d' % (value)) > > WORKS > ------------- > >>> hexoutput = hex(1234567890) > > Are you trying to insert a hex representation of the number into a > string for printing? If so the easiest way is using string format > characters: > > >>> print "In hex: %d = %X" % (42,42) > In hex: 42 = 2A > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > From RPhillips at engineer.co.summit.oh.us Wed May 25 16:05:55 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Wed, 25 May 2005 10:05:55 -0400 Subject: [Tutor] Am I making this harder than it needs to be? Message-ID: Oh, thanks! That didn't exactly do the trick, because I had data like [(1, 22),(2,11)], but from your code I came up with: def getBB(self): Es=[] Ns=[] for i in range(len(self)): Es.append((self[i].E)) Ns.append((self[i].N)) self.boundingBox=geoBox((min(Es),min(Ns)),(max(Es),max(Ns))) return(self.boundingBox) which works fine, and I think will be pretty fast. Ron >>> Pujo Aji 5/25/2005 9:47 AM >>> try this code: L = [(1,11),(2,22)] print max(L) print min(L) I don't know if that what you want. good luck pujo On 5/25/05, Ron Phillips wrote: > > short version: I need a way to get max and min E and N out of > [(E0,N0),(E1,N1)...(En,Nn)] without reordering the list > > long version: > > I would like a list of geographic coordinates (Easting, Northing) to > maintain a "bounding box" > [(minEasting,minNorthing),(maxEasting,maxNorthing)] > attribute. > > I did it like this: > > class geoCoordinateList(UserList): > def __init__(self): > UserList.__init__(self) > self.boundingBox = geoBox(minEN=geoCoordinate(), > maxEN=geoCoordinate()) > > def append(self, geoCoord): > self.extend([geoCoord]) > self.boundingBox.challenge(geoCoord)#bumps the max and min if > necessary > > but I'd have to override almost all the UserList methods, unless there's a > way to call boundingBox.challenge() on any change to the list. > > The other way I thought would be to make a getBB method, like: > > def getBB(self): > new=geoBox() > for gC in self: > new.challenge(gC)#bumps the corners if needed > self.boundingBox=new > return(new) > > but that seems like a lot of churning if nothing has changed. > > I suspect there's some slick, readable way to do this, and when I see it > I'll say "Doh!" > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ______________________________________________________________________ This email has been scanned by the MessageLabs Email Security System. For more information please visit http://www.messagelabs.com/email ______________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050525/6d0bc180/attachment.htm From kent37 at tds.net Wed May 25 16:19:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 May 2005 10:19:39 -0400 Subject: [Tutor] Am I making this harder than it needs to be? In-Reply-To: References: Message-ID: <4294897B.6000603@tds.net> Ron Phillips wrote: > short version: I need a way to get max and min E and N out of > [(E0,N0),(E1,N1)...(En,Nn)] without reordering the list not sure if your coordinates are strings like 'E0' or if that is a placeholder for an int. If they are ints you can use minE = min(e for e,n in coordList) If they are strings you have to convert minE = min(int(e[1:]) for e,n in coordList) etc For Python < 2.4 you need another set of [ ] e.g. min([e for e,n in coordList]) > long version: > > I would like a list of geographic coordinates (Easting, Northing) to > maintain a "bounding box" > [(minEasting,minNorthing),(maxEasting,maxNorthing)] attribute. > > I did it like this: > > class geoCoordinateList(UserList): > def __init__(self): > UserList.__init__(self) > self.boundingBox = geoBox(minEN=geoCoordinate(), > maxEN=geoCoordinate()) > def append(self, geoCoord): > self.extend([geoCoord]) > self.boundingBox.challenge(geoCoord)#bumps the max and min if > necessary > but I'd have to override almost all the UserList methods, unless there's > a way to call boundingBox.challenge() on any change to the list. If you don't need too much list functionality it might be easier to wrap a list and delegate the things you need: class geoCoordinateList(object): def __init__(self): self.list = list() self.boundingBox = geoBox(minEN=geoCoordinate(), maxEN=geoCoordinate()) def append(self, geoCoord): self.list.append(geoCoord) # No need for extend() here... self.boundingBox.challenge(geoCoord)#bumps the max and min if necessary I think you will want at least __getitem__() and __len__() as well. Kent From missive at hotmail.com Wed May 25 22:27:00 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 26 May 2005 00:57:00 +0430 Subject: [Tutor] Python Date picker Message-ID: >>>What I need to do is validate a date field (better if it's already done) >>>and >>>I want to know if anyone knows about a code to do that (a made code, >>>don't >>>mean you to do my work). I was hoping to find a calendar combo box as in >>>Visual Basic DropDown Calendar >>> >>> >>For which GUI system? >> >I'm working over Windows, Python 2.3., GUI Tkinter > I found this one: http://www2.gol.com/users/sshenoy/TkXtra.html but the date selector is a bit primitive. I recommend asking again at comp.lang.python _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From missive at hotmail.com Wed May 25 22:32:08 2005 From: missive at hotmail.com (Lee Harr) Date: Thu, 26 May 2005 01:02:08 +0430 Subject: [Tutor] Python won't play .wav file Message-ID: >>Strangely... I do not believe the wave module is meant to actually >>_play_ a wav file. It looks to me like it is only intended to read and >>parse the file for meta information. >> >>You could try passing the name of the file to another program >>via os.system, or you could use pygame. > >Ok.... drat. I was hoping that it would play the files. > > > >>------------------------------ >>Lee Harr wrote: >> >>If you are on windows try the winsound module. > >And if I'm on Linux or programing for Mac? > I did not write this. I did, however, write this: """ Strangely... I do not believe the wave module is meant to actually _play_ a wav file. It looks to me like it is only intended to read and parse the file for meta information. You could try passing the name of the file to another program via os.system, or you could use pygame. """ _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From mandziy at web.de Thu May 26 00:41:08 2005 From: mandziy at web.de (Khrystyna Mandziy) Date: Thu, 26 May 2005 00:41:08 +0200 Subject: [Tutor] Copy selected text of entry widget Message-ID: <4294FF04.7060507@web.de> Hi, all! How can be implemented copieng to clipboard of entry widget? This dosn't works self.selection = self.entry.get(SEL_FIRST, SEL_LAST) get takes only 1 arg. reg. From jeannot18 at hotmail.com Thu May 26 01:47:22 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Wed, 25 May 2005 23:47:22 +0000 Subject: [Tutor] (no subject) Message-ID: With the help of Pujo Aji I have written this little script that print every single ASCII code>> S = [chr(x) for x in range (0,256)] for x in S: print x, The next step is to use the built-in functin ord() in order to convert each character to an ASCII integer. I have had a look at the ord() function but it says that it only take one argument i.e. ord('a'). How could I execute to convert each character into an ASCII integer? Thanks in advance JC From jfouhy at paradise.net.nz Thu May 26 02:55:41 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 26 May 2005 12:55:41 +1200 (NZST) Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <1117068941.42951e8dd5f0f@www.paradise.net.nz> Quoting John Carmona : > The next step is to use the built-in functin ord() in order to convert > each character to an ASCII integer. I have had a look at the ord() function > but it says that it only take one argument i.e. ord('a'). How could I > execute to convert each character into an ASCII integer? The chr() function only takes one argument (eg: chr(97)). How did you use it to convert each integer into an ASCII character? -- John. From ajikoe at gmail.com Thu May 26 09:29:47 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 26 May 2005 09:29:47 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: Actually you can do the same way: # Convert intAscii to charAscii S = [chr(x) for x in range(0,256)] for x in S: print x #Convert charAscii to intAscii AsciiInt = [ord(x) for x in S] for x in AsciiInt: print x Best Regards, pujo On 5/26/05, John Carmona wrote: > With the help of Pujo Aji I have written this little script that print every > single ASCII code>> > > S = [chr(x) for x in range (0,256)] > for x in S: > print x, > > The next step is to use the built-in functin ord() in order to convert each > character to an ASCII integer. I have had a look at the ord() function but > it says that it only take one argument i.e. ord('a'). How could I execute to > convert each character into an ASCII integer? > > Thanks in advance > JC > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu May 26 10:08:18 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 09:08:18 +0100 Subject: [Tutor] Python won't play .wav file References: <6.1.0.6.2.20050525070737.01f3c038@pop.gmail.com> Message-ID: <025201c561ca$1398db80$0db78851@xp> > And if I'm on Linux or programing for Mac? Sadly sound is one of those things that tends to be system dependant. There is a Sun audio module somewhere too... On the Mac I believe its a Quicktime thing using the MacPython libraries. The good news is that I think PyGame provides a platform independant sound capability so I'd recommend that route, although I've never used it. In fact, come to think of it, in my 30 years of programming, sound is one of the few things I've never, ever worked with! (I once built a midi player on Windows using the Delphi player control but that hardly counts!) Alan G. From alan.gauld at freenet.co.uk Thu May 26 10:15:04 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 09:15:04 +0100 Subject: [Tutor] (no subject) References: Message-ID: <026401c561cb$05cc0800$0db78851@xp> > S = [chr(x) for x in range (0,256)] > for x in S: > print x, for x in range(256): print chr(x), > The next step is to use the built-in functin ord() in order to convert each > character to an ASCII integer. That will give you the numbers 0..255 ord() is simply the inverse of chr() so that x == ord(chr(x)) > it says that it only take one argument i.e. ord('a'). How could I execute to > convert each character into an ASCII integer? The same as you did for chr(), use a loop: S = [chr(x) for x in range (0,256)] for x in S: print ord(x), But it will simply print out the list of numbers from 0..255. Do you have a purpose in mind or are you simply wanting to observe chr() and ord() in action? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From benvinger at yahoo.co.uk Thu May 26 10:32:50 2005 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu, 26 May 2005 09:32:50 +0100 (BST) Subject: [Tutor] (no subject) Message-ID: <20050526083250.32271.qmail@web25802.mail.ukl.yahoo.com> Or like this: for x in range (0,256): print ord(chr(x)), ': ', chr(x) (you could just print x, instead of ord(chr(x)), but then you would not be using ord) Ben --- Pujo Aji wrote: > Actually you can do the same way: > > # Convert intAscii to charAscii > S = [chr(x) for x in range(0,256)] > for x in S: print x > > #Convert charAscii to intAscii > AsciiInt = [ord(x) for x in S] > for x in AsciiInt: print x > > Best Regards, > pujo > > On 5/26/05, John Carmona > wrote: > > With the help of Pujo Aji I have written this > little script that print every > > single ASCII code>> > > > > S = [chr(x) for x in range (0,256)] > > for x in S: > > print x, > > > > The next step is to use the built-in functin ord() > in order to convert each > > character to an ASCII integer. I have had a look > at the ord() function but > > it says that it only take one argument i.e. > ord('a'). How could I execute to > > convert each character into an ASCII integer? > > > > Thanks in advance > > JC > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ Can't remember an address in your address book? Enter the first few letters and Address AutoComplete will automatically finish it. Get Yahoo! Mail http://uk.mail.yahoo.com From RPhillips at engineer.co.summit.oh.us Thu May 26 13:22:25 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Thu, 26 May 2005 07:22:25 -0400 Subject: [Tutor] Am I making this harder than it needs to be? Message-ID: Ron Phillips wrote: >> short version: I need a way to get max and min E and N out of >> [(E0,N0),(E1,N1)...(En,Nn)] without reordering the list >>> Kent Johnson kent37 at tds.net> 5/25/2005 10:19 AM >> >For Python < 2.4 you need another set of [ ] e.g. min([e for e,n in coordList]) I knew I was working too hard!! That's exactly what I needed -- for some reason, ESRI (big name in geographic work) uses Python 2.2. Ron Phillips wrote: >> long version: >> >> I would like a list of geographic coordinates (Easting, Northing) to >> maintain a "bounding box" >> [(minEasting,minNorthing),(maxEasting,maxNorthing)] attribute. >> >>I did it like this: >> >>class geoCoordinateList(UserList): >>def __init__(self): >>UserList.__init__(self) >>self.boundingBox = geoBox(minEN=geoCoordinate(), >>maxEN=geoCoordinate()) >>def append(self, geoCoord): >>self.extend([geoCoord]) >>self.boundingBox.challenge(geoCoord)#bumps the max and min if >>necessary >>but I'd have to override almost all the UserList methods, unless there's >>a way to call boundingBox.challenge() on any change to the list. >If you don't need too much list functionality it might be easier to wrap a list and delegate the >things you need: >class geoCoordinateList(object): >def __init__(self): >self.list = list() >self.boundingBox = geoBox(minEN=geoCoordinate(), >maxEN=geoCoordinate()) >def append(self, geoCoord): >self.list.append(geoCoord) # No need for extend() here... >self.boundingBox.challenge(geoCoord)#bumps the max and min if necessary >I think you will want at least __getitem__() and __len__() as well. >Kent Yep, that was my problem; I had "too much list functionality" to delegate -- your way is much better for the purpose. I can expose that class without promising all the functionality of a list. In most languages there are a half-dozen stupid, painful ways to do a job, and maybe one that's merely painful, but in Python there's a half-dozen "ok" ways to do a job, and at least one that's a real pleasure! Thanks for the answers! Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050526/4ed2be7a/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: Header Type: application/octet-stream Size: 472 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050526/4ed2be7a/Header.obj From mark.kels at gmail.com Thu May 26 14:00:08 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu, 26 May 2005 14:00:08 +0200 Subject: [Tutor] Program to lock folders under win32 Message-ID: Hi list. I want to make a program to lock folders (so the user can only access them if he knows the password) under win32, the only problem is that I have no idea how to start or what to do. Do you guys have any ideas of how to do it? Thanks! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From feziwe at sanbi.ac.za Thu May 26 18:03:16 2005 From: feziwe at sanbi.ac.za (Feziwe Mpondo) Date: Thu, 26 May 2005 18:03:16 +0200 Subject: [Tutor] python problem Message-ID: <4295F344.8090206@sanbi.ac.za> hi i'm trying to write a code that handle errors help def print_menu(): print '1. Print Phone Numbers' print '2. Add a Phone Number' print '3. Remove a Phone Number' print '4. Lookup a Phone Number' print '5. Quit' print numbers = {} menu_choice = 0 print_menu() while menu_choice != 5: menu_choice = input("Type in a number (1-5):") break except(TypeError,NameError): if menu_choice == 1: print "Telephone Numbers:" for x in numbers.keys(): print "Name: ",x," \tNumber: ",numbers[x] print elif menu_choice == 2: print "Add Name and Number" name = raw_input("Name:") phone = raw_input("Number:") numbers[name] = phone elif menu_choice == 3: print "Remove Name and Number" name = raw_input("Name:") if numbers.has_key(name): del numbers[name] else: print name," was not found" elif menu_choice == 4: print "Lookup Number" name = raw_input("Name:") if numbers.has_key(name): print "The number is",numbers[name] else: print name," was not found" else: print_menu() From John.Gooch at echostar.com Thu May 26 17:42:47 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Thu, 26 May 2005 09:42:47 -0600 Subject: [Tutor] Are Empty "Placeholder" Functions possible? Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D40C@riv-excha5.echostar.com> Is there a way to create an empty function definition with no lines of code in it? In my coding style I will often do this ( in other languages ) for RAD just to remind myself that I will need to implement the function later. Example: For a file handling class, I may need functions such as copy,delete,move,etc so I want to start off with: class FileHandler: def __init__(self): def copy(self): def delete(self): . . . then in my driver/aka testing file: import FileHandler def main() MyHandler = FileHandler() print "Handler Created." main() Right now, this won't work as the compliler will error on functions with nothing in them. Is there a "no-op", "do nothing", or some similar command I can put in the empty functions to keep the compiler/interpreter from erroring on them? This would really help speed up my development so that I can create the class skeleton quickly and then implement each function and test it as I go. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From kent37 at tds.net Thu May 26 17:51:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 May 2005 11:51:32 -0400 Subject: [Tutor] Are Empty "Placeholder" Functions possible? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D40C@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D40C@riv-excha5.echostar.com> Message-ID: <4295F084.8010405@tds.net> Gooch, John wrote: > Is there a way to create an empty function definition with no lines of code > in it? In my coding style I will often do this ( in other languages ) for > RAD just to remind myself that I will need to implement the function later. A block cannot be empty but there is a placeholder statement 'pass' that does nothing. > > Example: For a file handling class, I may need functions such as > copy,delete,move,etc so I want to start off with: > > class FileHandler: > def __init__(self): > > def copy(self): > > def delete(self): class FileHandler: def __init__(self): pass def copy(self): pass def delete(self): pass Kent From william.ohiggins at utoronto.ca Thu May 26 18:16:23 2005 From: william.ohiggins at utoronto.ca (William O'Higgins) Date: Thu, 26 May 2005 12:16:23 -0400 Subject: [Tutor] Expression order problem Message-ID: <20050526161623.GA20115@sillyrabbi.dyndns.org> I am running into problems with script evaluation order - specifically, the Python interpreter seems to read and execute scripts line by line. This is a problem if you are used to Perl, where the whole script is parsed first (Perl also auto-vivifies variables, but that's a different problem for a different day). Here is a test script: #!/usr/bin/python import sys class test: variable = "is this a variable" + other_argument if sys.argv[1:]: argument = sys.argv[1] other_argument = sys.argv[2] instance = test() print instance.variable else: sys.exit() I am only beginning to get my head around OO programming, so please bear with me. In Perl, I would define all of my subs (functions or classes) at the end of the program, because the Perl parser will read the whole program, and then execute it. So I'm having trouble from the start because I can't do that - the interpreter whines about undefined calls when things are defined further down the page. In my example though - I want to use variables from one code block in another, but whichever one is first, something is undefined. I'm not necessarily looking for a fix, but pointers as to technique to avoid this would be appreciated. Thanks. -- yours, William -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050526/2eb4dc32/attachment.pgp From John.Gooch at echostar.com Thu May 26 19:05:13 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Thu, 26 May 2005 11:05:13 -0600 Subject: [Tutor] Are Empty "Placeholder" Functions possible? Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D410@riv-excha5.echostar.com> Thanks Kent! -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Thursday, May 26, 2005 9:52 AM To: Gooch, John Cc: tutor at python.org Subject: Re: [Tutor] Are Empty "Placeholder" Functions possible? Gooch, John wrote: > Is there a way to create an empty function definition with no lines of > code in it? In my coding style I will often do this ( in other > languages ) for RAD just to remind myself that I will need to > implement the function later. A block cannot be empty but there is a placeholder statement 'pass' that does nothing. > > Example: For a file handling class, I may need functions such as > copy,delete,move,etc so I want to start off with: > > class FileHandler: > def __init__(self): > > def copy(self): > > def delete(self): class FileHandler: def __init__(self): pass def copy(self): pass def delete(self): pass Kent From nick at javacat.f2s.com Thu May 26 19:06:41 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 26 May 2005 18:06:41 +0100 Subject: [Tutor] Are Empty "Placeholder" Functions possible? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D40C@riv-excha5.echostar.com> Message-ID: Hi John, you can use 'pass' . This works the same as with exceptions, eg try: open('somefile') except IOError: pass so we can have class doNothing: def __init__(self): pass def boring(self, other): pass Hope that helps :) Nick -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Gooch, John Sent: 26 May 2005 16:43 To: tutor at python.org Subject: [Tutor] Are Empty "Placeholder" Functions possible? Is there a way to create an empty function definition with no lines of code in it? In my coding style I will often do this ( in other languages ) for RAD just to remind myself that I will need to implement the function later. Example: For a file handling class, I may need functions such as copy,delete,move,etc so I want to start off with: class FileHandler: def __init__(self): def copy(self): def delete(self): . . . then in my driver/aka testing file: import FileHandler def main() MyHandler = FileHandler() print "Handler Created." main() Right now, this won't work as the compliler will error on functions with nothing in them. Is there a "no-op", "do nothing", or some similar command I can put in the empty functions to keep the compiler/interpreter from erroring on them? This would really help speed up my development so that I can create the class skeleton quickly and then implement each function and test it as I go. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- No virus found in this incoming message. Checked by AVG Anti-Virus. Version: 7.0.322 / Virus Database: 266.11.17 - Release Date: 25/05/2005 From project5 at redrival.net Thu May 26 20:24:57 2005 From: project5 at redrival.net (Andrei) Date: Thu, 26 May 2005 18:24:57 +0000 (UTC) Subject: [Tutor] Expression order problem References: <20050526161623.GA20115@sillyrabbi.dyndns.org> Message-ID: William O'Higgins utoronto.ca> writes: > This is a problem if you are used to Perl, where the whole script is > parsed first (Perl also auto-vivifies variables, but that's a different > problem for a different day). Here is a test script: The Python compiler parses the whole script too, can't compile otherwise. Of course a variable must exist if its value is requested. I don't know what vivifying a variable means, but surely Perl doesn't pull a non-existing variable out of its sleeves? > class test: > variable = "is this a variable" + other_argument > > if sys.argv[1:]: > other_argument = sys.argv[2] > instance = test() > print instance.variable > else: > sys.exit() > I am only beginning to get my head around OO programming, so please bear > with me. In Perl, I would define all of my subs (functions or classes) > at the end of the program, because the Perl parser will read the whole > program, and then execute it. So I'm having trouble from the start That's what Python does too. But the variable assignment above is not in a function, so it's executed immediately like any other statement. > because I can't do that - the interpreter whines about undefined calls > when things are defined further down the page. It whines if they're used before they're defined. It's perfectly fine to have them, undefined and all, as long as they aren't used. > In my example though - I > want to use variables from one code block in another, but whichever one > is first, something is undefined. I'm not necessarily looking for a > fix, but pointers as to technique to avoid this would be appreciated. > Thanks. I can think of several possibilities: 1. assign a value to your variable before using it in the class definition. You can do this by putting the assignment code above the class definition or putting the assignment code in a separate module and importing it at the top of the module which defines the class. 2. assign the attribute to the class only once its value is known: >>> class tst: ... var = None ... >>> myvar = 5 >>> tst.var = myvar >>> inst = tst() >>> inst.var 5 3. Make it an attribute of the instance rather than of the class: >>> class tst2: ... def __init__(self): ... self.var = newvar ... print 'tst2.__init__ executed' ... >>> tst2() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ NameError: global name 'newvar' is not defined >>> newvar = 57 >>> tst2().var tst2.__init__ executed 57 It would be better to pass the extra argument as function parameter to __init__, but anyway. 4. Generate the class after the value of the variable is known: >>> def generateclass(): ... class test4: ... var = newervar ... return test4 ... >>> test = generateclass() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in generateclass File "", line 3, in test4 NameError: name 'newervar' is not defined >>> newervar = 100 >>> test = generateclass() >>> instance = test() >>> instance.var 100 5. Use a class method instead of an attribute: >>> class test5: ... @classmethod ... def var(cls): ... return dummy ... >>> test5.var() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in var NameError: global name 'dummy' is not defined >>> dummy = 234 >>> test5.var() 234 >>> test5().var() 234 Which soultion is right, depends on your needs. I'm tempted to say (3) is the best one, unless you really need that to be a class attribute. Tip: http://zephyrfalcon.org/labs/python_pitfalls.html Yours, Andrei From zmerch at 30below.com Thu May 26 20:40:41 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Thu, 26 May 2005 14:40:41 -0400 Subject: [Tutor] better resolution on time.sleep()? In-Reply-To: <010b01c5602e$502fd000$0db78851@xp> References: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> Message-ID: <5.1.0.14.2.20050526131547.03a35908@mail.30below.com> Rumor has it that Alan G may have mentioned these words: > > I'm running an application that has a polling loop to check a serial >port > > for certain signals, and on my laptop I can get about 6700 samples >per > > second, which (of course) consumes 100% CPU; which may impact >battery life. > >Consuming 100% CPU won't make much difference, the CPU is running all >the time anyway (when its not asleep). Not mine... my laptop runs a Crusoe processor, and it can automatically scale itself from 300Mhz to 933Mhz. It's called "LongRun" technology, and it works quite well, too. On my extended battery at "near idle" ... say, playing Spider, I get 5+ hours of battery life (and the battery's 2 years old, just like the laptop). Running the program at full tilt, I get just over 2 hours (but admittedly, it's scanning my USB->RS232 dongle, and I don't know how much current that may take... However, it's not transmitting, so it shouldn't be an overly huge amount.) I can run more tests if anyone's interested, but... Since the first Pentium (and possibly '486s) the CPU could put itself in a wait state to conserve CPU cycles that weren't being used -- and "wake itself up" automatically when needed. WinNT 4.0 and newer (and most *nixen) could use that, altho it didn't make *as much* difference for thermal or power aspects back then; the ability was there mainly for multiprocessor applications. Now they've improved it for both thermal and power usage functions as well. > What will consume batteries much >faster is if you are accessing hardware such as disk or modem or other >power hungry devices. I would only get about 1.5 hours (when the battery was new) compiling my LinuxFromScratch -- 100% CPU, HD getting hammered and snagging packages off of the CDROM... yea, the battery (and external charger) got quite a workout those few weeks... ;-) >I've never tried in Python but can you use select()? >I've used it in C for short duration intervals. Never used it yet (altho I saw references that Python's time.sleep() actually *uses* select instead of usleep/nanosleep. Not being a C hacker, I don't know much about it, but I'll check it out. Thanks! =-=-= I was also looking into trying the usleep implementation in wxPython -- well, I couldn't get the rascal compiled on my old Linux From Scratch version 4 installation (my main working Linux for that laptop) no matter what I turned off in .configure... I guess I should prioritize my LFS6 install a bit higher. ;-) Thanks one and all, and back to "quiet mode" I go... ;-) Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Profile, don't speculate." SysAdmin, Iceberg Computers | Daniel J. Bernstein zmerch at 30below.com | From project5 at redrival.net Thu May 26 20:40:40 2005 From: project5 at redrival.net (Andrei) Date: Thu, 26 May 2005 18:40:40 +0000 (UTC) Subject: [Tutor] python problem References: <4295F344.8090206@sanbi.ac.za> Message-ID: Feziwe Mpondo sanbi.ac.za> writes: > i'm trying to write a code that handle errors help I think the indentation was screwed up. > while menu_choice != 5: > menu_choice = input("Type in a number (1-5):") I'd avoid using input. Use raw_input instead. > break break stops a loop. So you display the menu once and stop immediately after the user has selected an action. That can't be right. > except(TypeError,NameError): Exceptions are caught in a try except block, where the code that might malfunction comes after try, and the code to handle the malfunctioning comes after except. It therefore looks something like this: userinput = raw_input('Choice: ') try: # userinput may or may not be valid choice = int(userinput) # might fail if userinput is random text except (ValueError): # what to do if couldn't convert to integer print 'Not a number' choice = 5 Yours, Andrei From dyoo at hkn.eecs.berkeley.edu Thu May 26 20:53:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 May 2005 11:53:49 -0700 (PDT) Subject: [Tutor] Are Empty "Placeholder" Functions possible? In-Reply-To: Message-ID: > Is there a way to create an empty function definition with no lines of > code in it? In my coding style I will often do this ( in other languages > ) for RAD just to remind myself that I will need to implement the > function later. Hi Nick, I agree with the others; using the no-op statement 'pass' is probably the way to go here. If I'm paranoid, I sometimes use a body that just raises a NotImplementedError exception: ###### >>> def functionIHaventWrittenYet(): ... raise NotImplementedError ... >>> functionIHaventWrittenYet() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in functionIHaventWrittenYet NotImplementedError ###### but, often, just putting in 'pass' stubs is enough. Best of wishes! From cgw501 at york.ac.uk Thu May 26 21:15:46 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 26 May 2005 20:15:46 +0100 Subject: [Tutor] pattern matching problem Message-ID: Hi, I have to write a function that will return the index of a line like this: gvcdgvcgdvagTVTVTVTVTVTHUXHYGSXUHXSU where it first becomes capital letters. I've had about a hundred different ideas of the best way to do this, but always seem to hit a fatal flaw. Any thoughts? Thanks, Chris From dyoo at hkn.eecs.berkeley.edu Thu May 26 21:23:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 May 2005 12:23:08 -0700 (PDT) Subject: [Tutor] Expression order problem In-Reply-To: <20050526161623.GA20115@sillyrabbi.dyndns.org> Message-ID: On Thu, 26 May 2005, William O'Higgins wrote: > I am running into problems with script evaluation order - specifically, > the Python interpreter seems to read and execute scripts line by line. Hi William, Ah! This happens to me too; one common idiom to avoid definition-order issues like this is to create some central main() function: ###### def main(): ... ###### and then, at the very bottom of the file, add a bit of code to start things up: ###### if __name__ == '__main__': main() ###### The reason this works is because main() is called only after all the other definitions are in place. That is, we start things up only after the name bindings are done. > This is a problem if you are used to Perl, where the whole script is > parsed first (Perl also auto-vivifies variables, but that's a different > problem for a different day). Perl does do that first pass to collect symbols, but it can also be fraught with gotchas. For example, the Perl code here: ### Perl ### print count(), "\n"; print count(), "\n"; print count(), "\n"; { my $x = 42; sub count { $x++; $x; } } ###### exposes a similar kind of gotcha with evaluation order. It's usually best to avoid the situation altogether, and get the definitions in front first. Using the "main()/if __name__ == '__main__'" idiom is one way to avoid the definition sequence issues. Best of wishes! From python at venix.com Thu May 26 21:27:21 2005 From: python at venix.com (Lloyd Kvam) Date: Thu, 26 May 2005 15:27:21 -0400 Subject: [Tutor] Are Empty "Placeholder" Functions possible? Message-ID: <1117135641.5527.47.camel@laptop.venix.com> An alternative to pass is raise NotImplementedError This has the advantage/disadvantage of providing a meaningful exception when you start testing and forget to provide some processing logic for a stub function. pass will simply return None when used for a function body. I nearly always use the NotImplementedError exception now in my code as the place holder. -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Thu May 26 21:29:43 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 May 2005 12:29:43 -0700 (PDT) Subject: [Tutor] pattern matching problem In-Reply-To: Message-ID: On 26 May 2005 cgw501 at york.ac.uk wrote: > I have to write a function that will return the index of a line like this: > > gvcdgvcgdvagTVTVTVTVTVTHUXHYGSXUHXSU > > where it first becomes capital letters. I've had about a hundred > different ideas of the best way to do this, but always seem to hit a > fatal flaw. Hi Chris, It might be interesting (or amusing) to bring up one of those fatally-flawed schemes on the Tutor list, so that we know what not to do. *grin* In seriousness, your ideas might not be so bad, and one of us here might be able to point out a way to correct things and make the approach more reasonable. Show us what you've thought of so far, and that'll help catalize the discussion. > Any thoughts? Have you looked into using a regular expression pattern matcher? A.M. Kuchling has written a tutorial on regular expressions here: http://www.amk.ca/python/howto/regex/ Would they be applicable to your program? From dyoo at hkn.eecs.berkeley.edu Thu May 26 21:45:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 May 2005 12:45:08 -0700 (PDT) Subject: [Tutor] Program to lock folders under win32 In-Reply-To: Message-ID: On Thu, 26 May 2005, Mark Kels wrote: > I want to make a program to lock folders (so the user can only access > them if he knows the password) under win32, the only problem is that I > have no idea how to start or what to do. Do you guys have any ideas of > how to do it? Hi Mark, Out of curiosity, are you looking for something out-of-the-box, or are you trying to develop a system just to learn more about it? I ask this because I'm sure something's out there that does this already, such as the frontends for the GNU Privacy Guard (GPG) program: http://www.gnupg.org/(en)/related_software/frontends.html#win Also, this sounds a bit specific to the particular operating system you're using, and I'm not sure if we can answer your question well here on Tutor. You might want to bring up your question on the python-win32 list: http://mail.python.org/mailman/listinfo/python-win32 Hmmm, but I'll try thinking of random possibilities. *grin* You could probably do something that ties into the File Explorer, like the TortoiseSVN extension, and there's probably hooks that can be manipulated with Python, but I'm don't have enough experience with the win32api to know what to look at. The folks on the win32 list should be better equipped to help you if you go this route. One easier alternative might be to use a WebDAV server, since Windows can talk with WebDAV, and I believe it should be passwordable without much trouble. There are WebDAV servers written in Python, so you can probably take one of those and extend it to your needs. Best of wishes! From cgw501 at york.ac.uk Thu May 26 21:46:37 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 26 May 2005 20:46:37 +0100 Subject: [Tutor] pattern matching problem In-Reply-To: References: Message-ID: One of the worst I think was doing loads of real spazzy stuff trying to split whole files in to lists of letters and use string methods to find the first uppercase one. The re tutorial has sorted it out for me. I figured this was the way to go, I just couldn't work out how to get the index value back...but now I can. Thanks! Chris On May 26 2005, Danny Yoo wrote: > > > On 26 May 2005 cgw501 at york.ac.uk wrote: > > > I have to write a function that will return the index of a line like > > this: > > > > gvcdgvcgdvagTVTVTVTVTVTHUXHYGSXUHXSU > > > > where it first becomes capital letters. I've had about a hundred > > different ideas of the best way to do this, but always seem to hit a > > fatal flaw. > > > Hi Chris, > > It might be interesting (or amusing) to bring up one of those > fatally-flawed schemes on the Tutor list, so that we know what not to do. > *grin* > > In seriousness, your ideas might not be so bad, and one of us here might > be able to point out a way to correct things and make the approach more > reasonable. Show us what you've thought of so far, and that'll help > catalize the discussion. > > > > > Any thoughts? > > Have you looked into using a regular expression pattern matcher? A.M. > Kuchling has written a tutorial on regular expressions here: > > http://www.amk.ca/python/howto/regex/ > > Would they be applicable to your program? > > From dyoo at hkn.eecs.berkeley.edu Thu May 26 22:55:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 26 May 2005 13:55:47 -0700 (PDT) Subject: [Tutor] pattern matching problem In-Reply-To: Message-ID: On 26 May 2005 cgw501 at york.ac.uk wrote: > One of the worst I think was doing loads of real spazzy stuff trying to > split whole files in to lists of letters and use string methods to find > the first uppercase one. Hi Chris, An approach like this might work. Rather than read the whole thing into a honking big list, though, we can just iterate through it, letter by letter, by using read(1). Here's one way we might do it that way: ### Pseudocode ### currentLine = 1 while True: nextChar = someFile.read(1) if not nextChar: break elif isNewline(nextChar): currentLine += 1 elif isUppercased(nextChar): break print currentLine ###### This approach avoids sucking the whole file into memory, and is a reasonable approach too. Best of wishes! From alan.gauld at freenet.co.uk Thu May 26 23:05:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 22:05:52 +0100 Subject: [Tutor] python problem References: <4295F344.8090206@sanbi.ac.za> Message-ID: <029801c56236$b3bc8640$0db78851@xp> > i'm trying to write a code that handle errors help > > def print_menu(): ... Personally I try to get the menu function to return the value selected that way the meniu options and the code to check it is all wrapped up in the same place. But that is only a side issue... > while menu_choice != 5: > menu_choice = input("Type in a number (1-5):") > break > except(TypeError,NameError): You need to use try: before an except. So if you start your while loop body with a try while menu_choice != 5: try: menu_choice = input(...) if menu_choice == 1: etc... except NameError, TypeError: # handle error here break # only if you really need to.. print_menu() HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu May 26 23:07:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 22:07:21 +0100 Subject: [Tutor] Are Empty "Placeholder" Functions possible? References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D40C@riv-excha5.echostar.com> Message-ID: <029d01c56236$e8a23df0$0db78851@xp> > Is there a way to create an empty function definition with no lines of code > in it? In my coding style I will often do this ( in other languages ) for > RAD just to remind myself that I will need to implement the function later. > Use pass def f(): pass also works for classes: class MyClass: pass I use that a lot. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jeannot18 at hotmail.com Thu May 26 23:24:43 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu, 26 May 2005 21:24:43 +0000 Subject: [Tutor] (no subject). Ord and Chr query In-Reply-To: <026401c561cb$05cc0800$0db78851@xp> Message-ID: Pujo, Alan, John and Ben, thanks for the input. Sorry I should have been clearer with the query perhaps. Alan I am just going through the book "Learning Python" written by Lutz and Ascher, and this is part of one exercise. I am still having problem in putting my head around in writting even very simple script. I can see the whole picture but have enormous problem in putting it down to paper (or screen). Once I see the solution I can really understand. I am actually archiving everything that I am learning. Problem is I am not a programmer, I don't use Python on a regular/daily basis so of course it seems that the learing curve is very steep but I am really enjoying it. Pujo you were spot on again, thanks. Ben I could not get your script working I am probably screwing up somewhere. John can you see now the reason why I was asking those questions, sorry for not being clearer (i have even forgoten to put a line on the subject... Regards JC See you soon From alan.gauld at freenet.co.uk Thu May 26 23:44:51 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 22:44:51 +0100 Subject: [Tutor] (no subject). Ord and Chr query References: Message-ID: <02b001c5623c$25c58a70$0db78851@xp> Hi John, > Alan I am just going through the book "Learning Python" written by Lutz and > Ascher, and this is part of one exercise. I suspected it might be something you were doing just to explore. Lutz and Ascher is a great book but they do assume some knowledge of programming and computer concepts. > putting my head around in writting even very simple script. I can see the > whole picture but have enormous problem in putting it down to paper Learning to think in the minute level of detail that a computer 'thinks' is half the battle of programming. Humans are intelligent but slow, computers are stupid but fast. You have to break every action down to the simplest level and get the sequence just right. But once you do get this stupid box responding to your every whim then it is a grat buzz! Alan G. From alan.gauld at freenet.co.uk Thu May 26 23:52:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 22:52:38 +0100 Subject: [Tutor] better resolution on time.sleep()? References: <5.1.0.14.2.20050523180426.047cc008@mail.30below.com> <5.1.0.14.2.20050526131547.03a35908@mail.30below.com> Message-ID: <02cd01c5623d$3c41cec0$0db78851@xp> > Rumor has it that Alan G may have mentioned these words: > > >Consuming 100% CPU won't make much difference, the CPU is running all > >the time anyway (when its not asleep). > > Not mine... my laptop runs a Crusoe processor, and it can automatically > scale itself from 300Mhz to 933Mhz. It's called "LongRun" technology, Ah yes indeed, I confess I forgot about that little trick. But the real point I was trying to make was that the CPU itself is not usually the biggest drain on battery compared to HD and modems, WiFi, BlueTooth etc. If I activate my PCMCIA(??) modem my laptop life drops from 3-4 hours down to 45 minutes or so! And leaving my WiFi connection enabled on a train means I pick up any other WiFi enabled laptop and it cuts battery life by an hour compared to when I disable the WiFi... Alan G. From alan.gauld at freenet.co.uk Thu May 26 23:54:21 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 26 May 2005 22:54:21 +0100 Subject: [Tutor] pattern matching problem References: Message-ID: <02d601c5623d$7936aa80$0db78851@xp> > I have to write a function that will return the index of a line like this: > > gvcdgvcgdvagTVTVTVTVTVTHUXHYGSXUHXSU > > where it first becomes capital letters. I'd go with a regex search for that one... Alan g. From jfouhy at paradise.net.nz Fri May 27 00:06:51 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 27 May 2005 10:06:51 +1200 (NZST) Subject: [Tutor] Program to lock folders under win32 In-Reply-To: References: Message-ID: <1117145211.4296487b6c522@www.paradise.net.nz> Quoting Mark Kels : > I want to make a program to lock folders (so the user can only access > them if he knows the password) under win32, the only problem is that I > have no idea how to start or what to do. Do you guys have any ideas of > how to do it? Is your program going to be running all the time? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 is a recipe showing how to lock files on POSIX and Win32. So possibly you could do something like that, where your program acquires locks on all the files and then releases the lock when given the password... -- John. From kent37 at tds.net Fri May 27 00:11:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 May 2005 18:11:10 -0400 Subject: [Tutor] (no subject). Ord and Chr query In-Reply-To: References: Message-ID: <4296497E.2040801@tds.net> John Carmona wrote: > Sorry I should have been clearer with the query perhaps. > Alan I am just going through the book "Learning Python" written by Lutz and > Ascher, and this is part of one exercise. I am still having problem in > putting my head around in writting even very simple script. I can see the > whole picture but have enormous problem in putting it down to paper (or > screen). Once I see the solution I can really understand. I am actually > archiving everything that I am learning. Problem is I am not a programmer, I > don't use Python on a regular/daily basis so of course it seems that the > learing curve is very steep but I am really enjoying it. There are many Python learning resources for non-programmers, you might want to look at some of them. This page has a list: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From tim at johnsons-web.com Fri May 27 01:40:56 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 26 May 2005 15:40:56 -0800 Subject: [Tutor] (no subject). Ord and Chr query In-Reply-To: <4296497E.2040801@tds.net> References: <4296497E.2040801@tds.net> Message-ID: <20050526234056.GR2494@johnsons-web.com> * Kent Johnson [050526 14:16]: > John Carmona wrote: > > Sorry I should have been clearer with the query perhaps. > > Alan I am just going through the book "Learning Python" written by Lutz and > > Ascher, and this is part of one exercise. I am still having problem in > > putting my head around in writting even very simple script. I can see the > > whole picture but have enormous problem in putting it down to paper (or > > screen). Once I see the solution I can really understand. I am actually > > archiving everything that I am learning. Problem is I am not a programmer, I > > don't use Python on a regular/daily basis so of course it seems that the > > learing curve is very steep but I am really enjoying it. > > There are many Python learning resources for non-programmers, you might want to look at some of > them. This page has a list: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers The Lutz book is a good one, but when I set up an online curriculum for programming for a local school district, I chose python for the second semester and the book that we used was "Learn to Program Using Python", by Alan Gauld. I'm going to recommend it, even tho' many features have been added to python since (2001), it does a good job on the basics. -- tj -- Tim Johnson http://www.alaska-internet-solutions.com From benvinger at yahoo.co.uk Fri May 27 10:51:11 2005 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Fri, 27 May 2005 09:51:11 +0100 (BST) Subject: [Tutor] (no subject). Ord and Chr query In-Reply-To: 6667 Message-ID: <20050527085111.89377.qmail@web25804.mail.ukl.yahoo.com> --- John Carmona wrote: > Ben I could not get your script working indentation? ___________________________________________________________ Can't remember an address in your address book? Enter the first few letters and Address AutoComplete will automatically finish it. Get Yahoo! Mail http://uk.mail.yahoo.com From jeannot18 at hotmail.com Fri May 27 12:17:56 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Fri, 27 May 2005 10:17:56 +0000 Subject: [Tutor] (no subject). Ord and Chr query In-Reply-To: <20050527085111.89377.qmail@web25804.mail.ukl.yahoo.com> Message-ID: To all that have answered, many thanks. I will check the tutorials that have been pointed out to me. I have also got the Dive into Python printed and I will start reading that one too pretty soon. I am off on holiday starting Tuesday so I won't have the time to study too much in the next couple of days (maybe at work if it is quiet...). Speak to you soon guys and thanks again JC From johanmeskenscs3 at chromaticspaceandworld.com Fri May 27 13:46:46 2005 From: johanmeskenscs3 at chromaticspaceandworld.com (Johan Meskens CS3 jmcs3) Date: Fri, 27 May 2005 12:46:46 +0100 Subject: [Tutor] all methods in a module Message-ID: hello >>> import random >>> print random.setstate.__doc__ Restore internal state from object returned by getstate(). my question is " how can i loop through all the methods in a module and print out their '__doc__' content ? >>> for d in dir( random ): print random.???d???.__doc__ thanks jmcs3 From kent37 at tds.net Fri May 27 14:15:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 May 2005 08:15:07 -0400 Subject: [Tutor] all methods in a module In-Reply-To: References: Message-ID: <42970F4B.4040507@tds.net> Johan Meskens CS3 jmcs3 wrote: > my question is > " how can i loop through all the methods in a module > and print out their '__doc__' content ? > > >>>>for d in dir( random ): > > print random.???d???.__doc__ print getattr(random, d).__doc__ in general you should be prepared to catch AttributeErrors (for items that don't have __doc__ attributes) but for random you are OK. BTW dir() will show all attributes, not just methods. You might want to try help(random) as well... Kent From ewald.ertl at hartter.com Fri May 27 14:16:49 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri, 27 May 2005 14:16:49 +0200 Subject: [Tutor] all methods in a module In-Reply-To: References: Message-ID: <20050527141649.00003443@sunray2.hartter.com> Hi! I've the following solution: >>> for d in [ "random." + d for d in dir(random)]: ... if callable( eval(d) ): ... print "%30s :\n\n %s" % ( d, eval( "%s.__doc__" % ( d))) ... random.Random : Random number generator base class used by bound module functions. HTH Ewald on Fri, 27 May 2005 12:46:46 +0100 "Johan Meskens CS3 jmcs3" wrote : --------------------------------------------------------------------------------------------- Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > hello Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > >>> import random Johan Meskens CS3 jmcs3 > >>> print random.setstate.__doc__ Johan Meskens CS3 jmcs3 > Restore internal state from object returned by getstate(). Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > my question is Johan Meskens CS3 jmcs3 > " how can i loop through all the methods in a module Johan Meskens CS3 jmcs3 > and print out their '__doc__' content ? Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > >>> for d in dir( random ): Johan Meskens CS3 jmcs3 > print random.???d???.__doc__ Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > Johan Meskens CS3 jmcs3 > thanks Johan Meskens CS3 jmcs3 > jmcs3 Johan Meskens CS3 jmcs3 > _______________________________________________ Johan Meskens CS3 jmcs3 > Tutor maillist - Tutor at python.org Johan Meskens CS3 jmcs3 > http://mail.python.org/mailman/listinfo/tutor Johan Meskens CS3 jmcs3 > ------------------- end ---------------------- From johanmeskenscs3 at chromaticspaceandworld.com Fri May 27 14:20:10 2005 From: johanmeskenscs3 at chromaticspaceandworld.com (Johan Meskens CS3 jmcs3) Date: Fri, 27 May 2005 13:20:10 +0100 Subject: [Tutor] all methods in a module Message-ID: Johan Meskens CS3 jmcs3 wrote: > hello > > >>> import random > >>> print random.setstate.__doc__ > Restore internal state from object returned by getstate(). > > > my question is > " how can i loop through all the methods in a module > and print out their '__doc__' content ? > > >>> for d in dir( random ): > print random.???d???.__doc__ >>> for d in dir( random ): print getattr( random, d ).__doc__ > > thanks > jmcs3 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kraus at hagen-partner.de Fri May 27 14:19:14 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 27 May 2005 14:19:14 +0200 Subject: [Tutor] all methods in a module In-Reply-To: References: Message-ID: Johan Meskens CS3 jmcs3 wrote: > hello > > >>>>import random >>>>print random.setstate.__doc__ > > Restore internal state from object returned by getstate(). > > > my question is > " how can i loop through all the methods in a module > and print out their '__doc__' content ? > > >>>>for d in dir( random ): > > print random.???d???.__doc__ > > > thanks > jmcs3 Untest no-brainer with "eval", there might be better solutions: >>> import random >>> for d in dir(random): ... print eval('random.%s.__doc__' % d) HTH, Wolfram From John.Gooch at echostar.com Fri May 27 16:56:49 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Fri, 27 May 2005 08:56:49 -0600 Subject: [Tutor] Eclipse and Member Function Availability Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D417@riv-excha5.echostar.com> I am building a class and using a "main.py" script as the "driver" for testing. Where I am having problems is that the class is defined in another file ( say the class is "MyClass" and the file is "MyClass.py" that I am importing as a module. The problem itself ( not a major one ), is that when using autocomplete feature within Eclipse, where you type in the name of the module or a class and it lists the functions/variables that are available in a popup menu, it only shows the modules methods and variables. Hopefully this example will make things clear: -------------- import MyClass def main(): myObject = MyClass.MyClass """ Here I type in the name of the class, expecting a list of the classes member functions/etc to popup """ myObject. """<--- here I see a list of functions available to the module, not the class """ main() ------------- Now, if I take all of the classes methods out of the class and make them global within the module file, then I can see all of them using the autocomplete function, however, doesn't this defeat the purpose of OO? Should I use a module instead of a class, and pretend the module is a class? This would make the autocomplete available but make it more difficult to migrate the code from Python to say, Java or C++. Any advice is welcome. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 From boomeral at hotmail.com Wed May 25 18:43:31 2005 From: boomeral at hotmail.com (Mohammad Mohiuddin) Date: Wed, 25 May 2005 12:43:31 -0400 Subject: [Tutor] Formatted writing to a file Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050525/4d127e06/attachment.html From bgailer at sbcglobal.net Fri May 27 17:51:43 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Fri, 27 May 2005 08:51:43 -0700 Subject: [Tutor] all methods in a module In-Reply-To: References: Message-ID: <6.1.2.0.0.20050527083745.036ed268@pop.sbcglobal.yahoo.com> At 04:46 AM 5/27/2005, Johan Meskens CS3 jmcs3 wrote: >hello > > >>> import random > >>> print random.setstate.__doc__ >Restore internal state from object returned by getstate(). > > >my question is >" how can i loop through all the methods in a module > and print out their '__doc__' content ? > > >>> for d in dir( random ): > print random.???d???.__doc__ The prior responses use dir(), requiring then the use of eval() to get the object. You can get the name and object directly from random.__dict__. The following comprehension seems to handle all the stuff in random's dict: methods = [name, str(object.__doc__) for name, object in random.__dict__.iteritems() if callable(object) and object.__doc__] Then you can iterate over methods and format/print as desired. Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050527/1fd23b32/attachment.htm From erastley at charter.net Fri May 27 19:30:26 2005 From: erastley at charter.net (EUGENE ASTLEY) Date: Fri, 27 May 2005 10:30:26 -0700 Subject: [Tutor] two windows Message-ID: <000001c562e1$c622a4d0$6501a8c0@D3K8PT61> I asked for help on my problem but unfortunately now help yet. I am trying to put up instructions for a board game and then have the person read and then proceed onto the game. The following is what I have that displays the instructions just fine but will not let the game proceed on to the board and the game.: The instruction section works fine and the game part works fine but not together. I guess I need the widget to have a button that allows the reader to proceed. Appreciate help as I am just learning. I am thinking that the widget doesn't qualify as a screen. Gene import random, math from livewires import games, color from Tkinter import * SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 768 THE_SCREEN = games.Screen(SCREEN_WIDTH, SCREEN_HEIGHT) class Application(Frame): def __init__(self, master): """ Initialize the frame. """ Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create button, text, and entry widgets. """ # create instruction label self.inst_lbl = Label(self, text = "Enter your Name, please") self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W) # create label for name input self.pw_lbl = Label(self, text = "Name: ") self.pw_lbl.grid(row = 1, column = 0, sticky = W) # create entry widget to accept name self.pw_ent = Entry(self) self.pw_ent.grid(row = 1, column = 1, sticky = W) # create submit button self.submit_bttn = Button(self, text = "Submit", command = self.reveal) self.submit_bttn.grid(row = 2, column = 0, sticky = W) # create text widget to display message self.instruction_txt = Text(self, width = 65, height = 30, wrap = WORD) self.instruction_txt.grid(row = 3, column = 0, columnspan = 3, sticky = W) def reveal(self): """ Display message based on name. """ contents = self.pw_ent.get() if contents == "Joe": message = """ The rules of the game are: etc. etc. """ else: message = "That's not your first name, try again!" self.instruction_txt.delete(0.0, END) self.instruction_txt.insert(0.0, message) # main root = Tk() root.title("Name") root.geometry("1280x768") app = Application(root) my_screen = THE_SCREEN wall_image = games.load_image("board.jpg", transparent = False) my_screen.set_background(board_image) etc. etc. my_screen.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050527/dc45b04c/attachment-0001.html From kent37 at tds.net Fri May 27 19:47:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 May 2005 13:47:41 -0400 Subject: [Tutor] all methods in a module In-Reply-To: <6.1.2.0.0.20050527083745.036ed268@pop.sbcglobal.yahoo.com> References: <6.1.2.0.0.20050527083745.036ed268@pop.sbcglobal.yahoo.com> Message-ID: <42975D3D.9060507@tds.net> Bob Gailer wrote: >> my question is >> " how can i loop through all the methods in a module >> and print out their '__doc__' content ? >> >> >>> for d in dir( random ): >> print random.???d???.__doc__ > > > The prior responses use dir(), requiring then the use of eval() to get > the object. eval() is not required, getattr() is a better solution as I showed in my previous reply. > You can get the name and object directly from random.__dict__. The > following comprehension seems to handle all the stuff in random's dict: > > methods = [name, str(object.__doc__) > for name, object in random.__dict__.iteritems() > if callable(object) and object.__doc__] For the general case it would be prudent to say if callable(object) and hasattr(object, '__doc__') and object.__doc__ so a missing docstring doesn't terminate the loop. Kent From missive at hotmail.com Fri May 27 22:50:25 2005 From: missive at hotmail.com (Lee Harr) Date: Sat, 28 May 2005 01:20:25 +0430 Subject: [Tutor] Formatted writing to a file Message-ID: >Content-Type: text/html; format=flowed > > [...] What a mess. You should to post to the list in plain text. Someone might take the time to weed through that for your question, but you will get a lot more help and a lot sooner if you just configure your mailer to send plain text. _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From missive at hotmail.com Fri May 27 22:57:44 2005 From: missive at hotmail.com (Lee Harr) Date: Sat, 28 May 2005 01:27:44 +0430 Subject: [Tutor] Eclipse and Member Function Availability Message-ID: >using autocomplete feature within Eclipse Are you using pydev? http://pydev.sourceforge.net/ Their website says: """ New Release: 0.9.3!! Wohooo!! Code completion Rules! Check it out! """ So apparently this is something they are actively working on. You may have an old version, or you may have found a bug. Maybe try the users forum there: http://sourceforge.net/forum/forum.php?forum_id=293649 _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From carroll at tjc.com Fri May 27 23:31:18 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 27 May 2005 14:31:18 -0700 (PDT) Subject: [Tutor] Any Python interface to USPTO web site? Message-ID: I have the need to run periodic searches on the US Patent and Trademark Office website, www.uspto.gov. Before I reinvent the wheel, I thought I'd check to see if anyone knew of such a beast. For instance, It's like to be able to pass an argument like one of these: an/"dis corporation" in/newmar-julie to http://patft.uspto.gov/netahtml/search-adv.htm and get a list of all the patents owned by Dis Corporation, or invented by the 1960s Catwoman actress; or pass a patent number like 4,150,505 to http://patft.uspto.gov/netahtml/srchnum.htm to bring up a particular patent. Then I want to be able to parse out the patent metadata, e.g. inventor names, dates filed and issued, etc. Has this already been done? The closest my google searches have turned up is http://hacks.oreilly.com/pub/h/1724 , but that turns out to be Perl rather than Python, and not quite dead-on anyway. From alan.gauld at freenet.co.uk Fri May 27 23:58:37 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 27 May 2005 22:58:37 +0100 Subject: [Tutor] Formatted writing to a file References: Message-ID: <036b01c56307$3c362730$0db78851@xp> > 1. how can I format outfile so i can write multiple lines > and then apend multiple lines later before closing the file? I think you mean add a new column to the existing lines? try something like line = line + '%25s' % newdata > 2. how can I make data formatting string '%25s' intiger (in this case 25) a variable? Just create the string outsoide the formatting line: fmtString = '%%ds' % width s = fmtString % data HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From flamesrock at gmail.com Sat May 28 00:40:27 2005 From: flamesrock at gmail.com (Aaron Elbaz) Date: Fri, 27 May 2005 22:40:27 +0000 Subject: [Tutor] Help: wget-- how does it work? Message-ID: <2c2812b605052715401b9afa2b@mail.gmail.com> One of my favourite unix applications is wget. Thinking how easy (and fun) it might be to implement with pythons excellent librairies has led me to a few questions. First, I found the progress bar class from aspn http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 This could be used to simulate wgets progress bar. What I'm trying to figure out now is how one would stat a file as it was being downloaded so that I can feed information to the progress bar, and what the most optimal way to do this is? I realize you could request the filesize if it was on an ftp server, and then use 'os' to check the filesize. But how would you do this with regular http? Are there any tricks the experts have? How does wget do it? -thanks From carroll at tjc.com Sat May 28 00:52:03 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 27 May 2005 15:52:03 -0700 (PDT) Subject: [Tutor] Help: wget-- how does it work? In-Reply-To: <2c2812b605052715401b9afa2b@mail.gmail.com> Message-ID: On Fri, 27 May 2005, Aaron Elbaz wrote: > First, I found the progress bar class from aspn > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 > > This could be used to simulate wgets progress bar. What I'm trying to > figure out now is how one would stat a file as it was being downloaded > so that I can feed information to the progress bar, and what the most > optimal way to do this is? I use this for an app I have that reads the 27-meg Unihan.txt file; but I think I cheat and hardcode the 27-meg no. From bgailer at sbcglobal.net Sat May 28 00:15:10 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Fri, 27 May 2005 15:15:10 -0700 Subject: [Tutor] Formatted writing to a file In-Reply-To: <036b01c56307$3c362730$0db78851@xp> References: <036b01c56307$3c362730$0db78851@xp> Message-ID: <6.1.2.0.0.20050527151001.037e6be0@pop.sbcglobal.yahoo.com> >1. how can I format outfile so i can write multiple lines >and then apend multiple lines later before closing the file? It sounds like you want to update the file in successive passes. This is hard or impossible. Your best bet is to read one file and write another. > 2. how can I make data formatting string '%25s' intiger (in this >case 25) a variable? Use %*s. Assuming width = 25: %25s' % 3 == '%*s' % (width, 3) Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050527/ff9e2a69/attachment.htm From kent37 at tds.net Sat May 28 02:17:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 May 2005 20:17:11 -0400 Subject: [Tutor] Help: wget-- how does it work? In-Reply-To: <2c2812b605052715401b9afa2b@mail.gmail.com> References: <2c2812b605052715401b9afa2b@mail.gmail.com> Message-ID: <4297B887.6060909@tds.net> Aaron Elbaz wrote: > One of my favourite unix applications is wget. > > This could be used to simulate wgets progress bar. What I'm trying to > figure out now is how one would stat a file as it was being downloaded > so that I can feed information to the progress bar, and what the most > optimal way to do this is? You can get the content-length header from the object returned from urllib2.urlopen(): >>> import urllib2 >>> f=urllib2.urlopen('http://www.google.com') >>> f > >>> f.info() >>> i=f.info() >>> i.getheader('content-length') '1983' Now you can read the data in chunks (using f.read(n)) and update your status bar as you go. Kent From servando at mac.com Sat May 28 05:25:12 2005 From: servando at mac.com (Servando Garcia) Date: Fri, 27 May 2005 22:25:12 -0500 Subject: [Tutor] increment operator Message-ID: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> Hello Is there a increment operator in python similar to c++ like so "SomeVariable++" From leec03273 at mac.com Sat May 28 05:53:08 2005 From: leec03273 at mac.com (Lee Cullens) Date: Fri, 27 May 2005 23:53:08 -0400 Subject: [Tutor] increment operator In-Reply-To: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> References: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> Message-ID: <0C41D82A-157F-4EE2-9DD0-42266FE1E7DE@mac.com> I find the following invaluable - maybe you will also. http://rgruet.free.fr/PQR24/PQR2.4.html Lee C On May 27, 2005, at 11:25 PM, Servando Garcia wrote: > Hello > Is there a increment operator in python similar to c++ > like so "SomeVariable++" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at sbcglobal.net Sat May 28 05:12:36 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Fri, 27 May 2005 20:12:36 -0700 Subject: [Tutor] Formatted writing to a file In-Reply-To: <036b01c56307$3c362730$0db78851@xp> References: <036b01c56307$3c362730$0db78851@xp> Message-ID: <6.1.2.0.0.20050527201159.03815928@pop.sbcglobal.yahoo.com> At 02:58 PM 5/27/2005, Alan G wrote: > > 1. how can I format outfile so i can write multiple lines > > and then apend multiple lines later before closing the file? > >I think you mean add a new column to the existing lines? > >try something like > >line = line + '%25s' % newdata > > > 2. how can I make data formatting string '%25s' intiger (in this >case 25) a variable? > > >Just create the string outsoide the formatting line: > >fmtString = '%%ds' % width I think it should be '%%%ds' % width >s = fmtString % data > >HTH, > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050527/42c87018/attachment.html From bgailer at sbcglobal.net Sat May 28 05:31:53 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Fri, 27 May 2005 20:31:53 -0700 Subject: [Tutor] increment operator In-Reply-To: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> References: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> Message-ID: <6.1.2.0.0.20050527203000.036424c0@pop.sbcglobal.yahoo.com> At 08:25 PM 5/27/2005, Servando Garcia wrote: >Is there an increment operator in python similar to c++ like SomeVariable++ No. Closest is SomeVariable += 1. Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050527/a4d5e299/attachment.htm From magoldfish at gmail.com Sat May 28 10:05:54 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Sat, 28 May 2005 04:05:54 -0400 Subject: [Tutor] a generic table data structure for table / 2d array / lookup table? Message-ID: <5e183f3d05052801058bb0a07@mail.gmail.com> Before I try to reinvent the wheel, can anyone point me to a data structure suitable for storing non-numeric, 2-d arrays. For instance, something that can store the following: A B C D 1 'cat' 3 object 9 J 4 [1] 5 6 where the column and row labels in this example are ['A','B','C','D'] and [1,'J'], respectively. I need to access (set and get values) by cell, row, and column. I have a solution using 2-tuple keys and a dict, e.g., d[('A',1)], but it seems kludgy and doesn't handle the row/column access. Any pointers or code snippets would be appreciated! Marcus From alan.gauld at freenet.co.uk Sat May 28 10:34:17 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 28 May 2005 09:34:17 +0100 Subject: [Tutor] Formatted writing to a file References: <036b01c56307$3c362730$0db78851@xp> <6.1.2.0.0.20050527201159.03815928@pop.sbcglobal.yahoo.com> Message-ID: <038301c56360$09f1a9d0$0db78851@xp> > >Just create the string outsoide the formatting line: > > > >fmtString = '%%ds' % width > > I think it should be '%%%ds' % width Good catch Bob, you need the extra % to 'escape' the literal % character. Alan G. From alan.gauld at freenet.co.uk Sat May 28 10:38:00 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 28 May 2005 09:38:00 +0100 Subject: [Tutor] increment operator References: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> Message-ID: <03a201c56360$8e88afe0$0db78851@xp> > Is there a increment operator in python similar to c++ > like so "SomeVariable++" No. There is the shorthand += assignment but no ++ So x += 1 is the closest thing to x++ HTH, Alan G. From jeannot18 at hotmail.com Sat May 28 11:59:08 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Sat, 28 May 2005 09:59:08 +0000 Subject: [Tutor] (no subject). Ord and Chr query In-Reply-To: <20050527085111.89377.qmail@web25804.mail.ukl.yahoo.com> Message-ID: Hi Ben, you wrote --- John Carmona wrote: >Ben I could not get your script working indentation? You were right, it is working now, thanks JC From kent37 at tds.net Sat May 28 13:07:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 May 2005 07:07:53 -0400 Subject: [Tutor] a generic table data structure for table / 2d array / lookup table? In-Reply-To: <5e183f3d05052801058bb0a07@mail.gmail.com> References: <5e183f3d05052801058bb0a07@mail.gmail.com> Message-ID: <42985109.1000302@tds.net> Marcus Goldfish wrote: > Before I try to reinvent the wheel, can anyone point me to a data > structure suitable for storing non-numeric, 2-d arrays. For instance, > something that can store the following: > > A B C D > 1 'cat' 3 object 9 > J 4 [1] 5 6 > > where the column and row labels in this example are ['A','B','C','D'] > and [1,'J'], respectively. I need to access (set and get values) by > cell, row, and column. > > I have a solution using 2-tuple keys and a dict, e.g., d[('A',1)], but > it seems kludgy and doesn't handle the row/column access. > > Any pointers or code snippets would be appreciated! You caught me in a good mood this morning. I woke to sunshine for the first time in many days, that might have something to do with it :-) Here is a dict subclass that extends __getitem__ and __setitem__ to allow setting an entire row. I included extensive doctests to show you what it does. Note: you can write d['A',1] instead of d[('A',1)], which looks a little cleaner. Kent class Grid(dict): """ A two-dimensional array that can be accessed by row, by column, or by cell. Create with lists of row and column names plus any valid dict() constructor args. >>> data = Grid( ['A', 'B'], [1, 2] ) Row and column lists must not have any values in common. >>> data = Grid([1, 2], [2, 3]) Traceback (most recent call last): ... ValueError: Row and column lists must not have any values in common Here is an example with data: >>> rowNames = ['A','B','C','D'] >>> colNames = [1,'J'] >>> rawData = [ 'cat', 3, object, 9, 4, [1], 5, 6 ] >>> indices = [ (row, col) for col in colNames for row in rowNames ] >>> data = Grid(rowNames, colNames, zip(indices, rawData)) Data can be accessed by cell: >>> for i in indices: ... print i, data[i] ('A', 1) cat ('B', 1) 3 ('C', 1) ('D', 1) 9 ('A', 'J') 4 ('B', 'J') [1] ('C', 'J') 5 ('D', 'J') 6 >>> data['B', 'J'] = 5 Cell indices must contain valid row and column names: >>> data[3] Traceback (most recent call last): ... KeyError: 3 >>> data['C', 2] = 5 Traceback (most recent call last): ... ValueError: Invalid key or value: Grid[('C', 2)] = 5 Data can be accessed by row or column index alone to set or retrieve an entire row or column: >>> print data['A'] ['cat', 4] >>> print data[1] ['cat', 3, , 9] >>> data['A'] = ['dog', 2] >>> print data['A'] ['dog', 2] When setting a row or column, data must be the correct length. >>> data['A'] = ['dog'] Traceback (most recent call last): ... ValueError: Invalid key or value: Grid['A'] = ['dog'] """ def __init__(self, rowNames, colNames, *args, **kwds): dict.__init__(self, *args, **kwds) self.rowNames = list(rowNames) self.colNames = list(colNames) # Check for no shared row and col names if set(rowNames).intersection(colNames): raise ValueError, 'Row and column lists must not have any values in common' def __getitem__(self, key): if self._isCellKey(key): return dict.__getitem__(self, key) elif key in self.rowNames: return [ dict.__getitem__(self, (key, col)) for col in self.colNames ] elif key in self.colNames: return [ dict.__getitem__(self, (row, key)) for row in self.rowNames ] else: raise KeyError, key def __setitem__(self, key, value): if self._isCellKey(key): return dict.__setitem__(self, key, value) elif key in self.rowNames and len(value) == len(self.colNames): for col, val in zip(self.colNames, value): dict.__setitem__(self, (key, col), val) elif key in self.colNames and len(value) == len(self.rowNames): for row, val in zip(self.rowNames, value): dict.__setitem__(self, (row, key), val) else: raise ValueError, 'Invalid key or value: Grid[%r] = %r' % (key, value) def _isCellKey(self, key): ''' Is key a valid cell index? ''' return isinstance(key, tuple) \ and len(key) == 2 \ and key[0] in self.rowNames \ and key[1] in self.colNames if __name__ == '__main__': import doctest doctest.testmod() From ajikoe at gmail.com Sat May 28 13:51:26 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sat, 28 May 2005 13:51:26 +0200 Subject: [Tutor] a generic table data structure for table / 2d array / lookup table? In-Reply-To: <42985109.1000302@tds.net> References: <5e183f3d05052801058bb0a07@mail.gmail.com> <42985109.1000302@tds.net> Message-ID: You can create small class with handle table thing and use dictionary as the main data. Look at this code: class mytable: def __init__(self): self.dat = {} pass def input(self,row,col,val): self.dat[row] = {col:val} pass def output(self,row,col): try: return self.dat[row][col] except: return None pass if __name__ == '__main__': mytab = mytable() mytab.input(1,'A','cat') # Ok print mytab.output(1,'A') # it will result 'cat' # Not Ok --> No Data print mytab.output(2,'B') # it will result None Sincerely Yours, Pujo Aji On 5/28/05, Kent Johnson wrote: > Marcus Goldfish wrote: > > Before I try to reinvent the wheel, can anyone point me to a data > > structure suitable for storing non-numeric, 2-d arrays. For instance, > > something that can store the following: > > > > A B C D > > 1 'cat' 3 object 9 > > J 4 [1] 5 6 > > > > where the column and row labels in this example are ['A','B','C','D'] > > and [1,'J'], respectively. I need to access (set and get values) by > > cell, row, and column. > > > > I have a solution using 2-tuple keys and a dict, e.g., d[('A',1)], but > > it seems kludgy and doesn't handle the row/column access. > > > > Any pointers or code snippets would be appreciated! > > You caught me in a good mood this morning. I woke to sunshine for the first time in many days, that > might have something to do with it :-) > > Here is a dict subclass that extends __getitem__ and __setitem__ to allow setting an entire row. I > included extensive doctests to show you what it does. > > Note: you can write d['A',1] instead of d[('A',1)], which looks a little cleaner. > > Kent > > class Grid(dict): > """ > A two-dimensional array that can be accessed by row, by column, or by cell. > > Create with lists of row and column names plus any valid dict() constructor args. > > >>> data = Grid( ['A', 'B'], [1, 2] ) > > Row and column lists must not have any values in common. > > >>> data = Grid([1, 2], [2, 3]) > Traceback (most recent call last): > ... > ValueError: Row and column lists must not have any values in common > > Here is an example with data: > > >>> rowNames = ['A','B','C','D'] > >>> colNames = [1,'J'] > >>> rawData = [ 'cat', 3, object, 9, 4, [1], 5, 6 ] > >>> indices = [ (row, col) for col in colNames for row in rowNames ] > >>> data = Grid(rowNames, colNames, zip(indices, rawData)) > > > Data can be accessed by cell: > > >>> for i in indices: > ... print i, data[i] > ('A', 1) cat > ('B', 1) 3 > ('C', 1) > ('D', 1) 9 > ('A', 'J') 4 > ('B', 'J') [1] > ('C', 'J') 5 > ('D', 'J') 6 > > >>> data['B', 'J'] = 5 > > > Cell indices must contain valid row and column names: > > >>> data[3] > Traceback (most recent call last): > ... > KeyError: 3 > > >>> data['C', 2] = 5 > Traceback (most recent call last): > ... > ValueError: Invalid key or value: Grid[('C', 2)] = 5 > > > Data can be accessed by row or column index alone to set or retrieve > an entire row or column: > > >>> print data['A'] > ['cat', 4] > > >>> print data[1] > ['cat', 3, , 9] > > >>> data['A'] = ['dog', 2] > >>> print data['A'] > ['dog', 2] > > > When setting a row or column, data must be the correct length. > > >>> data['A'] = ['dog'] > Traceback (most recent call last): > ... > ValueError: Invalid key or value: Grid['A'] = ['dog'] > > """ > > def __init__(self, rowNames, colNames, *args, **kwds): > dict.__init__(self, *args, **kwds) > self.rowNames = list(rowNames) > self.colNames = list(colNames) > > # Check for no shared row and col names > if set(rowNames).intersection(colNames): > raise ValueError, 'Row and column lists must not have any values in common' > > def __getitem__(self, key): > if self._isCellKey(key): > return dict.__getitem__(self, key) > > elif key in self.rowNames: > return [ dict.__getitem__(self, (key, col)) for col in self.colNames ] > > elif key in self.colNames: > return [ dict.__getitem__(self, (row, key)) for row in self.rowNames ] > > else: > raise KeyError, key > > > def __setitem__(self, key, value): > if self._isCellKey(key): > return dict.__setitem__(self, key, value) > > elif key in self.rowNames and len(value) == len(self.colNames): > for col, val in zip(self.colNames, value): > dict.__setitem__(self, (key, col), val) > > elif key in self.colNames and len(value) == len(self.rowNames): > for row, val in zip(self.rowNames, value): > dict.__setitem__(self, (row, key), val) > > else: > raise ValueError, 'Invalid key or value: Grid[%r] = %r' % (key, value) > > > def _isCellKey(self, key): > ''' Is key a valid cell index? ''' > return isinstance(key, tuple) \ > and len(key) == 2 \ > and key[0] in self.rowNames \ > and key[1] in self.colNames > > > if __name__ == '__main__': > import doctest > doctest.testmod() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From servando at mac.com Sat May 28 17:53:55 2005 From: servando at mac.com (Servando Garcia) Date: Sat, 28 May 2005 10:53:55 -0500 Subject: [Tutor] reading comments Message-ID: <63264ad3f23d245752c14330107af6ad@mac.com> Hello list How do I read the comments attached to a zipfile or for any file .? From kent37 at tds.net Sat May 28 18:17:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 May 2005 12:17:46 -0400 Subject: [Tutor] reading comments In-Reply-To: <63264ad3f23d245752c14330107af6ad@mac.com> References: <63264ad3f23d245752c14330107af6ad@mac.com> Message-ID: <429899AA.5020302@tds.net> Servando Garcia wrote: > Hello list > How do I read the comments attached to a zipfile or for any file .? For a zipfile, you can open the file with the zipfile module. Each file in the zip has a ZipInfo object associated with it. You get a single ZipInfo using getinfo(name) on the opened ZipFile, or get a list of all ZipInfos with infolist(). >>> import zipfile >>> zip = zipfile.ZipFile('myfile.zip') >>> i = zip.getinfo('afile.txt') >>> i.comment '*' Kent From albertito_g at hotmail.com Sat May 28 19:02:20 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Sat, 28 May 2005 17:02:20 +0000 Subject: [Tutor] check PID In-Reply-To: <63264ad3f23d245752c14330107af6ad@mac.com> Message-ID: Hey all I want to check if a PID number is running I have the pid number from other program and I want to check if it's alive Using Python 2.2 over Linux Red Hat 9 I tried to google but find how to know process of the app but not check for other pids Thanks ina dvanced Alberto From carroll at tjc.com Sat May 28 19:44:10 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 28 May 2005 10:44:10 -0700 (PDT) Subject: [Tutor] increment operator In-Reply-To: <0C41D82A-157F-4EE2-9DD0-42266FE1E7DE@mac.com> Message-ID: On Fri, 27 May 2005, Lee Cullens wrote: > I find the following invaluable - maybe you will also. > > http://rgruet.free.fr/PQR24/PQR2.4.html That's a great resource. Thanks. From carroll at tjc.com Sat May 28 19:48:43 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 28 May 2005 10:48:43 -0700 (PDT) Subject: [Tutor] reading comments In-Reply-To: <63264ad3f23d245752c14330107af6ad@mac.com> Message-ID: On Sat, 28 May 2005, Servando Garcia wrote: > How do I read the comments attached to a zipfile or for > any file .? Someone's on riddle 6! :-) z = zipfile.ZipFile(zipfilename, mode='r') zi = z.getinfo(zfilename) print zi.comment From jonasmg at softhome.net Sat May 28 22:17:05 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sat, 28 May 2005 21:17:05 +0100 Subject: [Tutor] UTF-8 by default Message-ID: <4298D1C1.50402@softhome.net> Hi all, I'm working with an XML file, and i want to write in UTF-8 How write by default in UTF-8 instead of ASCII? And I want not to use: print u'String' Thanks in advance! From tomcloyd at bestmindhealth.com Sun May 29 01:21:44 2005 From: tomcloyd at bestmindhealth.com (Tom Cloyd) Date: Sat, 28 May 2005 16:21:44 -0700 Subject: [Tutor] oops! Message-ID: Sorry about that last post! I thought I was replying to a Komodo list post. -- t. ====================================================== Tom Cloyd Bellingham, Washington, U.S.A: (360) 920-1226 << BestMindHealth.com >> ====================================================== Using Opera's revolutionary e-mail client (program): http://www.opera.com/mail/ From kent37 at tds.net Sun May 29 02:29:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 May 2005 20:29:56 -0400 Subject: [Tutor] UTF-8 by default In-Reply-To: <4298D1C1.50402@softhome.net> References: <4298D1C1.50402@softhome.net> Message-ID: <42990D04.5000907@tds.net> Jonas Melian wrote: > Hi all, > > I'm working with an XML file, and i want to write in UTF-8 > How write by default in UTF-8 instead of ASCII? How are you writing the file? What encoding is your data originally? If the data is all in US-ASCII (codes 0-127) then it is already UTF-8 as US-ASCII is a subset of UTF-8. Kent From carroll at tjc.com Sun May 29 03:26:26 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat, 28 May 2005 18:26:26 -0700 (PDT) Subject: [Tutor] Help: wget-- how does it work? In-Reply-To: Message-ID: On Fri, 27 May 2005, Terry Carroll wrote: > I use this for an app I have that reads the 27-meg Unihan.txt file; but I > think I cheat and hardcode the 27-meg no. I just checked, and, yep, that's exactly what I do. From kent37 at tds.net Sun May 29 05:00:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 28 May 2005 23:00:01 -0400 Subject: [Tutor] Help: wget-- how does it work? In-Reply-To: <2c2812b605052715401b9afa2b@mail.gmail.com> References: <2c2812b605052715401b9afa2b@mail.gmail.com> Message-ID: <42993031.2060901@tds.net> Aaron Elbaz wrote: > One of my favourite unix applications is wget. > > Thinking how easy (and fun) it might be to implement with pythons > excellent librairies has led me to a few questions. > > First, I found the progress bar class from aspn > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 > > This could be used to simulate wgets progress bar. What I'm trying to > figure out now is how one would stat a file as it was being downloaded > so that I can feed information to the progress bar, and what the most > optimal way to do this is? See urllib.urlretrieve(). The reporthook argument gives you all the information you need to create a progress indicator. Here is Guido van Rossum's own Python wget, from the Python Cookbook: import sys, urllib def reporthook(*a): print a for url in sys.argv[1:]: i = url.rfind('/') file = url[i+1:] print url, "->", file urllib.urlretrieve(url, file, reporthook) Kent From jonasmg at softhome.net Sun May 29 10:00:26 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sun, 29 May 2005 09:00:26 +0100 Subject: [Tutor] UTF-8 by default In-Reply-To: <42990D04.5000907@tds.net> References: <4298D1C1.50402@softhome.net> <42990D04.5000907@tds.net> Message-ID: <4299769A.1080906@softhome.net> Kent Johnson wrote: >>How write by default in UTF-8 instead of ASCII? > > > How are you writing the file? What encoding is your data originally? > For writing the XML file: >>ElementTree.ElementTree(root).write("file.xml") The source encoding is UTF-8 ( # -*- coding: utf-8 -*- ) But I also want that the program shows its messages in differents languages, so it's necessary writting (>>>print 'Message') in UTF-8 by default From carroll at tjc.com Sun May 29 10:32:28 2005 From: carroll at tjc.com (Terry Carroll) Date: Sun, 29 May 2005 01:32:28 -0700 (PDT) Subject: [Tutor] Using Python to keep peace in the house (a little success story) Message-ID: My wife and I have a disagreement over the use of our digital camera. She likes to have the date printed on the image. I hate that, I like the image to be pristine. Our camera has the option to put the date on the image, but we can't agree on whether to enable it. Well, Python to the rescue. Since I learned about Python Imaging Library doing a couple of the Python Challenges, I decided to find whether I could add the date to the image after the fact. It turned out to be pretty easy. I had a proof-of-concept done in about 10 minutes, and a finished project a couple hours later. I now have a routine called "Imprint" that adds any arbitrary text to a JPG file; and one called "GetFileDate" that gets the date of the file (using the EXIF info stored with the image, if it exists). Now I can write a little program to loop through all the undated images (which keep me happy) and make copies with the date, (to keep her happy). Here's my solution, in case anyone is interested: ========================================================== import Image, ImageDraw, ImageFont def GetFileDate(file): """ Returns the date associated with a file. For JPEG files, it will use the EXIF data, if available """ try: import EXIF # EXIF.py from http://home.cfl.rr.com/genecash/digital_camera.html f = open(file, "rb") tags = EXIF.process_file(f) f.close() return str(tags['Image DateTime']) except (KeyError, ImportError): # EXIF not installed or no EXIF date available import os.path, time return time.ctime(os.path.getmtime(file)) def ReduceOpacity(im, opacity): """ Returns an image with reduced opacity. Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 """ import ImageEnhance assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im def Imprint(im, inputtext, font=None, color=None, opacity=.6, margin=(30,30)): """ imprints a PIL image with the indicated text in lower-right corner """ if im.mode != "RGBA": im = im.convert("RGBA") textlayer = Image.new("RGBA", im.size, (0,0,0,0)) textdraw = ImageDraw.Draw(textlayer) textsize = textdraw.textsize(inputtext, font=font) textpos = [im.size[i]-textsize[i]-margin[i] for i in [0,1]] textdraw.text(textpos, inputtext, font=font, fill=color) if opacity != 1: textlayer = ReduceOpacity(textlayer,opacity) return Image.composite(textlayer, im, textlayer) def test(): font=ImageFont.truetype("Arial.ttf", 40) imagefile = "DSCN0214.JPG" datetext = GetFileDate(imagefile) print datetext im = Image.open(imagefile) im0 = Imprint(im, datetext, font=font, opacity=0.5, color=(255,255,255)) im0.save("DSCN0214-dated.jpg", "JPEG") if __name__ == "__main__": test() ========================================================== From jonasmg at softhome.net Sun May 29 12:36:09 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sun, 29 May 2005 11:36:09 +0100 Subject: [Tutor] os.spawnlp and os.spawnlpe Message-ID: <42999B19.4010101@softhome.net> Hi, which is the difference between os.spawnlp and os.spawnlpe? With an example, please. I don't understand it. Thanks! From jonasmg at softhome.net Sun May 29 14:13:22 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sun, 29 May 2005 13:13:22 +0100 Subject: [Tutor] Dudes with os.spawnlp Message-ID: <4299B1E2.7050100@softhome.net> This code run 'X -configure' using $PATH for looking for its path :: try: #retcode = call("X" + " -configure", shell=True) # 2.4 code_return = os.spawnlp(os.P_WAIT, "X", "X", "-configure") if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e :: 1) The OSError exception never is runned. I tested with an command that doesnt exist (Xe) 2) For redirecting command output message, I think that I could to use: os.spawnlp(os.P_WAIT, "X", "X", "-configure", "&>/dev/null") But, is there any way more elegant in python? 3) That command built a file. Is it possible knows its name? Thanks in advance! From kent37 at tds.net Sun May 29 14:09:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 May 2005 08:09:23 -0400 Subject: [Tutor] UTF-8 by default In-Reply-To: <4299769A.1080906@softhome.net> References: <4298D1C1.50402@softhome.net> <42990D04.5000907@tds.net> <4299769A.1080906@softhome.net> Message-ID: <4299B0F3.4070008@tds.net> Jonas Melian wrote: > Kent Johnson wrote: > >>>How write by default in UTF-8 instead of ASCII? >> >> >>How are you writing the file? What encoding is your data originally? >> > > > For writing the XML file: > >>>ElementTree.ElementTree(root).write("file.xml") The elementTree.write() method takes an optional encoding parameter. For it to work, all the strings you put in your tree must be either ascii or unicode. > The source encoding is UTF-8 ( # -*- coding: utf-8 -*- ) Any strings you put in the elementtree should be u"" strings. > But I also want that the program shows its messages in differents > languages, so it's necessary writting (>>>print 'Message') in UTF-8 by > default 'Message' is already UTF-8; any 7-bit ASCII string is also a valid UTF-8 string. If you have non-ASCII strings you should encode them in the encoding of your terminal with print u'Message'.encode('utf-8'). Kent From kent37 at tds.net Sun May 29 14:22:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 May 2005 08:22:43 -0400 Subject: [Tutor] Dudes with os.spawnlp In-Reply-To: <4299B1E2.7050100@softhome.net> References: <4299B1E2.7050100@softhome.net> Message-ID: <4299B413.60200@tds.net> I don't know the answer to your question, but I wonder what you mean by 'dudes'. You use that word a lot and it never makes sense to me; I suspect you mistake its meaning. From dictionary.com: 1. Informal. An Easterner or city person who vacations on a ranch in the West. 2. Informal. A man who is very fancy or sharp in dress and demeanor. 3. Slang. 1. A man; a fellow. 2. dudes Persons of either sex. Can you find another word? Thanks, Kent From jonasmg at softhome.net Sun May 29 14:54:14 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Sun, 29 May 2005 13:54:14 +0100 Subject: [Tutor] Dudes with os.spawnlp In-Reply-To: <4299B413.60200@tds.net> References: <4299B1E2.7050100@softhome.net> <4299B413.60200@tds.net> Message-ID: <4299BB76.3080304@softhome.net> Kent Johnson wrote: > I don't know the answer to your question, but I wonder what you mean by 'dudes'. You use that word a > lot and it never makes sense to me; I suspect you mistake its meaning. > > Can you find another word? > Oh sorry, s/dudes/doubts From administrata at hotmail.com Sun May 29 21:21:33 2005 From: administrata at hotmail.com (. ,) Date: Sun, 29 May 2005 19:21:33 +0000 Subject: [Tutor] Planning a program with algorithm? Message-ID: I know how to write a prog. But, I don't know how to plan a prog. with algorithm. If algorithm of a part of a prog. is like.. ------------------------------------------------------------------------------------------------------------------------------------------- create an empty jumble word while the chosen word has letters in it extract a random letter from the chosen word add the random letter to the jumble word ------------------------------------------------------------------------------------------------------------------------------------------- It would be like.. ------------------------------------------------------------------------------------------------------------------------------------------- jumble = "" while word: position = random.random(len(word)) jumble += word[position] word = word[:position] + word[(position+1):] ------------------------------------------------------------------------------------------------------------------------------------------- If the prog. is like.. ------------------------------------------------------------------------------------------------------------------------------------------- #Game List list = ("GT4", "GTA Sanandreas", "Takken 5") print "My Games: " for i in list: print i print "\nI've got", len(list), "games." add = raw_input(\n\nAdd more games: ") adding = (add) list += adding print "Total games are..." print list raw_input("exit.") ------------------------------------------------------------------------------------------------------------------------------------------- What would the algorithm be for the prog.? Any useful advice for algorithm would be appreciated. Thanks. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From ajikoe at gmail.com Sun May 29 21:56:31 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Sun, 29 May 2005 21:56:31 +0200 Subject: [Tutor] Planning a program with algorithm? In-Reply-To: References: Message-ID: Before you write algorithm it is always good to know every aspect of the programing language you will use. python has built in function like set, data like list, dictionary, style like list comprehension, lambda etc.... that worth knowing before you start to write algorithm. It is always good to write program as soon as you have in my mind. in old program paradigm sometimes we needs planning, python makes it possible to do less planning because it is less typing language with battery included style. sometimes python code is more clear than the algorithm..... : ) About planning bigger project, I suggest you use extreme programming style (like refactoring etc,), since good program sometimes needs you to change your code quiet often. pujo On 5/29/05, . , wrote: > I know how to write a prog. > > But, I don't know how to plan a prog. with algorithm. > > If algorithm of a part of a prog. is like.. > ------------------------------------------------------------------------------------------------------------------------------------------- > create an empty jumble word > while the chosen word has letters in it > extract a random letter from the chosen word > add the random letter to the jumble word > ------------------------------------------------------------------------------------------------------------------------------------------- > > It would be like.. > ------------------------------------------------------------------------------------------------------------------------------------------- > jumble = "" > while word: > position = random.random(len(word)) > jumble += word[position] > word = word[:position] + word[(position+1):] > ------------------------------------------------------------------------------------------------------------------------------------------- > > > If the prog. is like.. > ------------------------------------------------------------------------------------------------------------------------------------------- > #Game List > > list = ("GT4", > "GTA Sanandreas", > "Takken 5") > > print "My Games: " > for i in list: > print i > > print "\nI've got", len(list), "games." > > add = raw_input(\n\nAdd more games: ") > adding = (add) > list += adding > > print "Total games are..." > print list > > raw_input("exit.") > ------------------------------------------------------------------------------------------------------------------------------------------- > > What would the algorithm be for the prog.? > > Any useful advice for algorithm would be appreciated. > > Thanks. > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz at h-lab.net Sat May 28 20:54:54 2005 From: hugonz at h-lab.net (hugonz@h-lab.net) Date: Sat, 28 May 2005 11:54:54 -0700 (PDT) Subject: [Tutor] increment operator In-Reply-To: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> References: <696d69f1a0842ebd7daef9cf8e6e5e2a@mac.com> Message-ID: <3662.201.133.68.98.1117306494.squirrel@webmail.h-lab.net> No, there is not. Integers are inmutable types, so you cannot modify them in place, so you do: i += 1 or i = i+1 which creates a new integer and makes "i" reference it. Hugo > Hello > Is there a increment operator in python similar to c++ > like so "SomeVariable++" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Mon May 30 05:28:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 29 May 2005 20:28:32 -0700 (PDT) Subject: [Tutor] os.spawnlp and os.spawnlpe In-Reply-To: <42999B19.4010101@softhome.net> Message-ID: On Sun, 29 May 2005, Jonas Melian wrote: > which is the difference between os.spawnlp and os.spawnlpe? With an > example, please. I don't understand it. Hi Jonas, The difference is that the one that ends with an 'e' allows us to make the spawned process use an entirely clean Unix shell environment. That is, we can define exactly what environmental variables the child process will be able to see. Usually, we want to just copy over our own os.environ and let our child see the same environmental variables that we see, but in some situations, we want to lock down those environmental variables. If it helps to understand the relationship between the two, we can define something that works like os.spawnlp(), using os.spawnlpe(): ### Pseudocode ### def my_spawnlp(mode, file, *args): args_and_env = [args] + [os.environ] return os.spawnlpe(mode, file, *args_and_env) ###### (I'm labeling this as pseudocode, because truthfully, I have not tested this well yet. *grin*) As another example: ###### >>> os.spawnlpe(os.P_WAIT, 'which', 'which', 'ls', os.environ) /bin/ls 0 >>> >>> os.spawnlpe(os.P_WAIT, 'which', 'which', 'ls', {"PATH":""}) 127 ###### The second call to the 'which' command fails predictibly, because we deliberately empty out the PATH in the child's environment. Best of wishes! From project5 at redrival.net Mon May 30 13:30:01 2005 From: project5 at redrival.net (Andrei) Date: Mon, 30 May 2005 11:30:01 +0000 (UTC) Subject: [Tutor] Planning a program with algorithm? References: Message-ID: . , hotmail.com> writes: > But, I don't know how to plan a prog. with algorithm. For small programs there's little value in planning - in fact, you'll probably end up wasting time. As far as individual algorithms go, it's usually best to go with whatever seems the easiest to understand and only do more advanced things once you know that you need more speed or something like that. > If algorithm of a part of a prog. is like.. That's a pseudocode implementation of an algorithm. You can describe an algorithm in human language, in pseudocode or in a programming language. > create an empty jumble word > while the chosen word has letters in it > extract a random letter from the chosen word > add the random letter to the jumble word That's actually *longer* than just writing the algorithm in Python directly, which is why we say that Python is executable pseudocode :). Pseudo-code design has IMO little value in Python and should stop at a higher level if it's used at all. In this example I'd have said this before going to Python code: randomize letters in word By going into too much detail, you've actually overlooked the fact that you're recreating functionality from the Python standard library: random.shuffle. > If the prog. is like.. > --------------------------------------------------------- > #Game List > > list = ("GT4", > "GTA Sanandreas", > "Takken 5") > > print "My Games: " > for i in list: > print i > > print "\nI've got", len(list), "games." > > add = raw_input(\n\nAdd more games: ") > adding = (add) > list += adding > > print "Total games are..." > print list > > raw_input("exit.") > ---------------------------------------------------------- > The pseudocode could be something like this: list all games show nr. of games get the name of a new game add the new game list all games exit If you go into more detail, you'll end up writing a long version of the Python code, which kind of defeats the purpose of pseudocode. > Any useful advice for algorithm would be appreciated. It's more important (at least for larger progams) to think about good design in terms of modules, classes and functions than in terms of individual lines of code. Always stop designing when designing becomes as low-level as just writing the code. Yours, Andrei From administrata at hotmail.com Mon May 30 20:42:07 2005 From: administrata at hotmail.com (. ,) Date: Mon, 30 May 2005 18:42:07 +0000 Subject: [Tutor] Planning a program with algorithm? In-Reply-To: Message-ID: I'm learning python by reading 'Python Programming for the Absolute Beginner' by Michael Dawson. And I'm doing chapter4. In the book it says it's recommended to plan a prog. with pseudocode. Can i just ignore it? Thanks. _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From marilyn at deliberate.com Mon May 30 19:45:25 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon, 30 May 2005 10:45:25 -0700 (PDT) Subject: [Tutor] Planning a program with algorithm? In-Reply-To: Message-ID: On Mon, 30 May 2005, . , wrote: > I'm learning python by reading 'Python Programming for the Absolute > Beginner' by Michael Dawson. > > And I'm doing chapter4. In the book it says it's recommended to plan a prog. > with pseudocode. > > Can i just ignore it? Yes! Python is a formalized pseudocode. Go for it! Marilyn > > Thanks. > > _________________________________________________________________ > FREE pop-up blocking with the new MSN Toolbar - get it now! > http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- From administrata at hotmail.com Mon May 30 21:03:43 2005 From: administrata at hotmail.com (. ,) Date: Mon, 30 May 2005 19:03:43 +0000 Subject: [Tutor] For loop exercise Message-ID: I finished the chapter which includes for loop, tuples, indexing and slicing. Can anyone suggest me 3 exercises to remind of the chapter? Thanks. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From jonasmg at softhome.net Mon May 30 22:05:27 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Mon, 30 May 2005 21:05:27 +0100 Subject: [Tutor] skip some directories Message-ID: <429B7207.2000107@softhome.net> Hi, I'm trying to working with some directories only import os dirName = "/usr/share/fonts/" dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi'] # directories to skip for root, dirs, files in os.walk(dirName): for end in dirBase: if root.endswith(end): print 'skiped' else: print root # but this fails, because always run 'print root' #This is the only way: if root.endswith('misc'): print 'skiped' else: ... #but how pass all values in 'dirBase'? Thanks in advance! From chuck at freshsources.com Mon May 30 22:14:57 2005 From: chuck at freshsources.com (Chuck Allison) Date: Mon, 30 May 2005 14:14:57 -0600 Subject: [Tutor] Frozen Binaries Message-ID: <325030707.20050530141457@freshsources.com> Hello tutor, Could someone please give me the quick lowdown on creating frozen binaries? Thanks. -- Best regards, -- Chuck Allison From project5 at redrival.net Mon May 30 22:11:56 2005 From: project5 at redrival.net (Andrei) Date: Mon, 30 May 2005 20:11:56 +0000 (UTC) Subject: [Tutor] Planning a program with algorithm? References: Message-ID: > I'm learning python by reading 'Python Programming for the Absolute > Beginner' by Michael Dawson. > In the book it says it's recommended to plan a prog. > with pseudocode. > > Can i just ignore it? I don't think it's a bad technique, but there's different ways of writing pseudocode. The benefit of pseudocode is that you can write and inspect an algorithm quickly (quicker than in the programming language). Having 1 line of code for 1 line of pseudocode is in that regard a pointless use of pseudocode. Code:pseudocode ratios of 3:1, 5:1 or so are more reasonable in my opinion. By the way, this is roughly equivalent to the ratio of code required to do something in a lower-level language compared to doing the same thing in Python, which is why Python is comparable to pseudocode from the POV of low-level languages. One approach you could consider is to write pseudocode, turn it into comments and write the real code in between those. That way you get the benefits of pseudocode (being able to spot algorithm errors at a higher level) as well as properly commented code. Difficult portions then automatically get more comments, while easier portions get fewer comments - just as it should be. Yours, Andrei From project5 at redrival.net Mon May 30 22:30:35 2005 From: project5 at redrival.net (Andrei) Date: Mon, 30 May 2005 20:30:35 +0000 (UTC) Subject: [Tutor] Planning a program with algorithm? References: Message-ID: . , hotmail.com> writes: > And I'm doing chapter4. In the book it says it's recommended to plan a prog. > with pseudocode. > > Can i just ignore it? Let me expand a bit on my previous post. You can use pseudocode iteratively, starting at a very high level and dropping lower until you start recognizing your programming language. Let's go back to your shuffling example and assume that code is part of a weak password generation tool. You could start with this (either in your editor, or in your mind): get source of letters process letters to generate password show password Then you can start expanding. What is that processing? Could be this: ask user for the desired password length randomize source of letters return piece of desired length At this point you probably already recognize Python code directly in there: a raw_input with validity checking (password can't be longer than the source), a random.shuffle and a list slice combined with a join(). There's no point in going even deeper, because you'd end up writing this: while desired length larger than source or smaller than 1 get desired length convert source to list shuffle source take slice of desired length return joined slice That's just a clumsy way of writing Python and therefore a waste of time. If on the other hand you were programming in ObjectPascal, C++ or something similar, this code would still not be quite high level, because shuffling the source, taking a slice and such are not built into those languages. In fact, in those languages you'd most likely choose a different approach at this level. Yours, Andrei From dyoo at hkn.eecs.berkeley.edu Tue May 31 03:31:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 May 2005 18:31:13 -0700 (PDT) Subject: [Tutor] skip some directories In-Reply-To: <429B7207.2000107@softhome.net> Message-ID: On Mon, 30 May 2005, Jonas Melian wrote: > I'm trying to working with some directories only > > import os > dirName = "/usr/share/fonts/" > dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi'] # directories to > skip > > for root, dirs, files in os.walk(dirName): > for end in dirBase: > if root.endswith(end): > print 'skiped' > else: > print root Hi Jonas, Let's break out the logic a little bit. Would it be accurate to write this as: ### Pseudocode ### for root, dirs, files in os.walk(dirName): if weShouldSkipThis(root): print "skipped" else: print root ###### and would this be more accurate to what you're trying to do? If so, then all you need to do is concentrate on weShouldSkipThis(). Making a separate helper function there should help you get it working properly. If you have more questions, please feel free to ask. From dyoo at hkn.eecs.berkeley.edu Tue May 31 03:33:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 May 2005 18:33:00 -0700 (PDT) Subject: [Tutor] Frozen Binaries In-Reply-To: <325030707.20050530141457@freshsources.com> Message-ID: On Mon, 30 May 2005, Chuck Allison wrote: > Could someone please give me the quick lowdown on creating frozen > binaries? Thanks. Hi Chuck, On Windows, the 'py2exe' program's probably the most straightforward of the freezers: http://py2exe.sf.net That page has a complete toy example that shows how to freeze a Python program. Does this help? If you have more questions, please feel free to ask. From dyoo at hkn.eecs.berkeley.edu Tue May 31 03:51:55 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 30 May 2005 18:51:55 -0700 (PDT) Subject: [Tutor] Planning a program with algorithm? In-Reply-To: Message-ID: On Mon, 30 May 2005, Andrei wrote: > . , hotmail.com> writes: > > > But, I don't know how to plan a prog. with algorithm. > > For small programs there's little value in planning - in fact, you'll > probably end up wasting time. As far as individual algorithms go, it's > usually best to go with whatever seems the easiest to understand and > only do more advanced things once you know that you need more speed or > something like that. I'm not sure about this, but I think we might be using the word "algorithm" a bit flippantly. *grin* I think we might be talking more about designing programs in general. Some design advocates say that program design should be a part of every program. At least, at minimum, we may want to think about: 1. What is the program supposed to do? What's the input, and what's the output? 2. What would a typical program run look like? 3. What can we test it with to know that the program's doing the right thing? For example, if we're trying to write a program to capitalize a name, we might want to "design" it as: The program takes a string, and returns a capitalized version of that string. For example, capitalize("john adams") --> "John Adams", and capitalize("elvis") --> "Elvis". I don't know what to do if we get a non-name string, so let's just leave those cases alone. i.e. capitalize("42") --> "42". At least, at minimum, we should do enough thinking to let us know if we're going astray as we write our program. *grin* A big problem in writing programs is not recognizing when they don't work, which is why Unit Testing is getting so much attention these days. The textbook "How to Design Programs" focuses on a design approach to program construction. The book's host language is Scheme, but I feel a lot of the material is language agnostic and valuable to any programmer: http://www.htdp.org Best of wishes! From dragonfly at nylonoxygen.com Tue May 31 04:39:59 2005 From: dragonfly at nylonoxygen.com (Adam McNutt) Date: Mon, 30 May 2005 20:39:59 -0600 Subject: [Tutor] ActiveState Komodo In-Reply-To: References: Message-ID: <1117507200.15498.2.camel@localhost.localdomain> I've just started out on Python (again) and found an IDE that I really like. Maybe others will like it as well. I know it's commercial, but I found a coupon code to get the personal edition free. Thought this may interest others. Here is the page that has the info (and it seems to be updated with other freebies often): http://www.pcuser.com.au/pcuser/hs2.nsf/Dir/registration And here is the actual coupon instructions: ActiveState Komodo 3.1 Personal To obtain your free license of Komodo Personal Edition please go to http://www.activestate.com/Products/Download/Register.plex?id=Komodo and click on the ?Buy? button for Komodo Personal Edition. Enter the promotion code ?kmd3n9-ur8? and click on the ?Update Your Cart? button to reduce the payment to zero, and then proceed to checkout. Register your details and a licence key will be sent to your nominated address. Ignore the download step if you have already installed the software on your PC. You will then receive an email with a link to a licence installer executable. Simply follow the instructions in that email. Offer ends December 31, 2005. Enjoy, Adam McNutt From jonasmg at softhome.net Tue May 31 09:04:25 2005 From: jonasmg at softhome.net (Jonas Melian) Date: Tue, 31 May 2005 08:04:25 +0100 Subject: [Tutor] skip some directories In-Reply-To: References: Message-ID: <429C0C79.4040709@softhome.net> Danny Yoo wrote: >>I'm trying to working with some directories only >> >>import os >>dirName = "/usr/share/fonts/" >>dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi'] # directories to >>skip >> >>for root, dirs, files in os.walk(dirName): >> for end in dirBase: >> if root.endswith(end): >> print 'skiped' >> else: >> print root > > Let's break out the logic a little bit. Would it be accurate to write > this as: > > ### Pseudocode ### > for root, dirs, files in os.walk(dirName): > if weShouldSkipThis(root): > print "skipped" > else: > print root > ###### > At the end, i found the way of make it: dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi','encodings', 'util'] for root, dirs, files in os.walk(dirName): print dirs # for checking all directories that i have at beginning for name in dirs: if name in dirBase: dirs.remove(name) print dirs # compare if all directories in dirBase has been deleted But it fails at delete some directories. Why? ['100dpi', '75dpi', 'TTF', 'Type1', 'arphicfonts', 'baekmuk-fonts', 'corefonts', 'cyrillic', 'default', 'encodings', 'freefont', 'kochi-substitute', 'local', 'misc', 'sharefonts', 'ukr', 'util'] ['75dpi', 'Type1', 'arphicfonts', 'baekmuk-fonts', 'corefonts', 'cyrillic', 'default', 'freefont', 'kochi-substitute', 'local', 'sharefonts', 'ukr'] It did fail with '75dpi', and 'Type1' From dyoo at hkn.eecs.berkeley.edu Tue May 31 09:41:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 31 May 2005 00:41:37 -0700 (PDT) Subject: [Tutor] skip some directories In-Reply-To: <429C0C79.4040709@softhome.net> Message-ID: > At the end, i found the way of make it: > > dirBase = ['misc','TTF','Type1','CID','100dpi','75dpi','encodings', 'util'] > > for root, dirs, files in os.walk(dirName): > print dirs # for checking all directories that i have at beginning > for name in dirs: > if name in dirBase: > dirs.remove(name) Hi Jonas, What's happening is a consequence of in-place deletion in lists: when we delete from the same collection that we iterate across, we run into the real possiblity of "yanking the rug" right underneath the loop. The for loop: for name in dirs: combined with deletions on 'dirs', is a likely culprit for the problem. Let's take a simpler loop to make it easier to see the potential bug. Say that we have a 'for' loop, like this: ###### names = ['bill', 'ted'] for n in names: print n names.remove(n) ###### What do you expect to see here? Try running it, and see if it matches with what you expect. If it helps, we can do a rough translation of this into a while loop with an explicit index counter: ###### names = ['bill', 'ted'] i = 0 while i < len(names): print names[i] names.remove(names[i]) i = i + 1 ###### One common way to avoid the problem is to iterate across a copy of the list when we do things that change the structure of our list: ###### names = ['bill', 'ted'] for n in names[:]: ### List slicing does a list copy print n names.remove(n) assert names == [] ###### Here, we use a trick by taking a "slice" of the whole list. A similar approach should fix the bug in your code. Best of wishes to you! From tubaranger at gmail.com Tue May 31 14:26:36 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Tue, 31 May 2005 07:26:36 -0500 Subject: [Tutor] For Loop Exercises Message-ID: <57aa550605053105265b9915e3@mail.gmail.com> >I finished the chapter which includes for loop, tuples, indexing and >slicing. Can anyone suggest me 3 exercises to remind of the chapter? A great place to find all sorts of programs to write -- from very easy to complex -- is the programming contest archive on the useless python page ( www.uselesspython.com ). Pick a couple and you will have all sorts of chances to use everything mentioned above. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050531/7378c28e/attachment.html From jeffpeery at yahoo.com Tue May 31 16:40:47 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 31 May 2005 07:40:47 -0700 (PDT) Subject: [Tutor] wxpython button icons? Message-ID: <20050531144047.77353.qmail@web30514.mail.mud.yahoo.com> Hello, does anyone know if there is a list of widows icons available? I'm creating an application for windows and I'd like to use standard icons for things like a "print" button or "save" button etc. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050531/baccd0c5/attachment.html From Christian.Wyglendowski at greenville.edu Tue May 31 16:52:58 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue, 31 May 2005 09:52:58 -0500 Subject: [Tutor] wxpython button icons? Message-ID: Hey Jeff, > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Jeff Peery > > Hello, does anyone know if there is a list of widows icons > available? I'm creating an application for windows and I'd > like to use standard icons for things like a "print" button > or "save" button etc. thanks. Checkout "images.py" in the wxPython demo directory. If you put it in your python path somewhere you can do an "import images" and then write code like this (grabbed from the wxPython toolbar demo): tb = self.CreateToolBar( wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT | wx.TB_TEXT ) tb.AddSimpleTool(10, images.getNewBitmap(), "New", "Long help for 'New'") self.Bind(wx.EVT_TOOL, self.OnToolClick, id=10) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=10) tb.AddSimpleTool(20, images.getOpenBitmap(), "Open", "Long help for 'Open'") self.Bind(wx.EVT_TOOL, self.OnToolClick, id=20) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRClick, id=20) There are probably other ways to do this as well, but there's my .02! Christian http://www.dowski.com From project5 at redrival.net Tue May 31 20:14:50 2005 From: project5 at redrival.net (Andrei) Date: Tue, 31 May 2005 18:14:50 +0000 (UTC) Subject: [Tutor] Planning a program with algorithm? References: Message-ID: Danny Yoo hkn.eecs.berkeley.edu> writes: > Some design advocates say that program design should be a part of every > program. At least, at minimum, we may want to think about: > > 1. What is the program supposed to do? What's the input, and what's > the output? > > 2. What would a typical program run look like? > > 3. What can we test it with to know that the program's doing the right > thing? It's hard to disagree with that :). My only gripe with such a generous definition is that it's pretty much impossible to make a program without 'designing' it, because you'd end up with a bunch of random statements. I find 'design' useful only if it means that some effort has gone into making sure the application is well structured, easy to maintain, easy to extend/modify (especially in the directions which could be foreseen beforehand). Going from design-in-head straight to production code doesn't (at least for me) lead to the best of results in those respects, even though the code may work. Yours, Andrei From hugonz-lists at h-lab.net Mon May 30 19:55:08 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 30 May 2005 12:55:08 -0500 Subject: [Tutor] check PID In-Reply-To: References: Message-ID: <429B537C.90402@h-lab.net> Check os.waitpid() Hugo Alberto Troiano wrote: > Hey all > > I want to check if a PID number is running > I have the pid number from other program and I want to check if it's alive > Using Python 2.2 over Linux Red Hat 9 > > I tried to google but find how to know process of the app but not check for > other pids > > Thanks ina dvanced > > Alberto > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From icarr at compxnet.com Tue May 31 21:33:00 2005 From: icarr at compxnet.com (Israel Carr) Date: Tue, 31 May 2005 15:33:00 -0400 Subject: [Tutor] ftplib: retrbinary all files in directory Message-ID: <35D8A7DE4D78AF4AB3CD455CF6085DFF08550F@CIXMX1.compxnet.com> I'm using ftplib to connect to a server, and I want to grab every file from a specific folder. The filenames change frequently. What is the best way to use retrbinary with wildcards(or some better option) to transfer all files? Thanks, Israel From denise.hartley at gmail.com Tue May 31 23:11:25 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 31 May 2005 14:11:25 -0700 Subject: [Tutor] Variations on putpixel - More Pixel manipulation - #14 Message-ID: <8daabe56050531141177e08c78@mail.gmail.com> Hello, everyone! I know you didn't expect to hear from me anymore about these pesky challenges, since I started the off-tutor list about it, but I'm afraid I'm stuck and cannot get a hint. If I want to rearrange a long string of pixels in a different order, using "putpixel" with a certain size new image (in this case, 100x100) will take the long string of pixels, fill the first line of the new image, and then more or less "carriage return" to fill the next line from the left to the right. Does anyone know a different way to .... put.. pixels? (Again, this *is* for the python challenges, if anyone has passed this point). Thanks, and sorry for bringing this back into the list! ~Denise