Announce: Pyevolve 0.5 released !
The Pyevolve v.0.5 was released. Pyevolve was developed to be a complete genetic algorithms framework written in pure python. More information at: http://pyevolve.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Why GIL? (was Re: what's the point of rpython?)
On Jan 23, 11:45 pm, Bryan Olson fakeaddr...@nowhere.org wrote: Carl Banks wrote: Classes in Python are mutable types, usually. Class instances are (except for the refcount) immutable objects, usually. There's where we disagree. I assert that class instances are usually mutable objects. Nope, you're dead wrong, nothing more to it. The bits of a class instance never change. The __dict__ is a mutable object. The class instance itself isn't. It's not reasonable to call an object whose bits can't change a mutable obect. Anyway, all you're doing is distracting attention from my claim that instance objects wouldn't need to be locked. They wouldn't, no matter how mutable you insist these objects whose bits would never change are. BTW, here's a minor brain bender: immutable types are mutable objects. Some brains are too easily bent. [Snip attempt to take this comment seriously] And some brains are so stodgy they can't even take a lighthearted comment lightheartedly. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Two import questions in Python 3.0
En Sat, 24 Jan 2009 05:24:15 -0200, Kay Schluehr kay.schlu...@gmx.net escribió: 1. I'd expected that absolute imports are used in Python 3.0 by default. I may be wrong. I've written two versions of a module sucks.py sucks.py - print (import from lib.sucks) sucks.py - print (import from package.sucks) The first is placed in the lib directory that is globally visible by means of PYTHONPATH. The second one is placed in a package package/ __init__.py sucks.py A.py The package also contains a module A.py defined by A.py -- import sucks Running A yields import from package.sucks which means unconditional relative import. It shadows the globally visible sucks.py module. I've expected it the other way round. If you run A.py as a script, it does not know it lives inside a package. You must *import* A for it to become aware of the package. Also, the directory containing the script comes earlier than PYTHONPATH entries in sys.path -- so watch for that case too. python test_parser.py Traceback (most recent call last): File test_parser.py, line 12, in module from . import support ValueError: Attempted relative import in non-package The standard error of the years to come that makes working with Python harder and reminds me that it is not a scripting language anymore because you can't run anything as a script not even a test. I always consider that packages are libraries. Application code uses a library (by importing things from it). Test code should mimic closely that behavior: my tests always import the package, like the application would do. Anyway I should revisit the strategy, I've not evaluated yet how much is affected by absolute imports and other changes in 3.0 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL?
Carl Banks pavlovevide...@gmail.com writes: On Jan 23, 11:45 pm, Bryan Olson fakeaddr...@nowhere.org wrote: Carl Banks wrote: Classes in Python are mutable types, usually. Class instances are (except for the refcount) immutable objects, usually. There's where we disagree. I assert that class instances are usually mutable objects. Nope, you're dead wrong, nothing more to it. The bits of a class instance never change. The __dict__ is a mutable object. The class instance itself isn't. It's not reasonable to call an object whose bits can't change a mutable obect. The bits of class instances can very well change. class X(object): pass ... x = X() d = x.__dict__ x.__dict__ = {} map(id, [d, x.__dict__]) [170329876, 170330012] The Python cookbook even describes patterns that depend on this operation working. Class instance's contents can also change if __slots__ is in use, when its __class__ is assigned to (admittedly the latter being a rare operation, but still). Anyway, all you're doing is distracting attention from my claim that instance objects wouldn't need to be locked. They wouldn't, no matter how mutable you insist these objects whose bits would never change are. Only if you're not implementing Python, but another language that doesn't support __slots__ and assignment to instance.__dict__. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL? (was Re: what's the point of rpython?)
En Sat, 24 Jan 2009 06:06:02 -0200, Carl Banks pavlovevide...@gmail.com escribió: On Jan 23, 11:45 pm, Bryan Olson fakeaddr...@nowhere.org wrote: Carl Banks wrote: Classes in Python are mutable types, usually. Class instances are (except for the refcount) immutable objects, usually. There's where we disagree. I assert that class instances are usually mutable objects. Nope, you're dead wrong, nothing more to it. The bits of a class instance never change. The __dict__ is a mutable object. The class instance itself isn't. It's not reasonable to call an object whose bits can't change a mutable obect. Anyway, all you're doing is distracting attention from my claim that instance objects wouldn't need to be locked. They wouldn't, no matter how mutable you insist these objects whose bits would never change are. Me too, I don't get what you mean. Consider a list instance, it contains a count of allocated elements, and a pointer to some memory block. They change when the list is resized. This counts as mutable to me. I really don't understand your claim. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Stalled ticket in Python bug tracker
Steven D'Aprano wrote: I'm interested in this ticket in the bug tracker: http://bugs.python.org/issue2527 but it seems to have been stalled for nine months. Is there a procedure for starting it up again? Should I ask about it on the python-dev mailing list, or just wait until somebody happens to notice it? Peter Otten, if you're reading this, is your offer to jump through the necessary hoops still standing? I guess what killed any chance for the patch to be included was that there was a competing patch that I asked to be reversed. Also, just saying that you are willing to provide docs and test didn't work either. What's needed then as a 'sine qua non' is an updated patch against the tip with documentation and tests. If you don't beat me to it I may give it another try, but probably not before next month. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL?
Hrvoje Niksic hnik...@xemacs.org writes: Not only registered at the beginning of the function, but also (since CPython uses C, not C++) explicitly unregistered at every point of exit from the function. Emacs implements these as macros called GCPRO and UNGCPRO, and they're very easy to get wrong. In a way, they are even worse than the current Python INCREF/DECREF. That's a fairly natural style in Lisp implementation and it is not that difficult to code in. I've hacked inside Emacs and have written another interpreter with a similar setup; it's certainly easier than keeping track of refcounts in my experience. For one thing, you can raise exceptions anywhere you want, and the stack unwind can clean up the gc protection, but it can't know nearly as easily which refcounts to adjust, unless you record all the increfs the same way as the GCPROs. -- http://mail.python.org/mailman/listinfo/python-list
Web authentication urllib2
Hello, I'm new in Python and i would like to write script which need to login to a website. I'm experimenting with urllib2, especially with something like this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username='user', password='pass')) f = opener.open('https://web.com', params) data = f.read() f.close() And the problem is, that this code logs me in on some sites, but on others doesn't, especially on the one I really need to login. And i don't know why. So is there some way how to debug this code and find out why that script cannot login on that specific site? Sorry if this question is too lame, but i am really beginner both in python and web programming .) -- http://mail.python.org/mailman/listinfo/python-list
Re: strange error whilst porting to 2.6
Benjamin Peterson wrote: Robin Becker robin at NOSPAMreportlab.com writes: Well that's not really acceptable as a solution is it? :) This doesn't happen in Python 3.0, so you could port to that. :) In 2.7, the better recursion depth handling in Py3k may be backported,but the best you can do for now is not touch the recursion limit or just shut the error up. Perhaps an interim solution would implement an error message more helpful in ensuring the exception not be raised? This is currently a bit like Your code is wrong: strictly correct, and totally unhelpful. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Relax Syntax for Augmented Arithmetic?
Aahz wrote: In article mailman.7801.1232715276.3487.python-l...@python.org, Steve Holden st...@holdenweb.com wrote: I understand what you are saying, but if the id() associated with a name doesn't change after augmented assignment it seems a little wrong-headed to argue that the augmented assignment always binds a new value to the name. What you are actually saying is that it's up to the method that implements the augmented assignment whether the same (mutated) object or a different one is returned, right? And that the left-hand side of the assignment is always bound to the result of that method. That's overall more correct, but I wanted to emphasize that there is *always* a binding operation being performed. Whether what gets bound to the target is a new object or an existing object is up to the augmented assignment method. nods Yes, we're on the same page. Maybe I was being too pedantic ... regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: var is None vs. var == None
Steven D'Aprano wrote: On Fri, 23 Jan 2009 20:33:45 -0500, Steve Holden wrote: Steven D'Aprano wrote: On Fri, 23 Jan 2009 14:58:34 -0500, Gerald Britton wrote: Hi -- Some time ago I ran across a comment recommending using var is None instead of var == None (also var is not None, etc.) That entirely depends on whether you wish to test for something which *is* None or something with *equals* None. Those two things have different meanings. No they don't, because the language *guarantees* the None object is a singleton, so anything that *equals* None *is* None. Twice in one day. Have they put funny chemicals in the water over there? *wink* Nope, but you know what newsgroup response propagation is like ... Steve, in case you missed my earlier response: class Empty: ... def __eq__(self, other): ... return not bool(other) ... e = Empty() e == None True e is None False An instance that compares equal to anything false doesn't strike me as particularly bizarre or pathological. For instance, the Python Cookbook has an implementation for the Null object pattern. The implementation given compares unequal to everything, but suggests defining an appropriate __eq__ if you need different behaviour. Sure, my syllogism was not strictly true, hence my final quote: Of course there can be pathological objects with bizarre comparison methods. And the is test helps avoid them. Personally I believe that the Empty class is at least slightly pathological. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Two import questions in Python 3.0
On 24 Jan., 09:21, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: If you run A.py as a script, it does not know it lives inside a package. You must *import* A for it to become aware of the package. Also, the directory containing the script comes earlier than PYTHONPATH entries in sys.path -- so watch for that case too. Thanks, yes. I always make the same error thinking that a directory with the ritual __init__ file is actually a package ( as some kind of platonic entity ), something that is more obvious to me than it is to the runtime. The relative import semantics introduced with Python 2.5 has made the error just visible that was hidden to me for about a decade. Shit. -- http://mail.python.org/mailman/listinfo/python-list
Re: strange error whilst porting to 2.6
Steve Holden wrote: Benjamin Peterson wrote: Robin Becker robin at NOSPAMreportlab.com writes: Well that's not really acceptable as a solution is it? :) This doesn't happen in Python 3.0, so you could port to that. :) my initial attempts in this direction were even less successful :( Perhaps an interim solution would implement an error message more helpful in ensuring the exception not be raised? This is currently a bit like Your code is wrong: strictly correct, and totally unhelpful. well after wrapping all the calls to isinstance I think I have found the particular call and args that are causing the problem, but I still don't really understand why the problem is occurring. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
En Sat, 24 Jan 2009 06:52:57 -0200, Gabriel dun...@dreams.sk escribió: I'm new in Python and i would like to write script which need to login to a website. I'm experimenting with urllib2, especially with something like this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username='user', password='pass')) f = opener.open('https://web.com', params) data = f.read() f.close() And the problem is, that this code logs me in on some sites, but on others doesn't, especially on the one I really need to login. And i don't know why. So is there some way how to debug this code and find out why that script cannot login on that specific site? Start by looking at the web page that you normally use to log into the site; probably the form contains more fields than just username and password. In some cases it may be necesary to use ethereal (or any protocol analizer), to see exactly what is actually transmitted when you log in using your browser. Later you may try to reproduce the same thing with Python. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL? (was Re: what's the point of rpython?)
Carl Banks wrote: On Jan 23, 8:22 pm, Bryan Olson fakeaddr...@nowhere.org wrote: Paul Rubin wrote: Bryan Olson writes: BTW, class instances are usually immutable and thus don't require a mutex in the system I described. Then you are describing a language radically different from Python. That one threw me for a minute too, but I think the idea is that the class instance itself is immutable, while its slots (specifically the attribute dictionary) point to mutable objects. The meaning of 'immutable' is well-established in the Python literature. Python's immutable types include tuple, frozenset, and various kinds of numbers and strings. Class instances, not so much. Of course class instances aren't immutable types: they're not even types. Let me suggest that there is a distinction between an immutable type and an immutable object. Immutable types are what you are talking about: it means that the type provides usable mutator methods. (Whether they mutate the object itself or some associated object doesn't matter.) Immutable objects are a different thing: it means the object cannot change in memory. Classes in Python are mutable types, usually. Class instances are (except for the refcount) immutable objects, usually. We usually talk about mutability of types, but mutability of objects is appropriate for discussion as well. So I can't really agree with your assessment that I wrong to call class instances immutable objects aside from refcounts. BTW, here's a minor brain bender: immutable types are mutable objects. What's more, this matters when considering a GIL-less implementation. Typical method calls can traverse lots of mutable stuff just to find the function to invoke. Now that doesn't make sense at all. What is all this mutable stuff you have to go through, and what does it have to do with the GIL-less implementation? Can you explain further? Or are you just saying it'll be slow. OK, so we have recently discussed whether objects are values, whether function arguments are passed by reference, whether names are references, and now we are, I suspect, about to have a huge further discussion on the meaning of immutable. Sometimes I start to find this eternal pedantry a little tedious. I suspect it's time I once more dropped out of c.l.py for a while. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Gabriel wrote: Hello, I'm new in Python and i would like to write script which need to login to a website. I'm experimenting with urllib2, especially with something like this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username='user', password='pass')) f = opener.open('https://web.com', params) data = f.read() f.close() And the problem is, that this code logs me in on some sites, but on others doesn't, especially on the one I really need to login. And i don't know why. So is there some way how to debug this code and find out why that script cannot login on that specific site? Sorry if this question is too lame, but i am really beginner both in python and web programming .) That's actually pretty good code for a newcomer! There are a couple of issues you may be running into. First, not all sites use application-based authentication - they may use HTTP authentication of some kind instead. In that case you have to pass the username and password as a part of the HTTP headers. Michael Foord has done a fair write-up of the issues at http://www.voidspace.org.uk/python/articles/authentication.shtml and you will do well to read that if, indeed, you need to do basic authentication. Second, if it *is* the web application that's doing the authentication in the sites that are failing (in other words if the credentials are passed in a web form) then your code may need adjusting to use other field names, or to include other data as required by the login form. You can usually find out what's required by reading the HTML source of the page that contains the login form. Thirdly [nobody expects the Spanish Inquisition ...], it may be that some sites are extraordinarily sensitive to programmed login attempts (possible due to spam), typically using a check of the Agent: HTTP header to make sure that the login attempt is coming from a browser and not a program. For sites like these you may need to emulate a browser response more fully. You can use a program like Wireshark to analyze the network traffic, though you can get add-ons for Firefox that will show you the HTTP headers on request and response. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: The First Law Of comp.lang.python Dynamics
Martin P. Hellwig martin.hell...@dcuktec.org wrote: Or you can argue that even when an argument is repeated indefinitely it doesn't make it suddenly right. This is no good. It's a well known fact that anything I tell you three times is true. To demonstrate: Tim Rowe's post earlier in this thread was the funniest one in a long time. Tim Rowe's post earlier in this thread was the funniest one in a long time. Tim Rowe's post earlier in this thread was the funniest one in a long time. see - it's true! - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of Readability counts?
On Fri, 23 Jan 2009 21:36:59 -0500, Luis Zarrabeitia wrote: Quoting Steven D'Aprano st...@remove-this-cybersource.com.au: On Fri, 23 Jan 2009 13:07:55 -0500, Luis Zarrabeitia wrote: It should be in _our_ power as the team of all participant coders on _our_ project to decide if we should mess with the internals or not. What makes no sense is that it should be in the original author's power to decide, if he is not part of _our_ team. Makes *no* sense? There's *no* good reason *at all* for the original author to hide or protect internals? My bad, sorry. It makes sense... if the original author is an egotist who believes he must control how I use that library. Then I guess Guido must be such an egotist, because there's plenty of internals in Python that you can't (easy) mess with. Or, if external forces make him do it (maybe like, 'oh, if I change python, then I'm not using python anymore'). That parenthesised comment makes no sense to me. Python has changed significantly since it was first released. Recently, print became a function instead of a statement, and one of the motivations for this was to allow people to change the behaviour of Python's print simply by defining a new function. Shadowing built-ins, as they call it, is a feature, not a bug. I can't see any good reason for thinking that if you change (say) the way Python prints, you don't have Python any more. Even more fundamental changes have occurred, e.g. new style classes, ABCs, nested scopes. [...] If a variable is marked as... I don't like 'private', I'll call it 'implementation detail', I would not use it without good reason. Not even by subclassing it. Why do you assume that I'd change list._length if I could? I wouldn't. I didn't say you would change it on a whim. I said that *if* it were exposed to Python code, you *could* change it. You might change it because you thought you had a good reason to. You might change it by accident. You might not realise the consequences of changing it. Who knows? It doesn't matter what your motives are. My point is that you claimed that there is no good reason at all for hiding implementation details. Python is full of implementation details which are quite effectively hidden from Python programmers. So there are two possibilities: (1) you are right that it makes no sense (your words) for the original author (in this case, Guido) to hide those implementation details from Python programmers; or (2) you are wrong that it makes no sense, because there is at least one case where the original author (Guido again) did a sensible thing by hiding implementation details. In an effort to avoid going round and round in circles, let me explicitly say that option (2) does not imply that it always makes sense to hide implementation details. Anyway, did you notice that your counter-example was a radical change-the-way-python-works scenario? No, my scenario is merely extending what you can already do with pure- Python classes to built-in classes written in C. It would have a radical effect (pure Python code could core dump easily) but it wouldn't be a radical change. It might take as little as one new function. [...] So what you're saying is that the fundamental design of Python -- to be a high-level language that manages memory for you while avoiding common programming errors such as buffer overflows -- makes no sense. Is that what you intended? Yes, that's what I intended, obviously. I'd like to have buffer overflows in python. In case you don't understand irony: don't go putting words in my mouth. I'm not putting words in yours. And neither am I. I'm pointing out the logical implications of your position. If you find those implications unpleasant, then perhaps you should modify your position to be less extreme and more realistic. As I see it, you have two coherent positions. On the one hand, you could be like Mark Wooding, and say that Yes you want to risk buffer overflows by messing with the internals -- in which case I'm not sure what you see in Python, which protects so many internals from you. Or you can say that you made a mistake, that there are *some* good reasons to protect/hide internals from external access. Or, I could have a third option: assume that I am a grownup who knows what he is doing. This is totally orthogonal to what we're discussing. Whether you are a grownup or a child, whether you have good reasons or bad reasons, you can still make either of the two choices. After all, even with all those protections in list, I could just create an extension module to shoot me in the foot anyway, if I really wanted to. Yes you could, and you could hack the OS to manipulate data behind the scenes, and you could build a hardware device to inject whatever data you want directly into the memory. You can do any of those things. So what? Data hiding isn't about some sort of mythical 100% certainty against
Re: About SCons Re: progress: compiling python2.5 under msys (specifically but not exclusively under wine) with msvcr80
On Sat, Jan 24, 2009 at 12:28 AM, Roumen Petrov I would better use SCons for both unix and windows builds. In case of windows for both compilers - mingw and microsoft ones. To port curses extension to windows I need to know what gcc options mean, what are the rules to write Makefiles and how to repeat these rules as well as find options in visual studio interface. Not mentioning various platform-specific defines and warning fixes. Did you select one of existing curses library for windows ? I've selected PDCurses and successfully compiled the module and run demos manually - you may see the batch and the patch at http://bugs.python.org/issue2889 However, I was asked for VS2008 project file and this is where it all stopped for 8 months already. First I couldn't get the VS2008, then it refused to run on my W2K and now I can't get enough time to learn it (including that I have 50%/40% experience in PHP/Python and only 5%/5% C/Java). -- --anatoly t. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
First, thank you both I think this isn't basic auth, because this page has form login. I read site's html source and used wireshark to analyze communication between my browser and website and i really find out that a was ignoring one field I added it to the parameters but it didn't help.. Maybe i'm still missing something Here's the post packet: http://student.fiit.stuba.sk/~sevecek06/auth.txt and here's the code again, with little change and real web location added: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(login='login', pwd='pass', page='')) f = opener.open('https://www.orangeportal.sk/', params) data = f.read() f.close() Login and pass are fake ofc. Thank you in advice for any help. Steve Holden wrote: Gabriel wrote: Hello, I'm new in Python and i would like to write script which need to login to a website. I'm experimenting with urllib2, especially with something like this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username='user', password='pass')) f = opener.open('https://web.com', params) data = f.read() f.close() And the problem is, that this code logs me in on some sites, but on others doesn't, especially on the one I really need to login. And i don't know why. So is there some way how to debug this code and find out why that script cannot login on that specific site? Sorry if this question is too lame, but i am really beginner both in python and web programming .) That's actually pretty good code for a newcomer! There are a couple of issues you may be running into. First, not all sites use application-based authentication - they may use HTTP authentication of some kind instead. In that case you have to pass the username and password as a part of the HTTP headers. Michael Foord has done a fair write-up of the issues at http://www.voidspace.org.uk/python/articles/authentication.shtml and you will do well to read that if, indeed, you need to do basic authentication. Second, if it *is* the web application that's doing the authentication in the sites that are failing (in other words if the credentials are passed in a web form) then your code may need adjusting to use other field names, or to include other data as required by the login form. You can usually find out what's required by reading the HTML source of the page that contains the login form. Thirdly [nobody expects the Spanish Inquisition ...], it may be that some sites are extraordinarily sensitive to programmed login attempts (possible due to spam), typically using a check of the Agent: HTTP header to make sure that the login attempt is coming from a browser and not a program. For sites like these you may need to emulate a browser response more fully. You can use a program like Wireshark to analyze the network traffic, though you can get add-ons for Firefox that will show you the HTTP headers on request and response. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Oh, nevermind, it's working. Thanks Gabriel wrote: First, thank you both I think this isn't basic auth, because this page has form login. I read site's html source and used wireshark to analyze communication between my browser and website and i really find out that a was ignoring one field I added it to the parameters but it didn't help.. Maybe i'm still missing something Here's the post packet: http://student.fiit.stuba.sk/~sevecek06/auth.txt and here's the code again, with little change and real web location added: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(login='login', pwd='pass', page='')) f = opener.open('https://www.orangeportal.sk/', params) data = f.read() f.close() Login and pass are fake ofc. Thank you in advice for any help. Steve Holden wrote: Gabriel wrote: Hello, I'm new in Python and i would like to write script which need to login to a website. I'm experimenting with urllib2, especially with something like this: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(username='user', password='pass')) f = opener.open('https://web.com', params) data = f.read() f.close() And the problem is, that this code logs me in on some sites, but on others doesn't, especially on the one I really need to login. And i don't know why. So is there some way how to debug this code and find out why that script cannot login on that specific site? Sorry if this question is too lame, but i am really beginner both in python and web programming .) That's actually pretty good code for a newcomer! There are a couple of issues you may be running into. First, not all sites use application-based authentication - they may use HTTP authentication of some kind instead. In that case you have to pass the username and password as a part of the HTTP headers. Michael Foord has done a fair write-up of the issues at http://www.voidspace.org.uk/python/articles/authentication.shtml and you will do well to read that if, indeed, you need to do basic authentication. Second, if it *is* the web application that's doing the authentication in the sites that are failing (in other words if the credentials are passed in a web form) then your code may need adjusting to use other field names, or to include other data as required by the login form. You can usually find out what's required by reading the HTML source of the page that contains the login form. Thirdly [nobody expects the Spanish Inquisition ...], it may be that some sites are extraordinarily sensitive to programmed login attempts (possible due to spam), typically using a check of the Agent: HTTP header to make sure that the login attempt is coming from a browser and not a program. For sites like these you may need to emulate a browser response more fully. You can use a program like Wireshark to analyze the network traffic, though you can get add-ons for Firefox that will show you the HTTP headers on request and response. regards Steve -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: A java hobbyist programmer learning python
On Jan 23, 8:57 am, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Fri, 23 Jan 2009 01:48:32 -0800 (PST), TheFlyingDutchman zzbba...@aol.com declaimed the following in comp.lang.python: abstraction. In Python, all class attributes are public but names may be mangled to discourage unauthorized access, but otherwise not prevented. It is up to the designer to provide the appropriate interfaces to the data so that the client programmer does not have to resort to manipulating the encapsulated data attributes. Double underscore mangling was not implemented to discourage unauthorized access. Its primary purpose is to prevent name space conflicts when an extended subclass and its parent class use the same name for an attribute, but that attribute is not of the same meaning. Using the __ prefix means BOTH attributes are part of the instance, but the subclass only see's its variant and should make calls into superclass methods to modify the parent variant. Python convention is that a single underscore -- which does NOT perform name mangling -- is the indicator meant to discourage unauthorized access. Is there a significant performance hit with using the double underscore for signifying a variable you want to be private? It seems like it is advantageous that someone trying for direct access has to use a different notation, which will help to emphasize that it shouldn't be access directly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Gabriel wrote: First, thank you both I think this isn't basic auth, because this page has form login. I read site's html source and used wireshark to analyze communication between my browser and website and i really find out that a was ignoring one field I added it to the parameters but it didn't help.. Maybe i'm still missing something Here's the post packet: http://student.fiit.stuba.sk/~sevecek06/auth.txt and here's the code again, with little change and real web location added: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(login='login', pwd='pass', page='')) f = opener.open('https://www.orangeportal.sk/', params) data = f.read() f.close() If you look at the login form on the home page of that portal you will see form name=form_login action=/portal/do_login.dwp method=POST This means that the form should be submitted to https://www.orangeportal.sk/portal/do_login.dwp Some forms submit to the same URL that contain them, but many don't. This is one of the ones that requires submission to a different URL! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Porting 3.0 to 2.6 - from __future__ import super missing?
Hi, I have some 3.0 code, which I would like to make work with 2.6. However, there does not seem to be support for the new super() (no args) via __future__. Is that correct? If so, what's the best way to handle this? Thanks, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Yep, i realize this a minute after posting, sorry. And thank you again .) Steve Holden wrote: Gabriel wrote: First, thank you both I think this isn't basic auth, because this page has form login. I read site's html source and used wireshark to analyze communication between my browser and website and i really find out that a was ignoring one field I added it to the parameters but it didn't help.. Maybe i'm still missing something Here's the post packet: http://student.fiit.stuba.sk/~sevecek06/auth.txt and here's the code again, with little change and real web location added: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) params = urllib.urlencode(dict(login='login', pwd='pass', page='')) f = opener.open('https://www.orangeportal.sk/', params) data = f.read() f.close() If you look at the login form on the home page of that portal you will see form name=form_login action=/portal/do_login.dwp method=POST This means that the form should be submitted to https://www.orangeportal.sk/portal/do_login.dwp Some forms submit to the same URL that contain them, but many don't. This is one of the ones that requires submission to a different URL! regards Steve -- http://mail.python.org/mailman/listinfo/python-list
What's the business with the asterisk?
Hello everyone, From time to time I spot an asterisk (*) used in the Python code _outside_ the usual *args or **kwargs application. E.g. here: http://www.norvig.com/python-lisp.html def transpose (m): return zip(*m) transpose([[1,2,3], [4,5,6]]) [(1, 4), (2, 5), (3, 6)] What does *m mean in this example and how does it do the magic here? Regards, mk -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the business with the asterisk?
From time to time I spot an asterisk (*) used in the Python code _outside_ the usual *args or **kwargs application. E.g. here: http://www.norvig.com/python-lisp.html def transpose (m): return zip(*m) transpose([[1,2,3], [4,5,6]]) [(1, 4), (2, 5), (3, 6)] What does *m mean in this example and how does it do the magic here? There's a good writeup on args/kwargs at http://www.megasolutions.net/python/-args-and---kwargs-78766.aspx (looks like the content was gleaned from comp.lang.python and credited) -tkc -- http://mail.python.org/mailman/listinfo/python-list
pygccxml xml output file
Hi all, I start to use this module in order to produce xml( and the make other things), but differently from gccxml I don't find the variable that set the name of the xml output file after the parsing (in gccxml is - fxml), so it creates temporary files. how can I do an Is there a tutorial that explain with dectails how it works? thank you, regards w -- http://mail.python.org/mailman/listinfo/python-list
Re: Porting 3.0 to 2.6 - from __future__ import super missing?
andrew cooke andrew at acooke.org writes: Hi, I have some 3.0 code, which I would like to make work with 2.6. However, there does not seem to be support for the new super() (no args) via __future__. Is that correct? If so, what's the best way to handle this? Just use the two argument super(): super(MyClass, instance) It's supported in both versions. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the business with the asterisk?
On 24 Jan., 13:31, mk mrk...@gmail.com wrote: Hello everyone, From time to time I spot an asterisk (*) used in the Python code _outside_ the usual *args or **kwargs application. E.g. here:http://www.norvig.com/python-lisp.html def transpose (m): return zip(*m) transpose([[1,2,3], [4,5,6]]) [(1, 4), (2, 5), (3, 6)] What does *m mean in this example and how does it do the magic here? Regards, mk If zip is specified as def zip(*args): ... one can pass zero or more arguments into zip. In the zip body one has access to the argument tuple args. So zip(a, b, c) yields args = (a, b, c). Now suppose you want to pass the tuple t = (a, b, c) to zip. If you call zip(t) then args = ((a, b, c),). When calling zip(*t) instead the tuple is passed as variable arguments just like they are specified in the signature of zip. So args = (a, b, c). Same holds for def foo(**kwd): ... and foo(**kwd) versus foo(kwd). -- http://mail.python.org/mailman/listinfo/python-list
Re: What is intvar?
W. eWatson wrote: r wrote: here is a good explanation of control vars: http://infohost.nmt.edu/tcc/help/pubs/tkinter/control-variables.html Here are 3 great Tkinter refernces in order: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://effbot.org/tkinterbook/ http://www.pythonware.com/library/tkinter/introduction/ Thanks to all for the reference and tips. tkinterbook is easy to follow, but it seems to have been abandoned in 2005. Did it appear in another guise somewhere else? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15' 7 N, 121° 2' 32 W, 2700 feet Web Page: www.speckledwithstars.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Porting 3.0 to 2.6 - from __future__ import super missing?
On Jan 24, 10:39 am, Benjamin Peterson benja...@python.org wrote: andrew cooke andrew at acooke.org writes: Hi, I have some 3.0 code, which I would like to make work with 2.6. However, there does not seem to be support for the new super() (no args) via __future__. Is that correct? If so, what's the best way to handle this? Just use the two argument super(): super(MyClass, instance) It's supported in both versions. Thanks. Any idea how to deal with ABCs? It's sufficient to use a simple class, but I want to expose an ABC in 3.0 as it will make it easier for others to extend. Unfortunately, metaclass= is a syntax error in 2.6 so the following still fails: from sys import version if version.startswith('2.'): class Matcher(): pass else: class Matcher(metaclass=ABCMeta): pass Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: OCaml, Language syntax, and Proof Systems
On Fri, Jan 23, 2009 at 6:16 PM, Xah Lee xah...@gmail.com wrote: The haskell tutorials you can find online are the most mothefucking stupid unreadable fuck. The Haskll community is almost stupid. What they talk all day is about monads, currying, linder myer fuck type. That's what they talk about all day. All day and night. Monad! What's a monad! The importance of monad! How to learn monad! Simple intro to monad! Fucking morons, but MONAD! http://www.youtube.com/watch?v=9fohXBj2UEI -- http://mail.python.org/mailman/listinfo/python-list
Re: Counter Class -- Bag/Multiset
On Thu, 22 Jan 2009 10:11:37 -0800 (PST) Raymond Hettinger pyt...@rcn.com wrote: The collections module in Python 2.7 and Python 3.1 has gotten a new Counter class that works like bags and multisets in other languages. I like that! Now that we have a multiset or Counter I think a redefinition of itertools.permutations is in order. For example something like this: def genperm(D, R = []): #generate the permutations of a multiset if not max(D.values()): yield tuple(R) else: for k,v in sorted(D.items()): if v: D[k] -= 1 for g in genperm(D,R+[k]): yield g D[k] += 1 def perm(seq): D = {} for x in seq: D[x] = D.get(x,0)+1 for X in genperm(D): yield X def test(): for i,x in enumerate(perm('aabbcc')): print i,x print len(set(perm('aabbcc'))) if __name__ == '__main__': test() The dictionary I'm using here could be seamlessly replaced by your Counter class. By the way, I like your itertools recipes a lot, but I miss something that repeats elements n times, an xcycle or ncycle or whatever, like I used in this (older code, sorry for the name overlap): def repeat(x,n = 0): i = 0 while i n : yield x i += 1 def xcycle(seq,n): while 1: for x in seq: for y in repeat(x,n): yield y def counter(symbols,width): base = len(symbols) R = [] k = width while k: k -= 1 R.append(xcycle(symbols,base**k)) nc = base**width while nc: yield list(x.next() for x in R) nc -=1 def test(): symbols = '01' width = 4 for state in counter(symbols,width): print state if __name__=='__main__': test() I think such a thing could be handy for generating more kinds of periodic sequences. By the way, itertools is starting to feel like it's becoming some sort of alternate programming design all by itself. I wonder when it is going to break loose from python! I like that way of thinking a lot, thanks. P. -- http://mail.python.org/mailman/listinfo/python-list
Doc for extended call syntax; was: Re: unzip array of arrays?
Tobiah wrote: Where can I read about this mysterious use of the '*'? Hmmm... that's a harder question than I thought. Am I missing it, or does Python's doc need a write-up of the extended call syntax? It only works in the context of the zip() function. It's hard to understand how the interpreter handles that. It works generally, for any callable. See the doc for 'apply': http://docs.python.org/library/functions.html#non-essential-built-in-functions It not only works in a call, but also in function definitions. You can call a function with the extended call syntax whether or not is defined with * and ** arguments. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Mathematica 7 compares to other languages
On Jan 21, 1:06 pm, soul.mirr...@gmail.com soul.mirr...@gmail.com wrote: On Dec 4 2008, 5:11 am, Andreas Waldenburger geekm...@usenot.de wrote: I vaguely remember you plonking [Xah Lee] before. Did you unplonk him in the meantime? Or was that just a figure of speech? teasingly yours, /W Andreas Waldenburger, I hold up a mirror to your soul! A couple of years ago you started posting to the newsgroup comp.lang.java.programmer. Unlike most newbies, instead of lurking for a while and then contributing on-topic posts about Java, you jumped into the nearest available flamewar and immediately got in up to your neck. Then, on November 13, 2007, you stooped to intentionally misquoting one of your opponents. When he wrote http://groups.google.com/group/comp.lang.java.programmer/msg/7797d4e9... A few days later, you did it again, misquoting this post http://groups.google.com/group/comp.lang.java.programmer/msg/fca19d41... in this one: http://groups.google.com/group/comp.lang.java.programmer/msg/397e1d4b... In both cases, you publicly portrayed this poor man as a pervert, even though, whatever his other [insult deleted], that is clearly not one of them. None of the nasty things that you have said or implied about me are at all true. Repeatedly you have claimed to be primarily motivated by finding the disrupting of newsgroups to be entertaining. This is tantamount to admitting to being a troll. Yes, and here you are, feeding him. Way to go, genius. (And cljp had just gotten peaceful again, too!) -- http://mail.python.org/mailman/listinfo/python-list
understanding nested lists?
I have a short peace of code that is not doing what I expect. when I assign a value to a list in a list alist[2][4]=z this seems replace all the 4 elements in all the sub lists. I assume it is supposed to but this is not what I expect. How would I assign a value to the 4th element in the 2nd sublist. here is the code I have. All the printed values are what I would expect except that all sublist values are replaced. Thanks for your help Vincent on the first iteration I get ; new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]] and expected this; new_list [[None, 0, 1, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] Code; list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]] new_list=[[None]*4]*6 print 'new_list',new_list for sublist in range(6): # 6 becuase it is the # of rows lists1 print 'sublist', sublist for x in list1[sublist]: print list1[sublist] print 'new_list[sublist][x]', new_list[sublist][x] new_list[sublist][x]=list1[sublist].index(x) print 'sublist', sublist, 'x', x print new_list[sublist][x] print 'new_list', new_list -- http://mail.python.org/mailman/listinfo/python-list
String comparision
Hi all, I am developing spell checker for my local language(tamil) using python. I need to generate alternative word list for a miss-spelled word from the dictionary of words.The alternatives must be as much as closer to the miss-spelled word.As we know, ordinary string comparison wont work here . Any suggestion for this problem is welcome. -- Yours, S.Selvam -- http://mail.python.org/mailman/listinfo/python-list
practical limits of urlopen()
Hi, Am I going to have problems if I use urlopen() in a loop to get data from 3000+ URLs? There will be about 2KB of data on average at each URL. I will probably run the script about twice per day. Data from each URL will be saved to my database. I'm asking because I've never opened that many URLs before in a loop. I'm just wondering if it will be particularly taxing for my server. Is it very uncommon to get data from so many URLs in a script? I guess search spiders do it, so I should be able to as well? Thank you, Ryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Porting 3.0 to 2.6 - from __future__ import super missing?
andrew cooke andrew at acooke.org writes: Unfortunately, metaclass= is a syntax error in 2.6 so the following still fails: from sys import version if version.startswith('2.'): class Matcher(): pass else: class Matcher(metaclass=ABCMeta): pass I would suggest that you use the 2.6 syntax, and run 2to3 -f metaclass on your code. (ABCs have been backported to 2.6.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Gabriel wrote: Yep, i realize this a minute after posting, sorry. And thank you again .) A pleasure. Next time, you might consider posting an explanation along with the it's working now message, just to give closure to the thread for anyone who ends up reading it later after a search. Good that you got your problem solved, anyway! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: understanding nested lists?
Vincent Davis wrote: I have a short peace of code that is not doing what I expect. when I assign a value to a list in a list alist[2][4]=z this seems replace all the 4 elements in all the sub lists. I assume it is supposed to but this is not what I expect. How would I assign a value to the 4th element in the 2nd sublist. here is the code I have. All the printed values are what I would expect except that all sublist values are replaced. Thanks for your help Vincent on the first iteration I get ; new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]] and expected this; new_list [[None, 0, 1, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] Code; list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]] new_list=[[None]*4]*6 print 'new_list',new_list for sublist in range(6): # 6 becuase it is the # of rows lists1 print 'sublist', sublist for x in list1[sublist]: print list1[sublist] print 'new_list[sublist][x]', new_list[sublist][x] new_list[sublist][x]=list1[sublist].index(x) print 'sublist', sublist, 'x', x print new_list[sublist][x] print 'new_list', new_list When you create new_list you are actually filling it with six references to the same list. Consequently when you change one of those list elements they all appear to change (because they are all referencing the same list object). Try instead new_list = [[None]*4 for i in range(6)] and you should find your code works as expected. In this case the list is constructed with a new sublist as each element. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: understanding nested lists?
vinc...@vincentdavis.net wrote: I have a short peace of code that is not doing what I expect. when I assign a value to a list in a list alist[2][4]=z this seems replace all the 4 elements in all the sub lists. I assume it is supposed to but this is not what I expect. How would I assign a value to the 4th element in the 2nd sublist. here is the code I have. All the printed values are what I would expect except that all sublist values are replaced. Thanks for your help Vincent on the first iteration I get ; new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]] and expected this; new_list [[None, 0, 1, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] Code; list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]] new_list=[[None]*4]*6 print 'new_list',new_list for sublist in range(6): # 6 becuase it is the # of rows lists1 print 'sublist', sublist for x in list1[sublist]: print list1[sublist] print 'new_list[sublist][x]', new_list[sublist][x] new_list[sublist][x]=list1[sublist].index(x) print 'sublist', sublist, 'x', x print new_list[sublist][x] print 'new_list', new_list -- http://mail.python.org/mailman/listinfo/python-list The problem is likely this right here: [[None]*4]*6 This first creates an inner list that has 4 Nones, then the outer list contains 6 references to that same list, so (new_list[0] is new_list[1]) and (new_list[1] is new_list[2]). I make this mistake a lot myself. l=[[None]*4]*6 print id(l[0]) # -1210893364 print id(l[1]) # -1210893364 l = [list([None]*4) for x in range(6)] print id(l[0]) # -1210893612 print id(l[1]) # -1210893580 Works better Brian Vanderburg II -- http://mail.python.org/mailman/listinfo/python-list
Re: Two import questions in Python 3.0
Kay Schluehr wrote: On 24 Jan., 09:21, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: If you run A.py as a script, it does not know it lives inside a package. You must *import* A for it to become aware of the package. Also, the directory containing the script comes earlier than PYTHONPATH entries in sys.path -- so watch for that case too. Thanks, yes. I always make the same error thinking that a directory with the ritual __init__ file is actually a package ( as some kind of platonic entity ), something that is more obvious to me than it is to the runtime. The relative import semantics introduced with Python 2.5 has made the error just visible that was hidden to me for about a decade. Shit. Temper the language a bit. You lose your effectiveness by some people reading the color of your words, rather than their meaning in code. By the way, if you run the script as: $ python -m package.A You may get what you want demo (language fixed up a bit, moe info printed): in .../lib/site-packages: possible.py - print('import from top possible: %s' % __file__) in .../lib/site-packages/package: possible.py - print('import from package.possible: %s' % __file__) __init__.py - print('package initialized: %s' % __file__) A.py -- print('A started: %s' % __file__) import possible print('A running: %s' % __file__) --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: practical limits of urlopen()
webcomm wrote: Hi, Am I going to have problems if I use urlopen() in a loop to get data from 3000+ URLs? There will be about 2KB of data on average at each URL. I will probably run the script about twice per day. Data from each URL will be saved to my database. I'm asking because I've never opened that many URLs before in a loop. I'm just wondering if it will be particularly taxing for my server. Is it very uncommon to get data from so many URLs in a script? I guess search spiders do it, so I should be able to as well? You shouldn't expect problem - though you might want to think about using some more advanced technique like threading to get your results more quickly. This is Python, though. It shouldn't take long to write a test program to verify that you can indeed spider 3,000 pages this way. With about 2KB per page, you could probably build up a memory structure containing the whole content of every page without memory usage becoming too excessive for modern systems. If you are writing stuff out to a database as you go and not retaining page content then there should be no problems whatsoever. Then look at a parallelized solution of some sort if you need it to work more quickly. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
RegEx issues
Using python 2.4.4 on OpenSolaris 2008.11 I have the following string created by opening a url that has the following string in it: td[ct] = [[ ... ]];\r\n The ... above is what I'm interested in extracting which is really a whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it. The problem is it appears that python is escaping the \ in the regex because I see this: reg = '\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' Now to me looks like it would match the string - \[\[ ... \]\]; Which obviously doesn't match anything because there are no literal \ in the above string. Leaving the \ out of the \[\[ above has re.compile throw an error because [ is a special regex character. Which is why it needs to be escaped in the first place. I am either doing something really wrong, which very possible, or I've missed something obvious. Either way, I thought I'd ask why this isn't working and why it seems to be changing my regex to something else. -- http://mail.python.org/mailman/listinfo/python-list
Parsing a string into a datetime object
Good day. Might someone comment on why %f is not accepted as a valid field directive in: from datetime import datetime created=2009-01-24 16:04:55.882788 dt = datetime.strptime(created,%Y-%m-%d %H:%M:%S.%f) Traceback (most recent call last): File stdin, line 1, in module File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/_strptime.py, line 321, in strptime (bad_directive, format)) ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f' This is for Python 2.5.1 under OS X. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx issues
Sean Brown sbrown.h...@[spammy] gmail.com wrote in message news:glflaj$qr...@nntp.motzarella.org... Using python 2.4.4 on OpenSolaris 2008.11 I have the following string created by opening a url that has the following string in it: td[ct] = [[ ... ]];\r\n The ... above is what I'm interested in extracting which is really a whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it. The problem is it appears that python is escaping the \ in the regex because I see this: reg = '\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' Now to me looks like it would match the string - \[\[ ... \]\]; You are viewing the repr of the string reg='\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' print reg \[\[(.*)\]\];== these are the chars passed to regex The slashes are telling regex the the [ are literal. Which obviously doesn't match anything because there are no literal \ in the above string. Leaving the \ out of the \[\[ above has re.compile throw an error because [ is a special regex character. Which is why it needs to be escaped in the first place. I am either doing something really wrong, which very possible, or I've missed something obvious. Either way, I thought I'd ask why this isn't working and why it seems to be changing my regex to something else. Did you try it? s='td[ct] = [[blah blah]];\r\n' re.search(reg,s).group(1) 'blah blah' -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: What is intvar?
W. eWatson wrote: W. eWatson wrote: r wrote: here is a good explanation of control vars: http://infohost.nmt.edu/tcc/help/pubs/tkinter/control-variables.html Here are 3 great Tkinter refernces in order: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://effbot.org/tkinterbook/ http://www.pythonware.com/library/tkinter/introduction/ Thanks to all for the reference and tips. tkinterbook is easy to follow, but it seems to have been abandoned in 2005. Did it appear in another guise somewhere else? There hasn't been a lot of development on Tkinter in the intervening period. It's a mature system, so there has been no need to update the documentation. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Gabriel wrote: Yep, i realize this a minute after posting, sorry. And thank you again .) Steve Holden wrote: ... I'll offer a couple of pointers about what we all expect here. Please treat this as advice, not a shout of disapproval. (1) Do not top post (put your response above the previous interaction). (2) When quoting previous interactions, cut until the portion you are quoting provides enough context to make your post's context comprehensible, but only that much context. (3) When you figure out you problem, especially on your own, summarize back in a final message what went wrong and how you fixed it. The reasons for these three rules are: (1) The message can be read in order, rather than reading up and down. (2) People _do_ have access to the previous messages (albeit sometimes only with some effort). The message should be comprehensible on its own, but your reader can go back for more detail if it turns out to be vital. You don't want to grow your message to the point where someone who might help you says, I don't have time to read that. (3) Generally it is a good idea to search for answers before asking. It can be incredibly frustrating to discover someone else had previously seen exactly the same problem you are bashing your head into the wall about, follow the chain, and finally read, Never mind, I figured it out. without a clue to what was determined. If you read comp.lang.python for a while, you'll see this is the norm for messages here, and these behaviors help make this a more pleasant place to read and write. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Doc for extended call syntax; was: Re: unzip array of arrays?
Bryan Olson wrote: Tobiah wrote: Where can I read about this mysterious use of the '*'? Hmmm... that's a harder question than I thought. Am I missing it, or does Python's doc need a write-up of the extended call syntax? No, you aren't mistaken. Looking at the * symbol in the 2.6 documentation index it lists only two references. The first is the language manual's explanation of its use in the def statement, the second is a transitory reference to its use in function calls, but that's in the tutorial where it is not likely to get much attention. It only works in the context of the zip() function. It's hard to understand how the interpreter handles that. It works generally, for any callable. See the doc for 'apply': http://docs.python.org/library/functions.html#non-essential-built-in-functions It not only works in a call, but also in function definitions. You can call a function with the extended call syntax whether or not is defined with * and ** arguments. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a string into a datetime object
Mark.Petrovic wrote: Good day. Might someone comment on why %f is not accepted as a valid field directive in: from datetime import datetime created=2009-01-24 16:04:55.882788 dt = datetime.strptime(created,%Y-%m-%d %H:%M:%S.%f) Traceback (most recent call last): File stdin, line 1, in module File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/_strptime.py, line 321, in strptime (bad_directive, format)) ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f' This is for Python 2.5.1 under OS X. Thank you. I believe that Python simply uses the 'strptime' (or equivalent) function in the underlying C library: if that doesn't accept %f then neither does Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx issues
Mark Tolonen wrote: Sean Brown sbrown.h...@[spammy] gmail.com wrote in message news:glflaj$qr...@nntp.motzarella.org... Using python 2.4.4 on OpenSolaris 2008.11 I have the following string created by opening a url that has the following string in it: td[ct] = [[ ... ]];\r\n The ... above is what I'm interested in extracting which is really a whole bunch of text. So I think the regex \[\[(.*)\]\]; should do it. The problem is it appears that python is escaping the \ in the regex because I see this: reg = '\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' Now to me looks like it would match the string - \[\[ ... \]\]; You are viewing the repr of the string reg='\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' print reg \[\[(.*)\]\];== these are the chars passed to regex The slashes are telling regex the the [ are literal. Which obviously doesn't match anything because there are no literal \ in the above string. Leaving the \ out of the \[\[ above has re.compile throw an error because [ is a special regex character. Which is why it needs to be escaped in the first place. I am either doing something really wrong, which very possible, or I've missed something obvious. Either way, I thought I'd ask why this isn't working and why it seems to be changing my regex to something else. Did you try it? s='td[ct] = [[blah blah]];\r\n' re.search(reg,s).group(1) 'blah blah' Beware, though, that by default regex matches are greedy, so if there's a chance that two [[ ... ]] [[ ... ]] can appear on the same line then the above pattern will match ... ]] [[ ... regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Byte oriented data types in python
I have following packet format which I have to send over Bluetooth. packet_type (1 byte unsigned) || packet_length (1 byte unsigned) || packet_data(variable) How to construct these using python data types, as int and float have no limits and their sizes are not well defined. -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx issues
Sean Brown sbrown.h...@[spammy]gmail.com wrote: The problem is it appears that python is escaping the \ in the regex because I see this: reg = '\[\[(.*)\]\];' The first trick of working with regexes in Python is to *always* use raw strings. Instead of reg = '\[\[(.*)\]\];' you want reg = r'\[\[(.*)\]\];' In this case, I think it ends up not mattering, but it's one less thing to worry about. Next, when looking at something like reg '\\[\\[(.*)\\]\\];' it's hard to see exactly what all the backslashes mean. Which are real and which are escapes? Try doing print reg \[\[(.*)\]\]; which gets you the str(reg) instead of repr(reg). Another trick when you're not 100% what you're looking at is to explode the string like this: [c for c in reg] ['\\', '[', '\\', '[', '(', '.', '*', ')', '\\', ']', '\\', ']', ';'] -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx issues
Sean Brown wrote: I have the following string ...: td[ct] = [[ ... ]];\r\n The ... (representing text in the string) is what I'm extracting So I think the regex \[\[(.*)\]\]; should do it. The problem is it appears that python is escaping the \ in the regex because I see this: reg = '\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' Now to me looks like it would match the string - \[\[ ... \]\]; ... OK, you already have a good answer as to what is happening. I'll mention that raw strings were put in the language exactly for regex work. They are useful for any time you need to use the backslash character (\) within a string (but not as the final character). For example: len(r'\a\b\c\d\e\f\g\h') == 16 and len('\a\b\c\d\e\f\g\h') == 13 If you get in the habit of typing regex strings as r'...' or r..., and examining the patters with print(somestring), you'll ease your life. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Porting 3.0 to 2.6 - from __future__ import super missing?
On Jan 24, 2:32 pm, Benjamin Peterson benja...@python.org wrote: I would suggest that you use the 2.6 syntax, and run 2to3 -f metaclass on your code. (ABCs have been backported to 2.6.) Thanks - with that hint I found this - http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/#using-the-metaclass-in-python-2-x-and-3-x Andrew -- http://mail.python.org/mailman/listinfo/python-list
TEST=`which test` equivalent in python?
Hi, Kindly help. import sys, os, string *SVNLOOK_PATH=os.system('which svnlook')* def main(repos, txn): svnlook_cmd = '%s log -t %s %s' % (*SVNLOOK_PATH*, txn, repos) check_msg = os.popen(svnlook_cmd, 'r').readline().rstrip('\n') if len(check_msg) 10: sys.stderr.write (Blahh Blahh\n) sys.exit(1) else: sys.exit(0) if __name__ == '__main__': if len(sys.argv) 3: sys.stderr.write(Usage: %s REPOS TXN\n % (sys.argv[0])) else: main(sys.argv[1], sys.argv[2]) The SVNLOOK_PATH is not working and python says its null when run as SVN hook-script. Do I need to load the os environment variable? How do i pass the value of 'which svnlook' to SVNLOOK_PATH variable. Thanks for your help. Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a string into a datetime object
Mark.Petrovic mspetro...@gmail.com writes: Might someone comment on why %f is not accepted as a valid field directive in: from datetime import datetime created=2009-01-24 16:04:55.882788 dt = datetime.strptime(created,%Y-%m-%d %H:%M:%S.%f) Traceback (most recent call last): File stdin, line 1, in module File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/_strptime.py, line 321, in strptime (bad_directive, format)) ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f' This is for Python 2.5.1 under OS X. time.strptime is documented to use the same set of directives as time.strftime, and http://docs.python.org/library/time.html#time.strftime doesn't mention a %f directive. -- http://mail.python.org/mailman/listinfo/python-list
Re: Byte oriented data types in python
I have following packet format which I have to send over Bluetooth. packet_type (1 byte unsigned) || packet_length (1 byte unsigned) || packet_data(variable) How to construct these using python data types, as int and float have no limits and their sizes are not well defined. Check out the struct module. You want something like: data = struct.pack(BB4s, 1, 4, this) It returns a string of bytes according to the specification -- B is unsigned byte, and 4s is a string of 4 characters. The 1 feeds into the first byte, the 4 into the second, etc. --Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: TEST=`which test` equivalent in python?
On Sat, Jan 24, 2009 at 2:03 PM, Jay Jesus Amorin jay.amo...@gmail.comwrote: Hi, Kindly help. import sys, os, string *SVNLOOK_PATH=os.system('which svnlook')* Read the docs on os.system. It returns the program's return code, not the child processes stdout. Use the subprocess module. def main(repos, txn): svnlook_cmd = '%s log -t %s %s' % (*SVNLOOK_PATH*, txn, repos) check_msg = os.popen(svnlook_cmd, 'r').readline().rstrip('\n') os.popen does what you want here, but it is deprecated in favor of the more powerful subprocess module. if len(check_msg) 10: sys.stderr.write (Blahh Blahh\n) sys.exit(1) else: sys.exit(0) if __name__ == '__main__': if len(sys.argv) 3: sys.stderr.write(Usage: %s REPOS TXN\n % (sys.argv[0])) else: main(sys.argv[1], sys.argv[2]) The SVNLOOK_PATH is not working and python says its null when run as SVN hook-script. Do I need to load the os environment variable? How do i pass the value of 'which svnlook' to SVNLOOK_PATH variable. Thanks for your help. Jay -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx issues
Roy Smith wrote: [snip] Another trick when you're not 100% what you're looking at is to explode the string like this: [c for c in reg] ['\\', '[', '\\', '[', '(', '.', '*', ')', '\\', ']', '\\', ']', ';'] A shorter way is list(reg). -- http://mail.python.org/mailman/listinfo/python-list
Re: ossaudiodev problem: sawtooth noise
On Fri, 23 Jan 2009 14:55:36 -0200, Gabriel Genellina wrote: En Fri, 23 Jan 2009 14:36:46 -0200, Peter Pearson ppear...@nowhere.invalid escribió: On Thu, 22 Jan 2009 20:58:14 -0200, Gabriel Genellina wrote: En Mon, 19 Jan 2009 21:57:04 -0200, Peter Pearson ppear...@nowhere.invalid escribió: The following code uses ossaudiodev to read 1000 values from my sound card at a rate of 12,000 samples per second: When I select a sample rate that is not a power of 2 times 3000 samples/second, a strong and very regular sawtooth is superimposed on the signal. At some sampling frequencies, it appears as a rising sawtooth, and at other sampling frequencies it is a declining sawtooth, so I'm presumably lost in some aliasing wilderness. As best I can tell, it's a 48 KHz sawtooth. That could be a hardware and/or driver limitation. By example, an AC97-compliant chipset may provide a fixed rate of 48000 samples/second any sample rate conversion must be done by other means, if possible at all. Oh! As a matter of fact, my soundcard *is* AC97-compliant (VT8233/A/8235/8237, according to Sysinfo). So . . . this sawtooth might result from some software, somewhere in the bucket brigade between me and the hardware, attempting to perform sample-rate conversion? The 48 KHz coincidence seems very significant. Yep. Google found this for me: http://mail-index.netbsd.org/port-i386/2003/02/18/0003.html Using a sample rate that is a sub-multiple of 48000 is perhaps a safe approach. Back around the time I installed Ubuntu's Hardy Heron, several copies of this line appeared in /var/log/user.log.0: Jan 4 21:32:53 eleodes pulseaudio[6437]: alsa-util.c: \ Device front:0 doesn't support 44100 Hz, changed to 48000 Hz. So I suppose I'll just restrict myself to well-behaved frequencies. I'm not sure what sub-multiple means, but all the successful frequencies I've found over 1 KHz have been multiples of 1.5 KHz that evenly divide 48 KHz. Frequencies showing large sawtooths include 2, 4, 8, 10, and 16 KHz. -- To email me, substitute nowhere-spamcop, invalid-net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Byte oriented data types in python
packet_type (1 byte unsigned) || packet_length (1 byte unsigned) || packet_data(variable) How to construct these using python data types, as int and float have no limits and their sizes are not well defined. In Python 2.x, use the regular string type: chr(n) will create a single byte, and the + operator will do the concatenation. In Python 3.x, use the bytes type (bytes() instead of chr()). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Byte oriented data types in python
Ravi packet_type (1 byte unsigned) || packet_length (1 byte unsigned) || Ravi packet_data(variable) Ravi How to construct these using python data types, as int and float have Ravi no limits and their sizes are not well defined. Take a look at the struct and ctypes modules. -- Skip Montanaro - s...@pobox.com - http://smontanaro.dyndns.org/ -- http://mail.python.org/mailman/listinfo/python-list
MaxInt on Vista-64bit?
Hi! I downloaded Python64 for Windows Vista64 but the value returned from sys.maxint is just a 32bit integer. I found out, thats by design, Microsoft decided to make the long value 32bit. What can I do to compile python 2.6 with maxint of 64bit integers? Can I replace the int values to a int64 value? Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: understanding nested lists?
Thanks for the info. I did not know that. Thanks Vincent Davis On Sat, Jan 24, 2009 at 10:46 AM, Steve Holden st...@holdenweb.com wrote: Vincent Davis wrote: I have a short peace of code that is not doing what I expect. when I assign a value to a list in a list alist[2][4]=z this seems replace all the 4 elements in all the sub lists. I assume it is supposed to but this is not what I expect. How would I assign a value to the 4th element in the 2nd sublist. here is the code I have. All the printed values are what I would expect except that all sublist values are replaced. Thanks for your help Vincent on the first iteration I get ; new_list [[None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None], [None, 0, 1, None]] and expected this; new_list [[None, 0, 1, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] Code; list1=[[1,2],[0,3,2,1],[0,1,3],[2,0,1],[3],[2,3]] new_list=[[None]*4]*6 print 'new_list',new_list for sublist in range(6): # 6 becuase it is the # of rows lists1 print 'sublist', sublist for x in list1[sublist]: print list1[sublist] print 'new_list[sublist][x]', new_list[sublist][x] new_list[sublist][x]=list1[sublist].index(x) print 'sublist', sublist, 'x', x print new_list[sublist][x] print 'new_list', new_list When you create new_list you are actually filling it with six references to the same list. Consequently when you change one of those list elements they all appear to change (because they are all referencing the same list object). Try instead new_list = [[None]*4 for i in range(6)] and you should find your code works as expected. In this case the list is constructed with a new sublist as each element. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL? (was Re: what's the point of rpython?)
On Jan 24, 12:40 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Sat, 24 Jan 2009 06:06:02 -0200, Carl Banks pavlovevide...@gmail.com escribió: On Jan 23, 11:45 pm, Bryan Olson fakeaddr...@nowhere.org wrote: Carl Banks wrote: Classes in Python are mutable types, usually. Class instances are (except for the refcount) immutable objects, usually. There's where we disagree. I assert that class instances are usually mutable objects. Nope, you're dead wrong, nothing more to it. The bits of a class instance never change. The __dict__ is a mutable object. The class instance itself isn't. It's not reasonable to call an object whose bits can't change a mutable obect. Anyway, all you're doing is distracting attention from my claim that instance objects wouldn't need to be locked. They wouldn't, no matter how mutable you insist these objects whose bits would never change are. Me too, I don't get what you mean. Consider a list instance, it contains a count of allocated elements, and a pointer to some memory block. They change when the list is resized. This counts as mutable to me. I really don't understand your claim. Yeah, yeah, I know that, and in the bickering that ensued some aspects of the original context were lost. I should really not have been pulled into Bryan's strawman over the definition of immutable, since it's just a label, I oughtn't give a damn what it's called, I only care what it does. I didn't handle this repartee very well. Anyway, it goes back to the original vision for a mark-and-sweep Python language as I presented what seems like a long time ago. I presented the type system that had three base metatypes instead of the one base metatype we have now: immutable_type, mutable_type, and mutable_dict_type. The default metatype for Python classes would be mutable_dict_type, which is a type wherein the object itself would be mutable but it would still have all the mutator methods __init__, __setattr__, etc., but they could only act on the __dict__. mutable_dict_types would not be allowed to define any slots, and __dict__ wouldn't be reassignable. (However, it seems reasonable to allow the base tp_new to accept a dict argument.) OTOTH, list's metatype would be mutable_type, so the type object itself would be mutable. Bryan claimed that that would be a very different language from Python, apparently because it hadn't occurred to him that by-and- large, the instance itself doesn't change, only the dict does. Perhaps Bryan was thinking of __dict__'s reassignability (that certainly didn't occur to me); if he was I apologize for my snideness. HAVING SAID THAT, I still still say what I proposed would not be a radically different language from Python. A little different, of course. Much slower, almost certainly. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: MaxInt on Vista-64bit?
I downloaded Python64 for Windows Vista64 but the value returned from sys.maxint is just a 32bit integer. I found out, thats by design, Microsoft decided to make the long value 32bit. What can I do to compile python 2.6 with maxint of 64bit integers? At a minimum, you need to change ob_ival to a 64-bit type in PyIntObject. Consequentially, you probably need to change a lot of other functions, e.g. PyInt_AsLong should probably also return a 64-bit integer (as should PyInt_FromLong accept one). In turn, you will need to change all callers of these functions to adjust their parameter types. And so on. Can I replace the int values to a int64 value? See above. In short: no. Use a real 64-bit operating system (such as 64-bit Linux, Solaris, FreeBSD, etc) Regards, Martin P.S. I do wonder why you want to do this, though. Isn't Python's long integer type good enough? -- http://mail.python.org/mailman/listinfo/python-list
Re: MaxInt on Vista-64bit?
Hi! Thanks for the fast answer. Yes, its enough but I never thought that Vista64 is not a real 64-bit operating system :-o. -- http://mail.python.org/mailman/listinfo/python-list
Regex for Python 2.7
Some time ago I discovered this difference between regular expressions in Python and Perl: Python \A matches at start of string \Z matches at end of string Perl \A matches at start of string \Z matches before terminal newline or at end of string \z matches at end of string In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^ and \Z != $ in single-string mode. Obviously, changing Python's \Z to match Perl's could break existing code. \z could be added, but with the opposite meaning to Perl's: Python's \Z == Perl's \z Python's \z == Perl's \Z Would that be confusing? Any suggests welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL?
On Jan 24, 12:33 am, Hrvoje Niksic hnik...@xemacs.org wrote: Carl Banks pavlovevide...@gmail.com writes: Anyway, all you're doing is distracting attention from my claim that instance objects wouldn't need to be locked. They wouldn't, no matter how mutable you insist these objects whose bits would never change are. Only if you're not implementing Python, but another language that doesn't support __slots__ and assignment to instance.__dict__. I am only going to say all Python types prior to 3.0 support classes without __slots__, so while I agree that this would be a different language, it wouldn't necessarily be not Python. (Python, of course, is what GvR says Python is, and he isn't going to say that the language I presented is Python. No worries there! :) I'm only saying that it is conceivably similar enough to be a different version of Python. It would be a different language in the same way that Python 2.6 is a different language from Python 3.0.) Incidentally, the proposal does allow slots to be defined, but only for actual mutable types, not for ordinary class instances. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL?
On Jan 24, 12:24 pm, Carl Banks pavlovevide...@gmail.com wrote: On Jan 24, 12:33 am, Hrvoje Niksic hnik...@xemacs.org wrote: Carl Banks pavlovevide...@gmail.com writes: Anyway, all you're doing is distracting attention from my claim that instance objects wouldn't need to be locked. They wouldn't, no matter how mutable you insist these objects whose bits would never change are. Only if you're not implementing Python, but another language that doesn't support __slots__ and assignment to instance.__dict__. I am only going to say all Python types prior to 3.0 support classes without __slots__, I made a mistake, and I don't want to risk confusion at this point. all Python ***versions** prior to 3.0 and I am talking about old-style classes, of course. Prior to 2.2 no classes at all supported slots. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Why GIL? (was Re: what's the point of rpython?)
On Jan 24, 12:05 pm, Carl Banks pavlovevide...@gmail.com wrote: The default metatype for Python classes would be mutable_dict_type, which is a type wherein the object itself would be mutable but it would still have all the mutator methods __init__, __setattr__, etc., but they could only act on the __dict__. Not wanting to risk confusion. The default metatype for Python classes would be mutable_dict_type, which is a type wherein the object itself would be ***immutable*** but it would still have all the mutator methods __init__, __setattr__, etc., but they could only act on the __dict__. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic methods and lambda functions
unine...@gmail.com wrote: The attributes are right, but the getter are not working. The problem is that the lambda function always execute the last parameter passed for all instances of the methods. How could it be done the right way? Basically, don't use a lambda. Create a real, local closure with a nested def block. That way the closure is created every time the parent function is called. Lambda expressions are only ever compiled once during execution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there anyway Vpython and pyODE can be made to work with newer versions of Python 2.6.1 etc. without a lot of changes to source code?
Casey Hawthorne wrote: Is there anyway Vpython and pyODE can be made to work with newer versions of Python 2.6.1 etc. without a lot of changes to source code? I suppose I'm thinking of an extra layer of indirection, which might slow things down to much. Aren't this just Python libraries that include extension modules (i. e. modules written in C to interface external C libraries). If so, there is a good chance that just compiling them against Python 2.6 works out of the box. Otherwise the adjustments necessary will be just minor ones. Python 3.0 compatibility is a different issue, though (more work). -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm a python addict !
On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote: I just started using python last week and I'm addicted. you need to try this: import antigravity http://xkcd.com/353/ -- http://mail.python.org/mailman/listinfo/python-list
Possible to slice a string with unpacked tuple?
Is there a way to slice a string with a tuple without unpacking the tuple? myString = 111-222-333-444 myString[ 4: 7 ] '222' Is there some way I could perform an identical slicing operation with a tuple like ( 4, 7 ) without having to unpack the tuple? myTuple = ( 4, 7 ) Thanks! Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to slice a string with unpacked tuple?
On Sat, Jan 24, 2009 at 5:31 PM, pyt...@bdurham.com wrote: Is there a way to slice a string with a tuple without unpacking the tuple? myString = 111-222-333-444 myString[ 4: 7 ] '222' Is there some way I could perform an identical slicing operation with a tuple like ( 4, 7 ) without having to unpack the tuple? myTuple = ( 4, 7 ) Thanks! Malcolm 1) What's wrong with unpacking the tuple? 2) Use the built-in slice. myString = 111-222-333-444 myTuple = (4,7) mySlice = slice(*myTuple) myString[mySlice] '222' -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm a python addict !
On Sat, Jan 24, 2009 at 5:35 PM, Lie Ryan lie.1...@gmail.com wrote: On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote: I just started using python last week and I'm addicted. you need to try this: import antigravity http://xkcd.com/353/ Just be careful with that. That guy was still floating 129 comics later (3 comics = 1 week). And still going Woo Python. You can see him floating near the peak of Mt. Everest. http://xkcd.com/482/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to slice a string with unpacked tuple?
pyt...@bdurham.com wrote: Is there a way to slice a string with a tuple without unpacking the tuple? myString = 111-222-333-444 myString[ 4: 7 ] '222' Is there some way I could perform an identical slicing operation with a tuple like ( 4, 7 ) without having to unpack the tuple? myTuple = ( 4, 7 ) Thanks! Does myString[myTuple[0] : myTuple[1]] count as unpacking? If it does, then how about myString.__getslice__(*myTuple)? -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to slice a string with unpacked tuple?
Benjamin, Use the built-in slice. Perfect!! That's exactly what I was looking for - I didn't know this object existed. What's wrong with unpacking the tuple? I'm extracting fields from a huge, multi-gig log file. I was trying to avoid doing something like myString[ myTuple[ 0 ]: myTuple[ 1 ] ) millions of times in a loop. Thank you! Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to slice a string with unpacked tuple?
MRAB, Does myString[myTuple[0] : myTuple[1]] count as unpacking? I'm not sure my use of the term 'unpacking' was totally correct, but, yes, that's what I was hoping to avoid with a simpler solution. then how about myString.__getslice__(*myTuple)? Very interesting. I'm going to try Ben's slice() object suggestion. Thanks for your help, Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Is (-1 ==True) True or False? Neither
Hi all, I ran into a strange case. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 ... >>> -1 == True False >>> -1 == False False This works though: >>> if -1: print "OK" OK After some head scratching, I realized that: - bool is a subclass of int and that True and False evaluates to 1 and 0, so -1 is equal to neither; and - The if -1: statement probably works by treating -1 as bool(-1). But I can't help finding the former comparison behavior odd. I admit that it is odd to write such code but when someone writes -1 == True, the intention is clearly a boolean comparison, not a numerical value comparison, isn't it? As far as I understand, to do this comparison, python is casting (loosely speaking) True to its numerical value, rather than casting -1 to its boolean value. So, my question is: wouldn't it make more sense to do just the opposite, i.e. cast -1 to its boolean value and do a boolean comparison of the operands, when one of the operands is True or False? Or is this too fancy? What do you think? -- http://mail.python.org/mailman/listinfo/python-list
Re: TEST=`which test` equivalent in python?
En Sat, 24 Jan 2009 17:03:33 -0200, Jay Jesus Amorin jay.amo...@gmail.com escribió: *SVNLOOK_PATH=os.system('which svnlook')* You've been told what's wrong with that. But instead of fixing how to invoke which, use distutils.spawn.find_executable instead: py from distutils.spawn import find_executable py find_executable('svnlook') 'c:\\apps\\svn\\bin\\svnlook.exe' -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Can webbrowser module get source code?
Hi All, I played the demo of webbrowser module, with the code below: import webbrowser url = 'https://login.yahoo.com' webbrowser.open_new_tab(url) when I ran the code, it popped out a webpage nicely. I want to go further: to get the source code of the webpage being displayed. Is it possible to do it? I tried webbrow.get() but didn't work. Somebody can help? Thanks! Muddy Coder -- http://mail.python.org/mailman/listinfo/python-list
why is this invalid b = a += b ?
hello, I can assign a value to more than 1 variable (name) in one line: a = b = 3 So evaluation of this line must start at the right part. But the following is not allowed: b = 2 a = b += 1 I would think that if b has a value, and the formula is evaluated from right to left, there's nothing wrong with the above formula. thanks Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex for Python 2.7
En Sat, 24 Jan 2009 18:23:51 -0200, MRAB goo...@mrabarnett.plus.com escribió: Some time ago I discovered this difference between regular expressions in Python and Perl: Python \A matches at start of string \Z matches at end of string Perl \A matches at start of string \Z matches before terminal newline or at end of string \z matches at end of string In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^ and \Z != $ in single-string mode. Why do you want the two to be equivalent? Isn't a good thing that you have both alternatives (\Z and $)? Use whichever is adequate in each case. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm a python addict !
Benjamin Kaplan wrote: On Sat, Jan 24, 2009 at 5:35 PM, Lie Ryan lie.1...@gmail.com mailto:lie.1...@gmail.com wrote: On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote: I just started using python last week and I'm addicted. you need to try this: import antigravity http://xkcd.com/353/ Just be careful with that. That guy was still floating 129 comics later (3 comics = 1 week). And still going Woo Python. You can see him floating near the peak of Mt. Everest. http://xkcd.com/482/ For a Python 'program', see http://xkcd.com/534/ -- http://mail.python.org/mailman/listinfo/python-list
Re: why is this invalid b = a += b ?
Stef Mientki wrote: hello, I can assign a value to more than 1 variable (name) in one line: a = b = 3 So evaluation of this line must start at the right part. But the following is not allowed: b = 2 a = b += 1 I would think that if b has a value, and the formula is evaluated from right to left, there's nothing wrong with the above formula. Assignment is a statement, not an expression. That's why: if a = 0: ... is illegal. However, simple serial assignment such as: a = b = 3 is useful enough to be supported as a special case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex for Python 2.7
Gabriel Genellina wrote: En Sat, 24 Jan 2009 18:23:51 -0200, MRAB goo...@mrabarnett.plus.com escribió: Some time ago I discovered this difference between regular expressions in Python and Perl: Python \A matches at start of string \Z matches at end of string Perl \A matches at start of string \Z matches before terminal newline or at end of string \z matches at end of string In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^ and \Z != $ in single-string mode. Why do you want the two to be equivalent? Isn't a good thing that you have both alternatives (\Z and $)? Use whichever is adequate in each case. Python's \Z is equivalent to Perl's \z, but there's no equivalent to Perl's \Z in multi-line mode. -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm a python addict !
Terry Reedy wrote: Benjamin Kaplan wrote: On Sat, Jan 24, 2009 at 5:35 PM, Lie Ryan lie.1...@gmail.com mailto:lie.1...@gmail.com wrote: On Fri, 23 Jan 2009 19:58:09 -0700, Linuxguy123 wrote: I just started using python last week and I'm addicted. you need to try this: import antigravity http://xkcd.com/353/ Just be careful with that. That guy was still floating 129 comics later (3 comics = 1 week). And still going Woo Python. You can see him floating near the peak of Mt. Everest. http://xkcd.com/482/ For a Python 'program', see http://xkcd.com/534/ It doesn't follow PEP 8! -- http://mail.python.org/mailman/listinfo/python-list
Re: Is (-1 ==True) True or False? Neither
On 2009-01-24 17:00, oktaysa...@superonline.com wrote: Hi all, I ran into a strange case. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 ... -1 == True False -1 == False False This works though: if -1: print OK OK After some head scratching, I realized that: - bool is a subclass of int and that True and False evaluates to 1 and 0, so -1 is equal to neither; and - The if -1: statement probably works by treating -1 as bool(-1). Yes. But I can't help finding the former comparison behavior odd. I admit that it is odd to write such code but when someone writes -1 == True, the intention is clearly a boolean comparison, not a numerical value comparison, isn't it? Not to me. The rules of Python state that the object on the left hand side is asked first how to compare the two values. Only if that fails is the object on the right hand side asked how to compare the objects. As far as I understand, to do this comparison, python is casting (loosely speaking) True to its numerical value, rather than casting -1 to its boolean value. Not really. No casting goes on at all. bool is just one of the types that int.__eq__ knows how to handle because bool is a subclass of int. Vice-versa, bool.__eq__ knows how to handle ints, and it also does a numerical comparison; it never casts to a boolean. So, my question is: wouldn't it make more sense to do just the opposite, i.e. cast -1 to its boolean value and do a boolean comparison of the operands, when one of the operands is True or False? Or is this too fancy? What do you think? I think that being explicit is better than being implicit. If you want to cast an object to a boolean, use bool() on it. Making special rules when comparing with booleans makes it harder to treat True and False as first-class objects. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm a python addict !
On 2009-01-23 22:25, Aahz wrote: In articlemailman.7865.1232765899.3487.python-l...@python.org, Linuxguy123linuxguy...@gmail.com wrote: I just started using python last week and I'm addicted. Welcome! Just be aware that excessive Perl-bashing is considered somewhat tasteless on this newsgroup, but the occasional snide comment should be fine. ;-) Or bash-bashing for that matter. :-) but-zsh-really-is-better'ly yrs, -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Can webbrowser module get source code?
Muddy Coder cosmo_general at yahoo.com writes: I want to go further: to get the source code of the webpage being displayed. Is it possible to do it? I tried webbrow.get() but didn't work. Somebody can help? Thanks! To do this, you actually need to fetch the page yourself: import urllib2 page_source = urllib2.urlopen(http://someaddress.com;).read() -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx issues
On Jan 25, 5:59 am, Scott David Daniels scott.dani...@acm.org wrote: Sean Brown wrote: I have the following string ...: td[ct] = [[ ... ]];\r\n The ... (representing text in the string) is what I'm extracting So I think the regex \[\[(.*)\]\]; should do it. The problem is it appears that python is escaping the \ in the regex because I see this: reg = '\[\[(.*)\]\];' reg '\\[\\[(.*)\\]\\];' Now to me looks like it would match the string - \[\[ ... \]\]; ... OK, you already have a good answer as to what is happening. I'll mention that raw strings were put in the language exactly for regex work. They are useful for any time you need to use the backslash character (\) within a string (but not as the final character). For example: len(r'\a\b\c\d\e\f\g\h') == 16 and len('\a\b\c\d\e\f\g\h') == 13 If you get in the habit of typing regex strings as r'...' or r..., and examining the patters with print(somestring), you'll ease your life. All excellent suggestions, but I'm surprised that nobody has mentioned the re.VERBOSE format. Manual sez: ''' re.X re.VERBOSE This flag allows you to write regular expressions that look nicer. Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash, and, when a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored. That means that the two following regular expression objects that match a decimal number are functionally equal: a = re.compile(r\d + # the integral part \.# the decimal point \d * # some fractional digits, re.X) b = re.compile(r\d+\.\d*) ''' My comments: (1)looks nicer is not the point; it's understandability (2) if you need a space, use a character class -[ ]- not an unescaped backslash -\ - (3) the indentation in the manual doesn't fit my idea of looks nicer; I'd do a = re.compile(r \d + # the integral part \.# the decimal point \d * # some fractional digits , re.X) (4) you can aid understandability by more indentation especially when you have multiple capturing expressions and (?..) gizmoids e.g. r ( . # prefix ) ( (?..) # look-back assertion (?) # etc etc ) Worth a try if you find yourself going nuts getting the parentheses matching. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: why is this invalid b = a += b ?
Stef Mientki wrote: hello, I can assign a value to more than 1 variable (name) in one line: a = b = 3 So evaluation of this line must start at the right part. But the following is not allowed: b = 2 a = b += 1 This strikes me as slightly incoherent. Given that v op=exp is mostly that same as v = v op exp, I suppose you expect a = b += 1 to be mostly the same as a = b = b+1, but what would you do with a += b = 1, or even a *= b += 1. There is some virtur to restricting augmented assignment to one target and one delimiter. Even that seems to cause some trouble. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to slice a string with unpacked tuple?
MRAB google at mrabarnett.plus.com writes: Does myString[myTuple[0] : myTuple[1]] count as unpacking? If it does, then how about myString.__getslice__(*myTuple)? Please don't use special method names directly and especially not __getslice__(). It's deprecated and will be removed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex for Python 2.7
On Jan 25, 7:23 am, MRAB goo...@mrabarnett.plus.com wrote: Some time ago I discovered this difference between regular expressions in Python and Perl: Python \A matches at start of string \Z matches at end of string Perl \A matches at start of string \Z matches before terminal newline or at end of string \z matches at end of string In Perl \A == ^ and \Z == $ in single-string mode, but in Python \A == ^ and \Z != $ in single-string mode. Obviously, changing Python's \Z to match Perl's could break existing code. \z could be added, but with the opposite meaning to Perl's: Python's \Z == Perl's \z Python's \z == Perl's \Z Would that be confusing? Any suggests welcome. IIRC there was an exchange some years ago where the perl guy (Larry?) admitted that he goofed and the consensus was that what Python had done was better. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a string into a datetime object
On Jan 24, 10:56 am, Hrvoje Niksic hnik...@xemacs.org wrote: Mark.Petrovic mspetro...@gmail.com writes: Might someone comment on why %f is not accepted as a valid field directive in: from datetime import datetime created=2009-01-24 16:04:55.882788 dt = datetime.strptime(created,%Y-%m-%d %H:%M:%S.%f) Traceback (most recent call last): File stdin, line 1, in module File /System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/_strptime.py, line 321, in strptime (bad_directive, format)) ValueError: 'f' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f' This is for Python 2.5.1 under OS X. time.strptime is documented to use the same set of directives as time.strftime, andhttp://docs.python.org/library/time.html#time.strftimedoesn't mention a %f directive. Thank you for the timely reply. I guess I got mixed up by looking at the Python 2.6.1 docs, but used the Python 2.5.1 interpreter: http://docs.python.org/library/datetime.html wherein datetime.html does show the availability of the %f directive (if I'm reading all this correctly). -- http://mail.python.org/mailman/listinfo/python-list