Re: [Tutor] program hangs in while loop using wx.yield
"Alex Hall" wrote I had this working back in the summer, but have since had to restructure some things in the code. Now, my program is hanging while it waits for the human player to take his/her turn, and I am not sure how to free it; I don't really understand this concept in a GUI? Why would you be waitying for the user? Surely you should just go back to the mainloop and let the GUI control the users input? Then after processing that call the computer move code. Something like: def handle_user_move_event(): processMoveOnGUI() movedata = generateComputerMove() processMoveOnGUI() return Thats what I would expect to see. while not self.grid.turnOver: print("in while") #just a test to make sure I got this far wx.Yield() time.sleep(1) #end while So this is presumably buried in some very long and complex method that you have written and you are briefly giving control back to wxPython before continuing your processing? Except that you appear to just cycle continually giving back control? It doesn't seem to make sense. some of them change the Grid's "turnOver" variable. Therefore, I loop until I see that the user performed an action on the grid that sets the Grid's turnOver to true, at which point the loop stops and the other user (a computer in this case) can go. Why are you doing all this inside ane event handler? Why don't you just make your move and hand back to the GUI? The problem is that this loop makes the app hang, with Windows saying it is not responding. Of course, the user can now not do anything at all, so I have to use ctrl-c from the cmd window where I launched it to kill it. No idea why its doing that. Have you tried playing with the Yield parameter and return value to see if they give a clue? But frankly I'd look to reconstruct the code to avoid the use of Yield completely. Yield should almost be a last resort... time to call any Grid function. Is this solvable, or should I just use threads? Based on the loop you posted you shouldn't need threads, just exit your method and wait for the user to do something and catch that event to restart your code. Leave it to the GUI. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating one file out of all the files in a directory
Hi Kushal, First of all, thanks a lot for your help. > > Your current code adds the marker line to the original files. Is that > intended? Well, no, this wasn't intended. The part of the code that did that was introduced in one of the many attempts to solve the problem. I knew that this was an unwanted result but since I didn't know how to get out of the situation I got myself in I decided to send the code as it was so that people in this list could see more clearly what the problems with my code were. > You can open the output file for writing by passing 'w' as the second > argument to open. You would do this before your directory-walking loop. Then > when you read the contents of any file, just write to your output file as > well, along with your marker line. Is there any reason to open the file before the directory-walking loop? Below I enclose the code I wrote with your help and Evert's help. In that code the output file is opened inside the loop and the script works as expected. Even if it works, this might not be the best way to do it. Please tell me. I'm learning and I don't just want my code to work but I want it to be as elegant and efficient as possible. >> - code >> import os >> path = '/Volumes/DATA/MyPath' >> os.chdir(path) >> file_names = glob.glob('*.txt') > > output_stream = open('outputfilename', 'w') > >> for subdir, dirs, files in os.walk(path): >> for file in files: >> f = open(file, 'r') >> text = f.readlines() > > output_stream.writelines(text) > output_stream.write('__\n') > >> f.close() >> f = open(file, 'a') >> f.write('\n\n' + '' + '\n') >> f.close() >> > > output_stream.close() > >> OK, here's what I did: import os path = '/Volumes/myPath' os.chdir(path) for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: #see tomboy note 'with statement' data = f.read() with open('/Volumes/myPath2/output.txt', 'a') as output_file: output_file.write('\n\n\n\n') output_file.write(data) output_file.write('\n\n\n\n') - if you notice, the output file is opened on the fourth line counting from the end, inside the loop. After following Evert's recommendations and yours, this seemed the most logical place to do it. As I said, it works like a charm but I don't know if I have committed some crime of style. Josep M. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating one file out of all the files in a directory
Hi Evert, Again, thanks a lot. Too bad you and Kushal don't live close. I would like to invite you to a beer or a coffe or something. >> >> - code >> import os >> path = '/Volumes/DATA/MyPath' >> os.chdir(path) >> file_names = glob.glob('*.txt') > > You don't use file_names any further. Depending on whether you want files > from subdirectories or not, you can use the os.walk below or file_names. You are totally right. Since I had used glob in another script before, I tried to use it in this one as well before I tried with os.walk() and then I left it there forgetting that with os.walk() it was no longer necessary. >> for subdir, dirs, files in os.walk(path): >> for file in files: >> f = open(file, 'r') >> text = f.readlines() > > Since you don't care about lines in your files, but just the entire file > contents, you could also simply use > data = f.read() Yes. Thanks. This is much better. I knew this from having read a chapter on working with files somewhere but I wound up using .readlines() because in my search for a solution I saw some piece of code that used it and got the results I wanted, > So close ;-). > What you're missing is the next write statement: > f.write(data) > > (or > f.write(''.join(text)) > which shows why read() is nicer in this case: readlines() returns a list, not > just a single string). > >> f.close() > > But actually, you can open and close the output file outside the entire loop; > just name it differently (eg, before the first loop, > outfile = open('outputfile', 'w') OK, I ask you (or anybody reading this) the same question I asked Kushal: why is it better to open the output file outside the entire loop. I understand why it should be closed outside the loop but if you see the code I came up with after your comments, I open the output file inside the loop and the script still works perfectly well. Is there any good reason to do it differently from the way I did it? Here's what I did: - import os path = '/Volumes/myPath' os.chdir(path) for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: #see tomboy note 'with statement' data = f.read() with open('/Volumes/myPath2/output.txt', 'a') as output_file: output_file.write('\n\n\n\n') output_file.write(data) output_file.write('\n\n\n\n') - I came up with this way of doing because I was trying to follow your advice of using the 'with' statement and this was the first way that I could think of to implement it. Since in the little test that I ran it worked, I left it like that but I would like to know whether there is a more elegant way to implement this so that I learn good habits. > In this case, though, there's one thing to watch out for: glob or os.walk > will pick up your newly (empty) created file, so you should either put the > all-containg file in a different directory (best practice) or insert an > if-statement to check whether file[name] != 'outputfile' You'll have seen that I opted for the best practice but I still used an if statement with file[name] != 'outputfile' in order to solve some problems I was having with a hidden file created by Mac OSX (.DS_Store). The output file contained some strange characters at the beginning and it took me a while to figure out that this was caused by the fact that the loop read the contents of the .DS_Store file. > Finally, depending on the version of Python you're using, there are nice > things you can do with the 'with' statement, which has an incredible > advantage in case of file I/O errors (since you're not checking for any read > errors). > See eg http://effbot.org/zone/python-with-statement.htm (bottom part for > example) or Google around. Great advice. I took the opportunity to learn about the 'with' statement and it will be very helpful in the future. While they don't come up with virtual drinks that are realistic enough to be enjoyable, I can only offer you my thanks for your time. Josep M. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating one file out of all the files in a directory
> Again, thanks a lot. Too bad you and Kushal don't live close. I would > like to invite you to a beer or a coffe or something. Thanks for the offer. Some time ever in the far, far future perhaps ;-). > >> So close ;-). >> What you're missing is the next write statement: >> f.write(data) >> >> (or >> f.write(''.join(text)) >> which shows why read() is nicer in this case: readlines() returns a list, >> not just a single string). >> >>>f.close() >> >> But actually, you can open and close the output file outside the entire >> loop; just name it differently (eg, before the first loop, >> outfile = open('outputfile', 'w') > > OK, I ask you (or anybody reading this) the same question I asked > Kushal: why is it better to open the output file outside the entire > loop. I understand why it should be closed outside the loop but if you > see the code I came up with after your comments, I open the output > file inside the loop and the script still works perfectly well. Is > there any good reason to do it differently from the way I did it? Your code will work fine. My reason (and there may be others) to do it this way is just to avoid a marginal bit of overhead. Closing and opening the file each time will cost some extra time. So that's why I would have moved the with statement for the output_file outside both loops. Though as said, I guess that the overhead in general is very little. > Here's what I did: > > - > import os > path = '/Volumes/myPath' > os.chdir(path) > for subdir, dirs, files in os.walk(path): >for filename in files: >if filename != '.DS_Store': >with open(filename, 'r') as f: #see tomboy note 'with > statement' >data = f.read() >with open('/Volumes/myPath2/output.txt', 'a') as > output_file: >output_file.write('\n\n\n\n') >output_file.write(data) >output_file.write('\n\n\n\n') > - > > I came up with this way of doing because I was trying to follow your > advice of using the 'with' statement and this was the first way that I > could think of to implement it. Since in the little test that I ran it > worked, I left it like that but I would like to know whether there is > a more elegant way to implement this so that I learn good habits. This is fine: 'with open(, ) as :' is, afaik, the standard way now to open a file in Python. >> In this case, though, there's one thing to watch out for: glob or os.walk >> will pick up your newly (empty) created file, so you should either put the >> all-containg file in a different directory (best practice) or insert an >> if-statement to check whether file[name] != 'outputfile' > > You'll have seen that I opted for the best practice but I still used > an if statement with file[name] != 'outputfile' in order to solve some > problems I was having with a hidden file created by Mac OSX > (.DS_Store). The output file contained some strange characters at the > beginning and it took me a while to figure out that this was caused by > the fact that the loop read the contents of the .DS_Store file. Yes, there'll few ways to avoid separate filenames apart from an if statement. Cheers, Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating one file out of all the files in a directory
"Josep M. Fontana" wrote OK, I ask you (or anybody reading this) the same question I asked Kushal: why is it better to open the output file outside the entire loop. Because you only need to open it once and leave it open. You are opening it each and every time which is wasteful. It could on some OSDS also lead to problems. And if you were writing a new file rather than appending it would overwrite the contents each time which would be bad. see the code I came up with after your comments, I open the output file inside the loop and the script still works perfectly well. Consider that more a matter of luck than good judgement. Is there any good reason to do it differently from the way I did it? Yes, see above. I came up with this way of doing because I was trying to follow your advice of using the 'with' statement and this was the first way that I could think of to implement it. Just put the with statement for the output file outside the loop: with open('/Volumes/myPath2/output.txt', 'a') as output_file: for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: #see tomboy note 'with statement' data = f.read() output_file.write('\n\n\n\n') output_file.write(data) output_file.write('\n\n\n\n') BTW you could use a single write with: output_file.write( '\n\n\n\n%s\n\n\n\n" % (filename, data) ) But thats largely a matter of personal style. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating one file out of all the files in a directory
Thanks Alan, why is it better to open the output file outside the entire >> loop. > > Because you only need to open it once and leave it open. > You are opening it each and every time which is wasteful. > It could on some OSDS also lead to problems. And if you > were writing a new file rather than appending it would overwrite > the contents each time which would be bad. Dah, yes, you are totally right and now that I think about it it seems pretty obvious. Now, why didn't I think about it? That's the problem. > Just put the with statement for the output file outside the loop: You mean like this? It seems to work. ... with open('/Volumes/myPath2/output.txt', 'a') as output_file: for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: data = f.read() output_file.write( "\n\n\n\n%s\n\n\n\n" % (filename, data) ) > > BTW you could use a single write with: > > output_file.write( '\n\n\n\n%s\n\n\n\n" % (filename, > data) ) > > But thats largely a matter of personal style. Well, since I don't have any personal style yet, I might as well go with the style of good programmers I learn from. If you notice in the revised code I introduced above, I replaced the single quote with a double quote to match the double quote you had used at the end. This was a typo, right? Josep M. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] program hangs in while loop using wx.yield
On 11/14/10, Alan Gauld wrote: > "Alex Hall" wrote > >> I had this working back in the summer, but have since had to >> restructure some things in the code. Now, my program is hanging >> while >> it waits for the human player to take his/her turn, and I am not >> sure >> how to free it; > > I don't really understand this concept in a GUI? > Why would you be waitying for the user? > Surely you should just go back to the mainloop > and let the GUI control the users input? Then > after processing that call the computer move code. > Something like: > > def handle_user_move_event(): > processMoveOnGUI() > movedata = generateComputerMove() > processMoveOnGUI() > return > > Thats what I would expect to see. The problem is that I want to go until there is a winner. You are right about just letting the mainloop of the gui handle input (I forgot the gui is already looping and waiting for input) but I would like to make the user pause while the computer goes, this way the user cannot just keep hammering out moves as fast as possible and input can be given to the user properly. Therefore, I have gotten rid of the loop I sent originally, but I still have a loop which switches between the two players as well as passing the results of one player's move to the other. If I fire (it is Battleship) and hit your ship,and I am the computer, then this loop will give you the information about where I fired. You will check to see if it was a hit and, since it was, pass back information about what was hit. You will also update the gui to reflect the new status of the damaged ship. However, while I am doing this, I do not want you firing as fast as possible, and I want you to take in the results before you are allowed to fire. I realize it is all rather confusing without seeing the code, but the loop itself is somewhat complex unless you can see what all the functions are doing. Still, here is the new loop: while not player1.isWinner or not player2.isWinner: if player1.grid.turnOver: print("player2 is going") player1.grid.speak("player 2 is going.") player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did player1.lock() #so p1 cannot interact with the gui player2.takeTurn() #decides what to do and updates its Grid object accordingly player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just output what p2 did after takeTurn() is over elif player2.grid.turnOver: print("player1 is going") player1.enemyMove=player2.grid.cmd player1.unlock() #p1 can now interact with the gui player1.grid.speak("It is now your turn.") player1.takeTurn() #end if #wx.Yield() time.sleep(.1) #end while > >> while not self.grid.turnOver: >> print("in while") #just a test to make sure I got this far >> wx.Yield() >> time.sleep(1) >> #end while > > So this is presumably buried in some very long and complex method > that you have written and you are briefly giving control back to > wxPython > before continuing your processing? Except that you appear to just > cycle continually giving back control? It doesn't seem to make sense. I am honestly not sure how all the control flows, but this loop is gone so hopefully it will not be a problem. > >> some of them change the Grid's "turnOver" variable. Therefore, I >> loop >> until I see that the user performed an action on the grid that sets >> the Grid's turnOver to true, at which point the loop stops and the >> other user (a computer in this case) can go. > > Why are you doing all this inside ane event handler? Why don't > you just make your move and hand back to the GUI? > > >> The problem is that this loop makes the app hang, >> with Windows saying it is not responding. Of >> course, the user can now not do anything at all, so I have to use >> ctrl-c from the cmd window where I launched it to kill it. > > No idea why its doing that. Have you tried playing with the > Yield parameter and return value to see if they give a clue? > > But frankly I'd look to reconstruct the code to avoid the use > of Yield completely. Yield should almost be a last resort... > >> time to call any Grid function. Is this solvable, or should I just >> use >> threads? > > > Based on the loop you posted you shouldn't need threads, > just exit your method and wait for the user to do something > and catch that event to restart your code. Leave it to the GUI. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating one file out of all the files in a directory
>> Again, thanks a lot. Too bad you and Kushal don't live close. I would >> like to invite you to a beer or a coffe or something. > > Thanks for the offer. Some time ever in the far, far future perhaps ;-). Well, if you or the other people who have been so helpful to me in this list ever happen to be in Barcelona, please let me know and I will certainly treat you to a beer or two (or whatever drink you prefer). Josep M. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] python at midnight
While processing weather data from the http://www.knmi.nl/ and building a small domotica system I ran into the following 'shortcomming' from the python doc: "class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]) The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints or longs, in the following ranges: [...] 0 <= hour < 24 [...] If an argument outside those ranges is given, ValueError is raised." from http://en.wikipedia.org/wiki/ISO_8601 : "ISO 8601 uses the 24-hour clock system. The basic format is [hh][mm][ss] and the extended format is [hh]:[mm]:[ss]. * [hh] refers to a zero-padded hour between 00 and 24 (where 24 is only used to notate midnight at the end of a calendar day). [...] Midnight is a special case and can be referred to as both "00:00" and "24:00". The notation "00:00" is used at the beginning of a calendar day and is the more frequently used. At the end of a day use "24:00". Note that "2007-04-05T24:00" is the same instant as "2007-04-06T00:00" (see Combined date and time representations below)." The use of 24:00 is very comfortable when using hourly datasets, the first set of a day is saved under 1:00, the fifth (4:00 to 5:00) under 5:00 and the last (23:00 - 24:00) under 24:00. No need to suddenly use 23:59:59 or 0:00 the next day. Actually in another part of Python SQLlite's date and time functions accept and output the 24:00. Adding some Python to an existing database made me aware of the problem. Questions, Is there a date time library that accepts the 24:00? mxDateTime doesn't. Is there a way to set the limit 'from the outside' (subclassing???) or a simple way around? How to get this functionality added to Python? i. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Recommend a MVC framework
I've been web programming for 15 years now. 8 of it using python. Lately I have been 'studying' PHP via the CodeIgnitor Framework. Since python remains my first choice, but since I am also impressed with the concept of CodeIgnitor, I would welcome recommendations on a python MVC framework. One restriction: must *not* need an application server, I.E. works thru Apache and is adaptable to a shared server. TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
> I've been web programming for 15 years now. 8 of it using python. > > Lately I have been 'studying' PHP via the CodeIgnitor Framework. > > Since python remains my first choice, but since I am also > impressed with the concept of CodeIgnitor, I would welcome > recommendations on a python MVC framework. Django is the default choice, ie, the most common one. Has lots of good documentation, and because of its popularity, lots of examples floating around on the web. Other ones include Pylons and TurboGears, but I have little to no experience with those. It'll also depend on your needs, but since you don't specify any, I'd suggest to look at Django first: http://www.djangoproject.com/ > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. Django can run be run through mod_wsgi (or mod_python if you really want). And other web servers than Apache will also work. Don't know what you mean with "shared server", but if you mean multiple accounts running their web apps through one Apache server, that can work (provided Apache is correctly configured). Cheers, Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
take a look at web2py. [1] http://www.web2py.com/ On Sun, Nov 14, 2010 at 5:26 PM, Tim Johnson wrote: > I've been web programming for 15 years now. 8 of it using python. > > Lately I have been 'studying' PHP via the CodeIgnitor Framework. > > Since python remains my first choice, but since I am also > impressed with the concept of CodeIgnitor, I would welcome > recommendations on a python MVC framework. > > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. > TIA > -- > Tim > tim at johnsons-web.com or akwebsoft.com > http://www.akwebsoft.com > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Leônidas S. Barbosa (Kirotawa) [DesenvolvedorWeb/CEFET/RN] [Ciências da Computação/UFRN] [pós-graduando em Inteligência Computacional/Processamento Gráfico /UFRN [Estudante de japonês nível Intermediário I - Japanese Student] [Desenvolvedor em python, PyGame] blog nerd: corecode.wordpress.com/ blog music: essenaomanja.blogspot.com blog tirinhas: elminiche.wordpress.com/ "Mais sábio é aquele que sabe que não sabe" (Sócrates) 日本語の学生です。 コンピュータサイエンスの学位. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
"Tim Johnson" wrote Since python remains my first choice, but since I am also impressed with the concept of CodeIgnitor, I would welcome recommendations on a python MVC framework. Don;t know CodeIgnitor but almost every web framework is MVC based from Struts in Jave through Rails on Ruby to almost all the Python stalwarts - Django, TurboGears, Pylons(I think) etc... One restriction: must *not* need an application server, I.E. works thru Apache and is adaptable to a shared server. Not quite sure how you defione your terms there. But all of the above can be used with Apache. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
Additionally to what's already been said, you may also want to have a look at the Pyjamas project (which can work in conjunction with Django as a back-end), there's a short article about implementing an MVC architecture in Pyjamas here: http://pyjs.org/wiki/modelviewcontroller/ Also you may want to have a look at the Python implementation of PureMVC (which as the previous page mentions can be used in conjuntion with Pyjamas as well): http://trac.puremvc.org/PureMVC_Python/ Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] While Loops: Coin Flip Game
Greetings, I'm a Python beginner and working my way through Michael Dawson's Python Programming for the Absolute Beginner. I'm stuck in a particular challenge that asks me to write a program that "flips a coin 100 times and then tells you the number of heads and tails." I've been trying to work on this challenge for a while now and can't get it to work (either it has 100 heads or 100 tails). I've been reworking this code many times and currently what I have does not do anything at all at IDLE. Please take a look at my code below: import random # set the coincoin = random.randrange(2)headsCount = 0tailsCount = 0count = 0 # the loopwhile count <= 100:coinif coin == 0:headsCount += 1 if coin == 1:tailsCount += 1count += 1 print "The number of heads was", headsprint "The number of tails was", tails raw_input("\n\nPress the enter key to exit.") Thanks,S. Dawn Samson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] program hangs in while loop using wx.yield
"Alex Hall" wrote The problem is that I want to go until there is a winner. You are right about just letting the mainloop of the gui handle input (I forgot the gui is already looping and waiting for input) but I would like to make the user pause while the computer goes, this way the user cannot just keep hammering out moves as fast as possible Thats fine so you simple stop accepting input while the computer goes. I'm sure your computer can keep up with aeven the fastest typist/mouse clicker. If you really want to add a delay simply add a short pause in your event handler - 1 second say. Or even better set a semaphore which blocks any input and then a timer to reset it after a given delay. This is all fairly satandard GUI practice none of which requires complex loops. You need to start thinking about a world controlled by the GUI firing events( or messages if you like) telling you what is happening which you catch and process. be given to the user properly. Therefore, I have gotten rid of the loop I sent originally, but I still have a loop which switches between the two players Is it two players or is it a player and a computer. If its the former you need a semaphore to block input from one player until the other has gone. In chess terms the values might be black and white and the semaphore called player. You then either need two input handlers, one for black and one for white which call a common utility fuction after checking the semaphor or a single function that somehow can identify the player. If its the latter then the computer should be faster than a hiuman so there should be little problem... the other. If I fire (it is Battleship) and hit your ship,and I am the computer, then this loop will give you the information about where I fired. You will check to see if it was a hit and, since it was, pass back information about what was hit. You will also update the gui to reflect the new status of the damaged ship. I'm confusing you and I, its safer to use explicit trerms when describing interactions. But the displaing of information and updating the GUI can all happen in a blink of an eye if its the computer playing. this, I do not want you firing as fast as possible, and I want you to take in the results before you are allowed to fire. Why do you care if the human "takes in the results" - if they want to trust in randomness surely thats their problem. You as a computer can match them blast for blast... while not player1.isWinner or not player2.isWinner: if player1.grid.turnOver: print("player2 is going") player1.grid.speak("player 2 is going.") player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did player1.lock() #so p1 cannot interact with the gui player2.takeTurn() #decides what to do and updates its Grid object accordingly player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just output what p2 did after takeTurn() is over elif player2.grid.turnOver: print("player1 is going") player1.enemyMove=player2.grid.cmd player1.unlock() #p1 can now interact with the gui player1.grid.speak("It is now your turn.") player1.takeTurn() #end if #wx.Yield() time.sleep(.1) #end while Still looks way too complicated to me! I am honestly not sure how all the control flows, but this loop is gone so hopefully it will not be a problem. You need to think about the control flow vfery carefully - after all you the programmer are supposed to be in charge of your program! And if you ever have to debug it you will need to understand where the control is going next! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
* Alan Gauld [101114 13:12]: > Not quite sure how you defione your terms there. > But all of the above can be used with Apache. Hi Alan. See my reply to Evert where I refer to situations where I would have neither SSH nor root access. thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
* Evert Rol [101114 12:12]: > Django can run be run through mod_wsgi (or mod_python if you > really want). And other web servers than Apache will also work. > Don't know what you mean with "shared server", but if you mean > multiple accounts running their web apps through one Apache > server, that can work (provided Apache is correctly configured). By "shared server", I mean a hosting situation where I would not be able to configure Apache. An example would be my own ISP's servers, which I avoid doing development work on *but* I just might have to. > It'll also depend on your needs, but since you don't specify any, > I'd suggest to look at Django first: http://www.djangoproject.com/ Actually, :) I *have* looked at django and I've considered it to have the greatest appeal. In fact, for most of my deployment environments I have SSH and root access. Django would be my first choice in that case, however, I would like to consider other cases as well, thus my question regarding "shared server". From http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ref=sr_1_2?s=books&ie=UTF8&qid=1289772638&sr=1-2 Can you comment on the following exerpt of the third review, where the reviewer says: """ one on deployment makes little mention of the fact that there's not really any good way to get Django running smoothly without root access to the server--something a lot of people do not have--and they actually expect their users to run TWO servers--one for Django and one for everything else, like image files. """ Thank you for the response. -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] What was your strategy?
Hello all. Quick question. I know some of you are with Python since started, some other maybe later. I was wondering if you can share what was the strategy you followed to master Python (Yes I know I have to work hard study and practice a lot). I mean did you use special books, special sites, a plan to learn each subject in a special way. I would like to know, if possible, comments specially from some of you who in the past had other languages, frameworks and platforms and left (almost) all of them and stayed with Python. Thanks in advance Jorge Biquez ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
>> Django can run be run through mod_wsgi (or mod_python if you >> really want). And other web servers than Apache will also work. > >> Don't know what you mean with "shared server", but if you mean >> multiple accounts running their web apps through one Apache >> server, that can work (provided Apache is correctly configured). > By "shared server", I mean a hosting situation where I would not > be able to configure Apache. An example would be my own ISP's > servers, which I avoid doing development work on *but* I just > might have to. That will all depend on how the webserver is configured by the provider. Some will have a good setup, with mod_wsgi or mod_python already available, and allow lots of options configurable in .htaccess. Because of the popularity of PHP (some time ago, that was), a lot of webservers have mod_php configured by default for this. But there really is not difference (imho) between a webserver with mod_php or mod_wsgi. Trick is to tell a hosting provider that, or find one that allows that. fastcgi is one of the options for "alternative" Django deployments: http://docs.djangoproject.com/en/1.2/howto/deployment/fastcgi/ But I'd suggest to read through the various sections of http://docs.djangoproject.com/en/1.2/howto/deployment/ first. Or google around if you know what situation you're in: lots of examples out there for setups with limited (root) access. > From > > http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ref=sr_1_2?s=books&ie=UTF8&qid=1289772638&sr=1-2 > Can you comment on the following exerpt of the third review, where > the reviewer says: > """ > > one on deployment makes little mention of the fact that there's > not really any good way to get Django running smoothly without > root access to the server--something a lot of people do not > have--and they actually expect their users to run TWO > servers--one for Django and one for everything else, like image > files. See above, and the Django folks only (strongly) suggest, not expect, to have two separate servers for Django & static stuff, but that's only for more heavily accessed websites. I'm running a website through fastcgi & using the same Apache to route both fastcgi and the static files (note that the static files don't go through Django/fastcgi though). Took a bit of figuring out how to set it up, but it now works excellent. See also the first comment on this comment ;-). Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game
On Sun, Nov 14, 2010 at 11:16 PM, Dawn Samson wrote: > Greetings, > I'm a Python beginner and working my way through Michael Dawson's Python > Programming for the Absolute Beginner. I'm stuck in a particular challenge > that asks me to write a program that "flips a coin 100 times and then tells > you the number of heads and tails." I've been trying to work on this > challenge for a while now and can't get it to work (either it has 100 heads > or 100 tails). I've been reworking this code many times and currently what I > have does not do anything at all at IDLE. Please take a look at my code > below: When you, as you say it, "set the coin," you call the randrange function. This picks a random number between 0 and 1 and returns it. You then assign that number to the coin variable. So at this point, coin contains either 0 or 1. In the while loop, you have a line that simply says "coin." You probably think that this calls the function again, but it doesn't. What it actually does is nothing. You simply mention the variable to the interpreter, which retrieves its value (0 or 1). Since you don't do anything with that value, it is simply immediately discarded again. You need to change your code so that the coin isn't set only once, but every iteration of the loop. Hope that helps Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommend a MVC framework
* Tim Johnson [101114 11:45]: > > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. > thanks for all of who responded. I should clarify: I have been considering django as a first choice for most of the deployment environments I have access to, *but* am also looking for something as a fall-back that can be installed without SSH or root access. Looks like web2py may be the fall-back. thanks again. -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python at midnight
ingo wrote: [...] Questions, Is there a date time library that accepts the 24:00? mxDateTime doesn't. I don't know of any. Is there a way to set the limit 'from the outside' (subclassing???) or a simple way around? Write a wrapper function: #Untested def datetime24(*args): try: return datetime.datetime(*args) except ValueError: args = list(args) if len(args) >= 4 and args[3] == 24: if ((not args[4:5] or args[4] == 0) and (not args[5:6] or args[5] == 0)): args[3] = 0 yesterday = datetime.datetime(*args) return yesterday + datetime.timedelta(1, 0, 0) raise This catches the error raised by the datetime object. If the hour is 24 and the minute and second arguments either don't exist, or are 0, it calculates the datetime from 0:00 instead of 24:00, then adds one day to it. Otherwise it re-raises the error. How to get this functionality added to Python? Make a feature request on the Python bug tracker: http://bugs.python.org/ -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game
Dawn Samson wrote: I've been trying to work on this challenge for a while now and can't get it to work (either it has 100 heads or 100 tails). Unfortunately your code has been mangled in the email, but I can guess your problem: you need to set coin = random.randrange(2) each time through the loop, not just once outside the loop. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game
Thanks everyone! I should be using algorithms for even such programs at my level. The solution to reiterate the coin flip every time in the loop works. Thanks a lot! Dawn ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game
On 14/11/10 22:16, Dawn Samson wrote: Greetings, I'm a Python beginner and working my way through Michael Dawson's Python Programming for the Absolute Beginner. I'm stuck in a particular challenge that asks me to write a program that "flips a coin 100 times and then tells you the number of heads and tails." I've been trying to work on this challenge for a while now and can't get it to work (either it has 100 heads or 100 tails). I've been reworking this code many times and currently what I have does not do anything at all at IDLE. Please take a look at my code below: import random # set the coin coin = random.randrange(2) headsCount = 0 tailsCount = 0 count = 0 # the loop while count <= 100: coin if coin == 0: headsCount += 1 if coin == 1: tailsCount += 1 count += 1 print "The number of heads was", heads print "The number of tails was", tails raw_input("\n\nPress the enter key to exit.") Thanks, S. Dawn Samson You try to print two variables, "heads" and "tails" which don't exist. The other replies covered the other main problems. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What was your strategy?
Jorge Biquez wrote: I was wondering if you can share what was the strategy you followed to master Python (Yes I know I have to work hard study and practice a lot). I started by working through the book "Learning Python" by Mark Lutz and David Ascher. I wrote lots and lots of little Python scripts and classes and functions, to get a feel for the language. I must have started a million different projects, and abandoned most of them due to time and distractions. I spent a *lot* of time on Usenet, comp.lang.python (also available on the pyt...@python.org mailing list, I believe) reading people's questions and answering them, and generally having an opinion on nearly everything :) Any time somebody would ask a question that I thought I *could* handle, but didn't already know the answer, I would call up the interactive interpreter and try to solve the problem. I learned to *never* post code unless I'd run it myself, unless I clearly labeled it as untested or pseudo-code. Be prepared to get told You're Doing It Wrong a lot. This is a *good* thing -- you learn by making mistakes and being corrected. I read a LOT of idiomatic Python code by the masters: people like the timbot, the effbot, Raymond Hettinger, and many, many others. I read the Python Cookbook and studied their code. If they answered a question, I tried to understand how their answer was better than mine. Usually I learned something. Sometimes I thought I knew better. Most of the time that I thought I knew better, I learned that I didn't, and the rest of the time it was just a matter of personal taste. I spent a lot of time (and still do) looking up unfamiliar terms on Google. Wikipedia is your best friend. The Python Cookbook at ActiveState Python is your second best friend. The c2c wiki is *not* your friend, but you'll learn a lot from reading it. Since 90% of the discussions there are about Java, C or Lisp, what you'll mostly learn is how happy you are to be using Python instead. But the other 10% of the time will really stretch your brain. http://c2.com/cgi/wiki?WelcomeVisitors -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game
From: tutor-bounces+bermanrl=cfl.rr@python.org [mailto:tutor-bounces+bermanrl=cfl.rr@python.org] On Behalf Of Dawn Samson Sent: Sunday, November 14, 2010 5:17 PM To: tutor@python.org Subject: [Tutor] While Loops: Coin Flip Game Greetings, I'm a Python beginner and working my way through Michael Dawson's Python Programming for the Absolute Beginner import random # set the coin coin = random.randrange(2) headsCount = 0 tailsCount = 0 count = 0 # the loop while count <= 100: coin if coin == 0: headsCount += 1 if coin == 1: tailsCount += 1 count += 1 print "The number of heads was", heads print "The number of tails was", tails raw_input("\n\nPress the enter key to exit.") Thanks, S. Dawn Samson > Hi, Think in terms of logical steps. You need to generate the results of a random coin toss for every toss of the coin. Therefore, if you are tossing 100 tosses, you need to generate 100 results based on a probability of zero or one. Since this is your homework assignment you write the code, but in terms of a logical frame work you would have something like the following. Tossknt = 1 Generate a random toss ; results being either one or 0. Further , assume 0 is tail; heads is one. If toss = 1 headcount = headcount + 1 Else tailcount = tailcount + 1 Tossknt = Tossknt + 1 If Tossknt < 100 Continue loop Else print nbr of heads tossed = , headcount Print nbr of tails tossed = , tailcount Obviously, this is not valid python code but it should give you enough information to solve your problem. Good luck, Robert -- I am using the free version of SPAMfighter. We are a community of 7 million users fighting spam. SPAMfighter has removed 53 of my spam emails to date. Get the free SPAMfighter here: http://www.spamfighter.com/len The Professional version does not have this message ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] program hangs in while loop using wx.yield
On 11/14/10, Alan Gauld wrote: > "Alex Hall" wrote > >> The problem is that I want to go until there is a winner. You are >> right about just letting the mainloop of the gui handle input (I >> forgot the gui is already looping and waiting for input) but I would >> like to make the user pause while the computer goes, this way the >> user >> cannot just keep hammering out moves as fast as possible > > Thats fine so you simple stop accepting input while the computer goes. > I'm sure your computer can keep up with aeven the fastest typist/mouse > clicker. If you really want to add a delay simply add a short pause in > your event handler - 1 second say. Or even better set a semaphore > which blocks any input and then a timer to reset it after a given > delay. > > This is all fairly satandard GUI practice none of which requires > complex > loops. You need to start thinking about a world controlled by the GUI > firing events( or messages if you like) telling you what is happening > which you catch and process. Is there a basic tutorial for this sort of thing? I think part of the problem is that both players have a Grid object. The human's grid includes a gui. For example, clicking a square will fire on that square. The computer has a grid as well, but (of course) with no gui element; its grid is simply an array holding its ships. All this to say that when the human fires, something happens to the gui but there is a lot of other updating going on behind the gui, in the human's grid object. When the computer "fires", its grid is updated as well, but not any gui, so message passing by the gui would not seem to apply. > >> be given to the user properly. Therefore, I have gotten rid of the >> loop I sent originally, but I still have a loop which switches >> between >> the two players > > Is it two players or is it a player and a computer. A human and a computer for now. I hope to one day add peer-to-peer support for two humans to play, but that was not working out at all so for now I am just trying to give myself some, even if it is digital, to play against. > If its the former you need a semaphore to block input from one > player until the other has gone. In chess terms the values might > be black and white and the semaphore called player. You then > either need two input handlers, one for black and one for white > which call a common utility fuction after checking the semaphor > or a single function that somehow can identify the player. > > If its the latter then the computer should be faster than a hiuman > so there should be little problem... Little problem for the computer, since its decision will be made in a fraction of a second. However, I need to wait for as long as the human takes to make a turn-ending move. Firing ends a turn, while moving the mouse or arrows does not. The computer does not have this problem, but I still need to know when the computer is done. > >> the other. If I fire (it is Battleship) and hit your ship,and I am >> the >> computer, then this loop will give you the information about where I >> fired. You will check to see if it was a hit and, since it was, pass >> back information about what was hit. You will also update the gui to >> reflect the new status of the damaged ship. > > I'm confusing you and I, its safer to use explicit trerms when > describing > interactions. But the displaing of information and updating the GUI > can > all happen in a blink of an eye if its the computer playing. You are right, that was confusing. What I am saying is that, each time a player goes (human or ai) a string gets updated. The opponent can then examine that string to see what happened, updating the gui (in the case of the human) accordingly and recording the information for consideration in future moves (in the case of the ai). > >> this, I do not want you firing as fast as possible, and I want you >> to >> take in the results before you are allowed to fire. > > Why do you care if the human "takes in the results" - if they want > to trust in randomness surely thats their problem. You as a computer > can match them blast for blast... Part of it is that I hope to eventually add sound, and the other part is that I have always found games that make a move instantly to be a bit too far from what I am used to. If it is easy to build in a delay, I would rather have it there. > >> while not player1.isWinner or not player2.isWinner: >> if player1.grid.turnOver: >> print("player2 is going") >> player1.grid.speak("player 2 is going.") >> player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did >> player1.lock() #so p1 cannot interact with the gui >> player2.takeTurn() #decides what to do and updates its Grid object >> accordingly >> player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just >> output what p2 did after takeTurn() is over >> elif player2.grid.turnOver: >> print("player1 is going") >> player1.enemyMove=player2.grid.cmd >> player1.unlock() #p1 can now interact with the
Re: [Tutor] What was your strategy?
"Jorge Biquez" wrote I was wondering if you can share what was the strategy you followed to master Python I started with Python 1.3 around early 1998 but switched to 1.5 very soon after. I started with the standard tutorial (I was already a pro programmer so it was easy to follow) then implemented some of my Perl and awk tools in Python for comparison's sake and just to gain some experience. I then bought a book by Guido which was adequate but not really well related to the programming things I do. I also bought the original Programming Python O'Reilly book and found it more helpful. Then around that time I was invited to review Grayson's Tkinter book - I'm not sure why, because I was still a Python newbie and only average on Tcl/Tk... I found Grayson's book more advanced than the stuff I'd been doing and it pushed me to explore new areas. I still refer to it regularly. Then I decided to write a tutorial on learning to program and chose Python as the preferred language. I also discovered the tutor list about the same time. The rest is history... or at least the list archive :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game :p:
On Sun, 14 Nov 2010 17:16:36 -0500 Dawn Samson wrote: > Greetings, > > I'm a Python beginner and working my way through Michael Dawson's > Python Programming for the Absolute Beginner. I'm stuck in a > particular challenge that asks me to write a program that "flips a > coin 100 times and then tells you the number of heads and tails." > I've been trying to work on this challenge for a while now and can't > get it to work (either it has 100 heads or 100 tails). I've been > reworking this code many times and currently what I have does not do > anything at all at IDLE. Please take a look at my code below: > > import random > > # set the coin > coin = random.randrange(2) > headsCount = 0 > tailsCount = 0 > count = 0 > > # the loop > while count <= 100: > coin > if coin == 0: > headsCount += 1 > if coin == 1: > tailsCount += 1 > count += 1 > > > print "The number of heads was", heads > print "The number of tails was", tails > > raw_input("\n\nPress the enter key to exit.") > > Thanks, > S. Dawn Samson >From one beginner to another - it looks to me like you set the value of coin once then checked it 100 times. If you want to reset the value of coin maybe it (i.e. setting the value of coin, not just calling the value of coin) should be in the loop too? tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] program hangs in while loop using wx.yield
On 15 November 2010 00:12, Alex Hall wrote: > Again: is there a basic tutorial that would explain how control works > when dealing with a gui, especially one that is meant to last a long > time but occasionally block input? > Normally the way is for the GUI controls (e.g. widgets, grids, objects whatever you want to call them) to ignore messages (e.g. clicks or keyboard input or whatever). To achieve this one can either use properties/methods/behaviours already available on the widgets being used (e.g. Buttons have an "Enabled" property that allows you to control whether they're clickable or not), or you have to implementsuch behaviour yourself, using some flag/state variables in your application. As a tiny example, see here: http://pastebin.com/LqJkwpwA As you can see, each time one of the buttons are clicked, the click handler alters the buttons' enabled properties which ensures that only the other one will be clickable next. This example obviously sidestepped tracking "who's turn it is" explicitly by directly flipping the Enabled state on the 2 buttons. In your app I would suppose it'd be better to be explicit about it and have variables to store this type of information, which can then refer to in order to decide what to do inside your event handlers. HTH, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Programs for Newbies?
> Any suggestions for a newbie to program while learning python? I am new to > programming and python. Port one of the old games from http://www.atariarchives.org/basicgames/ or similar antique books. Alan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python at midnight
On Sun, Nov 14, 2010 at 11:48 PM, Steven D'Aprano wrote: > > Write a wrapper function: > Thanks Steve, with this in hand I think I can solve the main problems for now i. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor