Re: loose methods : Smalltalk asPython
On Tue, 26 Dec 2006 22:49:30 -0500, Jan Theodore Galkowski wrote: Hi. One of the things I'd like to do with Python is find a way to consistently implement Smalltalk's loose methods. This is a capability whereby additional methods can be added dynamically to existing classes. You can't modify the built-in classes. I'm not sure that it is a good idea to allow built-ins to be modified. When I see an int, I like the fact that I know what the int can do, and I don't have to worry about whether it has been modified by some piece of code elsewhere. But custom classes can be modified (the risk of some other code modifying it is the price you pay for being able to customise the class in the first place): class MyInt(int): ... pass ... def odd(self): ... return bool(self % 2) ... MyInt.odd = odd n = MyInt(5) n.odd() True In some respects, it's possible with Python. While object cannot be touched, it's possible to define class MutableObject( object ) : pass ; and derive subclasses from MutableObject instead of object. Thereafter, for instance, if devising a class class Foo( MutableObject ) : isFoo = True ; ... you can also put in its module MutableObject.isFoo = False ; So, at least for the inheritance hierarchy descending from MutableObject, for an arbitrary object instance x, x.isFoo will return whether it's a Foo or not, effectively although not transparently extending the builtin type(.). Why not just say isinstance(x, Foo)? Like, then, what of other classes which descend from object and not MutableObject? You'd love to be able to set methods and attributes within them. Can you? Yes you can. Did you bother to try it? class Shrubbery(object): ... pass ... Shrubbery.spam = lambda self, n: repr(self) + spam*n Shrubbery().spam(5) '__main__.Shrubbery object at 0xb7d06aecspamspamspamspamspam' -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
File write() problem
Alright, I realize this is probably very basic to be posted on this newsgroup but I cannot figure out what is causing my problem. Here is the code I am using below: from getpass import getpass configfile = file('config.txt', 'w') serverPassword = configfile.readline() if serverPassword == '': print Server warning: No password has been set! pwd1 = getpass(New Password: ) pwd2 = getpass(Confirm Password: ) while pwd1 != pwd2: print Passwords did not match. pwd1 = getpass(New Password: ) pwd2 = getpass(Confirm Password: ) print Password set. Storing to file configfile.write(pwd2) serverPassword = configfile.readline() configfile.close() Now when I look at the file, I can see the password that I had typed in, but there are also a bunch of symbols that are added to the text file as well. My question is how can I write just the password to the text file and not any extra 'garbage'. Thanks! Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Introduction to 3D Graphics Programing
Dear Jon Harrop, Thanks for the informative reply. I don't know OpenGL, but i think it is a low-level crap, and have done the industry huge irreparable damage the same way unix has. This wikipedia excerpt from http://en.wikipedia.org/wiki/QuickDraw_3D summarize my sentiment: «Most 3D toolkits concentrate on the lowest levels of the 3D rendering pipeline... For instance, the OpenGL system consists primarily of a system for describing geometry in various ways... Higher-level concepts of the 3D world are generally not included in low-level libraries... To add to the problems, OpenGL was not truly low-level.. » Note this: « TODAY THERE REMAINS NO STANDARD HIGH-LEVEL API FOR 3D GRAPHICS. Several attempts have been made, including OpenGL++ and the SGI/Microsoft Fahrenheit graphics API, but none of these have made it to production. » -- As a practical example of its low-level problem, i looked at your basic OpenGL tutorial, the minimal program (http://www.ffconsultancy.com/products/ocaml_for_scientists/visualisation/): let () = let argv' = Glut.init Sys.argv in ignore (Glut.createWindow ~title:OpenGL Demo); GlClear.color (0.1, 0.3, 0.1); Glut.displayFunc ~cb:(fun () - GlClear.clear [ `color ]; Gl.flush ()); Glut.mainLoop () Immediately, a extremely intelligent alien who understand advanced programing and geometry in 3D and higher dimensions, but who is not familiar with OpenGL per se, would be facing 6 lines, almost all of it are irrelevant to geometry or the mathematics of programing, but are extraneous concepts created by the system itself . (the exceptions are the “color”, and “clear”) This is in contrast to the Mathematica system or its graphics. For example: http://xahlee.org/3d/mma.html e.g. Graphics3D[{ Cuboid[{0, 0, 0}], Point[{1.5, 1.5,0}], Polygon[{{2, 2, 1}, {2, 1, 1}, {1, 2, 1}}] }] Even if you don't know nothing about Mathematica or never coded a single line of 3d graphics application, the lines above are all very meaningful, as they are inalienable concepts of geometry, not something extraneous as most imperative languages or systems or unix forces upon its users. Note that the above sentiment about OpenGL, is just my sentiment on the overall situation of graphics programing. (and in general the low-level garbage situation applies to almost all imperative languages and vast majority of protocols in the industry.) I don't particular know OpenGL as a low-level graphic system is a good one or not. (but it is probably correct to assume that Microsoft's Direct3D is far more better designed system at the same level) Regarding VisualPython... i saw a demo in 2002 by a professor friend. I think it is good. Though, why is its licensing not GPL or otherwise Open Source? That's kinda odd since Pyhton is. Thanks for your links and tutorials. I find them useful. What i'm looking for, is a system that allows one to easily to graphics programing. By graphics programing, i mean 3d geometric shapes manipulation, as opposed to rendering or implementing CAD systems or how to write photoshop filters or the science of realistic rendering etc as most people are thinking of when hearing the term computer graphics programing. So far as i know, Mathematica is the platform that allows one to do graphics programing. But, i think Flash probably is another platform that does it. And i think VisualPython is also. I'm interested in other platforms that allows one to do this. Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ Jon Harrop wrote: Xah Lee wrote: Introduction to 3D Graphics Programing http://xahlee.org/3d/index.html You will probably find it more rewarding to use a more modern graphics system, such as OpenGL or DirectX, with a suitable programming language rather than Mathematica's. I would recommend any of OCaml, F#, Haskell, Lisp, Scheme, Python or Ruby for graphics, you can do much more sophisticated, animated, real time visualisations than you can with Mathematica's primitives. There are lots of great web pages out there. I've written some 2D and 3D graphics examples in OCaml: http://www.ffconsultancy.com/products/ocaml_for_scientists/visualisation http://www.ffconsultancy.com/free/ray_tracer http://www.ffconsultancy.com/free/fractal http://www.ffconsultancy.com/free/maze and more recently F#: http://www.ffconsultancy.com/dotnet/fsharp I was very impressed with the tutorial videos on VPython at ShowMeDo: http://showmedo.com/videos/series?name=pythonThompsonVPythonSeries For an introduction to OpenGL, look no further than the NeHe tutorials at GameDev: http://nehe.gamedev.net One of our future products at FF Consultancy is a suite of extensions for the F# interactive mode that allows you to visualise 2D and 3D graphics in real time with simplicity rivalling Mathematica but the sophistication and performance of DirectX, whilst also having the power of the F# programming language and .NET to
Re: File write() problem
In [EMAIL PROTECTED], apriebe47 wrote: configfile = file('config.txt', 'w') serverPassword = configfile.readline() Here you open a file for writing and try to read a line. This raises an exception: In [1]: configfile = file('test.txt', 'w') In [2]: configfile.readline() --- exceptions.IOErrorTraceback (most recent call last) /home/marc/ipython console IOError: [Errno 9] Bad file descriptor Please post the exact code you have trouble with. Don't retype it -- copy and paste it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variables in python
buffi [EMAIL PROTECTED] wrote: Is this concidered bad coding practice since I guess persistent variables in functions are not meant to be? There is a problem that this trick only works for functions and not for methods as it assumes that there is a global name through which you can access the function. I think that more significantly is the question how you initialize the value (Lee Harr's decorator does that quite nicely though) or reset it, or have multiple instances each with their own saved value. As soon as you start asking those types of questions it is time to switch to using a class. So in short, yes it is a plausible trick in some situations as a lightweight alternative to a class which has only static state and one method, but if you want a second method or multiple instances you'll want a real class. (And yes, I do realise that by embedding the function with state inside a factory function you can create multiple instances.) Python also provides another lightweight way of saving state between calls. Consider whether your particular use can be written as a generator: def dostuff(): timesused = 0 print First call! while 1: timesused += 1 print Function call, timesused yield timesused fn = dostuff() fn.next() First call! Function call 1 1 fn.next() Function call 2 2 fn.next() Function call 3 3 timesused = fn.next() Function call 4 print timesused 4 -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Introduction to 3D Graphics Programing
Xah Lee wrote: Dear Jon Harrop, Thanks for the informative reply. I don't know OpenGL, but i think it is a low-level crap, and have done the industry huge irreparable damage the same way unix has. OpenGL is low level, that's right, but it is not crap. OpenGL is hardware independent, and is a true multiplatform standard. The difference between OpenGL and higher level libraries, like OpenInventor, it is similar to the difference between a low-level programming language like C and a higher level object-oriented language, IMHO. I don't particular know OpenGL as a low-level graphic system is a good one or not. (but it is probably correct to assume that Microsoft's Direct3D is far more better designed system at the same level) Direct3D it is lower level than OpenGL, and usually needs more instructions than OpenGL to do the same things. -- http://mail.python.org/mailman/listinfo/python-list
Re: File write() problem
Marc 'BlackJack' Rintsch wrote: configfile = file('config.txt', 'w') serverPassword = configfile.readline() Hrm. When I run the code that I posted I don't seem to get those errors. Please post the exact code you have trouble with. Don't retype it -- copy and paste it. from getpass import getpass configfile = file('config.txt', 'w') serverPassword = configfile.readline() if serverPassword == '': print Server warning: No password has been set! pwd1 = getpass(New Password: ) pwd2 = getpass(Confirm Password: ) while pwd1 != pwd2: print Passwords did not match. pwd1 = getpass(New Password: ) pwd2 = getpass(Confirm Password: ) print Password set. Storing to admin/config... configfile.write(pwd2) serverPassword = configfile.readline() configfile.close() Again I tested the code before I posted and I get no errors, just not the result I am looking for in the text file. Thanks for taking the time to look at it. Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: BeautifulSoup bug when found in attribute value
John Nagle [EMAIL PROTECTED] wrote: And this came out, via prettify: addresssnippet siteurl=http%3A//apartmentsapart.com url=http%3A//www.apartmentsapart.com/Europe/Spain/Madrid/FAQ param name=movie value=/images/offersBanners/sw04.swf?binfot=We offer fantastic rates for selected weeks or days!!amp;blinkt=Click here gt;gt;gt;amp;linkurl=/Europe/Spain/Madrid/Apartments/Offer/2408 linkurl;=/Europe/Spain/Madrid/Apartments/Offer/2408 / /param BeautifulSoup seems to have become confused by the within a quoted attribute value. It first parsed it right, but then stuck in an extra, totally bogus line. Note the entity linkurl;, which appears nowhere in the original. It looks like code to handle a missing quote mark did the wrong thing. I don't think I would quibble with what BeautifulSoup extracted from that mess. The input isn't valid HTML so any output has to be guessing at what was meant. A lot of code for parsing html would assume that there was a quote missing and the tag was terminated by the first ''. IE and Firefox seem to assume that the '' is allowed inside the attribute. BeautifulSoup seems to have given you the best of both worlds: the attribute is parsed to the closing quote, but the tag itself ends at the first ''. As for inserting a semicolon after linkurl, I think you'll find it is just being nice and cleaning up an unterminated entity. Browsers (or at least IE) will often accept entities without the terminating semicolon, so that's a common problem in badly formed html that BeautifulSoup can fix. -- http://mail.python.org/mailman/listinfo/python-list
Re: loose methods : Smalltalk asPython
Jan Theodore Galkowski [EMAIL PROTECTED] wrote: Comments? Suggestions? http://www.ruby-lang.org -- Luc Heinrich -- http://mail.python.org/mailman/listinfo/python-list
Re: File write() problem
[EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: Marc 'BlackJack' Rintsch wrote: configfile = file('config.txt', 'w') serverPassword = configfile.readline() Hrm. When I run the code that I posted I don't seem to get those errors. Please post the exact code you have trouble with. Don't retype it -- copy and paste it. from getpass import getpass configfile = file('config.txt', 'w') serverPassword = configfile.readline() if serverPassword == '': print Server warning: No password has been set! pwd1 = getpass(New Password: ) pwd2 = getpass(Confirm Password: ) while pwd1 != pwd2: print Passwords did not match. pwd1 = getpass(New Password: ) pwd2 = getpass(Confirm Password: ) print Password set. Storing to admin/config... configfile.write(pwd2) serverPassword = configfile.readline() configfile.close() Again I tested the code before I posted and I get no errors, just not the result I am looking for in the text file. Thanks for taking the time to look at it. As Marc points out, you are opening the file in write mode and then reading from it. Did you try printing out what gets placed into serverPassword the first time? It may not be what you expect, for starters. But now the file pointer is at the end of the file, and that's where you write the input password. Amazingly, Python lets you do this, but even if you could read back those characters you just wrote by doing a readline() (which might be getting data from the ether by now), the password wouldn't be written over the original, but instead would be on the next line. If your intent is to update a flat file, you can try using seeks and rewinds and such to position the file pointer appropriately, but you'll still be in misery as soon as someone replaces the password G811ploo with ALongerPassword. Flat files aren't databases. You're better off reading the entire file (opened in read mode) into memory and closing it, then re-opening it in write mode and writing out the entire thing with the changed password, replacing the original file. -- rzed ... for some value of better off... -- http://mail.python.org/mailman/listinfo/python-list
Re: Mod_python
Lad wrote: In my web application I use Apache and mod_python. I allow users to upload huge files( via HTTP FORM , using POST method) I would like to store the file directly on a hard disk and not to upload the WHOLE huge file into server's memory first. Can anyone suggest a solution? The only solution you need is Apache and mod_python :) I mean, Apache won't load a huge POST request into its memory no matter what. All file uploads will be stored in temporary files. Under mod_python (provided you use FieldStorage) you'll need to deal only with 'file' objects. -- Maxim Sloyko -- http://mail.python.org/mailman/listinfo/python-list
Re: Fuzzy string comparison
John Machin [EMAIL PROTECTED] wrote: To compare two strings, take copies, and: Taking a copy of a string seems kind of superfluous in Python. -- http://mail.python.org/mailman/listinfo/python-list
Stani's Python Editor is looking for a new webhost
Dear Stani, Very much wishing you a new and great web host for the new year. I feel and read also from so many that you are doing a great service for Python users an d being an example of the Free software movement. i thank you very much and hope you will be back on the web soon. What help do you need now and what kind and level of contributions ( in expertise or lack of it) can we offer. All the best for the new year. markandeya -- http://mail.python.org/mailman/listinfo/python-list
Re: Fuzzy string comparison
Steve Bergman [EMAIL PROTECTED] writes: I'm looking for a module to do fuzzy comparison of strings. I have 2 item master files which are supposed to be identical, but they have thousands of records where the item numbers don't match in various ways. One might include a '-' or have leading zeros, or have a single character missing, or a zero that is typed as a letter 'O'. That kind of thing. These tables currently reside in a mysql database. I was wondering if there is a good package to let me compare strings and return a value that is a measure of their similarity. Kind of like soundex but for strings that aren't words. If you were using PostgreSQL there's a contrib package (pg_trgm) that could help a lot with that. It can show you the distance between two strings based on a trigram comparison. You can see how it works on the README (http://www.sai.msu.su/~megera/postgres/gist/pg_trgm/README.pg_trgm) and maybe port it for your needs. But it probably won't be a one operation only search, you'll have to post process results to decide what to do on multiple matches. -- Jorge Godoy [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Fuzzy string comparison
Duncan Booth wrote: John Machin [EMAIL PROTECTED] wrote: To compare two strings, take copies, and: Taking a copy of a string seems kind of superfluous in Python. You are right, I really meant don't do: original = original.strip().replace().replace() (a strange way of doing things which I see occasionally in other folks' code) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variables in python
There is a problem that this trick only works for functions and not for methods as it assumes that there is a global name through which you can access the function. I didn't really see any issue with this since methods can store the persistant data from the method inside the class containing it :) /buffi -- http://mail.python.org/mailman/listinfo/python-list
Re: loose methods : Smalltalk asPython
Steven D'Aprano: You can't modify the built-in classes. I'm not sure that it is a good idea to allow built-ins to be modified. When I see an int, I like the fact that I know what the int can do, and I don't have to worry about whether it has been modified by some piece of code elsewhere. I think it can be useful, there are many situations where you may need to change the behavior of built-in dicts, etc, but: - You need to keep code sorted and tidy to avoid problems. (This is true for most of Python code too today. For example ObjectPascal gives you less freedom to shoot yourself in the foot.) - Allowing the built-in objects to be dynamically modified like that may slow down the virtual machine some, if you don't design it quite carefully. Psyco can help here too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating over several lists at once
On Dec 13, 3:47 pm, Gal Diskin [EMAIL PROTECTED] wrote: Hi, I am writing a code that needs to iterate over 3 lists at the same time, i.e something like this: for x1 in l1: for x2 in l2: for x3 in l3: print do something with, x1, x2, x3 What I need to do is go over all n-tuples where the first argument is from the first list, the second from the second list, and so on... I was wondering if one could write this more easily in some manner using only 1 for loop. What I mean is something like this: for (x1,x2,x3) in (l1,l2,l3): print do something with, x1, x2, x3 Or maybe like this: for x1 in l1, x2 in l2, x3 in l3: print do something with, x1, x2, x3 However, this code obviously doesn't work... I'd be very happy to receive ideas about how to do this in one loop and with minimal initialization (if at all required). Thanks in advance,Gal Sorry for bumping this thread up. I just got back from a vacation and I had to say thanks to all the people that took the time to answer me. To Maksim - that's not what I meant, I want to iterate over the cartesian product of the lists (all ordered tuples, _not_ the tuple created from the first item in each list, then the tubple created from the second item in each list... as your example does). Thanks, Gal -- http://mail.python.org/mailman/listinfo/python-list
Re: Fuzzy string comparison
On Wed, 27 Dec 2006 02:52:42 -0800, John Machin wrote: Duncan Booth wrote: John Machin [EMAIL PROTECTED] wrote: To compare two strings, take copies, and: Taking a copy of a string seems kind of superfluous in Python. You are right, I really meant don't do: original = original.strip().replace().replace() (a strange way of doing things which I see occasionally in other folks' code) Well, sure it is strange if you call the variable original. But if you don't care about the original, what's so strange about writing this? astring = astring.strip().replace().replace() Why keep the original value of astring around if you no longer need it? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: loose methods : Smalltalk asPython
On Wed, 27 Dec 2006 19:03:12 +1100, Steven D'Aprano [EMAIL PROTECTED] wrote: You can't modify the built-in classes. I'm not sure that it is a good idea to allow built-ins to be modified. When I see an int, I like the fact that I know what the int can do, and I don't have to worry about whether it has been modified by some piece of code elsewhere. I wonder how this is different from any other class. If you see a StringIO or a socket, don't you also expect to know what it can do? But in fact you _do_ have to worry about whether it has been modified, at least according to your argument. Do you often worry about it, though? And if not, has it ever come back to bite you? If so, perhaps more than just built-in classes should be restricted in this way? If not, why should built-ins have the restriction? Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Introduction to 3D Graphics Programing
Xah Lee wrote: Regarding VisualPython... i saw a demo in 2002 by a professor friend. I think it is good. Though, why is its licensing not GPL or otherwise Open Source? That's kinda odd since Pyhton is. You are confusing VPython with Activestate's Visual Python IDE plugin for Visual Studio. From VPython's home page in very bold font - VPython is free and open-source http://www.vpython.org/ -- http://mail.python.org/mailman/listinfo/python-list
USB Missile.
I am trying to create a python version of the MS USB Missile Launcher code for Windows. I am basing it off one designed for linux. I note the following about dependencies: Requirements: - 0. python (=2.3) -Fine 1. libusb (=0.1.2) -Fine, however the windows version has the following note: If you are porting a libusb based program from Unix style systems to Windows, remove all references to the library's global variable usb_busses. Use the function usb_get_busses() instead to get this variable. Global variables in shared libraries (DLLs) do not work on Windows systems across different compilers. 2. pyusb (==0.3.1) python module with patch (to enable kernel detachment) -Fine, besides patch since this does not seem to be windows compatible (patch is hosted at http://scott.weston.id.au/software/pymissile/pyusb-0.3.1-kernel-detach.patch) 3. urwid python module -Fine I am trying to use the following code at http://scott.weston.id.au/software/pymissile/missile.py but with the following lines removed due to the patch above not being applied: self.handle.detachKernelDriver(0) self.handle.detachKernelDriver(1) It loads okay, but gives the following error: Traceback (most recent call last): File C:\Documents and Settings\Bob\Desktop\missile.py, line 367, in ? main(sys.argv[1:]) File C:\Documents and Settings\Bob\Desktop\missile.py, line 361, in main MissileDisplay().main() File C:\Documents and Settings\Bob\Desktop\missile.py, line 156, in main self.ui.run_wrapper(self.run) File C:\Python24\lib\urwid\curses_display.py, line 179, in run_wrapper return fn() File C:\Documents and Settings\Bob\Desktop\missile.py, line 197, in run m.move(MissileDevice.LEFTUP) File C:\Documents and Settings\Bob\Desktop\missile.py, line 83, in move self.dev.handle.controlMsg(0x21, 0x09, self.INITA, 0x02, 0x01) usb.USBError: usb_control_msg: sending control message failed, win error: The de vice does not recognize the command. Does anyone have any ideas of how to solve this error? I thought it might have something to do with busses = usb.busses() in the python, but libusb requiring the function usb_get_busses() to be used to obtain the usb_busses variable. I don't however have much python experience. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
how can I modify an imported variable ?
I've tried this: import MyPackage if MyPackage.aVariable is None: MyPackage.aVariable = True but when I tried to access MyPackage.aVariable from another file (ie through an other import) the value is still None. how can I do this thanks yomgui -- http://mail.python.org/mailman/listinfo/python-list
Re: Mod_python
Maxim Sloyko wrote: Lad wrote: In my web application I use Apache and mod_python. I allow users to upload huge files( via HTTP FORM , using POST method) I would like to store the file directly on a hard disk and not to upload the WHOLE huge file into server's memory first. Can anyone suggest a solution? The only solution you need is Apache and mod_python :) I mean, Apache won't load a huge POST request into its memory no matter what. All file uploads will be stored in temporary files. Under mod_python (provided you use FieldStorage) you'll need to deal only with 'file' objects. Maxim , Thank you for your reply. Here is an example: If a user uploads 100MB file , what will be a consumption of memory, when the upload is complete? Or does it mean that Apache will read a part of a file , store it in a temporary file, then read another part and adds this part to the temporary file and so on until the whole uploaded file is read? Thank you for the reply. Lad -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I modify an imported variable ?
On Wed, 27 Dec 2006 14:50:18 GMT, yomgui [EMAIL PROTECTED] wrote: I've tried this: import MyPackage if MyPackage.aVariable is None: MyPackage.aVariable = True but when I tried to access MyPackage.aVariable from another file (ie through an other import) the value is still None. how can I do this thanks yomgui You have the right idea, but you must have overlooked something. Consider this: [EMAIL PROTECTED]:~$ cat foo.py a = None [EMAIL PROTECTED]:~$ cat bar.py import foo foo.a = 10 [EMAIL PROTECTED]:~$ cat baz.py import bar import foo print foo.a [EMAIL PROTECTED]:~$ python baz.py 10 [EMAIL PROTECTED]:~$ However, think about avoiding this pattern. Instead of using globals to track state, define a class, create an instance, and pass it to the different functions and methods of your program so that they can inspect and mutate it. If you use globals, you will end with code which is harder to unit test and harder to re-use. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Combining C and Python
I found this text about combining C-code with Pyton scripting on the P2P networks in PDF: Python Scripting for Computational Science Hans Petter Langtangen Simula Research Laboratory and Department of Informatics University of Oslo amazon and others have it in print. software for the text is here: http://folk.uio.no/hpl/scripting/ if you want to download the 1st edition from http://folk.uio.no/hpl/scripting/ the password (first word on page 92) is leads (no quotes) -- http://mail.python.org/mailman/listinfo/python-list
newbie question: any better way to write this code?
i want to let a byte array to be xor with some value. but code show below i wrote seems not so .. good..., any better way to write such function? thanks. [code] def xor(buf): bout=[] for i in range(len(buf)): x = ord(buf[i]) x ^= 123 bout.append(chr(x)) return .join(buf) buf = .encode(utf8) buf = xor(buf) -- http://mail.python.org/mailman/listinfo/python-list
M2Crypto running error
Hello, I was install M2Crypto-0.17beta1.win32-py2.4,and when I run it, I get the error: import M2Crypto Traceback (most recent call last): File pyshell#0, line 1, in -toplevel- import M2Crypto File C:\Python24\Lib\site-packages\M2Crypto\__init__.py, line 14, in -toplevel- import __m2crypto ImportError: DLL load failed with error code 182 If anybody know how to solve this problem,please help me!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: any better way to write this code?
On 27 Dec 2006 07:18:22 -0800, neoedmund [EMAIL PROTECTED] wrote: i want to let a byte array to be xor with some value. but code show below i wrote seems not so .. good..., any better way to write such function? thanks. [code] def xor(buf): bout=[] for i in range(len(buf)): x = ord(buf[i]) x ^= 123 bout.append(chr(x)) return .join(buf) buf = .encode(utf8) buf = xor(buf) You can use numarray to do the same thing much more easily: import numarray buf = numarray.array('') buf.tostring() '' (buf ^ 123).tostring() '\x03\x03\x03\x03\x03\x03\x03\x03' In any case, you can at least drop the '.encode(utf8)'. xxx is already a byte string, there is no need to encode it. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
persistant gloabl vars (very newbie) ?
hi all, I'm investigating the possibilities to replace MatLab with Python (+NumPy +SciPy). I'm a very newbie, I just typed my first characters and calculated the sum of 2 and 3 in Python. My application is a Delphi program, for data-acquisition and real-time data analysis. The real-time analysis is done with MatLab, embedded through a OLE coupling. I already found PythonforDelphi which probably helps a lot to make the first steps. But I'm now stumbled about something very basic, which I don't understand. The problem might be due to the IDE I use (PyScripter), but I tried several and they all behave the same. And I expect that the observed behaviour might be very important notch in my final application (blockwise, real time interaction). In MatLab I declare a workspace, in which each variable I declare is automatically global, and can be reached from all views, i.e. from the command line interpreter as well as form the OLE environment, no matter where they are declared. I try to do something similar in Python: - I want to run an initialization part just once - I want to run some testcode often and interactively So the most simple example: #Initialization import time; A = 5; #code under test x=time.time(); # do something time consuming print 1000*(time.time()-x); Now if I run the initialization part, manual line by line in the command line interpreter, I can run the code under test as often as I want. My real initilization code is much larger and therefor very clumsy to run line by line in the command line interpreter. Is there a way to run the initialization code from a script(file) once, to achieve the same effect ? thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: any better way to write this code?
In [EMAIL PROTECTED], neoedmund wrote: i want to let a byte array to be xor with some value. but code show below i wrote seems not so .. good..., any better way to write such function? thanks. def xor(buf): bout=[] for i in range(len(buf)): x = ord(buf[i]) x ^= 123 bout.append(chr(x)) return .join(buf) buf = .encode(utf8) buf = xor(buf) def xor(buf): return ''.join(chr(ord(x) ^ 123) for x in buf) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: any better way to write this code?
neoedmund wrote: i want to let a byte array to be xor with some value. but code show below i wrote seems not so .. good..., any better way to write such function? thanks. [code] def xor(buf): bout=[] for i in range(len(buf)): x = ord(buf[i]) x ^= 123 bout.append(chr(x)) return .join(buf) 'bout' not 'buf', I think. A simple improvement: loop over the characters: def xor2(buf): #... for c in buf: x = ord(c) #... If you want to xor always with the same value you can prepare a lookup map once for every possible input value: _map = dict((chr(i), chr(i ^ 123)) for i in range(256)) def xor3(buf, _map=_map): return .join(_map[c] for c in buf) However, you still have to loop over the characters of buf in Python. Here's a way to move that loop (in the generator expression) into the str.translate() method which is coded in C: _map = .join(chr(i^123) for i in range(256)) def xor4(buf): return buf.translate(_map) Now let's do some measurements: $ python2.5 -m timeit -sfrom xor import xor; s = 'alpha ' * 10 xor(s) 1 loops, best of 3: 87.9 usec per loop $ python2.5 -m timeit -sfrom xor import xor2; s = 'alpha ' * 10 xor2(s) 1 loops, best of 3: 78.4 usec per loop $ python2.5 -m timeit -sfrom xor import xor3; s = 'alpha ' * 10 xor3(s) 1 loops, best of 3: 38.5 usec per loop $ python2.5 -m timeit -sfrom xor import xor4; s = 'alpha ' * 10 xor4(s) 100 loops, best of 3: 1.15 usec per loop But what if you don't know the value to xor with in advance? def xor5(buf, n=123): map = .join(chr(i^123) for i in range(256)) return buf.translate(map) $ python2.5 -m timeit -sfrom xor import xor5; s = 'alpha ' * 10 xor5(s) 1000 loops, best of 3: 221 usec per loop There goes our speed-up. I can think of various ways to remedy that, but if your input strings are long you might not even care: $ python2.5 -m timeit -sfrom xor import xor2; s = 'alpha ' * 1000 xor (s) 100 loops, best of 3: 7.93 msec per loop $ python2.5 -m timeit -sfrom xor import xor5; s = 'alpha ' * 1000 xor (s) 1000 loops, best of 3: 242 usec per loop Peter -- http://mail.python.org/mailman/listinfo/python-list
getting a process's PID
Hello, I am trying to get python to give me the PID of a process (in this case HUB). I have it working, except for the fact that the output includes \012 (newline). Is there a way to ask python not to give me a newline? Python 1.4 (Oct 14 1997) [C] Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam import os g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] Thanks in advanced for any guidance. -- Randomly generated signature Whoever said nothing is impossible never tried slamming a revolving door. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I modify an imported variable ?
hi, your sample code works, but mine doesn't. it must be a multi-thread issue. I am certain that I am modifying MyPackage.aVariable before using it. Both threads are importing MyPackage, but the modification of MyPackage.aVariable is not seen by the other thread. is this possible ? is there a turn around to allow it ? thanks yomgui -- http://mail.python.org/mailman/listinfo/python-list
re: Smalltalk asPython
On Tue, 26 Dec 2006 22:49:30 -0500, Jan Theodore Galkowski wrote: Hi. One of the things I'd like to do with Python is find a way to consistently implement Smalltalk's loose methods. This is a capability whereby additional methods can be added dynamically to existing classes. You can't modify the built-in classes. I'm not sure that it is a good idea to allow built-ins to be modified. When I see an int, I like the fact that I know what the int can do, and I don't have to worry about whether it has been modified by some piece of code elsewhere. Yes, that's the usual reaction on the part of Smalltalk newbies, too. But the point is that the inserting of loose methods are just as much a part of the current module as any other part of it, so the behavior of the classes in the module needs to be understood in the context of the amendments provided by the loose methods. Similarly, the amendment of these fundamental classes by a new class is an effect of the module and if the module is used is understood to be something it does. Also, sometimes adding such a loose method to a built-in class let things be done with reflection easily, such as for int: Perhaps there's an application context where the ordinal nature of ints is more important than their cardinal nature, and such a reflection would allow it to be easily implemented: int.ordinalQuizzle( self ) : return SpecialOrdinalQuizzleClass.ordinalQuizzleRealizer( self ) ; It is considered bad form to amend the behavior of *existing* methods in built-in classes of the class library. Usually, loose methods *add* new function only. But custom classes can be modified (the risk of some other code modifying it is the price you pay for being able to customise the class in the first place): Yes, thank you, Steven, that was the point of my isFoo illustration. [snip] Why not just say isinstance(x, Foo)? And, yes, i know about isinstance(.,.). I was using it purely for easy illustration. Like, then, what of other classes which descend from object and not MutableObject? You'd love to be able to set methods and attributes within them. Can you? Yes you can. Did you bother to try it? Yes, I did, as illustrated above, with the MutableObject class. The point is that you'd like all the intervening classes to inherit the amendment at the root of the hierarchy within having to touch all the lateral intervening classes or without having to redefine the intervening classes. Thus, my concern is probably overstated. All that needs to be done in practice is *know* what are the classes which derive directly from, say, int in a system and insert the loose methods into those, and the rest will follow. It's just that if you can augment object or int, you don't even need to know that. [snip] Thanks for the thoughts. - Jan -- http://mail.python.org/mailman/listinfo/python-list
re: loose methods: Smalltalk asPython
Jan Theodore Galkowski [EMAIL PROTECTED] wrote: Comments? Suggestions? http://www.ruby-lang.org Luc, don't misunderstand: There's nothing at all wrong with Python nor am I suggesting there is. I'm just exploring how far I can go using its dynamic nature. There's no hope of using loose methods in Java. I think Python is very fine although, arguably, because many are approaching it from a Java strong-typing static mindset, I bet the space of design possibilities hasn't been explored thoroughly. We've not had an excellent dynamic OO language since Smalltalk, IMO. Perhaps Ruby is or is not. But I've looked a bit at Ruby, and I like Python more. - Jan -- http://mail.python.org/mailman/listinfo/python-list
popen on windows
I am trying to set off commands on Windows 2003 from python. Specifically, I am trying to use diskpart with a script file (pointed to with path). cmd = [diskpart, /s, path] p = Popen(cmd, shell=True) The script is meant to loop through twice. It will do so if I comment out the Popen call and print cmd instead. But when Popen is called, one disk will be formated, but not the next. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
eldorado [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello, I am trying to get python to give me the PID of a process (in this case HUB). I have it working, except for the fact that the output includes \012 (newline). Is there a way to ask python not to give me a newline? Python 1.4 (Oct 14 1997) [C] Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam import os g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] There's more than one way to do it! (Oh, sorry, that's Perl...) The two most standard ways would be to call strip() on your string to get one sans both leading and trialing whitespace print h.strip() or if you know exactly what you've got (i.e., the newline you don't want is just the last character), you can just get rid of it: h = h[:-1] HTH, -ej -- http://mail.python.org/mailman/listinfo/python-list
Re: How to depress the output of an external module ?
Carl Banks wrote: Carl Banks wrote: [EMAIL PROTECTED] wrote: After some trials I found that put os.close(1) before calling the function will depress the output. In fact, os.close(1) closed standard output, but I don't know how to open it again after the function's execution. Try this: fd = os.dup(1) os.close(1) sys.stdout = os.fdopen(fd) Also, right after closing file descriptor 1, you might want to set it to something so as to eliminate an annoying warning message when Python tries to close it upon termination but finds it already closed. This opens /dev/null and puts it in file descriptor 1 if not there already (the fdz != 1 test might be unnecessary; I don't know if all flavors of Unix always use the lowest available file descriptor). fdz = os.open(/dev/null,os.O_WRONLY) Is it possible that I redirect low level standard output to a file-like object created by cStringIO.StringIO() instead of /dev/null ? if fdz != 1: os.dup2(fdz,1) os.close(fdz) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
Erik Johnson ej at wellkeeper dot com wrote: There's more than one way to do it! (Oh, sorry, that's Perl...) The two most standard ways would be to call strip() on your string to get one sans both leading and trialing whitespace print h.strip() or if you know exactly what you've got (i.e., the newline you don't want is just the last character), you can just get rid of it: h = h[:-1] Or if you don't know for sure it's there, but don't want to lose other whitespace: print h.rstrip('\n') -- http://mail.python.org/mailman/listinfo/python-list
Re: persistant gloabl vars (very newbie) ?
Stef Mientki [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Is there a way to run the initialization code from a script(file) once, to achieve the same effect ? Certainly. This is what Python modules are all about. You should probably read up on those a bit here: http://docs.python.org/tut/node8.html But briefly, probably what you want to do is put some code in a file, say init.py: # init.py X = 3 Y = 5 # A bunch of other stuff And then in your main program, execute from init import * That will take all the module-scoped variables defined in init.py and place them in the namespace of the import statement (whcih could be global, the interactive interpreter, or otherwise) See also the 'global' statement as it relates to modifying global variables in an inner scope. Good luck, -ej -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
On Wed, 27 Dec 2006, Erik Johnson wrote: eldorado [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello, I am trying to get python to give me the PID of a process (in this case HUB). I have it working, except for the fact that the output includes \012 (newline). Is there a way to ask python not to give me a newline? Python 1.4 (Oct 14 1997) [C] Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam import os g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] There's more than one way to do it! (Oh, sorry, that's Perl...) The two most standard ways would be to call strip() on your string to get one sans both leading and trialing whitespace print h.strip() or if you know exactly what you've got (i.e., the newline you don't want is just the last character), you can just get rid of it: h = h[:-1] Thanks for the help, however it doesnt look like those two solutions quite work: g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] h = h[:-1] h [] import string g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() print h.strip() File stdin, line 1 print h.strip() ^ SyntaxError: invalid syntax I looked up the syntax for print and it looks correct (at least to me ;) -- Randomly generated signature You can go anywhere you want if you look serious and carry a clipboard. -- http://mail.python.org/mailman/listinfo/python-list
Re: loose methods: Smalltalk asPython
In article [EMAIL PROTECTED], Jan Theodore Galkowski [EMAIL PROTECTED] wrote: I think Python is very fine although, arguably, because many are approaching it from a Java strong-typing static mindset, I bet the space of design possibilities hasn't been explored thoroughly. We've not had an excellent dynamic OO language since Smalltalk, IMO. Perhaps Ruby is or is not. But I've looked a bit at Ruby, and I like Python more. Guido was opposed to modifying builtin types before Java existed. It's similar to his opposition to dynamic syntax. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ I support family values -- Addams family values --www.nancybuttons.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Noobie: Open file - read characters multiply
Thanks to all that responded. I chose a modified version of Scott's second recommendation: time = line[:8] decoded_File.write( '%00.4f' % (int(time, 16) * .0001) + ', ') 'print ' added a CRLF that I didn't need, so I went with '.print' (I need to process about 20 values from the remaining bytes). Thank you. On 12/26/06, Scott David Daniels [EMAIL PROTECTED] wrote: ... Any help is really appreciated. for line in AP_file: print decoded_File, '%s.%04d' % divmod(int(line[:8], 16), 1 ), line[9:].rstrip() or: for line in AP_file: print decoded_File, '%.4f' % (int(line[:8], 16) * .0001 ), line[9:].rstrip() ... -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
eldorado [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] h = h[:-1] h [] Oh, sorry... h is a list here because you are using readlines(). I am used to doing this: fd = os.popen('ps -ef | grep python') s = fd.read() to get a single string. You can do something like s = h[0] and then operate on s, or you can use read() in place of readlines() to get h as a single string, or you can operate on the first element of h: h = ['87334\012'] h[0][:-1] '87334' h[0].rstrip('\n') '87334' All the error handling to do in the case where you actually have multiple processes being matched is up to you. ;) -ej -- http://mail.python.org/mailman/listinfo/python-list
Re: persistant gloabl vars (very newbie) ?
Erik Johnson ej at wellkeeper dot com (EJ) wrote: EJ But briefly, probably what you want to do is put some code in a file, say EJ init.py: EJ # init.py EJ X = 3 EJ Y = 5 EJ # A bunch of other stuff EJ And then in your main program, execute EJ from init import * EJ That will take all the module-scoped variables defined in init.py and place EJ them in the namespace of the import statement (whcih could be global, the EJ interactive interpreter, or otherwise) This way of saying it is slightly wrong or misleading. It does not place the global variables of init.py in the importing module in the same way as most other programming languages use this concept. Rather it makes new bindings in the importing module with the same names and the same values as in the original module. So they are new variables with the same values. If in the importing module e.g. you say X = 4, this will change the value of X in the importing module, but not in the init module, nor in any other module that has done 'from init import *'. If you want that kind of behaviour it is better to use: 'import init' and refer to the variables as init.X and init.Y so that you can change them. Whether that is a good idea is another matter. There are other reasons for not using the from init import * form, as you might overwrite bindings in the module in an unforseen way. from init import X,Y explicitely is probably safer. And, by the way, from init import * can only be used at module level, not in inner namespaces. -- Piet van Oostrum [EMAIL PROTECTED] URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I modify an imported variable ?
actually, it is not linked to threading but to the scope. the second attempt to access MyPackage.aVariable is inside the __init__ of a class and this seems to be the problem. I believe it is a genuine python bug. yomgui -- http://mail.python.org/mailman/listinfo/python-list
Re: BeautifulSoup bug when found in attribute value
Duncan Booth wrote: John Nagle [EMAIL PROTECTED] wrote: And this came out, via prettify: addresssnippet siteurl=http%3A//apartmentsapart.com url=http%3A//www.apartmentsapart.com/Europe/Spain/Madrid/FAQ param name=movie value=/images/offersBanners/sw04.swf?binfot=We offer fantastic rates for selected weeks or days!!amp;blinkt=Click here gt;gt;gt;amp;linkurl=/Europe/Spain/Madrid/Apartments/Offer/2408 linkurl;=/Europe/Spain/Madrid/Apartments/Offer/2408 / /param BeautifulSoup seems to have become confused by the within a quoted attribute value. It first parsed it right, but then stuck in an extra, totally bogus line. Note the entity linkurl;, which appears nowhere in the original. It looks like code to handle a missing quote mark did the wrong thing. I don't think I would quibble with what BeautifulSoup extracted from that mess. The input isn't valid HTML so any output has to be guessing at what was meant. A lot of code for parsing html would assume that there was a quote missing and the tag was terminated by the first ''. IE and Firefox seem to assume that the '' is allowed inside the attribute. BeautifulSoup seems to have given you the best of both worlds: the attribute is parsed to the closing quote, but the tag itself ends at the first ''. As for inserting a semicolon after linkurl, I think you'll find it is just being nice and cleaning up an unterminated entity. Browsers (or at least IE) will often accept entities without the terminating semicolon, so that's a common problem in badly formed html that BeautifulSoup can fix. It's worse than that. Look at the last line of BeautifulSoup output: linkurl;=/Europe/Spain/Madrid/Apartments/Offer/2408 / That / doesn't match anything. We're outside a tag at that point. And it was introduced by BeautifulSoup. That's both wrong and puzzling; given that this was created from a parse tree, that type of error shouldn't ever happen. This looks like the parser didn't delete a string item after deciding it was actually part of a tag. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variables in python
That's a matter of taste. Try replacing the try...except block with hasattr: def doStuff(): if hasattr(doStuff, timesUsed): doStuff.timesUsed += 1 else: doStuff.timesUsed = 1 do_common_code Ok, it is a matter of taste and I prefer the try/except way, but with hasattr you will do a function call and a intern 'truthness' verification each time you increment .timeUsed. With try/except, after the first time, you do nothing else than increment it. -- http://mail.python.org/mailman/listinfo/python-list
DOS, UNIX and tabs
Hi, I have a python script on a unix system that runs fine. I have a python script on a windows system that runs fine. Both use tabs to indent sections of the code. I now want to run them on the same system, actually in the same script by combining bits and pieces. But whatever I try my windows tabs get converted to spaces when I transfer it to the unix system and the interpreter complains that the indentation style is not consistant throughout the file. Short of going through 350 lines of code and manually replacing spaces with tabs what an I do? I'm thinking there surely must be a simple solution I have missed here! Cheers, Ben -- http://mail.python.org/mailman/listinfo/python-list
DOS, UNIX and tabs
Hi, I have a python script on a unix system that runs fine. I have a python script on a windows system that runs fine. Both use tabs to indent sections of the code. I now want to run them on the same system, actually in the same script by combining bits and pieces. But whatever I try my windows tabs get converted to spaces when I transfer it to the unix system and the interpreter complains that the indentation style is not consistent throughout the file. Short of going through 350 lines of code and manually replacing spaces with tabs what an I do? I'm thinking there surely must be a simple solution I have missed here! Cheers, Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I modify an imported variable ?
On Wed, 2006-12-27 at 18:10 +, yomgui wrote: actually, it is not linked to threading but to the scope. the second attempt to access MyPackage.aVariable is inside the __init__ of a class and this seems to be the problem. I believe it is a genuine python bug. Please post a minimal but complete (runnable) example that demonstrates your problem. That way, we'll have a chance to actually figure out what you're doing wrong. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS, UNIX and tabs
I've found the unexpand command, which seems to do the trick. However, it outputs to standard output, and I haven't worked out yet how to capture that output to a file... Ben Ben wrote: Hi, I have a python script on a unix system that runs fine. I have a python script on a windows system that runs fine. Both use tabs to indent sections of the code. I now want to run them on the same system, actually in the same script by combining bits and pieces. But whatever I try my windows tabs get converted to spaces when I transfer it to the unix system and the interpreter complains that the indentation style is not consistent throughout the file. Short of going through 350 lines of code and manually replacing spaces with tabs what an I do? I'm thinking there surely must be a simple solution I have missed here! Cheers, Ben -- http://mail.python.org/mailman/listinfo/python-list
Passing variable number of named arguments
Hi, I need to process few out of a variable number of named arguments in a function and pass the remaining to another function that also takes variable number of named arguments. Consider this simple example, def fun1(**kwargs): print kwargs.keys() def fun2(**kwargs): # get id param id = kwargs.pop('id', '') # pass on remaining to fun1 fun1(kwargs) When I try to call fun2 I get the following error- TypeError: fun1() takes exactly 0 arguments (1 given) It seems that the arguments are not passed to fun1 as named arguments. How can I go about this? Using a dictionary in place of kwargs would be a way, but I can't modify fun1, so thats ruled out for me. Thanks, Ram -- http://mail.python.org/mailman/listinfo/python-list
Re: BeautifulSoup bug when found in attribute value
John Nagle [EMAIL PROTECTED] wrote: It's worse than that. Look at the last line of BeautifulSoup output: linkurl;=/Europe/Spain/Madrid/Apartments/Offer/2408 / That / doesn't match anything. We're outside a tag at that point. And it was introduced by BeautifulSoup. That's both wrong and puzzling; given that this was created from a parse tree, that type of error shouldn't ever happen. This looks like the parser didn't delete a string item after deciding it was actually part of a tag. The / was in the original input that you gave it: param name=movie value=/images/offersBanners/sw04.swf?binfot=We offer fantastic rates for selected weeks or days!!blinkt=Click here linkurl=/Europe/Spain/Madrid/Apartments/Offer/2408 / You don't actually *have* to escape when it appears in html. As I said before, it looks like BeautifulSoup decided that the tag ended at the first although it took text beyond that up to the closing as the value of the attribute. The remaining text was then simply treated as text content of the unclosed param tag. Finally it inserted a /param to close the unclosed param tag. ... some time later ... Ok, it looks like I was wrong and this is a bug in BeautifulSoup: it seems that it *is* legal to have an unescaped in an attribute value, although it should (not must) be escaped: From the HTML 4.01 spec: Similarly, authors should use gt; (ASCII decimal 62) in text instead of to avoid problems with older user agents that incorrectly perceive this as the end of a tag (tag close delimiter) when it appears in quoted attribute values. Thank you, it looks like I just learned something new. Mind you, the sentence before that says 'should' for quoting characters which is just plain silly. -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS, UNIX and tabs
On 2006-12-27, Ben [EMAIL PROTECTED] wrote: I've found the unexpand command, which seems to do the trick. However, it outputs to standard output, and I haven't worked out yet how to capture that output to a file... unexpand file1 file2 -- Grant Edwards grante Yow! Hey, LOOK!! A pair of at SIZE 9 CAPRI PANTS!! They visi.comprobably belong to SAMMY DAVIS, JR.!! -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS, UNIX and tabs
Great - that worked.Thanks! Is that a general method in linux you can always use to redirect standard output to a file? Cheers, Ben Grant Edwards wrote: On 2006-12-27, Ben [EMAIL PROTECTED] wrote: I've found the unexpand command, which seems to do the trick. However, it outputs to standard output, and I haven't worked out yet how to capture that output to a file... unexpand file1 file2 -- Grant Edwards grante Yow! Hey, LOOK!! A pair of at SIZE 9 CAPRI PANTS!! They visi.comprobably belong to SAMMY DAVIS, JR.!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing variable number of named arguments
On Wed, 2006-12-27 at 10:37 -0800, Ramashish Baranwal wrote: [...] def fun2(**kwargs): # get id param id = kwargs.pop('id', '') # pass on remaining to fun1 fun1(kwargs) When I try to call fun2 I get the following error- TypeError: fun1() takes exactly 0 arguments (1 given) It seems that the arguments are not passed to fun1 as named arguments. You have to call fun1 like this: fun1(**kwargs). -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS, UNIX and tabs
On 2006-12-27, Ben [EMAIL PROTECTED] wrote: I've found the unexpand command, which seems to do the trick. However, it outputs to standard output, and I haven't worked out yet how to capture that output to a file... unexpand file1 file2 Great - that worked.Thanks! Is that a general method in linux you can always use to redirect standard output to a file? Yup. The operator redirects stdin, the operator redirects stdout. 2 redirects stderr. -- Grant Edwards grante Yow! Let's go to CHURCH! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Introduction to 3D Graphics Programing
[Followup-To: header set, but it's best not to followup at all.] On 2006-12-27, Raff [EMAIL PROTECTED] wrote: Xah Lee wrote: I don't know OpenGL, but i think it is a low-level crap, and have done ^^^ the industry huge irreparable damage the same way unix has. OpenGL is low level, that's right, but it is not crap. Whether it is or not, Xah doesn't know and doesn't care, as he is a troll (and anyone who would say I don't know X but it's crap is definitely either clueless or trolling). Please don't pay attention to his rants. --keith -- [EMAIL PROTECTED] (try just my userid to email me) AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt see X- headers for PGP signature information -- http://mail.python.org/mailman/listinfo/python-list
Re: Fuzzy string comparison
Thanks, all. Yes, Levenshtein seems to be the magic word I was looking for. (It's blazingly fast, too.) I suspect that if I strip out all the punctuation, etc. from both the itemnumber and description columns, as suggested, and concatenate them, pairing the record with its closest match in the other file, it ought to be pretty accurate. Obviously, the final decision will be up to a human being, but this should help them quite a bit. BTW, excluding all the items that match exactly, I only have 8000 items in one file to compare to 2600 in the other. As fast as python-levenshtein seems to be, this should finish in well under a minute. Thanks again. -Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS, UNIX and tabs
Ben [EMAIL PROTECTED] typed I have a python script on a windows system that runs fine. Both use tabs to indent sections of the code. Just a tip for you: In python you never use tabs for indentation. The python style guide [1] recommends four spaces per indentation level. [1] http://www.python.org/dev/peps/pep-0008/ -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
On Wed, 27 Dec 2006, Erik Johnson wrote: eldorado [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] h = h[:-1] h [] Oh, sorry... h is a list here because you are using readlines(). I am used to doing this: fd = os.popen('ps -ef | grep python') s = fd.read() to get a single string. You can do something like s = h[0] and then operate on s, or you can use read() in place of readlines() to get h as a single string, or you can operate on the first element of h: h = ['87334\012'] h[0][:-1] '87334' h[0].rstrip('\n') '87334' All the error handling to do in the case where you actually have multiple processes being matched is up to you. ;) Erik, Thank you very much. Works perfect. I am now off to work on the multiple process issue. -- Randomly generated signature Claiming that your operating system is the best in the world because more people use it is like saying McDonalds makes the best food in the world. -- http://mail.python.org/mailman/listinfo/python-list
Re: persistant gloabl vars (very newbie) ?
other module that has done 'from init import *'. If you want that kind of behaviour it is better to use: 'import init' and refer to the variables as init.X and init.Y so that you can change them. Whether that is a good idea is another matter. There are other reasons for not using the from init import * form, as you might overwrite bindings in the module in an unforseen way. from init import X,Y explicitely is probably safer. And, by the way, from init import * can only be used at module level, not in inner namespaces. thank you guys, but it's still not quit handy # initialization file (init1.py) import time; xx = 44 # main file was print xx x=time.time() # main file should become print init1.xx x=init1.time.time() so even for the standard functions like time I've to include the preceeding module init1 :-( cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating over several lists at once
Gal Diskin [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Dec 13, 3:47 pm, Gal Diskin [EMAIL PROTECTED] wrote: Hi, I am writing a code that needs to iterate over 3 lists at the same time, i.e something like this: for x1 in l1: for x2 in l2: for x3 in l3: print do something with, x1, x2, x3 What I need to do is go over all n-tuples where the first argument is from the first list, the second from the second list, and so on... I don't see your previous article. Not sure if you are still looking for a solution, but here's one: [(x, y, z) for x in [1,2,3] for y in list('abc') for z in list('XY')] [(1, 'a', 'X'), (1, 'a', 'Y'), (1, 'b', 'X'), (1, 'b', 'Y'), (1, 'c', 'X'), (1, 'c', 'Y'), (2, 'a', 'X'), (2, 'a', 'Y'), (2, 'b', 'X'), (2, 'b', 'Y'), (2, 'c', 'X'), (2, 'c', 'Y'), (3, 'a', 'X'), (3, 'a', 'Y'), (3, 'b', 'X'), (3, 'b', 'Y'), (3, 'c', 'X'), (3, 'c', 'Y')] This is a bit more compact, but I don't see anything wrong with what you have. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
eldorado [EMAIL PROTECTED] typed Hello, I am trying to get python to give me the PID of a process (in this case HUB). I have it working, except for the fact that the output includes \012 (newline). Is there a way to ask python not to give me a newline? Python 1.4 (Oct 14 1997) [C] Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam import os g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] Thanks in advanced for any guidance. Well, you could do everything in python itself, without using grep and awk at all: g = os.popen(ps -e -o pid,command) for line in g.readlines(): if 'HUB' in line: pid = line.strip().split(' ')[0] break print pid -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating over several lists at once
In article [EMAIL PROTECTED], Gal Diskin [EMAIL PROTECTED] wrote: Hi, I am writing a code that needs to iterate over 3 lists at the same time, i.e something like this: for x1 in l1: for x2 in l2: for x3 in l3: print do something with, x1, x2, x3 What I need to do is go over all n-tuples where the first argument is from the first list, the second from the second list, and so on... Take a look at http://mail.python.org/pipermail/python-list/2001-September/104983.html or http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975 There's nothing magic about either -- fundamentally, you're still doing an N^3 operation and it's going to be slow. You might want to stop and think if there's some better algorithm than an exhaustive search of the entire domain space for whatever it is that you're trying to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
On Wed, 27 Dec 2006, Sebastian 'lunar' Wiesner wrote: eldorado [EMAIL PROTECTED] typed Hello, I am trying to get python to give me the PID of a process (in this case HUB). I have it working, except for the fact that the output includes \012 (newline). Is there a way to ask python not to give me a newline? Python 1.4 (Oct 14 1997) [C] Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam import os g = os.popen(ps -ef | grep HUB | grep -v grep | awk '{ print $2 }') h = g.readlines() g.close() h ['87334\012'] Thanks in advanced for any guidance. Well, you could do everything in python itself, without using grep and awk at all: g = os.popen(ps -e -o pid,command) for line in g.readlines(): if 'HUB' in line: pid = line.strip().split(' ')[0] break print pid This looks cleaner than the way I was going. I created a file called ps.py #!/usr/local/bin/python import os g = os.popen(ps -e -o pid,command) for line in g.readlines(): if 'HUB' in line: pid = line.strip().split(' ')[0] break print pid When I run ps.py I get the following error. Traceback (innermost last): File ./ps.py, line 5, in ? if 'HUB' in line: TypeError: string member test needs char left operand I googled this error, but wasn't smart enough to figure out exactly what it means. -- Randomly generated signature On the other hand, the early worm gets eaten. -- http://mail.python.org/mailman/listinfo/python-list
Superclass for Errors?
I have a program which has a GUI front-end which that runs a separate thread to handle all the important stuff. However, if there is a problem with the important stuff, I want the GUI to raise a MessageBox alert to indicate this. For exceptions, I can simply use a catch-all except statement like: try: ... except Exception, error: JOptionPane.showMessageDialog(self, Error: %s % error) Only, I want it to catch Errors as well. Right now, I'm using: try: ... except (Exception, TypeError, NameError, RuntimeError, AttributeError), error: JOptionPane.showMessageDialog(self, Error: %s % error) I was wondering if there is a superclass for TypeError, NameError, RuntimeError, AttributeError, etc. Normally, I could simply use a regular except: but then I don't have access to the error message. So what's the best solution to this problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
eldorado [EMAIL PROTECTED] typed [snip] This looks cleaner than the way I was going. I created a file called ps.py #!/usr/local/bin/python import os g = os.popen(ps -e -o pid,command) for line in g.readlines(): if 'HUB' in line: pid = line.strip().split(' ')[0] break print pid When I run ps.py I get the following error. Traceback (innermost last): File ./ps.py, line 5, in ? if 'HUB' in line: TypeError: string member test needs char left operand Strange!? On my system with Python 2.4 I don't get this error. It is likely to be a problem of your really ancient python version. Do I guess correctly from your previous postings, that you're still using version 1.4?. The only thing, you could advice you to, is to replace the line with the following code, which should do very much the same thing: if line.find('HUB') -1: If you are really using version 1.4, you should replace the next line, too, because string methods came after 1.4: pid = string.split(string.strip(line), ' ')[0] Bye Sebastian Wiesner -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to suppress the output of an external module ?
Scott David Daniels wrote: [EMAIL PROTECTED] wrote: Hi, I'm writing a program which uses an external module written in C and calls a function provided by the module to do my job. The function produces a lot of output to the stdout. Is there a way to suppress the output produced by the function and hence make my program run faster? It's too complicated for me to modify the source code and recompile the external module. This would be the best method, you could define printf and fprintf macros that would eliminate the output code altogether. Any hints will be greatly appreciated. Well, it will depend on your OS, but the trick is to essentially replace the C stdout channel with a file which has been opened to write to /dev/null or NUL.txt (unix and Windows respectively). You'll need to first copy the channel to another so you can use it again after the function is done (a system call). Next do the raw open (which should get the available channel), and the C stdout stuff is successfully redirected. Once done w/ your function, close your new stdout and copy the channel back. In Windows the null device is, strictly speaking, nul or nul:, not nul.txt, but the latter appears to work too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Superclass for Errors?
tac-tics [EMAIL PROTECTED] writes: I have a program which has a GUI front-end which that runs a separate thread to handle all the important stuff. However, if there is a problem with the important stuff, I want the GUI to raise a MessageBox alert to indicate this. For exceptions, I can simply use a catch-all except statement like: try: ... except Exception, error: JOptionPane.showMessageDialog(self, Error: %s % error) Only, I want it to catch Errors as well. Right now, I'm using: try: ... except (Exception, TypeError, NameError, RuntimeError, AttributeError), error: JOptionPane.showMessageDialog(self, Error: %s % error) I was wondering if there is a superclass for TypeError, NameError, RuntimeError, AttributeError, etc. See http://rgruet.free.fr/PQR25/PQR2.5.html#BuiltInExc I would guess you're looking for StandardError. -- Christian Joergensen | Linux, programming or web consultancy http://www.razor.dk | Visit us at: http://www.gmta.info -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
On Wed, 27 Dec 2006, Sebastian 'lunar' Wiesner wrote: eldorado [EMAIL PROTECTED] typed Strange!? On my system with Python 2.4 I don't get this error. It is likely to be a problem of your really ancient python version. Do I guess correctly from your previous postings, that you're still using version 1.4?. Sebastian, Yes, I was running this on a box that had 1.4 - I just tested it on a box that has 2.3.5 and it runs perfect. Your changes also allow it to be run on the boxes that still have 1.4 Thanks for all your help. -- Randomly generated signature I have opinions of my own -- strong opinions --but I don't always agree with them.-G.W.Bush -- http://mail.python.org/mailman/listinfo/python-list
Re: Superclass for Errors?
On Wed, 2006-12-27 at 12:13 -0800, tac-tics wrote: I have a program which has a GUI front-end which that runs a separate thread to handle all the important stuff. However, if there is a problem with the important stuff, I want the GUI to raise a MessageBox alert to indicate this. For exceptions, I can simply use a catch-all except statement like: try: ... except Exception, error: JOptionPane.showMessageDialog(self, Error: %s % error) Only, I want it to catch Errors as well. Right now, I'm using: try: ... except (Exception, TypeError, NameError, RuntimeError, AttributeError), error: JOptionPane.showMessageDialog(self, Error: %s % error) I was wondering if there is a superclass for TypeError, NameError, RuntimeError, AttributeError, etc. Yes, that superclass is Exception: for klass in (TypeError, NameError, RuntimeError, AttributeError): ... print klass, issubclass(klass, Exception) ... exceptions.TypeError True exceptions.NameError True exceptions.RuntimeError True exceptions.AttributeError True Have you encountered many TypeError, NameError, RuntimeError or AttributeError exceptions that except Exception by itself failed to catch? -Carsten -- http://mail.python.org/mailman/listinfo/python-list
ANN: Skimpy CAPTCHA adds WAVE audio, and a problem
SKIMPY CAPTCHA ADDS AUDIO, AND A PROBLEM [or what I did over xmas weekend at the inlaws -- python/web/audio experts skip to the bottom and solve my problem please.] Skimpy Gimpy CAPTCHA now supports WAVE audio output to help people with visual impairments answer Skimpy challenges. Read more, try it out, download it here: http://skimpygimpy.sourceforge.net Skimpy is a tool for generating HTML visual and WAVE audio representations for strings which people can understand but which web robots and other computer programs will have difficulty understanding. Skimpy is an example of a Captcha: an acronym for Completely Automated Public Turing test to tell Computers and Humans Apart. The visual HTML Skimpy program skimpyGimpy.py and API (applications programmer interface) is implemented in a single self contained Python script (module). The input for Skimpy are words or phrases. The output of the program and API are strings containing HTML preformatted text. The preformatted text contains ASCII art representing the input phrase, which looks like somewhat sloppy handwriting on a speckled page, when viewed in an HTML browser. It is intended that it is easy for a human to read the word or phrase when rendered as HTML, but it is difficult for a program to extract the word or phrase automatically. The program uses a number of techniques to make the output difficult for a computer to interpret: curve interpolation, random rotation, random skew, random scale adjustment, smearing, and addition of noise. In order to allow CAPTCHA tests that are usable by people with visual empairment, Skimpy also provides an audio implementation. The audio WAVE Skimpy program waveTools.py uses a compiled audio sample file waveIndex.zip. The input of the program are words or phrases and the output are the words or phrases spelled as individual spoken characters in an audio stream. It is intended that a human can understand the audio stream but a computer program will not be able to analyse the stream and extract the letters. To make the audio stream more difficult to automatically analyse (without making it unintelligible) the program randomly overlaps and stretches/shrinks the input samples, among other things. The Skimpy tools are far easier to install, use, and embed than other similar technologies. THE PROBLEM Unfortunately there is a problem with using Firefox and Quicktime with the Skimpy audio. If you save the audio to a temporary file and stream from there everything works fine, but if you try to stream directly from the CGI or mod-python module via HTTP Quicktime TRUNCATES THE AUDIO TO ABOUT 3 SECONDS. This ONLY happens under Firefox afaik -- IE, for example has no problems. Am I doing something wrong? Please inform. The skimpygimpy1.1 download has all the relevant source code if you'd like to have a look. Help! Thanks in advance. I'm leaving the bug demonstrated in my sample web scripts for now, but if no one comes up with a fix I will hack around it in a few days... probably... -- Aaron Watters === Later on, we'll perspire as we stare at the fire and face so afraid the bills left unpaid walking in a winter wonderland -- seen in For Better or Worse -- http://mail.python.org/mailman/listinfo/python-list
Re: Mod_python
Lad wrote: Maxim Sloyko wrote: Lad wrote: In my web application I use Apache and mod_python. I allow users to upload huge files( via HTTP FORM , using POST method) I would like to store the file directly on a hard disk and not to upload the WHOLE huge file into server's memory first. Can anyone suggest a solution? The only solution you need is Apache and mod_python :) I mean, Apache won't load a huge POST request into its memory no matter what. All file uploads will be stored in temporary files. Under mod_python (provided you use FieldStorage) you'll need to deal only with 'file' objects. Maxim , Thank you for your reply. Here is an example: If a user uploads 100MB file , what will be a consumption of memory, when the upload is complete? Or does it mean that Apache will read a part of a file , store it in a temporary file, then read another part and adds this part to the temporary file and so on until the whole uploaded file is read? Thank you for the reply. Lad Are you working on *nix? Try this from the shell on your server: $ top Then upload a 100MB file and watch the memory usage. On Windows, I think you can do similar from Ctrl-Alt-Del, but graphically. Correct me if I'm wrong. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
re: loose methods: Smalltalk asPython
Guido was opposed to modifying builtin types before Java existed. It's similar to his opposition to dynamic syntax. Opposition or not, the language definition is there. Surely Smalltalk's OO style can be respected. Smalltalkers have been doing OO in a dynamic context longer than many. There are things to learn there. There are two things here that need to be kept straight, I think. One is the primacy of builtin types. The other is placing those builtins at the top of their own object hierarchy. Is int, properly speaking, a descendent of object? No, it's the root of its own tree. Smalltalk has int as well, as a *subclass* of Number. It's primitive. In any case, as respectful of Mr/Dr van Rossum as I am, simply because so-and-so says something is bad and therefore it must be true is a fallacious response. -- Jan -- http://mail.python.org/mailman/listinfo/python-list
urllib.urlopen unwanted password prompts - documentation problem
If you try to open a password protected page with urllib.urlopen(), you get Enter username for EnterPassword at example.com: on standard output, followed by a read for input! This seems to be an undocumented feature, if not a bug. Definitely the documentation for urllib should mention this. The effects of this in a CGI program are not good. A workaround is described here: http://cis.poly.edu/cs912/urlopen.txt; URLopener and FancyURLopener in urllib have many overrideable functions, none of which are documented at python.org and should be. There was once documentation at http://epydoc.sourceforge.net/stdlib/public/urllib.FancyURLopener-class.html but its current status is: An error has been encountered in accessing this page. 1. Server: epydoc.sourceforge.net 2. URL path: /stdlib/public/urllib.FancyURLopener-class.html 3. Error notes: File does not exist: /home/groups/e/ep/epydoc/htdocs/stdlib/public/urllib.FancyURLopener-class.html 4. Error type: 404 5. Request method: GET 6. Request query string: 7. Time: 2006-12-27 13:18:11 PST (1167254291) Reporting this problem: The problem you have encountered is with a project web site hosted by SourceForge.net. This issue should be reported to the SourceForge.net-hosted project (not to SourceForge.net). John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Feasible in Python ? list of object , with two exeptional objects
Is the following intuitively feasible in Python: I have an array (I come from C) of identical objects, called sections. These sections have some feature, say a length, measured in mm, which is calculated by a method A_length of the instantiation of the Section's class. Only, two elements in the array (or list ?) have a length that must be calculated according to a totally different procedure, a different function or method. After calculation of ALL the lengths, they must be added together and output. The calculation procedure screams for a FOR or a WHILE loop allong the list of sections, only those two sections mentioned make life difficult. I was thinking along the line of building a class Section, instantiate a list of objects of this class, and then replace 2 of the elements of the list by instantiations of the special class... Or maybe replace only the method in question by the special method... It would be neat, if I could just walk the FOR loop, constructing the list and calculate the total length in one go... Concretely, the situation is a Plone site that passes user section data to a Python / C server-side to do calculations on the section data and return the result over the web. -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Introduction to 3D Graphics Programing
Here's their license: http://www.vpython.org/webdoc/visual/license.txt I read it wrong before. Thanks for correction. This is superb! I'll be looking into vpython! Xah Ravi Teja wrote: Xah Lee wrote: Regarding VisualPython... i saw a demo in 2002 by a professor friend. I think it is good. Though, why is its licensing not GPL or otherwise Open Source? That's kinda odd since Pyhton is. You are confusing VPython with Activestate's Visual Python IDE plugin for Visual Studio. From VPython's home page in very bold font - VPython is free and open-source http://www.vpython.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I modify an imported variable ?
At Wednesday 27/12/2006 13:45, yomgui wrote: your sample code works, but mine doesn't. it must be a multi-thread issue. I am certain that I am modifying MyPackage.aVariable before using it. Both threads are importing MyPackage, but the modification of MyPackage.aVariable is not seen by the other thread. is this possible ? Put some print statements and see what happens. I'm sure things are a lot simpler than you think. You said a module, but now you use MyPackage - how do you assign to MyPackage.aVariable? inside its __init__.py? -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: Fuzzy string comparison
Steve Bergman wrote: Thanks, all. Yes, Levenshtein seems to be the magic word I was looking for. (It's blazingly fast, too.) I suspect that if I strip out all the punctuation, etc. from both the itemnumber and description columns, as suggested, and concatenate them, pairing the record with its closest match in the other file, it ought to be pretty accurate. Obviously, the final decision will be up to a human being, but this should help them quite a bit. BTW, excluding all the items that match exactly, I only have 8000 items in one file to compare to 2600 in the other. As fast as python-levenshtein seems to be, this should finish in well under a minute. The above suggests that you plan to do a preliminary pass using exact comparison, and remove exact-matching pairs from further consideration. If that is the case, here are a few questions for you to ponder: What about 789o123 in file A and 789o123 in file B? Are you concerned about standardising your item-numbers? What about cases like 7890123 and 789o123 in file A? Are you concerned about duplicated records within a file? What about cases like 7890123 and 789o123 in file A and 7890123 and 789o123 and 78-901-23 in file B? Are you concerned about grouping all instances of the same item? If you are, the magic phrase you are looking for is union find. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Getting unicode escape sequence from unicode character?
Given a Python unicode character (string of length one), how would I find out the \u escape sequence for it? This isn't obvious from the docs I've been looking through. Thanks, Ken -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlopen unwanted password prompts - documentation problem
John Nagle [EMAIL PROTECTED] writes: If you try to open a password protected page with urllib.urlopen(), you get Enter username for EnterPassword at example.com: on standard output, followed by a read for input! This seems to be an undocumented feature, if not a bug. Definitely the documentation for urllib should mention this. The effects of this in a CGI program are not good. A workaround is described here: http://cis.poly.edu/cs912/urlopen.txt; URLopener and FancyURLopener in urllib have many overrideable functions, none of which are documented at python.org and should be. [...] Bug reports tend not to result in a fix being applied unless the reporter him/herself actually goes to the trouble of filing a patch at sourceforge.net : http://sourceforge.net/tracker/?group_id=5470atid=305470 John -- http://mail.python.org/mailman/listinfo/python-list
Re: Feasible in Python ? list of object , with two exeptional objects
In [EMAIL PROTECTED], Osiris wrote: I have an array (I come from C) of identical objects, called sections. These sections have some feature, say a length, measured in mm, which is calculated by a method A_length of the instantiation of the Section's class. Only, two elements in the array (or list ?) have a length that must be calculated according to a totally different procedure, a different function or method. Is this something that the instances of section know or is some external knowledge needed to identify those special objects? After calculation of ALL the lengths, they must be added together and output. The calculation procedure screams for a FOR or a WHILE loop allong the list of sections, only those two sections mentioned make life difficult. Sounds like something like ``sum(section.length() for section in sections)``. Your description is a bit vague. Where and how do you start to treat the objects different. Is it possible to decide at instantiation time to create a `Section` object or a `SpecialSection` object? How much different is the calculation? Do you need two separate classes or just one with a flag or maybe a function as argument to the `__init__()` method? Are you writing the `Section` class(es) just for this calculation or do they contain other behavior too? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting unicode escape sequence from unicode character?
Kenneth McDonald wrote: Given a Python unicode character (string of length one), how would I find out the \u escape sequence for it? This isn't obvious from the docs I've been looking through. You can use the ord builtin, or the encode method with unicode_escape: a = u'\u1234' a u'\u1234' print a ሴ ord(a) 4660 hex(ord(a)) '0x1234' a.encode('unicode_escape') '\\u1234' Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
dbm
Hello list, I have a dbm database which needs to be accessed/writed by multiple processes. At the moment I do something like : @with_lock def _save(self): f = shelve.open(self.session_file, 'c') try: f[self.sid] = self.data finally: f.close() the with_lock() decorator create a .lock file which is deleted when the function exit, so every operation did the following: - acquire .lock file - open the dbm file - do the operation (save, load, ...) - close the dbm file - delete the .lock file I made some tests and following my results the open() / close() add some overhead (about 5 times slower). I read that the gdbm module should be safe against multiple processes (I saw the 'u' -- Do not lock database. in the doc, so I presume it's locked by default ?). Does it mean that two (or more) processes can open the dbm file and write in the same time without errors/corruptions/segfaults/... ? Thanks, Julien -- http://mail.python.org/mailman/listinfo/python-list
Re: Feasible in Python ? list of object , with two exeptional objects
Osiris [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Is the following intuitively feasible in Python: I have an array (I come from C) of identical objects, called sections. These sections have some feature, say a length, measured in mm, which is calculated by a method A_length of the instantiation of the Section's class. Only, two elements in the array (or list ?) have a length that must be calculated according to a totally different procedure, a different function or method. After calculation of ALL the lengths, they must be added together and output. The calculation procedure screams for a FOR or a WHILE loop allong the list of sections, only those two sections mentioned make life difficult. Any reason you don't just use simple inheritance? from random import choice class BasicSection(object): def __str__(self): return %s: %s % (self.__class__.__name__, self.A_length()) class OrdinarySection(BasicSection): def __init__(self): # boring numbers self.mundaneLengthValue = choice(range(10)) def A_length(self): return self.mundaneLengthValue class ExceptionalSection(BasicSection): def __init__(self): # exceptional numbers! self.extraordinaryLengthValue = choice([1.414,3.14159,2.71828,1.6180339,]) def A_length(self): return self.extraordinaryLengthValue # create list of Sections, randomly choosing Ordinary or Exceptional ones listOfSections = [ choice( (OrdinarySection,ExceptionalSection) )() for i in range(10) ] # now iterate over the list and get length for each totalLength = 0 for sec in listOfSections: print Adding length of + str(sec) totalLength += sec.A_length() print total =, totalLength # or more Pythonically, use a generator expression totalLength = sum( sec.A_length() for sec in listOfSections ) print total =, totalLength One sample run gives this result (although because we randomly choose which class to create when adding elements to the list, the results are different every time): Adding length of OrdinarySection: 6 Adding length of OrdinarySection: 2 Adding length of OrdinarySection: 0 Adding length of OrdinarySection: 4 Adding length of OrdinarySection: 1 Adding length of ExceptionalSection: 3.14159 Adding length of OrdinarySection: 4 Adding length of ExceptionalSection: 3.14159 Adding length of ExceptionalSection: 2.71828 Adding length of ExceptionalSection: 1.414 total = 27.41546 total = 27.41546 In truth, it is not even necessary for both classes to subclass from BasicSubject (as would be the case in C++ or Java). Python's duck-typing will take any object that implements A_length() - I just created a common superclass to put the __str__ method in, and to more classically follow common inheritance patterns. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Mod_python
Maxim Sloyko wrote: Lad wrote: In my web application I use Apache and mod_python. I allow users to upload huge files( via HTTP FORM , using POST method) I would like to store the file directly on a hard disk and not to upload the WHOLE huge file into server's memory first. Can anyone suggest a solution? The only solution you need is Apache and mod_python :) I mean, Apache won't load a huge POST request into its memory no matter what. All file uploads will be stored in temporary files. Under mod_python (provided you use FieldStorage) you'll need to deal only with 'file' objects. Note though that the default behaviour of FieldStorage is to store files in whatever directory the 'tempfile' module uses. This may not always be acceptable, especially with very large files, as the user may want to have the files actually reside elsewhere in some special directory and having to make a copy of the file, if a different file system, may in itself cause issues. Thus, provided you are using a recent version of mod_python, you still may have to customise how files are handled using the FieldStorage file callbacks to have the file stored in the desired location from the outside. The other alternative to FieldStorage is to write a custom Apache/mod_python input filter to process uploads. An example of this is Tramline (http://www.infrae.com/products/tramline). Graham -- http://mail.python.org/mailman/listinfo/python-list
re: loose methods: Smalltalk asPython
In [EMAIL PROTECTED], Jan Theodore Galkowski wrote: Guido was opposed to modifying builtin types before Java existed. It's similar to his opposition to dynamic syntax. The other is placing those builtins at the top of their own object hierarchy. Is int, properly speaking, a descendent of object? In [108]: issubclass(int, object) Out[108]: True In any case, as respectful of Mr/Dr van Rossum as I am, simply because so-and-so says something is bad and therefore it must be true is a fallacious response. I don't think the response was meant to say that it must be bad but that it won't show up as feature in Python as long as the BDFL thinks it's bad. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: loose methods: Smalltalk asPython
Jan Theodore Galkowski wrote: We've not had an excellent dynamic OO language since Smalltalk, IMO. I would say that excellence in object oriented programming is not a strong design goal of Python. Python tries to support OOP well, but not to enhance OOP to the detriment of other, more important goals. [snip] Guido was opposed to modifying builtin types before Java existed. It's similar to his opposition to dynamic syntax. Opposition or not, the language definition is there. Surely Smalltalk's OO style can be respected. Smalltalkers have been doing OO in a dynamic context longer than many. There are things to learn there. Well, that Smalltalk and Ruby do this at least suggests that it won't be the end of the world as we know it if it were to happen in Python. Personally, I'm with Guido here. Allowing this might make Python's OOP more excellent, but it would be to the detriment of other, more important goals, like minimizing surprise. There are two things here that need to be kept straight, I think. One is the primacy of builtin types. The other is placing those builtins at the top of their own object hierarchy. Is int, properly speaking, a descendent of object? No, it's the root of its own tree. Are you saying that it shouldn't be a descendant of object, or that it isn't? int is certainly a subclass of object in Python (as are all objects). Smalltalk has int as well, as a *subclass* of Number. It's primitive. Number is primitive? I thought all types in Smalltalk had a common base type. Anyways, Python 3000 is exploring the idea of an abstract hierarchy that has classes (interfaces?) like Number and Sequence. In fact, I even saw some talk about somehow being able to retrofit classes to support one of these interfaces/ABCs, though it was pretty conjectural. In any case, as respectful of Mr/Dr van Rossum as I am, simply because so-and-so says something is bad and therefore it must be true is a fallacious response. The same could be said of Smalltalk, i.e., because Smalltalk does it therefore it is good is just as fallacious. Regardless, whatever Guido pronounces is what happens. If he's adamantly against something, it's pretty much an academic discussion. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
failing to instantiate an inner class because of order of inner classes
class model:pass class view: model() class controller: model() I can instantiate clsss model from inside class view but I can't instantiate class model from inside controller, due to the nature of python interpreter. I wish to circumvent this restriction by: class model:pass class view: parent_class.model() class controller: parent_class.model() but, I don't know the built-in variable that points to the parent class. Could someone tell me how can I instantiate class model from inside controller AND instantiate class model from inside view? -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS, UNIX and tabs
Sebastian 'lunar' Wiesner [EMAIL PROTECTED] writes: Just a tip for you: In python you never use tabs for indentation. For some value of you. The python style guide [1] recommends four spaces per indentation level. [1] http://www.python.org/dev/peps/pep-0008/ It's not quite absolute on the topic: For new projects, spaces-only are strongly recommended over tabs. -- \ I filled my humidifier with wax. Now my room is all shiny. | `\ -- Steven Wright | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: failing to instantiate an inner class because of order of inner classes
Pyenos wrote: class model:pass class view: model() class controller: model() I can instantiate clsss model from inside class view but I can't instantiate class model from inside controller, due to the nature of python interpreter. I wish to circumvent this restriction by: class model:pass class view: parent_class.model() class controller: parent_class.model() but, I don't know the built-in variable that points to the parent class. Could someone tell me how can I instantiate class model from inside controller AND instantiate class model from inside view? I would try the following: class model: def printFoo(self): print foo class view: def __init__(self): self.model = model() class controller: def __init__(self): self.model = model() Then you can do: vObj = view() vObj.model.printFoo() And: cObj = controller() cObj.model.printFoo() -- http://mail.python.org/mailman/listinfo/python-list
failing to instantiate an inner class because of its order
class Model: Controller() class View: Model() class Controller:pass Python interpreter complains that 'Name Error: Controller()' not defined. -- http://mail.python.org/mailman/listinfo/python-list
Re: failing to instantiate an inner class because of order of inner classes
Edward Kozlowski [EMAIL PROTECTED] writes: Pyenos wrote: class model:pass class view: model() class controller: model() I can instantiate clsss model from inside class view but I can't instantiate class model from inside controller, due to the nature of python interpreter. I wish to circumvent this restriction by: class model:pass class view: parent_class.model() class controller: parent_class.model() but, I don't know the built-in variable that points to the parent class. Could someone tell me how can I instantiate class model from inside controller AND instantiate class model from inside view? I would try the following: class model: def printFoo(self): print foo class view: def __init__(self): self.model = model() class controller: def __init__(self): self.model = model() Then you can do: vObj = view() vObj.model.printFoo() And: cObj = controller() cObj.model.printFoo() I've made an error in the original article that you have quoted here but I have cancelled it. However, I have understood your solution and I think it is helpful. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a process's PID
At Wednesday 27/12/2006 17:33, eldorado wrote: Yes, I was running this on a box that had 1.4 - I just tested it on a box that has 2.3.5 and it runs perfect. Your changes also allow it to be run on the boxes that still have 1.4 Ouch! 1.4 is really really ancient! Even the most conservative libraries -like PIL- require at least 1.5 -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: failing to instantiate an inner class because of its order
Pyenos [EMAIL PROTECTED] writes: class Model: Controller() #problem class View: Model() class Controller:pass Python interpreter complains that 'Name Error: Controller()' not defined. Following Edward Kozlowski's advice I can suggest to myself a solution: class Model:pass class View: Model() #this part is fine class Controller: def __init__(self): self.Model=Model() Controller.Model.Controller() #solution -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variables in python
At Tuesday 26/12/2006 21:06, Steven D'Aprano wrote: It just feels so ugly to use try/except to enable the variable but I've found it useful at least once. That's a matter of taste. Try replacing the try...except block with hasattr: def doStuff(): if hasattr(doStuff, timesUsed): doStuff.timesUsed += 1 else: doStuff.timesUsed = 1 do_common_code Using hasattr you end checking every access to timesUsed twice. Using a try/except, after the initial setup, there is no additional overhead. hasattr does exactly that: it calls getattr to see if it raises an exception (this is documented behavior, not a hidden implementation detail). In Python it's far more common EAFP ('easier to ask for forgiveness than permission') than LBYL ('look before you leap'). -- Gabriel Genellina Softlab SRL __ Preguntá. Respondé. Descubrí. Todo lo que querías saber, y lo que ni imaginabas, está en Yahoo! Respuestas (Beta). ¡Probalo ya! http://www.yahoo.com.ar/respuestas -- http://mail.python.org/mailman/listinfo/python-list
Re: persistant gloabl vars (very newbie) ?
but it's still not quit handy # initialization file (init1.py) import time; xx = 44 # main file was print xx x=time.time() # main file should become print init1.xx x=init1.time.time() so even for the standard functions like time I've to include the preceeding module init1 :-( Ummm... does this help? /src/python/Foo cat init.py #! /usr/local/bin/python from time import time xx = 44 /src/python/Foo python Python 2.3.4 (#1, Feb 7 2005, 15:50:45) [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 Type help, copyright, credits or license for more information. from init import * dir() ['__builtins__', '__doc__', '__file__', '__name__', 'time', 'xx'] xx 44 time built-in function time time() 1167262478.6845641 xx = 42 # this does not change the init module's value! import init init.xx 44 As Piet points out, you get a copy of variables defined in a module when using the from module import * syntax (as is demonstrated by the assignment above). (And I stand corrected on the notion that you could execute from module import * in other than module level scope.) If it is your intention to use those variables defined in init to communicate with other modules making the same sort of import, then you probably don't want to use from module import * syntax. In that case, you can import just the module, and make assignments into that module's namespace. (e.g., init.xx = 3) If all you care about is getting some stuff into your global namespace in a convenient and repeatable way, then I think what I showed both above and originally is fine. -ej -- http://mail.python.org/mailman/listinfo/python-list