Re: Python Makefiles... are they possible?
>> One thing we do in our Makefiles is "find . -name '*.pyc' | xargs rm". >> It avoids all sorts of nasty and hard to track down bugs (consider what >> happens if you move a .py file from one place in your source tree to >> another and leave the old .pyc behind). > > How often do you move files around in the source tree? Meanwhile, *every* > time you run make, you take a performance hit on every Python module in > your project, whether it has moved or not. > > Seems to me like a fairly heavy-handed response for something quite rare, > but I suppose that depends on how often you run make. If the performance hit doesn't really matter. Then simply walk the build tree, compare time date stamps, anything that doesn't match up in the make directory, gets deleted. Anything that has different Date Created / Date Modified time from the build tree match, get's deleted. This way, we are preserving any files that should be identical. But there should be some mechanism documented to forcibly clear the build cache. - Benjamin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Makefiles... are they possible?
On 02/13/2013 12:54 AM, Steven D'Aprano wrote: On Tue, 12 Feb 2013 20:06:35 -0500, Roy Smith wrote: One thing we do in our Makefiles is "find . -name '*.pyc' | xargs rm". It avoids all sorts of nasty and hard to track down bugs (consider what happens if you move a .py file from one place in your source tree to another and leave the old .pyc behind). How often do you move files around in the source tree? Meanwhile, *every* time you run make, you take a performance hit on every Python module in your project, whether it has moved or not. Seems to me like a fairly heavy-handed response for something quite rare, but I suppose that depends on how often you run make. That's why I assumed that his command was triggered by the "make clean" command. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Makefiles... are they possible?
In article <511b2a7c$0$11096$c3e8...@news.astraweb.com>, Steven D'Aprano wrote: > On Tue, 12 Feb 2013 20:06:35 -0500, Roy Smith wrote: > > > One thing we do in our Makefiles is "find . -name '*.pyc' | xargs rm". > > It avoids all sorts of nasty and hard to track down bugs (consider what > > happens if you move a .py file from one place in your source tree to > > another and leave the old .pyc behind). > > > How often do you move files around in the source tree? It has happened enough times to make us look for a solution. Which means "more than once". > Meanwhile, *every* time you run make, you take a performance hit on > every Python module in your project, whether it has moved or not. The performance hit is minimal. The hours of tearing out your hair trying to figure out why bizarre things are happening is not. Another solution would be if there was a flag you could give to Python to tell it, "Only import a .pyc if the corresponding .py file exists". It's already checking to see if the .py is newer, so this wouldn't even cost anything. -- http://mail.python.org/mailman/listinfo/python-list
Re: Monitoring updating directory for image for GUI
ciscorucin...@gmail.com writes: > WOW...I am thinking that all of this was actually unnecessary, I don't think > I need a Queue, or List / Stack, or any traversal of the file system to > accomplish this!! > > I only need one image displayed at a time and don't care about them > after a newer image is generated. So my prototype of just replacing > the image over and over again SHOULD suffice. All I need the for the > "monitor" now is to grab the image file (that might have or might not > have been updated by Lilypond) at set amount of times and refresh the > GtkImage object. > > The only reason why I originally suggested using multiple files was > because I wanted to make sure that I had to most recent image and I > was not sure if the threads would guarantee that. So my only remaining > question (for now) is... > > I'm I guaranteed that if I have threads 1...n, that were all started > in **quick** succession to call an OS command on Lilypond, that if I > replaced the image file being generated with the completion of each > thread that I would end up with the final image being from thread > n...and that if I were able to update the GUI in a fast enough > fashion, that I would see the images being displayed on the screen > from 1 to n without anything being out of place? No, I don't think so. You have no guarantee that the images will be completed in the same order as the threads are started. > All of my tests have shown that seems to be a reasonable assumption, > but I need to know for sure. If that was the case were I am not > guaranteed that, then when a user decides to stop the stream I could > resend the note stream that I have saved on my end to Lilypond one > last time to guarantee that all of the notes are displayed. > > > So I would only create one image location at "images\sheetMusic.png" > and that file would be continuously updated as new notes are streamed > in. My "monitor" class (might be a legacy component now) would > basically look for that one image - "images\sheetMusic.png", grab it, > and update the GUI at an interval that is easy on the eyes (maybe a > half second for example). > It could very well be that the image is being constructed and therefore does not yet contain a complete image when you want to display it. > Could there be a problem where the image is being updated, so the OS > deletes the image, and my program tries to update the image but cannot > find it, and the OS reassigns that file location to that previous file > location and name? Maybe it can find it, but it might not be a valid image > > Let me know what you thing or if anything is confusing you. > Thanks for the comments so far! I think the way I described it in my previous message still gives you the easiest solution: I'll repeat it here in case you missed it. I suppose you have two threads, one for producing the music by calling Lilypond, and one for displaying the generated images. Because it is multithreaded you should use a Queue from the module Queue(Python2)/queue(Python3) to communicate between the threads. Producing thread: send note to Lilypond wait until PNG file is generated (Lilypond completed) Q.put(filename) Displaying thread: while True: fn = Q.get() # this will block until a filename is available # now check if there is more in the queue while True: try: fn = Q.get_nowait # here we got a newer one except Empty: break # stop the inner loop display the image in fn. In this way you always display the most recent one. You can make it more sophisticated by removing files that have been displayed and files that you skip. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] -- http://mail.python.org/mailman/listinfo/python-list
Re: Awsome Python - chained exceptions
On Wednesday, February 13, 2013 12:58:46 AM UTC-6, Chris Angelico wrote: > On Wed, Feb 13, 2013 at 1:47 PM, Rick Johnson wrote: > >On Tuesday, February 12, 2013 12:15:29 AM UTC-6, Steven D'Aprano wrote: > >> If you've ever written an exception handler, you've probably written a > >> *buggy* exception handler: > >> > >> def getitem(items, index): > >> # One-based indexing. > >> try: > >> return items[index-1] > >> except IndexError: > >> print ("Item at index %d is missing" % index - 1) # Oops! > >> > >> > >> Unfortunately, when an exception occurs inside an except or finally > >> block, the second exception masks the first, and the reason for the > >> original exception is lost: > >> > >> py> getitem(['one', 'two', 'three'], 5) # Python 2.6 > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "", line 6, in getitem > >> TypeError: unsupported operand type(s) for -: 'str' and 'int' > > > > Which (by showing the offensive line) is quite clear to me. > > No, the offending (not offensive) line is "return items[index-1]", > which doesn't feature in your traceback at all. Do you realize that you are quoting DeAprano and not me? Whether you realize this fact or not, consider the next two questions. Q1: How could a line in the "try" block ever be considered offensive? Because it throws an error? Are you serious? Q2: Why would the line in the try block be shown as a "feature" of the traceback when the whole intent of exception handling is to hide the error in the try block! If you want to raise the exception in the try block then you place a naked raise statement in the exception block, BUT THEN, why even wrap the code in a try/except in the first damn place!? Man, you and DeAprano must be cut from the same block; or more correctly, carved by the same shaky hand of a creator suffering the late-stage effects of Alzheimers disease. > It DOES, however, > feature in the Py3.1 double traceback (it's listed as line 4).. > > > 1. You are using the print function (so we can assume you are using Python > > 3.x) > > He is? Could just as easily be the print statement with a single > argument, with unnecessary parentheses around that argument. Which, if > I recall correctly, is one of the recommended approaches for making > 2/3 bi-compatible code. Really? Because if he did in-fact write the print statement using parenthesis (in some foolish attempt to make his code forward-compatible) that would mean i should add /another/ coding abomination to my earlier list of abominations. The proper method of using a forward compatible print function is by /importing/ the feature. from future import print_function > No. Definitely not. Percent interpolation isn't going anywhere - core > devs have said so - and there are many occasions when it is at least > as well suited to the task as .format() is. In other words: Screw consistency and to hell with the zen? > Also, it's a notation > that's well understood *across languages* and in a variety of message > interpolation systems. Anyone who's worked with *any* of them will > understand that %s inserts a string, %d a number (in decimal), etc, Oh yes, because indexing the list of arguments in the format method is SO much more overhead! Heck, Python>=2.7 (read the docs for exact release number) will allow you to implicitly pass the index: print "{} is one more than {}".format("five", "four") # 3.something ...is equivalent to: print "{0} is one more than {1}".format("five", "four") ...but what about when you need to substitute the /same/ substring in more than one location? Using the old nasty interpolation you are foced to write this: print "Chris is a %s who is very %s-ish"%('troll', 'troll') ...e yuck! String.format() to the rescue! print "Chris is a {0} who is very {0}-ish".format('troll') In fact all of these posted examples work in Python>=2.7. So the moral is: You can pass no indexes and the format method will intuit the indexes from their linear position in the string, or you can pass indexes and be explicit (plus you can reference a value more than once!), or you can choose one of the many other great options available of the format method. http://docs.python.org/2/library/string.html#format-string-syntax > etc. Granted, the exact details after that may change (eg Python has > %r to emit the representation, while Pike uses %O for "any object", > with similar notation), but the format specifiers and modifiers that > came from C are fairly stable, readable, and compact. The fact is that "str.format(args)" beats the pants off string interpolation any day and anybody arguing for keeping string interpolation is not thinking clearly (especially when they first claim consistency between languages and them expose that claim as a lie) and is also anti-pythonic! To continue to propagate foolish language designs simply because other peopl
Re: Awsome Python - chained exceptions
On Wednesday, February 13, 2013 10:14:34 AM UTC-6, Rick Johnson wrote: > The proper method of using a forward compatible print > function is by /importing/ the feature. > >from future import print_function Urm... of course the proper /PROPER/ way would be to NOT throw an import error! from __future__ import print_function O:-) -- http://mail.python.org/mailman/listinfo/python-list
Re: string.replace doesn't removes ":"
On Wednesday, February 13, 2013 1:10:14 AM UTC-6, jmfauth wrote: > > >>> d = {ord('a'): 'A', ord('b'): '2', ord('c'): 'C'} > >>> 'abcdefgabc'.translate(d) > 'A2CdefgA2C' > >>> > >>> > >>> def jmTranslate(s, table): > ... table = {ord(k):table[k] for k in table} > ... return s.translate(table) > ... > >>> d = {'a': 'A', 'b': '2', 'c': 'C'} > >>> jmTranslate('abcdefgabc', d) > 'A2CdefgA2C' > >>> d = {'a': None, 'b': None, 'c': None} > >>> jmTranslate('abcdefgabc', d) > 'defg' > >>> d = {'a': '€', 'b': '', 'c': ''} > >>> jmTranslate('abcdefgabc', d) > '€defg€' [quip] I just really prefer a cryptic solution to a problem when a simplistic and consistent approach would suffice.[/quip] TO HELL WITH THE ZEN! "Beautiful is better than ugly." BROKEN! "Explicit is better than implicit." BROKEN! "Simple is better than complex." BROKEN! "Sparse is better than dense." BROKEN! "Readability counts." BROKEN BROKEN BROKEN "Special cases aren't special enough to break the rules." BROKEN! "In the face of ambiguity, refuse the temptation to guess." BROKEN! "There should be one-- and preferably only one --obvious way to do it." BROKEN BROKEN BROKEN! "If the implementation is hard to explain, it's a bad idea." BROKEN! "If the implementation is easy to explain, it may be a good idea." REINFORCED BY BAD EXAMPLE -- http://mail.python.org/mailman/listinfo/python-list
Re: string.replace doesn't removes ":"
On 13/02/2013 16:34, Rick Johnson wrote: On Wednesday, February 13, 2013 1:10:14 AM UTC-6, jmfauth wrote: d = {ord('a'): 'A', ord('b'): '2', ord('c'): 'C'} 'abcdefgabc'.translate(d) 'A2CdefgA2C' def jmTranslate(s, table): ... table = {ord(k):table[k] for k in table} ... return s.translate(table) ... d = {'a': 'A', 'b': '2', 'c': 'C'} jmTranslate('abcdefgabc', d) 'A2CdefgA2C' d = {'a': None, 'b': None, 'c': None} jmTranslate('abcdefgabc', d) 'defg' d = {'a': '€', 'b': '', 'c': ''} jmTranslate('abcdefgabc', d) '€defg€' [quip] I just really prefer a cryptic solution to a problem when a simplistic and consistent approach would suffice.[/quip] TO HELL WITH THE ZEN! "Beautiful is better than ugly." BROKEN! "Explicit is better than implicit." BROKEN! "Simple is better than complex." BROKEN! "Sparse is better than dense." BROKEN! "Readability counts." BROKEN BROKEN BROKEN "Special cases aren't special enough to break the rules." BROKEN! "In the face of ambiguity, refuse the temptation to guess." BROKEN! "There should be one-- and preferably only one --obvious way to do it." BROKEN BROKEN BROKEN! "If the implementation is hard to explain, it's a bad idea." BROKEN! "If the implementation is easy to explain, it may be a good idea." REINFORCED BY BAD EXAMPLE jmf and rr in combination reminded me of this. I hope you all get my drift :) http://www.cc.gatech.edu/fac/Spencer.Rugaber/poems/love.txt -- Cheers. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: string.replace doesn't removes ":"
On Wed, 13 Feb 2013 16:55:36 +, Mark Lawrence wrote: > On 13/02/2013 16:34, Rick Johnson wrote: >> On Wednesday, February 13, 2013 1:10:14 AM UTC-6, jmfauth wrote: >>> >> d = {ord('a'): 'A', ord('b'): '2', ord('c'): 'C'} >> 'abcdefgabc'.translate(d) >>> 'A2CdefgA2C' >> >> >> def jmTranslate(s, table): >>> ... table = {ord(k):table[k] for k in table} >>> ... return s.translate(table) >>> ... >> d = {'a': 'A', 'b': '2', 'c': 'C'} >> jmTranslate('abcdefgabc', d) >>> 'A2CdefgA2C' >> d = {'a': None, 'b': None, 'c': None} >> jmTranslate('abcdefgabc', d) >>> 'defg' >> d = {'a': '€', 'b': '', 'c': ''} >> jmTranslate('abcdefgabc', d) >>> '€defg€' >> >> [quip] I just really prefer a cryptic solution to a problem when a >> simplistic and consistent approach would suffice.[/quip] TO HELL WITH >> THE ZEN! >> >> "Beautiful is better than ugly." >>BROKEN! >> >> "Explicit is better than implicit." >>BROKEN! >> >> "Simple is better than complex." >>BROKEN! >> >> "Sparse is better than dense." >>BROKEN! >> >> "Readability counts." >>BROKEN BROKEN BROKEN >> >> "Special cases aren't special enough to break the rules." >>BROKEN! >> >> "In the face of ambiguity, refuse the temptation to guess." >>BROKEN! >> >> "There should be one-- and preferably only one --obvious way to do it." >>BROKEN BROKEN BROKEN! >> >> "If the implementation is hard to explain, it's a bad idea." >>BROKEN! >> >> "If the implementation is easy to explain, it may be a good idea." >>REINFORCED BY BAD EXAMPLE >> >> > jmf and rr in combination reminded me of this. I hope you all get my > drift :) > > http://www.cc.gatech.edu/fac/Spencer.Rugaber/poems/love.txt 10-4, good buddy. -- http://mail.python.org/mailman/listinfo/python-list
Suggested feature: slice syntax within tuples (or even more generally)?
Hello, Would it be feasible to modify the Python grammar to allow ':' to generate slice objects everywhere rather than just indexers and top-level tuples of indexers? Right now in Py2.7, Py3.3: "obj[:,2]" yields "obj[slice(None),2]" but "obj[(:,1),2]" is an error, instead of "obj[(slice(None), 1), 2]" Also, more generally, you could imagine this working in (almost?) any expression without ambiguity: "a = (1:2)" could yield "a = slice(1,2)" See motivating discussion for this at: https://github.com/pydata/pandas/issues/2866 There might not be very many use cases for this currently outside of pandas, but apparently the grammar was already modified to allow '...' outside indexers and there's probably even fewer valid use cases for that: "e = ..." yields "e = Ellipsis" Would there be any downside to changing the handling of ':' as well? It might even make the grammar simpler, in some ways, since indexers won't have to be treated specially. Let me know if you have any thoughts. Thanks! Stephen -- http://mail.python.org/mailman/listinfo/python-list
Simulate Keyboard keypress Delay
I am using the windows api feature getasynckeystate() to check the status of every key pressed; like this; #always checking while(True): #iterate through list of ascii codes for num in range(0,127): #if ascii code key is being pressed if win32api.GetAsyncKeyState(num): #do stuff This works great, almost. The issue that comes up now is that every time i press a key, the code grabs two or three key presses. So i tried making sure that repeated keys weren't pressed repeatedly; #always checking while(True): #iterate through list of ascii codes for num in range(0,127): #if ascii code key is being pressed if win32api.GetAsyncKeyState(num): if oldkeychar == num: #don't do stuff else: #do stuff this works great, but It won't record stuff like 'look' or 'suffer' because it doesn't record repeated keys. So I try doing a delay instead; #always checking while(True): #iterate through list of ascii codes for num in range(0,127): #if ascii code key is being pressed if win32api.GetAsyncKeyState(num): if oldkeychar == num: if crrenttime > (time.time() - .5) #do stuff because key has been repeated, but not because it was held down else: #don't do stuff because key is pressed to soon else: #do stuff because key is not repeated currenttime = time.time() this almost works, but I end recording some double keypresses, and missing others. Does anybody have any suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Help understanding import error
I'm using TortoiseHg on Windows, which is implemented in python and includes python (2.7.3) as dlls and a bunch of python modules bunded into a library.zip file. I'm trying to use an extension whose __init__.py does the following import: from distutils.version import LooseVersion and am getting the error message "*** failed to import extension reviewboard from C:\Program Files\TortoiseHg\reviewboard: No module named version" The thing I don't get is that the library.zip file contains distutils\version.pyo and looking at the text in that it does contain LooseVersion. Also, many other library modules are imported and used without problem, and this extension works fine on my Linux box. Any ideas what could be causing this and how to fix it? thx, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: string.replace doesn't removes ":"
Rick Johnson於 2013年2月14日星期四UTC+8上午12時34分11秒寫道: > On Wednesday, February 13, 2013 1:10:14 AM UTC-6, jmfauth wrote: > > > > > > >>> d = {ord('a'): 'A', ord('b'): '2', ord('c'): 'C'} > > > >>> 'abcdefgabc'.translate(d) > > > 'A2CdefgA2C' > > > >>> > > > >>> > > > >>> def jmTranslate(s, table): > > > ... table = {ord(k):table[k] for k in table} > > > ... return s.translate(table) > > > ... > > > >>> d = {'a': 'A', 'b': '2', 'c': 'C'} > > > >>> jmTranslate('abcdefgabc', d) > > > 'A2CdefgA2C' > > > >>> d = {'a': None, 'b': None, 'c': None} > > > >>> jmTranslate('abcdefgabc', d) > > > 'defg' > > > >>> d = {'a': '€', 'b': '', 'c': ''} > > > >>> jmTranslate('abcdefgabc', d) > > > '€defg€' > In python the variables of value types, and the variables of lists and dictionaries are passed to functions somewhat different. This should be noticed by any serious programmer in python. -- http://mail.python.org/mailman/listinfo/python-list
I made a small reddit console feed with python last night
If you would like to get a copy of it, instructions are here on Github https://github.com/jawerty/AlienFeed -- http://mail.python.org/mailman/listinfo/python-list
Re: Awsome Python - chained exceptions
On Thu, Feb 14, 2013 at 3:14 AM, Rick Johnson wrote: > On Wednesday, February 13, 2013 12:58:46 AM UTC-6, Chris Angelico wrote: >> No, the offending (not offensive) line is "return items[index-1]", >> which doesn't feature in your traceback at all. > > Do you realize that you are quoting DeAprano and not me? Whether you realize > this fact or not, consider the next two questions. I knew who I was quoting. > Q1: How could a line in the "try" block ever be considered > offensive? Because it throws an error? Are you serious? You're the one who said offensive. I specifically corrected you to "offending", which is the appropriate word in that situation. > Q2: Why would the line in the try block be shown as > a "feature" of the traceback when the whole intent of > exception handling is to hide the error in the try > block! If you want to raise the exception in the try block > then you place a naked raise statement in the exception > block, BUT THEN, why even wrap the code in a try/except > in the first damn place!? You seriously need to get into the real world and do some actual debugging work. Here, let me give you an example of what you might come across in the real world: 1) The program doesn't exhibit the failure symptoms until it's been running for a couple of days. 2) Sending the program a SIGHUP influences the symptoms in peculiar ways. 3) The main symptom visible is that something that ought to have 2-3 threads actually has several hundred. 4) Your boss is paranoid about security, so the script files on the running nodes have all been minified - no comments, no linebreaks, short variable names, etc. 5) The exact nature of the bug depends on the interactions of up to 12 computers, all running similar code but doing different tasks. Now tell me, what's the first thing you do? There are many right answers to this question, but most of them involve one thing: Get more information. Turn on verbose logging, add a monitoring wrapper, insert output statements in various places... and make sure your exception tracebacks give ALL the information. > Man, you and DeAprano must be cut from the same block; or more correctly, > carved by the same shaky hand of a creator suffering the late-stage effects > of Alzheimers disease. D'Aprano (note, that's a 39 not a 101) and I both happen to have some real-world experience. A bit of a rough teacher, and the tuition fees are ridiculously high, but you learn things that aren't taught anywhere else. >> He is? Could just as easily be the print statement with a single >> argument, with unnecessary parentheses around that argument. Which, if >> I recall correctly, is one of the recommended approaches for making >> 2/3 bi-compatible code. > > Really? > > Because if he did in-fact write the print statement using parenthesis (in > some foolish attempt to make his code forward-compatible) that would mean i > should add /another/ coding abomination to my earlier list of abominations. > The proper method of using a forward compatible print function is by > /importing/ the feature. > >from future import print_function >>> import __future__ >>> __future__.print_function _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 65536) Which works back as far as 2.6 but that's all. Simply putting parens around the argument works all the way back to... hmm. Further back than I've ever had to support, but then, I only started using Python seriously a few years ago. Steven? >> No. Definitely not. Percent interpolation isn't going anywhere - core >> devs have said so - and there are many occasions when it is at least >> as well suited to the task as .format() is. > > In other words: Screw consistency and to hell with the zen? Percent interpolation is plenty obvious, it's simple, it's clean, and you're welcome to hate it if you like. Doesn't bother me. > ...but what about when you need to substitute the /same/ substring in more > than one location? Using the old nasty interpolation you are foced to write > this: > > print "Chris is a %s who is very %s-ish"%('troll', 'troll') > > ...e yuck! String.format() to the rescue! > > print "Chris is a {0} who is very {0}-ish".format('troll') Yeah, in Pike I'd just use %desc;++row) printf("%-15s%4d%11.2f\n",row->desc,row->count,row->load); //Pike, direct translation foreach (data,array row) write("%-15s%4d%11.2f\n",@row); //Pike, making use of array-output feature write("%{%-15s%4d%11.2f\n%}",data); Note how easily tabulated data can be produced, *across languages*, with the exact same syntax. Actually, str.format borrows heavily from printf notation, and I was able to make it look almost the same; all it does is replace the percent sign with {:}. (Oh, and it defaults to left-justifying strings, so I don't need the minus sign to do that. Big deal.) > (especially when they first claim consistency between languages and them > expose that claim as a lie) I think the comparison above shows
First attempt at a Python prog (Chess)
New to Python, which I really like BTW. First serious prog. Hope you like it. I know it needs a 'can't move if your King would be put into check' test. But the weighted value of the King piece does a surprising emergent job. #!/usr/bin/python -tt # -*- coding: utf-8 -*- # Copyright (C) 2013 Chris Hinsley, GPL V3 License import sys import random import os PLY = 3 EMPTY = 0 BLACK = 1 WHITE = 2 NO_CAPTURE = 3 MAY_CAPTURE = 4 MUST_CAPTURE = 5 def piece_type(piece): return EMPTY if piece == 32 else BLACK if chr(piece) in 'KQRBNP' else WHITE def display_board(board): print ' a b c d e f g h' print '+---+---+---+---+---+---+---+---+' for row in range(8): for col in range(8): sys.stdout.write('| ') sys.stdout.write(chr(board[row * 8 + col])) sys.stdout.write(' ') sys.stdout.write('|') print 8 - row print '+---+---+---+---+---+---+---+---+' def piece_moves(board, index, dx, dy, capture_flag, distance): piece = board[index] type = piece_type(piece) cx = index % 8 cy = index / 8 for step in range(distance): nx = cx + (dx * (step + 1)) ny = cy + (dy * (step + 1)) if nx in range(8) and ny in range(8): newindex = ny * 8 + nx newpiece = board[newindex] newtype = piece_type(newpiece) if capture_flag == MUST_CAPTURE: if newtype != EMPTY and newtype != type: board[index] = ' ' if (ny == 0 or ny == 7) and chr(piece) in 'Pp': for promote in 'QRBN' if type == BLACK else 'qrbn': board[newindex] = promote yield board else: board[newindex] = piece yield board board[index], board[newindex] = piece, newpiece elif capture_flag == MAY_CAPTURE: if newtype == EMPTY or newtype != type: board[index], board[newindex] = ' ', piece yield board board[index], board[newindex] = piece, newpiece break elif newtype == EMPTY: board[index] = ' ' if (ny == 0 or ny == 7) and chr(piece) in 'Pp': for promote in 'QRBN' if type == BLACK else 'qrbn': board[newindex] = promote yield board else: board[newindex] = piece yield board board[index], board[newindex] = piece, newpiece else: break def pawn_moves(board, index, options): for x, y, flag, distance in options: for new_board in piece_moves(board, index, x, y, flag, distance): yield new_board def other_moves(board, index, options, distance): for x, y in options: for new_board in piece_moves(board, index, x, y, MAY_CAPTURE, distance): yield new_board def black_pawn_moves(board, index): distance = 2 if index in range(8, 16) else 1 for new_board in pawn_moves(board, index, [(0, 1, NO_CAPTURE, distance), (-1, 1, MUST_CAPTURE, 1), (1, 1, MUST_CAPTURE, 1)]): yield new_board def white_pawn_moves(board, index): distance = 2 if index in range(48, 56) else 1 for new_board in pawn_moves(board, index, [(0, -1, NO_CAPTURE, distance), (-1, -1, MUST_CAPTURE, 1), (1, -1, MUST_CAPTURE, 1)]): yield new_board def rook_moves(board, index): for new_board in other_moves(board, index, [(0, -1), (-1, 0), (0, 1), (1, 0)], 7): yield new_board def bishop_moves(board, index): for new_board in other_moves(board, index, [(-1, -1), (-1, 1), (1, 1), (1, -1)], 7): yield new_board def knight_moves(board, index): for new_board in other_moves(board, index, [(-2, 1), (2, -1), (2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2)], 1): yield new_board def queen_moves(board, index): for new_board in bishop_moves(board, index): yield new_board for new_board in rook_moves(board, index): yield new_board def king_moves(board, index): for new_board in other_moves(board, index, [(0, -1), (-1, 0), (0, 1), (1, 0), (-1, -1), (-1, 1), (1, 1), (1, -1)], 1): yield new_board moves = {'P' : black_pawn_moves, 'p' : white_pawn_moves, \ 'R' : rook_moves, 'r' : rook_moves, \ 'B' : bishop_moves, 'b' : bishop_moves, \ 'N' : knight_moves, 'n' : knight_moves, \ 'Q' : queen_moves, 'q' : queen_moves, \ 'K' : king_moves, 'k' : king_moves} def all_moves(board, turn): for index, piece in enumerate(board): if piece_type(piece) == turn: for new_board in moves[chr(piece)](board, index): yield new_board piece_values = {'K' : (100, 0), 'k' : (0, 100), \ 'P' : (1, 0), 'p' : (0, 1), \ 'N' : (3, 0), 'n' : (0, 3), \ 'B' : (3, 0), 'b' : (0, 3), \
Re: First attempt at a Python prog (Chess)
On 13 February 2013 23:25, Chris Hinsley wrote: > New to Python, which I really like BTW. Glad to hear it. > First serious prog. Hope you like it. I know it needs a 'can't move if your > King would be put into check' test. But the weighted value of the King piece > does a surprising emergent job. [SNIP program] Your program looks good. Were you looking for feedback (I'm sure someone would give some if so)? Oscar -- http://mail.python.org/mailman/listinfo/python-list
Re: I made a small reddit console feed with python last night
On 02/13/2013 04:40 PM, Jared Wright wrote: > If you would like to get a copy of it, instructions are here on Github > > https://github.com/jawerty/AlienFeed > What's a "reddit" console feed? -- http://mail.python.org/mailman/listinfo/python-list
Re: Simulate Keyboard keypress Delay
DaGeek247於 2013年2月14日星期四UTC+8上午3時47分36秒寫道: > I am using the windows api feature getasynckeystate() to check the status of > every key pressed; like this; > > > > #always checking > > while(True): > > #iterate through list of ascii codes > > for num in range(0,127): > > #if ascii code key is being pressed > > if win32api.GetAsyncKeyState(num): > > #do stuff > > > > This works great, almost. The issue that comes up now is that every time i > press a key, the code grabs two or three key presses. > > > > So i tried making sure that repeated keys weren't pressed repeatedly; > > > > #always checking > > while(True): > > #iterate through list of ascii codes > > for num in range(0,127): > > #if ascii code key is being pressed > > if win32api.GetAsyncKeyState(num): > > if oldkeychar == num: > > #don't do stuff > > else: > > #do stuff > > > > this works great, but It won't record stuff like 'look' or 'suffer' because > it doesn't record repeated keys. So I try doing a delay instead; > > > > #always checking > > while(True): > > #iterate through list of ascii codes > > for num in range(0,127): > > #if ascii code key is being pressed > > if win32api.GetAsyncKeyState(num): > > if oldkeychar == num: > > if crrenttime > (time.time() - .5) > > #do stuff because key has been repeated, but not because > it was held down > > else: > > #don't do stuff because key is pressed to soon > > else: > > #do stuff because key is not repeated > > currenttime = time.time() > > > > this almost works, but I end recording some double keypresses, and missing > others. Does anybody have any suggestions? I believe you can use the raw_input function in python. But loop through strings ended by \r\n or \r. -- http://mail.python.org/mailman/listinfo/python-list
Re: First attempt at a Python prog (Chess)
On 2013-02-13 23:55:20 +, Oscar Benjamin said: On 13 February 2013 23:25, Chris Hinsley wrote: New to Python, which I really like BTW. Glad to hear it. First serious prog. Hope you like it. I know it needs a 'can't move if your King would be put into check' test. But the weighted value of the King piece does a surprising emergent job. [SNIP program] Your program looks good. Were you looking for feedback (I'm sure someone would give some if so)? Oscar I suppose so yes. I was just 'putting it out there' to see if it was interesting/useful to anyone. No doubt there are many Python features I could use to improve on this. First thing that occurred to me on deciding to try Python was the idea of Generator functions to enumerate all the possible moves of a Chess game, and that 'yield' would make the prog relatively compact. I wish Shedskin could cope with them ! PyPy runs it OK. Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
I am sure I have python installed. I have been running it. in command line the window title is c:\python33\python.exe. The first line begins Python 3.3.0. Later in the line is the string "64 bit ] on Win32". Thus it appears I am trying to run a 32bit numpy with a 64bit python. (Seems like a big ole 64 bit python should be able to swallow a little 32 bitty numpy). Is there a 64bit numpy? If not why not? Can someone get on this? Seriously, I'm under the impression that I need the 64 bit python because I have a 64 bit OS. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Makefiles... are they possible?
Roy Smith wrote: > In article <511b2a7c$0$11096$c3e8...@news.astraweb.com>, > Steven D'Aprano wrote: > >> On Tue, 12 Feb 2013 20:06:35 -0500, Roy Smith wrote: >> >> > One thing we do in our Makefiles is "find . -name '*.pyc' | xargs rm". >> > It avoids all sorts of nasty and hard to track down bugs (consider what >> > happens if you move a .py file from one place in your source tree to >> > another and leave the old .pyc behind). >> >> >> How often do you move files around in the source tree? > > It has happened enough times to make us look for a solution. Which > means "more than once". Maybe the solution is education, not a technical fix. I've suspicious of technical fixes for developer problems, because in my experience that strategy ends in a race to the bottom where you end up with coding standards and procedures that assume everyone is a code monkey who can barely spell PC. It doesn't protect the monkeys, because there is no end to the ways they can screw up, while the competent developers suffer under repressive, B&D procedures that hinder more than help. YMMV. I prefer to keep the .pyc files, and only remove them when necessary, rather than to remove them whether it's necessary or not. It's not just because I'm an arrogant SOB who expects my team of developers to know at least more than me, therefore if I know enough to look for orphaned .pyc files so should they. It's because I am a big believer that your development system should be as close as possible to the eventual deployment system as is practical. Your app will (probably) use .pyc files when it is deployed, so you should do the same when developing. Otherwise you can get bugs in deployment that you cannot reproduce in development because the environments are different. >> Meanwhile, *every* time you run make, you take a performance hit on >> every Python module in your project, whether it has moved or not. > > The performance hit is minimal. I guess that depends on the size of your project and how much you care about the start up time. But as general advice, no, it may not be minimal. [...] > Another solution would be if there was a flag you could give to Python > to tell it, "Only import a .pyc if the corresponding .py file exists". > It's already checking to see if the .py is newer, so this wouldn't even > cost anything. That's called "Python 3.3" :-) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Makefiles... are they possible?
In article <511c501d$0$6512$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano wrote: > I prefer to keep the .pyc files, and only remove them when necessary, rather > than to remove them whether it's necessary or not. It's not just because > I'm an arrogant SOB who expects my team of developers to know at least more > than me, therefore if I know enough to look for orphaned .pyc files so > should they. It's because I am a big believer that your development system > should be as close as possible to the eventual deployment system as is > practical. Your app will (probably) use .pyc files when it is deployed, so > you should do the same when developing. Heh. Our deployment system rolls out all the source code from scratch on every deploy. > Meanwhile, *every* time you run make, you take a performance hit on > every Python module in your project, whether it has moved or not. Yup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggested feature: slice syntax within tuples (or even more generally)?
On 2/13/2013 2:00 PM, stephenw...@gmail.com wrote: Hello, Would it be feasible to modify the Python grammar to allow ':' to generate slice objects everywhere rather than just indexers and top-level tuples of indexers? Right now in Py2.7, Py3.3: "obj[:,2]" yields "obj[slice(None),2]" but "obj[(:,1),2]" is an error, instead of "obj[(slice(None), 1), 2]" Also, more generally, you could imagine this working in (almost?) any expression without ambiguity: "a = (1:2)" could yield "a = slice(1,2)" I believe the idea of slice literals has been rejected. See motivating discussion for this at: https://github.com/pydata/pandas/issues/2866 There might not be very many use cases for this currently outside of pandas, but apparently the grammar was already modified to allow '...' outside indexers and there's probably even fewer valid use cases for that: "e = ..." yields "e = Ellipsis" One dubious move does not justify another. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Statistics...help with numpy/scipy install
On 2/13/2013 9:38 PM, Rex Macey wrote: I am sure I have python installed. I have been running it. in command line the window title is c:\python33\python.exe. The first line begins Python 3.3.0. Later in the line is the string "64 bit ] on Win32". Thus it appears I am trying to run a 32bit numpy with a 64bit python. (Seems like a big ole 64 bit python should be able to swallow a little 32 bitty numpy). Is there a 64bit numpy? If not why not? Ask the numpy people. I am surprised since a reason to be using 64 rather than 32 bit python is to have objects larger than 2 gigabytes and memory larger than 4 gigabytes. Numerical/scientific programming is relatively likely to need such. someone get on this? Seriously, I'm under the impression that I need the 64 bit python because I have a 64 bit OS. If you look on your C: drive, you should have both 'Program Files' and 'Program Files (x86)' directories. The latter is for 32 bit programs. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggested feature: slice syntax within tuples (or even more generally)?
> > I believe the idea of slice literals has been rejected. > That's too bad...do you have a link to prior discussion on this and what the reasoning was for rejection? There doesn't seem to be any particular downside and things would be more consistent with slice syntax allowed anywhere. It would be helpful in other cases as well other than the one linked to, since there's good reason to be able to succinctly create and reuse the same indexer object multiple times without having to convert everything into slice() calls. -Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: First attempt at a Python prog (Chess)
Chris Hinsley wrote: >New to Python, which I really like BTW. > >First serious prog. Hope you like it. I know it needs a 'can't move if >your King would be put into check' test. But the weighted value of the >King piece does a surprising emergent job. It looks a little like a C program ported line-by-line to Python. For example, in Python, there's no reason not to keep the board as an 8x8 array instead of a 64-element list. That by itself would make the code easier to read. It would also let you replace this: for row in range(8): for col in range(8): with the more Pythonic: for row in board: for cell in row: I would probably replace the piece_type function with a map that maps the piece number directly to the piece -- Tim Roberts, t...@probo.com Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggested feature: slice syntax within tuples (or even more generally)?
Apparently Travis Oliphant of numpy would like this as well... http://technicaldiscovery.blogspot.com/2011/06/python-proposal-enhancements-i-wish-i.html On Wednesday, February 13, 2013 2:00:15 PM UTC-5, steph...@gmail.com wrote: > Hello, > > > > Would it be feasible to modify the Python grammar to allow ':' to generate > slice objects everywhere rather than just indexers and top-level tuples of > indexers? > > > > Right now in Py2.7, Py3.3: > > "obj[:,2]" yields "obj[slice(None),2]" > > but > > "obj[(:,1),2]" is an error, instead of "obj[(slice(None), 1), 2]" > > > > Also, more generally, you could imagine this working in (almost?) any > expression without ambiguity: > > "a = (1:2)" could yield "a = slice(1,2)" > > > > See motivating discussion for this at: > > https://github.com/pydata/pandas/issues/2866 > > > > There might not be very many use cases for this currently outside of pandas, > but apparently the grammar was already modified to allow '...' outside > indexers and there's probably even fewer valid use cases for that: > > "e = ..." yields "e = Ellipsis" > > > > Would there be any downside to changing the handling of ':' as well? It might > even make the grammar simpler, in some ways, since indexers won't have to be > treated specially. > > > > Let me know if you have any thoughts. > > > > Thanks! > > Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: Awsome Python - chained exceptions
On Thu, 14 Feb 2013 09:10:42 +1100, Chris Angelico wrote: Quoting Rick Johnson: >> Q2: Why would the line in the try block be shown as a "feature" of >> the traceback when the whole intent of exception handling is to hide >> the error in the try block! If you want to raise the exception in the >> try block then you place a naked raise statement in the exception >> block, BUT THEN, why even wrap the code in a try/except in the first >> damn place!? Here is one example of using raise to re-raise an exception you have just caught: import errno paths = ["here", "there", "somewhere else"] for location in paths: filename = os.path.join(location, "prefs.ini") try: f = open(filename) except IOError as e: if e.errno != errno.ENOENT: # File not found. raise > You seriously need to get into the real world and do some actual > debugging work. Amen to that brother. What is it that they say? "Those who can, do. Those who can't, teach. Those who can't teach, write rants on the Internet criticising others." [...] >>> He is? Could just as easily be the print statement with a single >>> argument, with unnecessary parentheses around that argument. Which, if >>> I recall correctly, is one of the recommended approaches for making >>> 2/3 bi-compatible code. >> >> Really? >> >> Because if he did in-fact write the print statement using parenthesis >> (in some foolish attempt to make his code forward-compatible) that >> would mean i should add /another/ coding abomination to my earlier list >> of abominations. The proper method of using a forward compatible print >> function is by /importing/ the feature. >> >>from future import print_function > import __future__ __future__.print_function > _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 65536) > > Which works back as far as 2.6 but that's all. Simply putting parens > around the argument works all the way back to... hmm. Further back than > I've ever had to support, but then, I only started using Python > seriously a few years ago. Steven? Putting parens around the argument to print works going back to at least Python 0.9.1, which is before Python had "" delimiters: steve@runes:~$ ./python0.9.1 >>> s = "string" Parsing error: file , line 1: s = "string" ^ Unhandled exception: run-time error: syntax error >>> s = 'string' >>> print s string >>> print (s) string You can always wrap any expression with an extra pair of round brackets. Of course, the correct way of doing this is with "from __future__ import print_function", but really, who cares? It's just a trivial example. If the worst criticism someone can make of my example is that I took a short- cut when printing, I can live with that. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Makefiles... are they possible?
On Thu, Feb 14, 2013 at 1:46 PM, Steven D'Aprano wrote: > I prefer to keep the .pyc files, and only remove them when necessary, rather > than to remove them whether it's necessary or not. Solution to that could be just to have your makefile wipe out orphanned pyc files, rather than all of them. Still might be a performance hit (if it has to wade through piles of pyc/py files to see which ones aren't needed), but otherwise should be safe. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Awsome Python - chained exceptions
On Tue, Feb 12, 2013 at 8:01 PM, Rick Johnson wrote: > On Tuesday, February 12, 2013 12:01:45 PM UTC-6, Zero Piraeus wrote: > >> You could call them PyW00ts. > > +1 on the name > -INFINITY on the execution > > Actually i am happy that DeAprano used the unintuitive tag now. Bad enough to > use an unintuitive tag. Worse to misspell it. But it would been a crime to > tarnish such an intuitive tag as "PyW00ts" with the clumsy teachings provided. 1. Subject lines are not tags. If you want to categorize the post with a tag for later reference, then by all means do so; any halfway decent reader will let you do this. It's not up to the post author to tag posts for you. 2. If you're going to criticize someone for their spelling, at least be sure to spell correctly the name of the person you are addressing. You've consistently misspelled Steven's surname in several posts that I've noticed. -- http://mail.python.org/mailman/listinfo/python-list
"Exception ... in ignored" Messages
Hi, Running the unit tests for some generator code, prints, as a side effect, numerous messages of the form: ... Exception NameError: "global name 'l' is not defined" in ignored Exception AttributeError: "'NoneType' object has no attribute 'close'" in ignored Exception AttributeError: "'NoneType' object has no attribute 'close'" in ignored ... The tests otherwise run fine. Is there any way to catch the point where such a message originates, and print a traceback? I find it difficult to debug otherwise. I've tried running Python with -W error, catching warnings with context managers, and so forth, but without any success. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggested feature: slice syntax within tuples (or even more generally)?
On Wed, 13 Feb 2013 21:54:43 -0800, stephenwlin wrote: >> I believe the idea of slice literals has been rejected. >> >> > That's too bad...do you have a link to prior discussion on this and what > the reasoning was for rejection? There doesn't seem to be any particular > downside and things would be more consistent with slice syntax allowed > anywhere. There's *always* downside to new syntax. The question is, does the benefit exceed the downside? - new syntax requires more complexity in the parser; - new tests for it; - more documentation; - increase in the number of things people have to learn before they can read and write Python code; - takes the language further away from "executable pseudo-code" and closer to "line noise"; - somebody has to actually write the code, write the tests, write the documentation; and somebody else has to review it; for a chronically short-handed dev team where there are hundreds of bugs and feature requests in the queue, this is a significant cost. Now, you might argue that these are all *low* cost, but they're not zero, and how do they stack up against the benefits? What are the benefits of syntactic sugar for slice objects? Personally, there's not much difference to my eye between: S = slice S(1, 20, 3) versus (1:20:3) so I'm skeptical that the benefit is much greater than the cost, as low as that cost may be. > It would be helpful in other cases as well other than the one linked to, > since there's good reason to be able to succinctly create and reuse the > same indexer object multiple times without having to convert everything > into slice() calls. I don't quite understand this argument. If you mean that you can do this: s = (1:2) # Like slice(1, 2). print alist[s] print blist[s] # reuse the slice object print clist[s] you can replace the line s = (1:2) to a call to slice, and still reuse the slice object. So I don't understand what the syntactic sugar gains you. -- Steven -- http://mail.python.org/mailman/listinfo/python-list