Re: Abend with cls.__repr__ = cls.__str__ on Windows.
On Fri, 18 Mar 2011 14:15:46 -0700, Carl Banks wrote: > I observed the same behavior (2.6 and 3.2 on Linux, hangs) and went > ahead and submitted a bug report. Thank you. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On Fri, 18 Mar 2011 21:39:20 -0700, Manatee wrote: > I hope this is the place to post this question. I am a really new > pythonista. I am studying Tkinter and when I run this basic code, I get > a syntax error on line 20, print "hi there, everyone". Its a simple > print line, but I can't see the problem. Well, what does the syntax error say? Please post the complete traceback showing the full error. Copy and paste it, in full, do not summarize, paraphrase, re-word, simplify or otherwise change it. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: value of pi and 22/7
On Fri, 18 Mar 2011 07:22:43 -0700, Kee Nethery wrote: > On Mar 18, 2011, at 5:17 AM, Neil Cerutti wrote: > >> On 2011-03-18, peter wrote: >>> The Old Testament (1 Kings 7,23) says ... "And he made a molten sea, >>> ten cubits from the one brim to the other: it was round all about, and >>> his height was five cubits: and a line of thirty cubits did compass it >>> round about. ". So pi=3. End Of. >> >> RIIght. What's a cubit? > > I use cubits all the time. The distance from my elbow to my finger tips > equals one cubit. When you don't have a proper measuring tape, it can be > pretty accurate for comparing two measurements. "Measure with micrometer, mark with chalk, cut with axe." Just wait until you tell your apprentice to go fetch a piece of wood three cubits long... damn kids with their short/long arms... :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Bounds checking
On Fri, 18 Mar 2011 07:24:33 -0700, Martin De Kauwe wrote: > Hi, > > if one has a set of values which should never step outside certain > bounds (for example if the values were negative then they wouldn't be > physically meaningful) is there a nice way to bounds check? I > potentially have 10 or so values I would like to check at the end of > each iteration. assert all(x >= 0 for x in (a, b, c, d, e, f, g, h, i, j)) > However as the loop is over many years I figured I > probably want to be as optimal as possible with my check. Any thoughts? > > e.g. this is my solution > > # module contain data > # e.g. print state.something might produce 4.0 import state as state > > def main(): > for i in xrange(num_days): > # do stuff > > # bounds check at end of iteration > bounds_check(state) Why don't you do the range check *before* storing it in state? That way you can identify the calculation that was wrong, instead of merely noticing that at some point some unknown calculation went wrong. > def bounds_check(state): > """ check state values are > 0 """ > for attr in dir(state): > if not attr.startswith('__') and getattr(state, attr) < 0.0: You're looking at every single attribute, including those of super classes, when you only want to check "10 or so" attributes. That's probably not wise. At the very least, dir() will be a fairly expensive call. If you insist on checking state *after* the value is stored, instead of preventing it from being stored in the first place, it is better to make the state object responsible for doing it's own bounds checking. That way only the state object needs to be updated when you change those ten attributes, instead of some arbitrary number of places scattered all throughout your code. > print "Error state values < 0: %s" % (attr) > sys.exit() Python already has a mechanism for printing an error message and exiting: raise. if condition: raise ValueError("attribute %s is negative" % name) This will still halt the application, but it does so without stomping all over normal conventions for command line applications (error messages should go to stderr, not stdout; the return result should be non-zero) as well as normal conventions for Python code (the caller should be able to easily catch the exception -- catching sys.exit can be done, but it is a pretty unusual thing to do). -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Bounds checking
On Fri, 18 Mar 2011 15:35:40 -0700, Martin De Kauwe wrote: >> Don't check for bounds, fix any bug in the code that would set your >> values out of bounds and use asserts while debugging. >> >> > whilst that is a nice idea in practice this just is not a practical > solution. Sorry, are you trying to say that it is not practical to write correct code that isn't buggy? Well, you're honest, at least, still I can't help but feel that you're admitting defeat before even starting. >> Otherwise if you really need dynamic checks, it will cost you cpu, for >> sure. > > Yes I agree and I hadn't decided whether to add it or not as there > aren't any current issues. However I can see that the check would > overall be safer. I was just wondering if there was some super smartie > pants solution :P Make each of the attributes a computed attribute with a setter that raises an exception if you try to store a negative value. That way each attribute is responsible for ensuring that itself is never negative. Here's a toy example: >>> class Demo(object): ... def __init__(self, x): ... self.x = x ... def _getx(self): ... return self._x ... def _setx(self, value): ... if value < 0: ... raise ValueError('attempt to set x to negative value') ... self._x = value ... x = property(_getx, _setx) ... >>> d = Demo(-42) Traceback (most recent call last): File "", line 1, in File "", line 3, in __init__ File "", line 8, in _setx ValueError: attempt to set x to negative value >>> d = Demo(42) >>> d.x 42 >>> d.x = -23 Traceback (most recent call last): File "", line 1, in File "", line 8, in _setx ValueError: attempt to set x to negative value >>> d.x = 23 >>> d.x 23 -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading/Writing files
On Fri, 18 Mar 2011 16:00:55 -0700, Ethan Furman wrote: Dan Stromberg wrote: > / works fine on windows, and doesn't require escaping ("/foo/bar"). "/" works fine in most contexts, but not in shell commands, where "/" is conventionally used to indicate a switch. Commands which follow this convention typically recognise "/" as the start of a switch even when it is immediately preceded by a letter (with no intervening whitespace). -- http://mail.python.org/mailman/listinfo/python-list
Re: Bounds checking
> dir() has to do a bit a computation. I would be tempted to give 'state' > a set of attributes to check. Call it 'nonnegatives'. > for attr in nonnegatives: > if ... > > This allows for attributes not subject to that check. > > -- > Terry Jan Reedy Agreed. I was trying to just write a dummy example quickly to go with my question and that was just the way that came to mind so that I could loop over them to test. It wasn't a great example sorry! In reality I would just have like you said a subset a list I guess of the ones I would check. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bounds checking
> assert all(x >= 0 for x in (a, b, c, d, e, f, g, h, i, j)) yep neat! > Why don't you do the range check *before* storing it in state? That way > you can identify the calculation that was wrong, instead of merely > noticing that at some point some unknown calculation went wrong. I guess no reason really. I suppose in my mind I was thinking it was an unlikely safeguard but I liked the idea of adding so would just do it at the end of a time step. In reality I think there is practically no difference and this way it is done once, in a single location vs. potential 10 separate checks? I don't see the advantage? > You're looking at every single attribute, including those of super > classes, when you only want to check "10 or so" attributes. That's > probably not wise. At the very least, dir() will be a fairly expensive > call. yes your right, sorry I was just trying to post a quick example to go with my question. I would use a list of the attributes to check. > > If you insist on checking state *after* the value is stored, instead of > preventing it from being stored in the first place, it is better to make > the state object responsible for doing it's own bounds checking. That way > only the state object needs to be updated when you change those ten > attributes, instead of some arbitrary number of places scattered all > throughout your code. yes I think this is what I was getting at, I will look at your suggestion thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bounds checking
> Sorry, are you trying to say that it is not practical to write correct > code that isn't buggy? Well, you're honest, at least, still I can't help > but feel that you're admitting defeat before even starting. No. What I am saying is the code is written has been well tested and *appears* to be working well. However the code is complicated and there is potential for bugs. I think I am just been practical here, evidently I can't think of everything, but there are some clear and obvious errors that would be worth checking for. I can only explain this in the terms of the code (sorry)...but for example the model estimates plant photosynthesis and then allocates the carbon. So one clear example is that the model cuts back carbon production if there is water stress for the plant. This involves "removing" carbon from the state. Clearly if you ended up in a situation where there is negative carbon in a leaf, i.e. the leaf doesn't exist well this is not physically possible and would be a code issue. Whilst this is unlikely I think it would be nice to have a catch for it. Another example would be the amount of soil water available to the plant, again there can be zero but not negative soil water. It wouldn't be meaningful. I hope that makes sense? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: install excel xlwt in ubuntu 9
On 19.03.2011 07:29, ratna PB wrote: Hey friends i tried a lot to install excel xlwt in ubuntu 9 but failed please help me before i get full fraustrated... What have you tried and how did it failed? On 9.10, simply do (you might need to enable the universe repository in Synaptic first): $ sudo apt-get install python-xlwt Alternatively, install python-setuptools and then use easy_install: $ sudo apt-get install python-setuptools $ sudo easy_install xlwt -- http://mail.python.org/mailman/listinfo/python-list
Re: install excel xlwt in ubuntu 9
ratna PB wrote: > Hey friends i tried a lot to install excel xlwt in ubuntu 9 but > failed > please help me before i get full fraustrated... sudo apt-get install python-xlwt -- //Aho -- http://mail.python.org/mailman/listinfo/python-list
Re: Bounds checking
On Sat, 19 Mar 2011 01:38:10 -0700, Martin De Kauwe wrote: >> Why don't you do the range check *before* storing it in state? That way >> you can identify the calculation that was wrong, instead of merely >> noticing that at some point some unknown calculation went wrong. > > I guess no reason really. I suppose in my mind I was thinking it was an > unlikely safeguard but I liked the idea of adding so would just do it at > the end of a time step. In reality I think there is practically no > difference and this way it is done once, in a single location vs. > potential 10 separate checks? I don't see the advantage? You should always aim to fail as close as possible to the source of the error as is practical. That decreases the amount of debugging required when something fails: instead of searching your entire program, you only have to search a very small amount of code. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Thanks...
Hi guys... A few weeks ago I joined here with a couple of code snippets that I gave away and someone on here - can`t remember who pointed me to:- http://code.activestate.com/recipes/langs/python/ Well I have uploaded 6 items but a day or so ago I uploaded this one:- http://code.activestate.com/recipes/577612-seven-bit-colored-analogue-bar-graph-generator-dem/?in=lang-python Already it has been voted up to 3... Many thanks for the pointer chap, whoever it was, it looks like people are interested in what I do with Python... ;oD -- 73... Bazza, G0LCU... Team AMIGA... http://homepages.tesco.net/wisecracker/ http://main.aminet.net/search?readme=wisecracker http://mikeos.berlios.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes pointer to structure memory swap
On Mar 18, 6:42 pm, Nobody wrote: > On Fri, 18 Mar 2011 15:16:40 -0700, Wanderer wrote: > > Thanks for the reply, but I'm still not sure I understand. Why should > > Object1 be at address1 and Object2 be at address2 and the next moment > > Object2 is at address1 and Object1 is at address2? I'll try casting > > them to see what the value is before and after calling > > ReleaseCameraSettingStruct. > > QCamSettingsEx is a ctypes Struct object. The pSettingsID "field" is a > ctypes field, not a Python field. It will contain a "bare" pointer to the > C-struct for the QCamSettingId object. > > The point of a ctypes Struct is to store data in a format usable by C > code, i.e. the memory layout will match that of a C struct. In particular, > pointers within that struct will be pointers to C-compatible data (e.g. C > structs), not pointers to Python objects. If you access the fields from > Python, ctypes will generate Python objects on-the-fly from the raw data. > > Whenever you read the pSettingsID field, ctypes will generate a ctypes > pointer object (LP_QCamSettingId?) which wraps the underlying C pointer. > If you dereference that, ctypes will generate a Python QCamSettingId > object which wraps the C struct. > > As you aren't storing the references, as soon as the print statement > completes, the reference count will drop to zero and the object will be > deallocated. The next time you reference pSettingsID or pSettingsID[0], a > new object will be constructed. The addresses (and thus IDs) of the Python > objects are entirely arbitrary. Great explanation. Now I understand. Thanks -- http://mail.python.org/mailman/listinfo/python-list
puzzle about file Object.readlines()
i use python 2.5. os is window 7. the puzzle is :python don't read the leave text when meet character: chr(26) the code is: * fileObject=open('d:\\temp\\1.txt','w') fileObject.write('22\r\n') fileObject.write(chr(26)+'\r\n') fileObject.write('33') fileObject.close() fileObject=open('d:\\temp\\1.txt','r') i=0 for line in fileObject: i+=1 print str(i)+'**'+line fileObject.close()* the output only print: * >>> 1**22* but can't print next line text:*'33'' 。who tell me why? * -- http://mail.python.org/mailman/listinfo/python-list
Re: value of pi and 22/7
On Fri, 18 Mar 2011 13:45:47 +0100 Stefan Behnel wrote: > Neil Cerutti, 18.03.2011 13:17: > > RIIght. What's a cubit? > > http://en.wikipedia.org/wiki/Cubit I don't believe that Neil was asking a serious question. http://www.youtube.com/watch?v=so9o3_daDZw -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Surge 2011 Conference CFP
We are excited to announce Surge 2011, the Scalability and Performance Conference, to be held in Baltimore on Sept 28-30, 2011. The event focuses on case studies that demonstrate successes (and failures) in Web applications and Internet architectures. This year, we're adding Hack Day on September 28th. The inaugural, 2010 conference (http://omniti.com/surge/2010) was a smashing success and we are currently accepting submissions for papers through April 3rd. You can find more information about topics online: http://omniti.com/surge/2011 2010 attendees compared Surge to the early days of Velocity, and our speakers received 3.5-4 out of 4 stars for quality of presentation and quality of content! Nearly 90% of first-year attendees are planning to come again in 2011. For more information about the CFP or sponsorship of the event, please contact us at surge (AT) omniti (DOT) com. -- Katherine Jeschke Marketing Director OmniTI Computer Consulting, Inc. 7070 Samuel Morse Drive, Ste.150 Columbia, MD 21046 O: 410/872-4910, 222 C: 443/643-6140 omniti.com circonus.com -- http://mail.python.org/mailman/listinfo/python-list
ANN: PyGUI 2.4
PyGUI 2.4 is available: http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/ Highlights of this release: * Python 3 Compatible on MacOSX and Windows. * ScrollableView has been overhauled on Windows and should now work with all builds of pywin32 as far as I know. What is PyGUI? -- PyGUI is a cross-platform GUI toolkit designed to be lightweight and have a highly Pythonic API. -- Gregory Ewing greg.ew...@canterbury.ac.nz http://www.cosc.canterbury.ac.nz/greg.ewing/ -- http://mail.python.org/mailman/listinfo/python-list
ANN: fathom 0.1.0
Hello everyone! I have created a small python package for python3 called fathom that provides database inspection. It is in a very early stage, rather a proof of concept right now. It provides basic information about database schema and works with Sqlite3, PostgreSQL and MySQL. I am looking for comments and additional ideas for new features.. Documentation can be found here: http://code.google.com/p/fathom/wiki/Manual Package can be downloaded from PyPi or from here: http://code.google.com/p/fathom/downloads/list -- Filip Gruszczyński -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzle about file Object.readlines()
On 19/03/2011 13:15, 林桦 wrote: > i use python 2.5. os is window 7. > the puzzle is :python don't read the leave text when meet character: > chr(26) > the code is: > /fileObject=open('d:\\temp\\1.txt','w') > fileObject.write('22\r\n') > fileObject.write(chr(26)+'\r\n') > fileObject.write('33') > fileObject.close() > fileObject=open('d:\\temp\\1.txt','r') > i=0 > for line in fileObject: > i+=1 > print str(i)+'**'+line > fileObject.close()/ > > the output only print: > />>> > 1**22/ > > but can't print next line text:/'33'' 。who tell me why? > / > chr(26) can sometimes be used in text files to indicate the end of the text. In Microsoft Windows it dates from MS-DOS, which borrowed from CP/M, an operating system which stored the file size as the number of 128-byte records. chr(26) was used to indicate where the text ended in the last record. -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On Mar 19, 1:03 am, Vlastimil Brom wrote: > 2011/3/19 Manatee : > > > I hope this is the place to post this question. I am a really new > > pythonista. I am studying Tkinter and when I run this basic code, I > > get a syntax error on line 20, print "hi there, everyone". Its a > > simple print line, but I can't see the problem. I am using Python > > 2.71, gVim for an editor, and a console window to execute the program. > > Here is the link to the website that I am trying to follow: > > >http://www.pythonware.com/library/tkinter/introduction/hello-again.htm > > > Thanks for any help. > > > [...] > > Hi, > the code on the mentioned page as well as yours (with adapted > indentation and wordwrapping from the mail) seems ok for python 2. > > Is it possible, that you are actually using python3? > This would give something like > print "hi there, everyone!" > ^ > SyntaxError: invalid syntax > > as print was changed to a funcion in this version. > print("hi there, everyone!") > > hth, > vbr Ah, yes that's exactly what the traceback shows. Well, I know that I am using Python 2.71 as downloaded from the python site. That's why I didn't think there would be a version problem. However it would appear that is the problem. I will download 2.6 and see if that fixes my problem. Thank you very much. From now on I will also post the complete traceback. -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On Mar 19, 2:00 am, Terry Reedy wrote: > On 3/19/2011 1:03 AM, Vlastimil Brom wrote: > > > 2011/3/19 Manatee: > >> I hope this is the place to post this question. > > Yes. > Lesson 1. Report Python version used, as things change. For anything > that seems like it might by os/system specific, include that too. > Lesson 2. Always include tracebacks when there is one. > > > > > > >> I am a really new > >> pythonista. I am studying Tkinter and when I run this basic code, I > >> get a syntax error on line 20, print "hi there, everyone". Its a > >> simple print line, but I can't see the problem. I am using Python > >> 2.71, gVim for an editor, and a console window to execute the program. > >> Here is the link to the website that I am trying to follow: > > >>http://www.pythonware.com/library/tkinter/introduction/hello-again.htm > > >> Thanks for any help. > > >> [...] > > > Hi, > > the code on the mentioned page as well as yours (with adapted > > indentation and wordwrapping from the mail) seems ok for python 2. > > > Is it possible, that you are actually using python3? > > This would give something like > > print "hi there, everyone!" > > ^ > > SyntaxError: invalid syntax > > > as print was changed to a funcion in this version. > > print("hi there, everyone!") > > If running with Py3, 'import Tkinter' will fail; change to 'import tkinter'. > > -- > Terry Jan Reedy- Hide quoted text - > > - Show quoted text - Ok, great. I don't know what I was thinking. But the traceback should always be included; thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On Mar 19, 3:26 am, Steven D'Aprano wrote: > On Fri, 18 Mar 2011 21:39:20 -0700, Manatee wrote: > > I hope this is the place to post this question. I am a really new > > pythonista. I am studying Tkinter and when I run this basic code, I get > > a syntax error on line 20, print "hi there, everyone". Its a simple > > print line, but I can't see the problem. > > Well, what does the syntax error say? Please post the complete traceback > showing the full error. Copy and paste it, in full, do not summarize, > paraphrase, re-word, simplify or otherwise change it. > > -- > Steven Here is the complete traceback as copied from the DOS window. C:\Users\Rivetmr\MyPythonScripts>Hello2.py File "C:\Users\Rivetmr\MyPythonScripts\Hello2.py", line 20 print "hi there, everyone" ^ SyntaxError: invalid syntax -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On Mar 19, 3:26 am, Steven D'Aprano wrote: > On Fri, 18 Mar 2011 21:39:20 -0700, Manatee wrote: > > I hope this is the place to post this question. I am a really new > Also, this is what is printed in the window when I type "Python" C:\Users\Rivetmr\MyPythonScripts>Python Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] onI win32 Type "help", "copyright", "credits" or "license" for more information. >>> I guess I have to go to an earlier version; maybe 2.6? -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On Mar 19, 3:26 am, Steven D'Aprano wrote: > On Fri, 18 Mar 2011 21:39:20 -0700, Manatee wrote: > > I hope this is the place to post this question. I am a really new > > pythonista. I am studying Tkinter and when I run this basic code, I get > > a syntax error on line 20, print "hi there, everyone". Its a simple > > print line, but I can't see the problem. > > Well, what does the syntax error say? Please post the complete traceback > showing the full error. Copy and paste it, in full, do not summarize, > paraphrase, re-word, simplify or otherwise change it. > > -- > Steven If I want to start up different versions of Python from the dos window I would actually have to be in the directory where that version lives? is that correct? -- http://mail.python.org/mailman/listinfo/python-list
Re: puzzle about file Object.readlines()
On 01/-10/-28163 02:59 PM, MRAB wrote: On 19/03/2011 13:15, 林桦 wrote: i use python 2.5. os is window 7. the puzzle is :python don't read the leave text when meet character: chr(26) the code is: /fileObject=open('d:\\temp\\1.txt','w') fileObject.write('22\r\n') fileObject.write(chr(26)+'\r\n') fileObject.write('33') fileObject.close() fileObject=open('d:\\temp\\1.txt','r') i=0 for line in fileObject: i+=1 print str(i)+'**'+line fileObject.close()/ the output only print: />>> 1**22/ but can't print next line text:/'33'' 。who tell me why? / chr(26) can sometimes be used in text files to indicate the end of the text. In Microsoft Windows it dates from MS-DOS, which borrowed from CP/M, an operating system which stored the file size as the number of 128-byte records. chr(26) was used to indicate where the text ended in the last record. On Win a ctrl-z is end of file. So if you want to read beyond the end of a text file, you have to pretend it's binary. Open it with "rb" instead of "r" DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing Pool workers cannot create subprocesses
On 3/18/2011 7:54 PM, Jason Grout wrote: Right; thanks. Let me rephrase my questions: 1. Why is important that the multiprocessing Pool worker processors have daemon=True (I think this is the same as asking: why is it important that they be terminated with terminate() rather than join() )? 2. Is it safe for us to reset a Pool worker process to have daemon=False before starting a subprocess from that worker, like in the code from the original message? Thanks, Jason Jason, I just happen to be dealing with a project that uses multiprocessing. What I have learned is this... If a child thread (pool worker) is not set to daemon (daemon=False), if for some reason the parent thread terminates either normally or abnormally and the worker thread has not completed its task, the child thread will terminate by throwing all sorts of nasty errors. However, in daemon mode, multiprocessing will terminate the child thread 'cleanly'. That's not to say that the worker has a chance to complete its work or shut itself down. Multiprocessing will absorb the exceptions and not pass them along. You may terminate a child thread using join(). That is probably the safest way to do it. terminate() will just kill the worker thread immediately without any regard to whether or not it has completed its tasks. I believe multiprocessing uses terminate() as well to kill a daemon thread if the parent thread disappears. join() will, however, block until the task has competed and returned. If you want to continue doing work in the parent thread while the child thread is off doing its thing, then another means of syncing up the parent and children threads is needed. As for allowing children threads to spawn off children of its own using subprocess runs the risk of creating a little army of zombie 'grandchildren' if either the parent or child threads terminate before the subprocess completes and returns. Hope that helps John -- http://mail.python.org/mailman/listinfo/python-list
Re: Syntax Error
On 3/19/2011 2:07 PM, Manatee wrote: C:\Users\Rivetmr\MyPythonScripts>Python Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] onI win32 Type "help", "copyright", "credits" or "license" for more information. I guess I have to go to an earlier version; maybe 2.6? No reason to think that. 2.7 is not much different. I suggest that you comment out the print line (add # to beginning) to see if the syntax error is really in the print line or if there there is a previous error which is only caught on that line. Also try moving the line to a different place (and adjusting indent as necessary) to see what happens. Debugging is often a matter of trying different things to collect more bits of information. Python, especially with IDLE or other editor with a Run key, make that especially easy. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
Hello, On Thu, Mar 10, 2011 at 04:58:53PM -0800, Justin Ezequiel wrote: > We have an old barcode program (MSDOS and source code unavailable.) > I've figured out how to populate the fields (by hacking into one of > the program's resource files.) > However, we still need to hit the following function keys in sequence. > F5, F2, F7 > Is there a way to pipe said keys into the program? It's a very old and good known trick IMO. You just need to write keycodes to kbd ring buffer in BIOS data area (I don't remember exact address, soemewhere in 1st 4kbytes of PC memory), then wait till the scancode gets consumed. I'd put "scancode feeding" code into timer interrupt handler. -- With best regards, xrgtn -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading/Writing files
On Sat, Mar 19, 2011 at 12:55 AM, Nobody wrote: > On Fri, 18 Mar 2011 16:00:55 -0700, Ethan Furman wrote: > > Dan Stromberg wrote: > > > / works fine on windows, and doesn't require escaping ("/foo/bar"). > > "/" works fine in most contexts, but not in shell commands, where "/" is > conventionally used to indicate a switch. Commands which follow this > convention typically recognise "/" as the start of a switch even when it > is immediately preceded by a letter (with no intervening whitespace). > Yeah, you got me. It's also pretty crummy as a statement separator in Pascal too. http://en.wikipedia.org/wiki/Path_%28computing%29#MS-DOS.2FMicrosoft_Windows_style http://www.htl-steyr.ac.at/~morg/pcinfo/hardware/interrupts/inte2zxs.htm ...but I'm not going to suggest that cmd.exe's quoting rules are rational, or that changing your switchchar is a good idea anymore. This is more of just another normpath thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
On Sun, Mar 20, 2011 at 12:52:28AM +0200, Alexander Gattin wrote: > On Thu, Mar 10, 2011 at 04:58:53PM -0800, Justin > Ezequiel wrote: > > We have an old barcode program (MSDOS and source code unavailable.) > > I've figured out how to populate the fields (by hacking into one of > > the program's resource files.) > > However, we still need to hit the following function keys in sequence. > > F5, F2, F7 > > Is there a way to pipe said keys into the program? > > It's a very old and good known trick IMO. You just > need to write keycodes to kbd ring buffer in BIOS > data area (I don't remember exact address, > soemewhere in 1st 4kbytes of PC memory), then wait > till the scancode gets consumed. I'd put "scancode > feeding" code into timer interrupt handler. Taken from RBIL/MEMORY.LST (http://www.cs.cmu.edu/~ralf/interrupt-list/inter61c.zip): K-M0040001A-- MEM 0040h:001Ah - KEYBOARD - POINTER TO NEXT CHARACTER IN KEYBOARD BUFFER Size: WORD SeeAlso: MEM 0040h:001Ch,MEM 0040h:0080h,MEM 0040h:0082h,INT 16/AH=00h K-M0040001C-- MEM 0040h:001Ch - KEYBOARD - POINTER TO FIRST FREE SLOT IN KEYBOARD BUFFER Size: WORD SeeAlso: MEM 0040h:001Ah,MEM 0040h:001Eh,MEM 0040h:0080h,MEM 0040h:0082h SeeAlso: INT 16/AH=00h K-M0040001E-- MEM 0040h:001Eh - KEYBOARD - DEFAULT KEYBOARD CIRCULAR BUFFER Size: 16 WORDs SeeAlso: MEM 0040h:001Ah,MEM 0040h:001Ch,MEM 0040h:0080h,MEM 0040h:0082h SeeAlso: INT 16/AH=00h,INT 16/AH=05h Buffer is considered empty if word[0x41A]==word[0x41C] IIRC. You need to place 2 bytes into the circular buffer to simulate key press. Lower byte is ASCII code, higher byte is scan code (they are the same for functional keys, whe using default keycode set#1): F5: 0x3F 0x3F F2: 0x3C 0x3C F7: 0x41 0x41 -- With best regards, xrgtn -- http://mail.python.org/mailman/listinfo/python-list
Some Minor questions on Class and Functions
Dear Group, I am trying to pose two small questions. 1) I am using Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v. 1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information, on WINXP SP2. As I am writing a code for class like the following: IDLE 2.6.5 >>> class Message: def __init__(self,str1): self.text="MY NAME" def printmessage(self): print self.text It works fine as can be seen in the result: >>> x1=Message(1) >>> x1.printmessage() MY NAME Now if I open a new window and write the same code value in printmessage is giving arbitrary or no values. Am I doing any problem in writing the code? 2) Suppose I have a code: >>> def hello(): print "HELLO SIR" Can I write another function where I can call the value of this function or manipulate it? If any learned member can slightly help me out. Thanks in advance, Best Regards, Subhabrata. -- http://mail.python.org/mailman/listinfo/python-list
Re: class error
On Sat, 19 Mar 2011 02:15:55 -, Terry Reedy wrote: On 3/18/2011 5:27 PM, monkeys paw wrote: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) OK, i overlooked that and the error was not very enlightening. A detailed explanation: every module is an instance of a class we will call Module. Every class is an instance of some class, its metaclass. The default metaclass, in the absence of any indication otherwise, is class type. So your class statement was translated to type('FileInfo',(UserDict,), d) where d is a dict mappint '__init__' to the function object. type.__new__ checks the types (metaclasses) of each of the base classes. In particular, it sees that type(UxerDict) is Module, not type. Since it assumed that UserDict is a class (since you said it was), it assumed that Module is a proper metaclass and called Module('FileInfo',(UserDict,), d) But Module is not a metaclass and does not expect the tuple of base classes, and Module.__new__ passed too much to Module.__init__. Since others have made the same mistake, I opened an issue to improve the message. http://bugs.python.org/issue11604 It has to be said that the confusion is exacerbated by ignoring PEP-8 and using the same (CamelCase) name for the module and the class. That does provide a rich source of errors in cases like this. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
os.walk/list
so i am trying to add md5 checksum calc to my file copy stuff, to make sure the source and dest. are same file. i implemented it fine with the single file copy part. something like : for files in sourcepath: f1=file(files ,'rb') try: shutil.copy2(files, os.path.join(destpath,os.path.basename(files))) except: print "error file" f2=file(os.path.join(destpath,os.path.basename(files)), 'rb') truth = md5.new(f1.read()).digest() == md5.new(f2.read()).digest() if truth == 0: print "file copy error" this worked swimmingly. i moved on to my backupall function, something like for (path, dirs, files) in os.walk(source): #os.walk drills down thru all the folders of source for fname in dirs: currentdir = destination+leftover try: os.mkdir(os.path.join(currentdir,fname),0755) except: print "error folder" for fname in files: leftover = path.replace(source, '') currentdir = destination+leftover f1=file(files ,'rb') try: shutil.copy2(os.path.join(path,fname), os.path.join(currentdir,fname)) f2 = file(os.path.join(currentdir,fname,files)) except: print "error file" truth = md5.new(f1.read()).digest() == md5.new(f2.read()).digest() if truth == 0: print "file copy error" but here, "fname" is a list, not a single file.i didn't really want to spend a lot of time on the md5 part. thought it would be an easy add- on. i don't really want to write the file names out to a list and parse through them one a time doing the calc, but it sounds like i will have to do something like that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove all directories using wildcard
On 2011-03-18, JSkinn3 wrote: > I'm new to python and I am trying to figure out how to remove all sub > directories from a parent directory using a wildcard. For example, > remove all sub directory folders that contain the word "PEMA" from the > parent directory "C:\Data". > > I've trying to use os.walk with glob, but I'm not sure if this is the > right path to take. I see you've got 2 suggestions allready. Wichever you use, please note you need to begin the search from the bottom of the tree. The call to os.walk should include a False value for the direction of the walk: os.walk("c:/data", False). -- When in doubt, use brute force. -- Ken Thompson -- http://mail.python.org/mailman/listinfo/python-list
Re: Some Minor questions on Class and Functions
On Sat, Mar 19, 2011 at 7:57 PM, joy99 wrote: > > Dear Group, > > I am trying to pose two small questions. > > 1) I am using Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v. > 1500 32 bit (Intel)] on win32 Type "copyright", "credits" or > "license()" for more information, on WINXP SP2. > > As I am writing a code for class like the following: > IDLE 2.6.5 class Message: > def __init__(self,str1): > self.text="MY NAME" > def printmessage(self): > print self.text > > It works fine as can be seen in the result: x1=Message(1) x1.printmessage() > MY NAME > > Now if I open a new window and write the same code value in > printmessage is giving arbitrary or no values. > Nothing in Python returns arbitrary values. If you are getting values that you don't expect, then you're probably not copying this code exactly. Anyway, printmessage doesn't give you any values at all- it just writes self.text to the standard output. > Am I doing any problem in writing the code? > > 2) Suppose I have a code: > def hello(): > print "HELLO SIR" > > Can I write another function where I can call the value of this > function or manipulate it? > What do you mean by the value of the function? Python functions are not mathematical functions- they don't evaluate to a value. You have a function, which is an object. You can pass the function object around just like any other variable. >>> def hello() : ...print "HELLO SIR" ... >>> hello >>> hello() HELLO SIR >>> foo = hello >>> foo() HELLO SIR A function can also return something. But that isn't the value of the function because the function has side effects and can potentially do different things even if you call it with the same arguments. >>> x = iter(['a','b','c']) >>> next(x) 'a' >>> next(x) 'b' >>> next(x) 'c' In your case, your function isn't returning anything. It's just writing text to stdout (a side effect as far as the program is concerned) and then returning nothing. In some languages, such as Java, you'd get an error if you tried storing the return value of a function that doesn't return anything. In Python, you just get the None object. > If any learned member can slightly help me out. > > Thanks in advance, > Best Regards, > Subhabrata. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk/list
You're not really supposed to call into the md5 module directly anymore; you might use hashlib instead. But actually, using a cryptographic hash doesn't really help comparing just one pair of files; it's more certain to do a block by block comparison, and the I/O time is roughly the same - actually, it's less when the files differ. Comparing unbroken cryptographic hashes gives near certainty (md5 is broken), but file compares give certainty. So file compares give slightly greater certainty in less time. But if you're comparing 1,000,000 files, each against all the others, cryptographic hashes help a lot. This example code does lots of file comparisons, including via hashes - the equivs3d version is probably the best example. equivs3d reduces dividing a huge number of files into groups having equal content, to almost an O(n) operation, without assuming the hashes always tell the truth: http://stromberg.dnsalias.org/~strombrg/equivalence-classes.html Also, I believe it's preferred to use open() rather than file(). You could probably avoid writing a list of filenames by doing your comparisons at the same time you do your copies. It doesn't provide quite as strong assurance that way, but it does get rid of the need to save what files were processed. You could also do a second os.walk, but of course, that's subject to issues when one of the trees has been changed by something other than your copying program. Finally... Why not just use rsync or robocopy? On Sat, Mar 19, 2011 at 5:45 PM, ecu_jon wrote: > so i am trying to add md5 checksum calc to my file copy stuff, to make > sure the source and dest. are same file. > i implemented it fine with the single file copy part. something like : > for files in sourcepath: >f1=file(files ,'rb') >try: >shutil.copy2(files, > os.path.join(destpath,os.path.basename(files))) >except: >print "error file" >f2=file(os.path.join(destpath,os.path.basename(files)), 'rb') >truth = md5.new(f1.read()).digest() == > md5.new(f2.read()).digest() >if truth == 0: >print "file copy error" > > this worked swimmingly. i moved on to my backupall function, something > like > for (path, dirs, files) in os.walk(source): >#os.walk drills down thru all the folders of source >for fname in dirs: > currentdir = destination+leftover >try: > os.mkdir(os.path.join(currentdir,fname),0755) >except: >print "error folder" >for fname in files: >leftover = path.replace(source, '') >currentdir = destination+leftover >f1=file(files ,'rb') >try: >shutil.copy2(os.path.join(path,fname), > os.path.join(currentdir,fname)) >f2 = file(os.path.join(currentdir,fname,files)) >except: >print "error file" >truth = md5.new(f1.read()).digest() == > md5.new(f2.read()).digest() >if truth == 0: >print "file copy error" > > but here, "fname" is a list, not a single file.i didn't really want to > spend a lot of time on the md5 part. thought it would be an easy add- > on. i don't really want to write the file names out to a list and > parse through them one a time doing the calc, but it sounds like i > will have to do something like that. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing Pool workers cannot create subprocesses
On 3/19/11 4:17 PM, John L. Stephens wrote: On 3/18/2011 7:54 PM, Jason Grout wrote: Right; thanks. Let me rephrase my questions: 1. Why is important that the multiprocessing Pool worker processors have daemon=True (I think this is the same as asking: why is it important that they be terminated with terminate() rather than join() )? 2. Is it safe for us to reset a Pool worker process to have daemon=False before starting a subprocess from that worker, like in the code from the original message? Thanks, Jason Jason, I just happen to be dealing with a project that uses multiprocessing. What I have learned is this... If a child thread (pool worker) is not set to daemon (daemon=False), if for some reason the parent thread terminates either normally or abnormally and the worker thread has not completed its task, the child thread will terminate by throwing all sorts of nasty errors. However, in daemon mode, multiprocessing will terminate the child thread 'cleanly'. That's not to say that the worker has a chance to complete its work or shut itself down. Multiprocessing will absorb the exceptions and not pass them along. You may terminate a child thread using join(). That is probably the safest way to do it. terminate() will just kill the worker thread immediately without any regard to whether or not it has completed its tasks. I believe multiprocessing uses terminate() as well to kill a daemon thread if the parent thread disappears. join() will, however, block until the task has competed and returned. If you want to continue doing work in the parent thread while the child thread is off doing its thing, then another means of syncing up the parent and children threads is needed. As for allowing children threads to spawn off children of its own using subprocess runs the risk of creating a little army of zombie 'grandchildren' if either the parent or child threads terminate before the subprocess completes and returns. Hope that helps Thanks. That helps tremendously! Jason -- http://mail.python.org/mailman/listinfo/python-list
This algorithm written in Python solves at least a subset of the Hamilton Circuit problem, which is NP complete, in n^3 time.
This algorithm written in Python solves at least a subset of the Hamilton Circuit problem, which is NP complete, in n^3 time. #!/usr/bin/env python # # hamiltoncircuit.python # # Copyright 2011 Martin Musatov # # This program is free software; you may redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope it is useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You may obtain a copy of the GNU General Public License # with this program from the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. // numnodes=10 // // import random // // class allnodes(): // connect = [] // gridpos = [] // initpos = [] // def __init__(self, numnodes): // for i in range(0, numnodes): // self.gridpos.append(i) // self.initpos.append(i) // self.connect.append([]) // // nodes=allnodes(numnodes) // def swapref(n, a, b): // t = nodes.initpos[a] // nodes.initpos[a] = nodes.initpos[b] // nodes.initpos[b] = t // for i in range(0, len(n)): // for j in range(0, len(n[i])): // if n[i][j] == a: // n[i][j] = b // elif n[i][j] == b: // n[i][j] = a // return n // def makeswap(grida, gridb): // ascore = 0 // aswapscore = 0 // bscore = 0 // bswapscore = 0 // if grida > 1 and grida < numnodes-1: // for i in range(0, len(nodes.connect[grida])): // if nodes.connect[grida][i] == grida - 2 or nodes.connect[grida][i] == grida + 2: // ascore+=1 // // elif grida == 0: // for i in range(0, len(nodes.connect[grida])): // if nodes.connect[grida][i] == grida + 1 or nodes.connect[grida][i] == grida + 2: // ascore+=1 // elif grida == 1: // for i in range(0, len(nodes.connect[grida])): // if nodes.connect[grida][i] == grida - 1 or nodes.connect[grida][i] == grida + 2: // ascore+=1 // elif grida == numnodes: // for i in range(0, len(nodes.connect[grida])): // if nodes.connect[grida][i] == grida - 1 or nodes.connect[grida][i] == grida - 2: // ascore+=1 // elif grida == numnodes-1: // for i in range(0, len(nodes.connect[grida])): // if nodes.connect[grida][i] == grida + 1 or nodes.connect[grida][i] == grida - 2: // ascore+=1 // if gridb > 1 and gridb < numnodes-1: // for i in range(0, len(nodes.connect[gridb])): // if nodes.connect[gridb][i] == gridb - 2 or nodes.connect[gridb][i] == gridb + 2: // bscore+=1 // elif gridb == 0: // for i in range(0, len(nodes.connect[gridb])): // if nodes.connect[gridb][i] == gridb + 1 or nodes.connect[gridb][i] == gridb + 2: // bscore+=1 // elif gridb == 1: // for i in range(0, len(nodes.connect[gridb])): // if nodes.connect[gridb][i] == gridb - 1 or nodes.connect[gridb][i] == gridb + 2: // bscore+=1 // elif gridb == numnodes: // for i in range(0, len(nodes.connect[gridb])): // if nodes.connect[gridb][i] == gridb - 1 or nodes.connect[gridb][i] == gridb - 2: // bscore+=1 // elif gridb == numnodes-1: // for i in range(0, len(nodes.connect[gridb])): // if nodes.connect[gridb][i] == gridb + 1 or nodes.connect[gridb][i] == gridb - 2: // bscore+=1 // tempnodes = [] // tempnodes.extend(nodes.connect) // t = tempnodes[grida] // tempnodes[grida]=tempnodes[gridb] // tempnodes[gridb]=t // // if grida > 1 and grida < numnodes-1: // for i in range(0, len(tempnodes[grida])): // if tempnodes[grida][i] == grida - 2 or tempnodes[grida][i] == grida + 2: // aswapscore+=1 // // elif grida == 0: // for i in range(0, len(tempnodes[grida])): // if tempnodes[grida][i] == grida + 1 or tempnodes[grida][i] == grida + 2: // aswapscore+=1 // elif grida == 1: // for i in range(0, len(tempnodes[grida])): // if tempnodes[grida][i] == grida - 1 or tempnodes[grida][i] == grida + 2: // aswapscore+=1 // elif grida == numnodes: // for i in ra
import newer
I begin to study with <> I met a problem with import. first I creat a file hello.py then in fedora /14 I type python to the interpreter >>> import hello Traceback (most recent call last): File "", line 1, in ImportError: No module named hello What should i do now. The current path is not added defaultly ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Some Minor questions on Class and Functions
On Sat, 19 Mar 2011 16:57:58 -0700, joy99 wrote: > Dear Group, > > I am trying to pose two small questions. > > 1) I am using Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v. > 1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" > for more information, on WINXP SP2. > > As I am writing a code for class like the following: IDLE 2.6.5 class Message: > def __init__(self,str1): > self.text="MY NAME" > def printmessage(self): > print self.text > > It works fine as can be seen in the result: x1=Message(1) x1.printmessage() > MY NAME > > Now if I open a new window and write the same code value in printmessage > is giving arbitrary or no values. The description of your problem does not make sense to me. Can you show an example? > 2) Suppose I have a code: > def hello(): > print "HELLO SIR" > > Can I write another function where I can call the value of this function > or manipulate it? No. The string "HELLO SIR" is a local variable to the hello() function. You cannot modify it from outside that function. Since your hello() function prints the result, instead of returning it, another function cannot capture it either. Perhaps what you want is something like this: def hello(message="HELLO SIR"): return message Now you can call the function, and print the result: print hello() If you want to capture the return value, you can: result = hello() print result.lower() If you want to change the message used, you can pass it to the function as an argument: hello("Greetings and salutations!") Hope this helps, -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Distributing Python Program
I have a Python program (which I've "frozen" via py2exe) that I'd like to distribute online, but I'm not sure of the steps to take. My thoughts were to create an account with RegNow or FastSpring, who could accept the payment and offer the download, but I'm unsure as to how you deal with licensing issues (i.e. how do you implement license keys)? I'm only looking to sell the program for around $40, so this is by no means a huge expense to a business - however, I'd like to at least have something in place that would make it a bit more difficult for the software to be pirated (or used above than the paid number of licenses). Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
On 3/10/2011 4:58 PM, Justin Ezequiel wrote: Greetings, We have an old barcode program (MSDOS and source code unavailable.) I've figured out how to populate the fields (by hacking into one of the program's resource files.) However, we still need to hit the following function keys in sequence. F5, F2, F7 Is there a way to pipe said keys into the program? I know it's not really a python problem but I got nowhere else to go. I've tried other barcode solutions but none give the same output. Look into DOSbox. http://www.dosbox.com It's an open-source software emulator for an x86 machine running DOS. So you can go into the emulator and connect to the "keyboard" or "screen" from another program. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Some Minor questions on Class and Functions
On Mar 20, 9:39 am, Steven D'Aprano wrote: > On Sat, 19 Mar 2011 16:57:58 -0700, joy99 wrote: > > Dear Group, > > > I am trying to pose two small questions. > > > 1) I am using Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v. > > 1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" > > for more information, on WINXP SP2. > > > As I am writing a code for class like the following: IDLE 2.6.5 > class Message: > > def __init__(self,str1): > > self.text="MY NAME" > > def printmessage(self): > > print self.text > > > It works fine as can be seen in the result: > x1=Message(1) > x1.printmessage() > > MY NAME > > > Now if I open a new window and write the same code value in printmessage > > is giving arbitrary or no values. > > The description of your problem does not make sense to me. Can you show > an example? > > > 2) Suppose I have a code: > > def hello(): > > print "HELLO SIR" > > > Can I write another function where I can call the value of this function > > or manipulate it? > > No. The string "HELLO SIR" is a local variable to the hello() function. > You cannot modify it from outside that function. Since your hello() > function prints the result, instead of returning it, another function > cannot capture it either. > > Perhaps what you want is something like this: > > def hello(message="HELLO SIR"): > return message > > Now you can call the function, and print the result: > > print hello() > > If you want to capture the return value, you can: > > result = hello() > print result.lower() > > If you want to change the message used, you can pass it to the function > as an argument: > > hello("Greetings and salutations!") > > Hope this helps, > > -- > Steven Thanks Steven and Benjamin for your kind time to answer my question. I am sending the code soon, actual code is pretty long that has so many variables, it may well take your long time to evaluate, so I am making a sizable prototype and trying to send it to you. Best Regards, Subhabrata. -- http://mail.python.org/mailman/listinfo/python-list
Re: class error
On Sun, 20 Mar 2011 00:08:16 +, Rhodri James wrote: > It has to be said that the confusion is exacerbated by ignoring PEP-8 > and using the same (CamelCase) name for the module and the class. That > does provide a rich source of errors in cases like this. It's not so much that UserDict ignores PEP-8, as that it pre-dates PEP-8. -- Steven -- http://mail.python.org/mailman/listinfo/python-list