Re: do_POST not working on http.server with python
Le jeudi 28 avril 2016 10:36:27 UTC+2, Rahul Raghunath a écrit : > 0 > down vote > favorite > > > I'm trying to create a simple http server with basic GET and POST > functionality. The program is supposed to GET requests by printing out a > simple webpage that greets a user and askes how he would rather be greeted. > When the user enters a greeting of his choice, the webpage should now greet > him as he had chosen. > > While GET seems to be working fine, POST is not. I tried debugging by > printing at every code execution and it seems to be getting stuck here: > > ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) > > I'll paste the code full code below, along with my terminal output. > > Code: > > from http.server import BaseHTTPRequestHandler, HTTPServer > import cgi > > > class webServerHandler(BaseHTTPRequestHandler): > > def do_GET(self): > try: > if self.path.endswith("/hello"): > self.send_response(200) > self.send_header('Content-type', 'text/html') > self.end_headers() > output = "" > output += "" > output += "Hello!" > output += ''' enctype='multipart/form-data' action='/hello'>What would you like me to > say? value="Submit"> ''' > output += "" > self.wfile.write(output.encode(encoding = 'utf_8')) > print (output) > return > > if self.path.endswith("/hola"): > self.send_response(200) > self.send_header('Content-type', 'text/html') > self.end_headers() > output = "" > output += "" > output += "¡ Hola !" > output += ''' enctype='multipart/form-data' action='/hello'>What would you like me to > say? value="Submit"> ''' > output += "" > self.wfile.write(output.encode(encoding = 'utf_8')) > print (output) > return > > except IOError: > self.send_error(404, 'File Not Found: %s' % self.path) > > def do_POST(self): > try: > self.send_response(201) > print("Sent response") > self.send_header('Content-type', 'text/html') > print("Sent headers") > self.end_headers() > print("Ended header") > ctype, pdict = > cgi.parse_header(self.headers.getheader('content-type')) > print("Parsed headers") > if ctype == 'multipart/form-data': > fields = cgi.parse_multipart(self.rfile, pdict) > messagecontent = fields.get('message') > print("Receiver message content") > output = "" > output += "" > output += " Okay, how about this: " > output += " %s " % messagecontent[0] > output += ''' enctype='multipart/form-data' action='/hello'>What would you like me to > say? value="Submit"> ''' > output += "" > print(output) > self.wfile.write(output.encode(encoding = 'utf_8')) > print ("Wrote through CGI") > except: > pass > > > def main(): > try: > port = 8080 > server = HTTPServer(('', port), webServerHandler) > print ("Web Server running on port", port) > server.serve_forever() > except KeyboardInterrupt: > print (" ^C entered, stopping web server") > server.socket.close() > > if __name__ == '__main__': > main() > > Terminal Output: > > Web Server running on port 8080 > 127.0.0.1 - - [28/Apr/2016 13:28:59] "GET /hello HTTP/1.1" 200 - > Hello! enctype='multipart/form-data' action='/hello'>What would you like me to > say? value="Submit"> > 127.0.0.1 - - [28/Apr/2016 13:29:09] "POST /hello HTTP/1.1" 201 - > Sent response > Sent headers > Ended header > > As you can see, the POST function does not seem to go beyong the parse_header > command. I cannot figure this out, and any help would be usefu! Hi, It's generally not considered good practise to silently ignore exceptions in a try/except where the except clause is just : except: pass If you remove the try/except in do_POST you will see this interesting error message : AttributeError: 'HTTPMessage' object has no attribute 'getheader' -- https://mail.python.org/mailman/listinfo/python-list
Re: how to setup for localhost:8000
> > 127.0.0.1 - - [15/Apr/2016 20:57:32] "GET / HTTP/1.1" 200 - > Hi Pierre, > > When I type http://localhost:8000, I did not see anything in the console > after the line "Serving HTTP on 0.0.0.0 port 8000 ... I believe the way I ran > was not correct as shown below: > > python -m http.server > Serving HTTP on 0.0.0.0 port 8000 ... > > Also if I use internet Explorer, it shows HTTP 404 errors. > Do you think the way I am doing of the localhost:8000 setting was not correct? > > Thanks, > Wen-Ruey If you're not seeing anything there, it is sure that the Python server doesn't serve requests on port 8000. But if you're seeing a blank screen or a 404 error instead of a message saying that a connection couldn't be set up, it is likely that another HTTP server is running on your machine on port 8000. Could you try to start the server on another port, eg "python -m http.server 8085" and see what happens in the browser with "http://127.0.0.1:8085"; ? -- https://mail.python.org/mailman/listinfo/python-list
Re: how to setup for localhost:8000
Le jeudi 14 avril 2016 22:50:33 UTC+2, wrh...@gmail.com a écrit : > On Thursday, April 14, 2016 at 2:23:36 PM UTC-4, Andrew Farrell wrote: > > What happens when you type > > > > http://localhost:8000 > > > > Into the address bar of your browser as this is running? > > > > On Thu, Apr 14, 2016 at 12:46 PM, wrote: > > > > > Hi, > > > > > > I am working on window 7 and Python 3.5 to setup a localhost:8000 but it > > > did not get through as shown below: > > > > python -m http.server > > > Serving HTTP on 0.0.0.0 port 8000 ... > > > > > > But it did not show the results. > > > > > > Can someone help me how to setup the localhost? > > > > > > Thanks, > > > Wen-Ruey > > > > > > -- > > > https://mail.python.org/mailman/listinfo/python-list > > > > > hi Andrew, > > Yes. after I type http:\\localhost:8000, the browser did not show anything > except a empty page without any errors. > > Thanks, > Wen-Ruey Hi, When you type http://localhost:8000, do you see something in the console after the line "Serving HTTP on 0.0.0.0 port 8000 ..." ? If the server actually serves requests on port 8000 you should see a log message such as 127.0.0.1 - - [15/Apr/2016 20:57:32] "GET / HTTP/1.1" 200 - -- https://mail.python.org/mailman/listinfo/python-list
Re: Iterators membership testing
> The trap you're seeing here is that iterating over an iterator always > consumes it, but mentally, you're expecting this to be iterating over > a new instance of the same sequence. No, I just tried to apply what I read in the docs : 1. I have y = A(10) which is an instance of a class which does not define __contains__ but does define __iter__ 2. The value z = 0 is produced while iterating over y. 3. The sentence "x in y is true if some value z with x == z is produced while iterating over y" lead me to think that "0 in y" would be true. -- https://mail.python.org/mailman/listinfo/python-list
Re: Iterators membership testing
Le dimanche 9 août 2015 11:25:17 UTC+2, Chris Angelico a écrit : > On Sun, Aug 9, 2015 at 7:06 PM, Pierre Quentel > wrote: > > "For user-defined classes which do not define __contains__() but do define > > __iter__(), x in y is true if some value z with x == z is produced while > > iterating over y. If an exception is raised during the iteration, it is as > > if > > in raised that exception." > > > > ... > > I get an assertion error. Setting a trace on __next__ suggests that for > > membership testing, the interpreter consumes the iterator until the searched > > value is found (or until exhaustion), then it resumes iteration at this > > point. > > That's exactly right. The only way for the interpreter to handle 'in' > on an iterator is something like this: > > def contains(iter, obj): > for val in iter: > if val == obj: return True > return False > > That's what the docs describe. So what you have is something like this: > > for i in iterator: > for j in iterator: > if i == j: break > else: > assert False, '%s not found' %i > > You're dragging values from the same iterator, so you're consuming it > as part of your membership test. You can do this kind of thing: > > >>> 5 in A(10) > True > > but if you've already consumed a few values, those won't be in the > iterator any more: > > >>> x = A(10) > >>> next(x) > 0 > >>> next(x) > 1 > >>> next(x) > 2 > >>> next(x) > 3 > >>> 2 in x > False > > This is simply how iterators work. They're very different from > repeatable iterables like lists or range objects, where you _can_ test > for membership that way: > > >>> x = [10,20,30] > >>> for i in x: assert i in x > ... > >>> x = iter([10,20,30]) > >>> for i in x: assert i in x > ... > Traceback (most recent call last): > File "", line 1, in > AssertionError > > Note that I _could_ create a list that would pass this assertion, > simply by duplicating every value: > > >>> x = iter([10,10,20,20,30,30]) > >>> for i in x: assert i in x > ... > > But it's iterating only three times here, and the 'in' check is > consuming the other three values. Once your A(10) has yielded some > value, it will never yield it again, so the assertion can never pass. > > Does that explain matters? > > ChrisA Thanks for the explanation. I understand that an iterator can't test membership any other way, but I'm still worried about how the documentation explains it. Reading it, I naively expected that an iterator which produces the integer 0 such as the one included in my post would say that "0 in iterator" is True, because "some value z with 0 == z is produced while iterating over y". Shouldn't it be more clear if the documentation said something like : "For user-defined classes which do not define __contains__() but do define __iter__(), x in y consumes the iterator y until some value z with x == z is produced" ? -- https://mail.python.org/mailman/listinfo/python-list
Iterators membership testing
The documentation at https://docs.python.org/3.5/reference/expressions.html#not-in says : "For user-defined classes which do not define __contains__() but do define __iter__(), x in y is true if some value z with x == z is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception." However, if I define a class with class A: def __init__(self, x): self.x = x self.counter = -1 def __iter__(self): return self def __next__(self): self.counter += 1 if self.counter >= self.x: raise StopIteration return self.counter and test for membership with iterator = A(10) for i in iterator: assert i in iterator, '%s not found' %i I get an assertion error. Setting a trace on __next__ suggests that for membership testing, the interpreter consumes the iterator until the searched value is found (or until exhaustion), then it resumes iteration at this point. For instance : >>> iterator = A(10) >>> for i in iterator: ... print(i) ... assert i+1 in iterator ... 0 2 4 6 8 >>> If this is correct, should the documentation mention it ? -- https://mail.python.org/mailman/listinfo/python-list
[ANN] Brython 3.0.0 relased
Hi, Version 3.0.0 of Brython has been released recently Brython is an implementation of Python 3 running in the browser, with an interface to DOM elements and events. It allows writing web client applications with Python instead of Javascript. Python programs are inserted in the HTML page inside tags
Re: Problem with the console on the new python.org site
Le lundi 24 février 2014 14:19:12 UTC+1, Jean-Michel Pichavant a écrit : > - Original Message - > > On Sun, 23 Feb 2014 10:20:15 -0800, Pierre Quentel wrote: > > > > > The new home page of python.org is very nice, congratulations ! > > > > The best I can say about it is that I'm extremely underwhelmed by the > > design, which is far more "busy" and colourful than the old design > > (this > > is not a complement), and not happy that it doesn't work correctly > > without Javascript. > > Steven, you must have been the grumpy smurf in another life ;) > > > > But there is a problem with the online console provided by > > > PythonAnywhere : with my azerty keyboard, I can't enter characters > > > such > > > as ) or ] - very annoying ! > > I have an azerty keyboard and it works just fine, your problem must be > something else. It seems to depend on the browser. I had the problem with Firefox 27.0.1 on Windows XP ; the link "Feedback" didn't work with this browser, this is why I posted here With Chrome 33.0.1750.117 m and Opera 12.12 the characters are recognised I reported the issue on the feedback form, and discovered it was already known by the PythonAnywhere team (https://www.pythonanywhere.com/forums/topic/213/). Hope it will be fixed quickly, it doesn't give a good impression for newcomers to Python whose first contact with the language is this console > > JM > > > -- IMPORTANT NOTICE: > > The contents of this email and any attachments are confidential and may also > be privileged. If you are not the intended recipient, please notify the > sender immediately and do not disclose the contents to any other person, use > it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Problem with the console on the new python.org site
The new home page of python.org is very nice, congratulations ! But there is a problem with the online console provided by PythonAnywhere : with my azerty keyboard, I can't enter characters such as ) or ] - very annoying ! It this going to be fixed soon ? - Pierre -- https://mail.python.org/mailman/listinfo/python-list
Re: Brython (Python in the browser)
Le vendredi 27 décembre 2013 17:12:09 UTC+1, Johannes Schneider a écrit : > On 27.12.2013 07:14, Pierre Quentel wrote: > > > Hi, > > > > > > Ever wanted to use Python instead of Javascript for web client programming > > ? Take a look at Brython, an implementation of Python 3 in the browser, > > with an interface with DOM elements and events > > > > > > Its use is very simple : > > > - load the Javascript library brython.js :
Re: Brython (Python in the browser)
Le vendredi 27 décembre 2013 15:56:33 UTC+1, jonas.t...@gmail.com a écrit : > Den fredagen den 27:e december 2013 kl. 07:14:35 UTC+1 skrev Pierre Quentel: > > > Hi, > > > > > > > > > > > > Ever wanted to use Python instead of Javascript for web client programming > > ? Take a look at Brython, an implementation of Python 3 in the browser, > > with an interface with DOM elements and events > > > > > > > > > > > > Its use is very simple : > > > > > > - load the Javascript library brython.js :
Brython (Python in the browser)
Hi, Ever wanted to use Python instead of Javascript for web client programming ? Take a look at Brython, an implementation of Python 3 in the browser, with an interface with DOM elements and events Its use is very simple : - load the Javascript library brython.js :
Re: Brython - Python in the browser
I forgot to mention : list comprehensions and the ternary operator (r1 if cond else r2) are now supported ! - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> Still, it tends to be a lot harder to explain, document, and read > documentation for, something that uses operators weirdly, rather than > keyword-searchable method names. You don't explain how to use the Python syntax (for instance the operator %, which behaves very differently between integers and strings) by explaining what happens in the underlying C code in the different cases, do you ? I would put the above explanations in the "implementation notes" of Brython, but not on the "how to use Brython" documentation, which is quite simple to explain with <= and + (it's in the section "Handling of HTML documents" in the docs) -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
I was over-simplifying - or, to put is less diplomatically, I screwed up - when I answered that the addition returned a string. As Chris pointed out, it made the explanation very confusing. My apologies The objects handled by + and <= can be : - strings, integers, floats - instances of $TagClass instances (more precisely, of classes copied from $TagClass, one for each HTML tag) : they are wrappers around a DOM element. The DOM element itself is the attribute "elt" of the $TagClass instance - the document, represented by the keyword doc. Its attribute "elt" is the document (top of the DOM tree) - instances of $AbstractClass, a container with a list of DOM elements. This list is the attribute "children" of the $TagClass instance Depending of the objects types, a+b returns the following objects : string + string : string (!) string + $TagClass : $AbstractTag with children [textNode(a),b.elt] string + $AbstractTag : $AbstractTag with [textNode(b)]+ b.children The 2 latter are implemented by the method __radd__ of $TagClass and $AbstractTag, invoqued by the method __add__ of the string class $TagClass + string : $AbstractTag with [a.elt,textNode(b)] $TagClass + $TagClass : $AbstractTag with [a.elt,b.elt] $TagClass + $AbstractTag : $AbstractTag with [a.elt]+b.children $AbstractTag + string : $AbstractTag with a.children+[textNode(b)] $AbstractTag + $TagClass : $AbstractTag with a.children + [b.elt] $AbstractTag + $AbstractTag : $AbstractTag with a.children + b.children (any type) + doc : unsupported doc + (any type) : unsupported The operation x <= y does the following : string <= (any object) : comparison, if possible ($TagClass | doc) <= string | integer | float : adds textNode(str(y)) to x.elt ($TagClass | doc) <= $TagClass : adds child y.elt to parent x.elt ($TagClass | doc) <= $AbstractTag : adds DOM elements in y.children to x.elt $AbstractClass <= (any type) : unsupported - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> Oh, and repr is just a synonym of str, which makes it useless. 3 days ago repr was not even implemented at all, so it's a step forward... -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> The interpreter, though, will be more than happy to treat that as a > comparison if the LHS is not the type that you think it is. For > example, maybe you've added it to a string at some point, and now it's > a string instead of an element. I guess that since doc is made a > keyword, that probably couldn't happen in this example, but it could > happen when trying to add child nodes to other nodes. Unsurprisingly, the translation engine in Brython transforms x <= y into x.__le__(y) If x is a string, then __le__ means of course "lesser or equal" so y can only be a string, otherwise an exception is raised ; this is similar to trying to add a child node to a text node in the DOM > By the way, what is Brython actually doing when you append a child to > the document itself like that? Usually I would expect a div to be > appended to the body or to another div. The above looks like it would > attach the new div as a sibling of the html element. Or is it just > calling document.write()? dom_elt <= obj actually adds one or several DOM nodes (it depends of the class of obj) to the DOM node represented by dom_elt. It's difficult to explain all the cases here, you would have to take a look at the code in py_dom.js, but <= and + work on the DOM tree, there is no document.write anywhere -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> Hmm. So when that gets added into a DIV, it has to get parsed for > tags? How does this work? This seems very odd. I would have expected > it to remain as DOM objects. In DIV(child) : - if child is a string, integer or float, a text node is added (addChild) to the DIV element, with the string value of child - if child is another DOM element (as in DIV(B('foo'))) then this element is added to the DIV element The code is in module py_dom.js, class $TagClass > > What happens if I do, for instance: > 'blah blah x You can test this code in the console on the Brython site (http://brython.info/tests/console_fr.html) : doc <= 'blah blah xhttp://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> <= is a comparison expression operator, which is completely different. > It is just wrong for this usage. I am 99.9% sure you will come to regret > it eventually. Better to make the change now than in Brython2 or Brython3. I am 99.99% sure of the contrary, having used this syntax for more than 3 years now, as the users of the Karrigell framework with the HTMLTags module Another point why there is no possible confusion is that when <= is a comparison operator, it is never used in an standalone expression like "a <= b", with the left term of the comparison starting the line ; it is always used in an expression like "if x <= 10", "while x <= 5", "assert x <= 0", "return foo <= bar" etc. So when you see a line like doc <= DIV('hello') it should be obvious that you are not *comparing* doc and DIV('hello'), because if it was the case, the line would do nothing -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> Pythonic also means: > If the implementation is hard to explain, it's a bad idea. > What, exactly, does the sum of a string and a bolded string produce? Can you > explain that easily and clearly? Yes : a+b returns the string a+str(b) It is exactly what you get in CPython with >>> class B: ... def __init__(self,value): ... self.value = value ... def __radd__(self,other): ... return '%s%s' %(other,self.value) ... >>> 'hello '+B('world') 'hello world' > The DOM structure is, undeniably, quite verbose. But you could go for > something with the same tree structure while a lot less wordy by > simply returning self from lots of methods, thus allowing method > chaining - something like this: > > https://github.com/Rosuav/Gypsum/blob/master/window.pike#L247 > Hang me if I understand what this code is supposed to do ;-) > > To produce the HTML code > > hello world > > you might use: > > doc.add(Tag('DIV').add('hello ').add(Tag('B').add('world'))) > No, with this syntax, the result of Tag('B').add('world') is below 'hello' in the tree structure, not at the same level (just below Tag('DIV')) as it should be In this case it's not a real problem, but it's obvious if you want to produce onetwo : you would need 2 different 'add' top = Tag('UL') top.add(Tag('LI').add('one')) top.add(Tag('LI').add('two')) With the syntax used in Brython : UL(LI('one')+LI('two')) > > Reject the idea if you will, but do at least please consider it :) > I did in fact consider many options before proposing this one. I have done a lot of web programming, including a web framework, and I faced the problem of generating HTML code from Python. I started with a syntax with nested parenthesis and chained methods returning self, only ending in ugly, unreadable code. Once I started using <= for "add child" and "+" for "add brother" (I first proposed it in the Python Cookbook recipe #366000, the HTMLTags module) - and I've used it on fairly large projects - the result was a much cleaner code -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
> If that's your intention, then instead of coming up with something totally > new, unpythonic and ugly, why not take the normal Python route and > implement a subset of the ElementTree API? > > Stefan Because the tree implementation in ElementTree or other tree modules in Python require a lot of typing and parenthesis To produce the HTML code hello world these modules require writing something like div = Tag('DIV') div.appendChild(TextNode('hello ')) b = Tag('B') b.appendChild(TextNode('world')) div.appendChild(b) doc.appendChild(div) With the tree syntax proposed in Brython it would just be doc <= DIV('hello '+B('world')) If "pythonic" means concise and readable, which one is more pythonic ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
Le jeudi 20 décembre 2012 01:54:44 UTC+1, Ian a écrit : > On Wed, Dec 19, 2012 at 5:07 PM, Terry Reedy wrote: > > > That says that my browser, Firefox 17, does not support HTML5. Golly gee. I > > > don't think any browser support5 all of that moving target, and Gecko > > > apparently supports about as large a subset as most. > > > https://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29 > > > It is possible the FF still does not support the particular feature needed > > > for the clock, but then the page should say just that. Has the latest FF > > > (17) actually been tested? > > > > It works for me using FF 17.0.1. > > > > >> To create an element, for instance an HTML anchor : > > >> doc <= A('Python',href="http://www.python.org";) > > > > > > > > > To me, that is a awful choice and I urge you to change it. > > > > +1. The DOM already has a well-established API. The following may > > require more typing: > > > > link = document.createElement('a') > > link.setAttribute("href", "http://www.python.org/";) > > link.appendChild(document.createTextNode('Python')) > > document.body.appendChild(link) > > > > But it is much clearer in intent. Since these methods map directly to > > DOM methods, I know exactly what I expect them to do, and I can look > > them up in the browser documentation if I have any doubts. With the > > one-liner above, I don't know exactly what that maps to in actual DOM > > calls, and so I'm a lot less clear on what exactly it is supposed to > > do. I'm not even entirely certain whether it's actually equivalent to > > my code above. > > > > I suggest that Brython should have a "low-level" DOM API that matches > > up to the actual DOM in as close to a 1:1 correspondence as possible. > > Then if you want to have a higher-level API that allows whiz-bang > > one-liners like the above, build it as an abstraction on top of the > > low-level API and include it as an optional library. This has the > > added benefit that if the user runs into an obscure bug where the > > fancy API breaks on some particular operation on some specific > > browser, they will still have the option of falling back to the > > low-level API to work around it. It would also make the conversion > > barrier much lower for web programmers looking to switch to Brython, > > if they can continue to use the constructs that they're already > > familiar with but just write them in Python instead of JavaScript. We don't have the same point of view. Mine is to offer an alternative to Javascript, with the simplicity and elegance of the Python syntax, for a programer who wants to develop a web application and doesn't know Javascript. Ultimately this means that the whole DOM API would be described without any mention of Javascript, only with the Python API With this idea in mind, asking Brython to have a Javascript-like low-level API is like asking CPython to support iteration with a low-level construct like "for i=0;i<10;i++" along with "for i in range(10)". The Python engine is stable enough that we don't have to inspect the bytecode for debugging ; similarly, when Brython is mature enough, you won't have to look at the generated Javascript code (which you can do though, eg in the console) -- http://mail.python.org/mailman/listinfo/python-list
Re: Brython - Python in the browser
Le jeudi 20 décembre 2012 01:07:15 UTC+1, Terry Reedy a écrit : > On 12/19/2012 1:19 PM, Pierre Quentel wrote: > > > > > The objective of Brython is to replace Javascript by Python as the > > > scripting language for web browsers, making it usable on all > > > terminals including smartphones, tablets, connected TVs, etc. Please > > > forgive the lack of ambition ;-) > > > > This sounds similar to pyjs, but the latter has two big problems: a) > > personality conflicts splits among the developers; b) last I knew, it > > was stuck on Python 2. > It is indeed different from pyjs : both translate Python into Javascript, but with Brython the translation is done on the fly by the browser, with pyjs is is done once by a Python script > > > I think your home page/doc/announcement should specify Python 3 at the > > top, so it is not a mystery until one reads down to > > "Brython supports most keywords and functions of Python 3 : " > Done on the home page > > > "lists are created with [] or list(), tuples with () or tuple(), > > dictionaries with {} or dict() and sets with set()" > > > > non-empty sets are also created with {} and you should support that. > Ok, I put this point in the issue tracker > > > > The best introduction is to visit the Brython site > > > (http://www.brython.info). > > > > That says that my browser, Firefox 17, does not support HTML5. Golly > > gee. I don't think any browser support5 all of that moving target, and > > Gecko apparently supports about as large a subset as most. > > https://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29 > > It is possible the FF still does not support the particular feature > > needed for the clock, but then the page should say just that. Has the > > latest FF (17) actually been tested? > I changed the error message adding "or Javascript is turned off" > > > > To create an element, for instance an HTML anchor : > > > doc <= A('Python',href="http://www.python.org";) > > > > To me, that is a awful choice and I urge you to change it. > > > > '<=' is not just an operator, it is a comparison operator. It normally > > return False or True. Numpy array comparison returns arrays of booleans, > > so the meaning is extended, not completely changed. People will often be > > using it with its normal mean in conditionals elsewhere, so this usage > > creates strong cognitive dissonance. Also, using an expression as a > > statement is allowed, but except in the interactive interpreter, it only > > makes sense with an expression that obviously has side-effects or could > > have side-effects (like the expression 'mylist.sort()'. It just looks > > wrong to an experienced Python programmer like me. > > > > It also is unnecessary. Use '+=' or '|='. The former means just what you > > want the statement to do and the latter is at least somewhat related > > (bit or-addition) and is rarely used and is very unlikely to be used in > > code intended for a browser. > > I'm afraid I am going to disagree. The document is a tree structure, and today Python doesn't have a syntax for easily manipulating trees. To add a child to a node, using an operator instead of a function call saves a lot of typing ; <= looks like a left arrow, which is a visual indication of the meaning "receive as child". |= doesn't have this arrow shape += is supported by Brython, but it means something different. <= means "add child" ; the addition operator + means "add brother" For instance, d = UL(LI('test1')) d += UL(LI('test2')) doc <= d will show two unordered lists at the same level, while d = UL(LI('test1')) d <= UL(LI('test2')) doc <= d will nest the second list inside the first one In fact, even in CPython there could be a built-in tree class that could be managed by a syntax such as this one > > > > > It still lacks important features of Python, mostly list > > > comprehensions and classes ; > > > > Since Python 3 has 4 types of comprehensions, while Python 2 only has > > list comprehensions, I took this to mean that Brython was Python 2. > > > > And yes, I am all in favor of being able to use a subset of Py3 instead > > of javascript. A full Python interpreter in a browser is too dangerous. > > (Actually, I think javascript is too, but that is a different issue.) > > Python translated to javascript cannot be worse than javascript. I > > presume the same would be true if the javascript step were omitted and > > Python were directly compiled to the virtual machines defined by current > > javascript engines. > > > > -- > > Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Brython - Python in the browser
Hi, The objective of Brython is to replace Javascript by Python as the scripting language for web browsers, making it usable on all terminals including smartphones, tablets, connected TVs, etc. Please forgive the lack of ambition ;-) The best introduction is to visit the Brython site (http://www.brython.info). Right click on the page with a clock and take a look at the source code : no Javascript, only Python code inside a tag
[ANN] Karrigell-4.3.6 released
Hi, A new version of the Karrigell web framework for Python 3.2+ has just been released on http://code.google.com/p/karrigell/ One of the oldest Python web frameworks around (the first version was released back in 2002), it now has 2 main versions, one for Python 2 and another one for Python 3. The Python 2.x version is available at http://karrigell.sf.net ; this branch is maintained, but no new feature is going to be developed All the development work is now focused on the version for Python 3. The first release was published in February and we are already at the 10th release Karrigell's design is about simplicity for the programmer and integration of all the web environment in the scripts namespace. For instance, the "Hello world" script requires 2 lines : def index(): return "Hello world" All the HTML tags are available as classes in the scripts namespace : def index(): return HTML(BODY("Hello world")) To build an HTML document as a tree, the HTML tags objects support the operators + (add brother) and <= (add child) : def index(): form = FORM(action="insert",method="post") form <= INPUT(name="foo")+BR()+INPUT(name="bar") form <= INPUT(Type="submit",value="Ok") return HTML(BODY(form)) The scripts can be served by a built-in web server, or through the Apache server, either on CGI mode or using the WSGI interface The package obvioulsy has built-in support for usual features such as cookie and session management, localization, user login/logout/role management. It also includes a complete documentation, with a tutorial and a set of how-to's A helpful and friendly community welcomes users at http://groups.google.com/group/karrigell Enjoy ! Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Relative seeks on string IO
> > Please post code without non-code indents, like so: > Sorry about that. After the line "Example :" I indented the next block, out of habit ;-) > > What system are you using? Does it have a narrow or wide unicode build? > (IE, what is the value of sys.maxunicode?) > I use Windows XP Pro, version 2002, SP3. sys.maxunicode is 65535 I have the same behaviour with 3.1.1 and with 2.7 I don't understand why variable sized code units would cause problems. On text file objects, read(nb) reads nb characters, regardless of the number of bytes used to encode them, and tell() returns a position in the text stream just after the next (unicode) character read As for SringIO, a wrapper around file objects simulates a correct behaviour for relative seeks : txt = "abcdef" txt += "تخصيص هذه الطبعة" txt += "머니투데이" txt += "endof file" out = open("test.txt","w",encoding="utf-8") out.write(txt) out.close() fobj = open("test.txt",encoding="utf-8") fobj.seek(3) try: fobj.seek(2,1) except IOError: print('raises IOError') class _file: def __init__(self,file_obj): self.file_obj = file_obj def read(self,nb=None): if nb is None: return self.file_obj.read() else: return self.file_obj.read(nb) def seek(self,offset,whence=0): if whence==0: self.file_obj.seek(offset) else: if whence==2: # read till EOF while True: buf = self.file_obj.read() if not buf: break self.file_obj.seek(self.file_obj.tell()+offset) fobj = _file(open("test.txt",encoding="utf-8")) fobj.seek(3) fobj.seek(2,1) fobj.seek(-5,2) print(fobj.read(3)) == - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Relative seeks on string IO
Hi, I am wondering why relative seeks fail on string IO in Python 3.2 Example : from io import StringIO txt = StringIO('Favourite Worst Nightmare') txt.seek(8) # no problem with absolute seek but txt.seek(2,1) # 2 characters from current position raises "IOError: Can't do nonzero cur-relative seeks" (tested with Python3.2.2 on WindowsXP) A seek relative to the end of the string IO raises the same IOError However, it is not difficult to simulate a class that performs relative seeks on strings : class FakeIO: def __init__(self,value): self.value = value self.pos = 0 def read(self,nb=None): if nb is None: return self.value[self.pos:] else: return self.value[self.pos:self.pos+nb] def seek(self,offset,whence=0): if whence==0: self.pos = offset elif whence==1: # relative to current position self.pos += offset elif whence==2: # relative to end of string self.pos = len(self.value)+offset txt = FakeIO('Favourite Worst Nightmare') txt.seek(8) txt.seek(2,1) txt.seek(-8,2) = Is there any reason why relative seeks on string IO are not allowed in Python3.2, or is it a bug that could be fixed in a next version ? - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Crazy what-if idea for function/method calling syntax
On 18 juil, 07:54, Steven D'Aprano wrote: > On Mon, 18 Jul 2011 08:54 am ΤΖΩΤΖΙΟΥ wrote: > > > Jumping in: > > > What if a construct > > > xx(*args1, **kwargs1)yy(*args2, **kwargs2) > > > was interpreted as > > > xxyy(*(args1+args2), **(kwargs1+kwargs2)) > > > (Note: with **(kwargs1+kwargs2) I mean “put keyword arguments in the > > order given”, since dicts can't be added) > > > This construct is currently a syntax error. The intent of this idea is > > to help improve legibility. > > I don't think it does that. I think it is misleading, as it looks like two > independent function calls. It also makes it hard to search for a function > call -- instead of searching for > > do_something\(.*\) > > you have to now search for > > do_something\(.*\) > do\(.*\)_something\(.*\) > do_\(.*\)something\(.*\) > do_some\(.*\)thing\(.*\) > > and so on. > > > Example: > > def place_at(item, x, y): blah blah > > could be called as > > place(item)_at(x, y) > > You would probably like the Xtalk family of languages, starting with > Hypertalk from Apple in the late 80s or early 90s. > > There's a neat implementation here:http://code.google.com/p/openxion/ > > Xtalk includes syntax like this: > > put newStr into character 23 to 42 of theStr > put suffix after theStr > delete first char of theStr > > although this only applied to built-in functions, not user-functions. > > -- > Steven If I understand correctly, you propose to translate "do something to X with arguments a,b,c" to (1) do_something_to(X)_with_arguments(a,b,c) instead of (2) do_something(X,a,b,c) I agree that the first one is more readable than the second, because in the arguments list in (2) you mix the object you are working on and the parameters used. But there is another option : (3) X.do_something_with_arguments(a,b,c) which would be in your examples : "item.place_at(x,y)" or "iterable.group_by(collection)" It's valid Python code and probably as readable than what you suggest, with a clear distinction between the object and the arguments - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Forum
On 4 juin, 07:11, Steven D'Aprano wrote: > On Thu, 03 Jun 2010 03:16:03 -0700, Pierre Quentel wrote: > > So the OP's initiative should be an incentive to think on the format of > > the interaction between all the range of Python users, from newbees to > > gurus. We are in the 2.0 era, with social networks all over the place > > using a pleasant interface, > > Really? I can't think of any 2.0 era social networks using pleasant > interfaces. All the ones I've seen or used start with mediocre interfaces > and get worse from there. > > > while c.l.p has a rather austere look and feel, with text only, > > Thank goodness for that! > > > no way to present code snippets in a different > > font / background than discussions, > > If somebody can't distinguish code from comments in a post by the > context, they aren't cut out to be a programmer and should probably stick > to posting "OMG LOL" on a social networking site. They certainly *can* distinguish. But it's so easy to make it more explicit with syntax highlighting, background color, border etc. that most sites about programing languages use it, including the Python home site itself, or the Python cookbook on Active State > > > and even an unintuitive way of entering links... > > Pasting or typing a URL is unintuitive? > > If somebody can't take the time and effort to post a URL in a form that > is not broken, well, that doesn't say much for their skills as a coder > does it? If you can't handle the fact that URLs can't be broken over > multiple lines in email and news posts, how do you expect to handle even > more vigorous requirements while programming? That's 2 different things. When you use a programming language you know you have to adopt the syntax defined by the program. When you write something in a forum, you expect that the editor will be smart enough to know that http://pythonforum.org is a URL > > > I'm not saying that pythonforum.org is the best solution but it > > certainly looks more attractive than c.l.p. to the new generation of > > Python users > > I get: > > While trying to retrieve the URL:http://pythonforum.org/ > The following error was encountered: > Connection to 173.83.46.254 Failed > The system returned: > (111) Connection refused > > Oops. Looks like they can't handle the millions of new users joining up. > > Despite my sarcasm, I actually do wish them the best. I'm not too worried > about fragmenting the community -- the community is already fragmented, > and that's a *good thing*. There are forums for newbies, for development > *of* Python (rather than development *in* Python), for numeric work in > Python, for Italian-speakers, for game development, etc. This is the way > it should be, and I don't fear a competing general Python forum or > forums. If they're better than comp.lang.python, they will attract more > users and become the place to be, and if they're not, they won't. > > -- > Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Forum
On 3 juin, 10:57, Ben Finney wrote: > News123 writes: > > However, whether we like it or not: > > Fewer and fewer newcomers are willing, knowledgable, aware of nntp > > If so, isn't that an indication that better education about the benefits > is required? Perhaps in combination with improving the tool support for > the NNTP protocol? > > > If you think, that newbies are unlikely to use nntp, then create a > > forum, web front end or whatever, which looks very nice and cool, > > which will automatically relay messages (forward and backward) to this > > group. > > > In my opinion new forums should integrate nntp and not try to replace > > it. > > For this purpose, Papercut may be useful: > > Open source news server written in Python. Its main objective is to > integrate existing web based message board software, like Phorum > which is supported, with a Usenet front-end. > > http://pessoal.org/papercut/> > > -- > \ “To stay young requires unceasing cultivation of the ability to | > `\ unlearn old falsehoods.” —Robert Anson Heinlein | > _o__) | > Ben Finney Hi all, I agree that it's not efficient to split the community by creating another forum. But we can't ignore the fact that c.l.p's activity has been decreasing in the last years : 200042971 200155265 200256774 200364521 200455929 200558864 200659664 200749105 200848722 200944111 which certainly doesn't match the popularity of the language itself So the OP's initiative should be an incentive to think on the format of the interaction between all the range of Python users, from newbees to gurus. We are in the 2.0 era, with social networks all over the place using a pleasant interface, while c.l.p has a rather austere look and feel, with text only, no way to present code snippets in a different font / background than discussions, and even an unintuitive way of entering links... I'm not saying that pythonforum.org is the best solution but it certainly looks more attractive than c.l.p. to the new generation of Python users - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Cookie Script: Not recognising Cookie
On 8 avr, 07:03, Jimbo wrote: > Hi I have a simple Python program that assigns a cookie to a web user > when they open the script the 1st time(in an internet browser). If > they open the script a second time the script should display the line > " You have been here 2 times." , if they open the script agai it > should show on the webpage "You have been here 3 times" and so on. > > But for some reason, my program is not assigning or recognising an > assigned cookie & outputing the line "You have been here x times". I > have gone over my code for like 2 hours now I cant figure out what is > going wrong?? > > Can you help me figure out whats wrong? I have my own cgi server that > just runs on my machine so its not that its the code to recognise/ > assign a cookie > > [code]#!/usr/bin/env python > > import Cookie > import cgi > import os > > HTML_template = """ > > > > > > %s > > > """ > > def main(): > > # Web Client is new to the site so we need to assign a cookie to > them > cookie = Cookie.SimpleCookie() > cookie['SESSIONID'] = '1' > code = "No cookie exists. Welcome, this is your first visit." > > if 'HTTP_COOKIE' in os.environ: > cookie = Cookie.SimpleCookie(os.environ['HTTP_COOKIE']) > # If Web client has been here before > if cookie.has_key('SESSIONID'): > cookie['SESSIONID'].value = int(cookie['SESSIONID'].value) > +1 > code = "You have been here %s times." % > cookie['SESSIONID'].value > else: > cookie = Cookie.SimpleCookie() > cookie['SESSIONID'] = '1' > code = "I Have a cookie, but SESSIONID does not exist" > > print "Content-Type: text/html\n" > print HTML_template % code > > if __name__ == "__main__": > main() > [/code] Hi, You are confusing the cookie sent by the browser to the server - you get it by os.environ['HTTP_COOKIE'] - and the one sent by the server to the browser : it it sent in the response headers You can change method main() like this : def main(): # defaut cookie to send if web Client is new to the site set_cookie = Cookie.SimpleCookie() set_cookie['SESSIONID'] = 1 code = "No cookie exists. Welcome, this is your first visit." if 'HTTP_COOKIE' in os.environ: cookie = Cookie.SimpleCookie(os.environ['HTTP_COOKIE']) if cookie.has_key('SESSIONID'): # web client has been here before : increment number of visits set_cookie['SESSIONID'] = int(cookie['SESSIONID'].value) +1 code = "You have been here %s times." % cookie['SESSIONID'].value else: code = "I Have a cookie, but SESSIONID does not exist" print "Content-Type: text/html" print set_cookie.output() # send cookie to web client print print HTML_template % code - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Python script error when using print
On 6 avr, 20:14, "Albert W. Hopkins" wrote: > On Tue, 2010-04-06 at 08:38 -0700, Robbie wrote: > > Hi all, > > > So, I'm trying to use Python with an apache2 server to create some web > > pages. The web server is configured and seems to work correctly, but > > only with a certain type of script. > > > For instance, this script works fine > > > #!/usr/bin/env python > > def index(): > > s = "Hello World" > > return s > > > But, a script like this, does not. > > #!/usr/bin/env python > > print "hello world" > > > When I try to use the script with print, the server returns a broken > > link error. There is nothing in the apache error log to help me > > understand why it won't work. > > Is this a CGI script? You need to return headers (like Content-type): > > e.g. (untested) > > print "Content-type: text/plain" > print > print "hello world" > > See alsohttp://docs.python.org/library/cgi.html > > -a Hi, Are you trying to use some Python web framework behind Apache ? (as suggested by the fact that your first script "runs", i.e. probably prints "Hello World"). In this case the "not found" error in the second script would mean that the framework requires a function in the script - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: (a==b) ? 'Yes' : 'No'
On 30 mar, 21:19, John Bokma wrote: > Robert Fendt writes: > > In fact, the syntax just shouts 'do [...] unless' to me. And > > that's so strong a Perl-ism I cannot quite express how ugly I > > actually find it... > > And > > a == b and 'Yes' or 'No' > > isn't a Perl-ism? > > Sheesh, this group would be so much nicer without the constant dragging > in of Perl to make a point. On top of that, do { } unless blocks are > not idomatic in Perl. Perl Best Practices even clearly states to *never* > use unless. > > -- > John Bokma j3b > > Hacking & Hiking in Mexico - http://johnbokma.com/http://castleamber.com/- > Perl & Python Development I'm surprised nobody proposed a solution with itertools ;-) - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Karrigell 3.0.4 published
On 27 fév, 08:57, Pierre Quentel wrote: > Hi, > > A new version of the web framework Karrigell is on line > > The main changes are : > - more robust session management in multi-threaded and multi-process > environments > - Unicode management in the HTMLTags module (HTML generation in > Python) > - Unicode management and error reports in Karrigell Templates (simple > templating system) > - more of MySQL : can be used for users database ; improved online > management ; blog application > - use of the WhizzyWig Javascript library for blog applications > - make script caching and HTTP caching optional > - the alias keys can be regular expressions for a more flexible url > resolution > - bug fix for default host configuration and for cookie expiry date > > Home page :http://karrigell.sourceforge.net > Download :http://sourceforge.net/project/showfiles.php?group_id=67940 > Google Group :http://groups.google.com/group/karrigell > > Cheers, > Pierre Oops ! wrong group, sorry. It's for c.l.p.announce -- http://mail.python.org/mailman/listinfo/python-list
Karrigell 3.0.4 published
Hi, A new version of the web framework Karrigell is on line The main changes are : - more robust session management in multi-threaded and multi-process environments - Unicode management in the HTMLTags module (HTML generation in Python) - Unicode management and error reports in Karrigell Templates (simple templating system) - more of MySQL : can be used for users database ; improved online management ; blog application - use of the WhizzyWig Javascript library for blog applications - make script caching and HTTP caching optional - the alias keys can be regular expressions for a more flexible url resolution - bug fix for default host configuration and for cookie expiry date Home page : http://karrigell.sourceforge.net Download : http://sourceforge.net/project/showfiles.php?group_id=67940 Google Group : http://groups.google.com/group/karrigell Cheers, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic HTML controls
On 12 jan, 04:26, Alan Harris-Reid wrote: > Hi, > > Does anyone know where I can find any decent dynamically-constructed > HTML control classes (dropdown list, table, input field, checkbox, etc.) > written in Python. For example, for a HTML table I would like something > like... > > MyTable = html_table() # instantiate class > MyTable.data = data_list # data-list (eg. cursor from SQL SELECT > statement) > MyTable.border = 1 > MyTable.width = 987 > MyTable.column_headers = col_headers # list or tuple of column-headers > table_code = MyTable.table.create() # returns string > containing appropriate HTML code > > I don't mind writing my own classes (it will be good practice for me), > but I don't want to re-invent the wheel if it can be avoided. > > TIA, > Alan Harris-Reid Hi, There are a few modules to generate HTML from Python : there is a list at http://wiki.python.org/moin/Templating, section HTML Generation packages With HTMLTags, your example would be coded like this : from HTMLTags import * table = TABLE(border=1,width=987) table <= TR(Sum([TD(header) for header in col_headers])) for result in data_list: table <= TR(Sum([TD(value) for value in result])) print table The operator <= means "add child" in the DOM tree structure, it avoids having to nest tags with brackets - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: select lines in python
On 14 juil, 19:33, amr...@iisermohali.ac.in wrote: > Dear all, > > Can anyone tell me that suppose i have a file having content like: > > _Atom_name > _Atom_type > _Chem_shift_value > _Chem_shift_value_error > _Chem_shift_ambiguity_code > 1 1 PHE H H 8.49 0.02 1 > 2 1 PHE HA H 4.60 0.02 1 > 3 1 PHE CA C 57.83 0.3 1 > 4 2 LEU H H 8.23 0.02 1 > 5 2 LEU HA H 4.25 0.02 1 > 6 2 LEU HB2 H 1.54 0.02 1 > 7 3 ASP H H 8.10 0.02 1 > 8 3 ASP HA H 4.52 0.02 1 > 9 3 ASP HB2 H 2.65 0.02 1 > stop > > now what i want that instead of copying all the lines it will just write > the information about PHE and ASP then how i acn do that using python > programming.Kindly tell me the command for that. > > Thanks, > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA Hi, The problem here is to test the values at specific colums in the file. So I'd rather split each line into a list of values and do a test on relevant items, like : for line in open(filename): items = line.strip().split() if items[1] in ["ASP","PHE"]: (... handle this case ...) Using re here is probably not the best way. It may happen that a sequence appearing in a column also appears in another one ; and when the tests become more complex the regular expression itself might become complex, or even impossible (imagine the OP wants to test that the numeric values are below a certain threshold) - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: fastest native python database?
On 18 juin, 05:28, per wrote: > hi all, > > i'm looking for a native python package to run a very simple data > base. i was originally using cpickle with dictionaries for my problem, > but i was making dictionaries out of very large text files (around > 1000MB in size) and pickling was simply too slow. > > i am not looking for fancy SQL operations, just very simple data base > operations (doesn't have to be SQL style) and my preference is for a > module that just needs python and doesn't require me to run a separate > data base like Sybase or MySQL. > > does anyone have any recommendations? the only candidates i've seen > are snaklesql and buzhug... any thoughts/benchmarks on these? > > any info on this would be greatly appreciated. thank you Hi, buzhug syntax doesn't use SQL statements, but a more Pythonic syntax : from buzhug import Base db = Base('foo').create(('name',str),('age',int)) db.insert('john',33) # simple queries print db(name='john') # complex queries print [ rec.name for rec in db if age > 30 ] # update rec.update(age=34) I made a few speed comparisons with Gadfly, KirbyBase (another pure- Python DB, not maintained anymore) and SQLite. You can find the results on the buzhug home page : http://buzhug.sourceforge.net The conclusion is that buzhug is much faster than the other pure- Python db engines, and (only) 3 times slower than SQLite - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: BaseHttpServer
On 15 fév, 18:31, Paul wrote: > Hi, > I currently have a webserver using BaseHttpServe that serves images > like this: > if self.path.endswith(".jpg"): > print(curdir + sep + self.path) > f = open(curdir + sep + self.path,"b") > self.send_response(200) > self.send_header('Content-type', 'image/jpg') > self.end_headers() > self.wfile.write(f.read()) > f.close() > return > Whilst it works, it does take quite a while to load (approx 10secs for > a 4mb file even though its over the local connection) - does anyone > have any hints/tips for speeding it up? > Thanks, > Paul Hi, This is probably because you first load the file content in memory by f.read() before sending it. In this case it's better to send the content by chunk, using shutil : replace self.wfile.write(f.read()) by : shutil.copyfileobj(f,self.wfile) - Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: SQL, lite lite lite
On 29 déc, 19:06, Aaron Brady wrote: > Hi all, > > About a year ago, I posted an idea I was having about thread > synchronization to the newsgroup. However, I did not explain it well, > and I really erred on the side of brevity. (After some finagling, Mr. > Bieber and I decided it wasn't exactly anything groundbreaking.) But > I think the brevity cost me some readers, who might have had more > interest. The affair was on the whole discouraging. So, I'm going to > try another idea, and assume that readers have some time, and will > spend it on it. > > I don't think relational data can be read and written very easily in > Python. There are some options, such as 'sqllite3', but they are not > easy. 'sqllite3' statements are valid SQL expressions, which afford > the entire power of SQL, but contrary to its name, it is not that > 'lite'. To me, 'lite' is something you could learn (even make!) in an > afternoon, not a semester; something the size of an ActiveState > recipe, or a little bigger, maybe a file or two. If you think SQL is > a breeze, you probably won't find my idea exciting. I assume that the > basics of SQL are creating tables, selecting records, and updating > records. > > My idea is to create a 'Relation' class. The details are basically > open, such as whether to back it with 'sqllite3', 'shelve', 'mmap', or > just mapping and sequence objects; what the simplest syntax is that > can capture and permit all the basics, and how much and what else can > fit in at that level; how and whether it can include arbitrary Python > objects, and what constraints there are on them if not; how and > whether to permit transactions; and what the simplest and coolest > thing you can do with a little Python syntax is. > > This is basically an invitation for everyone to brainstorm. (No > hijackings, good humor & digression ok.) Lastly, ... > > **warning, spoiler! here's what I thought of already.** > > **repeat! spoiler! here's what I thought of already.** > > #Just the select and update syntax: > > >>> a= people._select( "firstname== 'Joe'" ) > > #select 'key' from 'people' where 'firstname'== 'joe'>>> a > > [Entry2864, Entry3076, Entry3172]>>> entry1= a[ 0 ] > >>> entry1.phone > > #select 'phone' from 'people' where 'key'==self.key > "555-2413">>> entry1.phone= "555-1234" > > #update 'people' set 'phone'= '555-1234' where 'key'==self.key>>> entry1.phone > > "555-1234" > > #Create table syntax (a-whole-nother beast in itself): > > >>> classes= db.Relation( 'class_', 'person', Unique( 'class_', 'person' ) ) > > #create table 'classes' ( 'key', 'class_', 'person' ) unique > ( 'class_', 'person' ) > > >>> classes._unique( 'class_', 'person' ) > >>> classes.class_.noneok= False #'class_' cannot be null > >>> classes.person.noneok= False > >>> classes._insert( 'Physics', 'Dan' ) > >>> classes._insert( 'Chem', 'Tim' ) > > Hoping-"good critic"-is-self-consistent-ly, hoping-to-hear-it's-too- > complicated-already-ly, > A. Brady Hi, PyDbLite (http://pydblite.sourceforge.net/) is not far from what you describe. The basic version stores data in cPickle format, and there are interfaces to use the same Pythonic syntax with SQLite and MySQL backends Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: brackets content regular expression
On 31 oct, 20:38, netimen <[EMAIL PROTECTED]> wrote: > there may be different levels of nesting: > > "a < b < Ó > d > here starts a new group: < 1 < e < f > g > 2 > > another group: < 3 >" > > On 31 окт, 21:57, netimen <[EMAIL PROTECTED]> wrote: > > > Thank's but if i have several top-level groups and want them match one > > by one: > > > text = "a < b < Ó > d > here starts a new group: < e < f > g >" > > > I want to match first " b < Ó > d " and then " e < f > g " but not " > > b < Ó > d > here starts a new group: < e < f > g " > > On 31 ÏËÔ, 20:53, Matimus <[EMAIL PROTECTED]> wrote: > > > > On Oct 31, 10:25šam, netimen <[EMAIL PROTECTED]> wrote: > > > > > I have a text containing brackets (or what is the correct term for > > > > '>'?). I'd like to match text in the uppermost level of brackets. > > > > > So, I have sth like: ' 123 < 1 aaa < t bbb < a ff > > 2 > > > > > b'. How to match text between the uppermost brackets ( 1 aaa < t > > > > bbb < a ff > > 2 )? > > > > > P.S. sorry for my english. > > > > I think most people call them "angle brackets". Anyway it should be > > > easy to just match the outer most brackets: > > > > >>> import re > > > >>> text = " 123 < 1 aaa < t bbb < a ff > > 2 >" > > > >>> r = re.compile("<(.+)>") > > > >>> m = r.search(text) > > > >>> m.group(1) > > > > ' 1 aaa < t bbb < a ff > > 2 ' > > > > In this case the regular expression is automatically greedy, matching > > > the largest area possible. Note however that it won't work if you have > > > something like this: " ". > > > > Matt > > Hi, Regular expressions or pyparsing might be overkill for this problem ; you can use a simple algorithm to read each character, increment a counter when you find a < and decrement when you find a > ; when the counter goes back to its initial value you have the end of a top level group Something like : def top_level(txt): level = 0 start = None groups = [] for i,car in enumerate(txt): if car == "<": level += 1 if not start: start = i elif car == ">": level -= 1 if start and level == 0: groups.append(txt[start+1:i]) start = None return groups print top_level("a < b < 0 > d > < 1 < e < f > g > 2 > < 3 >") >> [' b < 0 > d ', ' 1 < e < f > g > 2 ', ' 3 '] Best, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to the most probable type
> >>> def convert(x): > > if '.' in x: > try: return float(x) > except ValueError: return x > else: > try: return int(x) > except: return x > > >>> convert('123') > 123 > >>> convert('123.99') > 123.98 > >>> convert('hello') > Hi, That's fine for people who write floats with a "." ; but others learn to enter them with "," For the same float, the French write the literal 123.456.789,99 when others write 123,456,789.99 ; for us, today is 8/3/2008 (or 08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8 Popular spreadsheets know how to "guess" literals ; if the guess is not correct users can usually specify the pattern to use. My question was just to know if something similar had already been developed in Python ; I understand that the answer is no Thanks, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Converting a string to the most probable type
Hi, I would like to know if there is a module that converts a string to a value of the "most probable type" ; for instance : - if the string is "abcd" the value is the same string "abcd" - string "123" : value = the integer 123 - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value = the float -1.23 - string "2008/03/06" (the format is also locale-dependant) : value = datetime.date(2008,03,06) Like in spreadsheets, special prefixes could be used to force the type : for instance '123 would be converted to the *string* "123" instead of the *integer* 123 I could code it myself, but this wheel is probably already invented Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple List division problem
On 12 jan, 19:37, marcstuart <[EMAIL PROTECTED]> wrote: > How do I divide a list into a set group of sublist's- if the list is > not evenly dividable ? > consider this example: > > x = [1,2,3,4,5,6,7,8,9,10] > y = 3 # number of lists I want to break x into > z = y/x > > what I would like to get is 3 sublists > > print z[0] = [1,2,3] > print z[2] = [4,5,6] > print z[3] = [7,8,9,10] > > obviously not even, one list will have 4 elements, the other 2 will > have 3., > the overriding logic, is that I will get 3 lists and find a way for > python to try to break it evenly, if not one list can have a greater > amount of elements > > Would I use itertools ? How would I do this ? > > Thanks Hi, If you want to split the list in 4, do you want [1,2],[3,4],[5,6],[7,8,9,10] : all extra items in the last sublist or [1,2],[3,4],[5,6,7],[8,9,10] : one extra item in each of the last sublists ? Assuming you want the second version : === def split_list(lst,nb): # ln = length of smaller sublists # extra = number of longer sublists (they have ln+1 items) ln,extra = divmod(len(lst),nb) pos = ln*(nb-extra) # position where larger sublists begin return [ lst[i*ln:(i+1)*ln] for i in xrange(nb-extra) ] \ + [lst[pos+i*(ln+1):pos+(i+1)*(ln+1)] for i in xrange(extra)] == x = range(1,11) print split_list(x,1) >>>[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] print split_list(x,2) >>>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] print split_list(x,3) >>>[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] print split_list(x,4) >>>[[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]] print split_list(x,5) >>>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] print split_list(x,10) >>>[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] -- http://mail.python.org/mailman/listinfo/python-list
Re: Calculate an age
On Dec 8, 10:04 am, Shane Geiger <[EMAIL PROTECTED]> wrote: > What is so obvious about dealing with months that vary in length and the > leap-year issue? Nothing. If you were born on a day that does not > exist every year (Feb 29th), how old are you on Feb 28th? X years, 11 months, 28 days or Mar 1 of > non-leap years? X' years, 0 month, 1 day If you were born on Feb 29th, then you would be one > month old on March 29th, but would you be one year, one month and one > day old on March 29th of the next year? or would you merely be one year > and one month old? 1 year, 1 month, 0 day ; why would there be one day more ? People born on the 28th would be one year, one month and one day old. If two dates have the same day-in-the-month then the difference is X years, Y months and 0 day I understand that there is no possible conversion from a number of days to a (X,Y,Z) tuple of (years,months,days), and the reverse. But the difference between 2 dates can be unambiguously expressed as (X,Y,Z), and given a start date and an interval (X,Y,Z) you can also find the end date unambiguously, provided the arguments are valid (for instance, 1 month after the 30th of January is not valid) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Calculate an age
On Dec 7, 7:09 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > How many days in a year? 365.25 (J2000 epoch), 365.2422 [as I > recall](B1900 epoch), 365.0 (non-leap year), 366 (leap year)? Gregorian > or Julian calendar -- and depending upon one's country, the Gregorian > reform may take place at different years. > > Simple months of (year/12) days, or calendrical mishmash (30 days > hath September, April, June, and November...) again with leap year > exceptions? > Hi, I don't see where the ambiguity is. Isn't it obvious what we mean by "I am X years, Y months and Z days" ? Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Calculate an age
Hi all, I have searched in the standard distribution if there was a function to return the difference between 2 dates expressed like an age : number of years, of months and days. The difference between datetime instances returns a timedelta object that gives a number of days, but not an age So is there such a function somewhere ? If not, for what reason, since it's a rather usual task Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: List of objects X Database
On 3 oct, 22:01, MindMaster32 <[EMAIL PROTECTED]> wrote: Hi, Maybe PyDbLite (http://quentel.pierre.free.fr/PyDbLite/index.html) is what you need : a single Python module, compatible with Python 2.3+, that lets you manipulate data in memory You can manage a database like this : import PyDbLite db = PyDbLite.Base("dummy") db.create("record,"artist","released") # fields are untyped db.insert("Closer","Joy Division",1980) db.insert("Different Class","Pulp",1996) db.commit() # save to disk print [ r for r in db if r["released"] > 1990 ] print db(artist="Joy Division") Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing drag & drop on the desktop
On 21 sep, 08:58, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > The shortcut must point to a *program*, not a *document*. > Change the "shortcut destination" to point to: > c:\path\to\python c:\path\to\your\script.py > > -- > Gabriel Genellina Thanks for the explanation Gabriel, it works fine now Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing drag & drop on the desktop
On 17 sep, 17:08, Larry Bates <[EMAIL PROTECTED]> wrote: > Pierre Quentel wrote: > > Hi all, > > > I would like to create an application on a Windows machine, such that > > when a document is dragged and dropped on the application icon on the > > desktop, the document is processed by the application > > > For instance, if I drag & drop an Outlook message or a PPT > > presentation, the application would propose to tag the document with > > keywords taken from a database > > > Is it possible to do this with a Python script, and how ? > > > Regards, > > Pierre > > If you write a python application and put a shortcut on the desktop, when you > drop any file on it in Windows it is passed into the program via the sys.argv > list as the second (e.g. sys.argv[1]) argument. If you drop multiple files, > they are passed in sys.argv[1] sys.argv[n]. All you need to do is to pick up > the filename and do your processing. > > -Larry- Masquer le texte des messages précédents - > > - Afficher le texte des messages précédents - Thanks for the answers, but it still doesn't work I tried to do this : create a Python script with import sys out = open("dummy","wb") out.write(str(sys.argv)) out.close() === then put a shortcut to this script on the desktop When I drop a file on the shortcut, nothing happens (when I double- click on the shorcut, a console window opens and sys.argv is actually stored in the file) Am I missing something ? Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Processing drag & drop on the desktop
Hi all, I would like to create an application on a Windows machine, such that when a document is dragged and dropped on the application icon on the desktop, the document is processed by the application For instance, if I drag & drop an Outlook message or a PPT presentation, the application would propose to tag the document with keywords taken from a database Is it possible to do this with a Python script, and how ? Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python create a dictionary from a list comprehension?
On 27 mai, 22:55, erikcw <[EMAIL PROTECTED]> wrote: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] ) With Python2.4 and above you can use a "generator expression" entries = dict( (int(d.date.strftime('%m')),d.id) for d in links ) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: File DB instead of real database?
On 14 avr, 06:14, "Jia Lu" <[EMAIL PROTECTED]> wrote: > Hello all > > I donot want to use a real DB like MySQL ... But I need something to > save about more than 1000 articles. > Is there any good ways? > Hi, For small sets of data PyDbLite is a good alternative to full-blown db engines >>> import PyDbLite >>> db = PyDbLite.Base("records").create('title','artist') >>> db.insert('Ok Computer','Radiohead') 0 >>> db.insert('Night On Earth','Rialto') 1 >>> db.insert('Employment','Kaiser Chiefs') 2 >>> print [ r['title'] for r in db ] ['Ok Computer', 'Night On Earth', 'Employment'] >>> print [ r['artist'] for r in db if r['artist'].startswith('R') ] ['Radiohead', 'Rialto'] >>> The syntax is intuitive for Python programmers (list comprehensions) ; it's a single, small Python module downloable at http://quentel.pierre.free.fr/PyDbLite/index.html Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: how to build a forum in Python?
Hi, I think you should take a look at Karrigell : http://karrigell.sourceforge.net It's a Python web framework and the package includes a forum application Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: help with dates
> Four groups of firefighters (group1, group2, group3, group4). Each > group works a 24 hr shift. So group1 works April 1, group2 works April > 2, group3 works April 3, group4 works April 4, group 1 works April 5, > etc. It just keeps rolling like this forever into next year, etc. > > I need to come up with a methodology for the following: > > If given a date, find out what group is working on that date. > Hello, You can use method datetime.date.toordinal() : from datetime import date start = date(2007,4,1) # Arpil 1, 2007 def group(_date): return (date.toordinal(_date)-date.toordinal(start)) % 4 print group(date(2007,4,15)) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: List comprehension returning subclassed list type?
On 25 mar, 08:43, "bullockbefriending bard" <[EMAIL PROTECTED]> wrote: > Given: > > class Z(object): > various defs, etc. > > class ZList(list): > various defs, etc. > > i would like to be able to replace > > z_list = ZList() > for y in list_of_objects_of_class_Y: > z_list.append(y) > > with something like this: > > z_list = [Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y] > > Of course this just gives me a plain list and no access to the > methodsof z_list. I could, of course go and write a static method in > ZList which takes a plain list of Z objects and returns a ZList. > > Anyway, my question is whether or not this can be done more elegantly > via list comprehension? Hello, A list comprehension will give you a list. But you can use a generator expression : z_list = ZList(Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: CGI handler: Retrieving POST and GET at the same time
On 10 mar, 19:52, "Samuel" <[EMAIL PROTECTED]> wrote: > Hi, > > I have the following form: > > > > > > and would like to retrieve both fields, "one" and "two". However, the > following does not work: > > form_data = cgi.FieldStorage() > for key in form_data: > print key + ":", form_data[key].value > > It prints out: > two: 2 > > How can I retrieve the GET variables in that context? > > -Samuel Hi, The argument passed in the url of the "action" attribute can be retrieved by : os.environ["QUERY_STRING"] To get the key-value dictionary : cgi.parse_qs(os.environ["QUERY_STRING"]) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a dictionary from a tuple of variable length
Hi, > Therefore, how do I build the tuple of Falses to reflect the length of my t > tuple? Yet another solution : d = dict(zip(t,[False]*len(t))) Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: paseline(my favorite simple script): does something similar exist?
> >>> parseline( 'A 1 22 3 6', 'sdxf') > ['A', 1, None, 3.0] Yes, but in this case the OP expects to get ['A',1,3.0] A shorter version : def parseline(line,format): xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [ xlat[f](w) for f,w in zip(format,line.split()) if xlat.get(f,None) ] if len(result) == 0: return None if len(result) == 1: return result[0] return result Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: paseline(my favorite simple script): does something similar exist?
Hi Rick, Nice little script indeed ! You probably mean > trans = xlat.get(f,None) instead of > trans = xlat.get(f,'None') in the case where an invalid format character is supplied. The string 'None' evaluates to True, so that trans(words[i]) raises an exception A variant, with a list comprehension instead of the for loop : def parseline(line,format): xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [] words = line.split() result = [ xlat[f](w) for f,w in zip(format,words) if xlat.get(f,None) ] if not result: return None if len(result) == 1: return result[0] return result Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Leave the putdowns in the Perl community, the Python world does not need them
I am also shocked by Fredrick Lundh's impoliteness and think he makes this group less friendly than I expected when I read this on http://www.python.org/community/lists/: "Rudeness and personal attacks, even in reaction to blatant flamebait, are strongly frowned upon. People may strongly disagree on an issue, but usually discussion remains civil" This should apply to anyone, from the newbie to the most valuable contributor to Python Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Python blogging software
Hi, There is a blog demo in Karrigell : http://karrigell.sourceforge.net There is a project called KarriBlog aiming to offer a more complete application, it's still beta but you can see it working on this site (in French) : http://www.salvatore.exolia.net/site Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: best small database?
Buzhug (like Karrigell and Strakell) is a Breton word ; Breton is the language spoken in Brittany, the westernmost part of France. Less and less spoken, actually, but I do, like all my ancestors. It is a close cousin of Welsh, and has common roots with Irish and Gaelic Buzhug means "earthworm", the big long brown worms that you find when you dig ; the shape is the same as a python, only smaller and less dangerous... You pronounce it "buzuk", with the French "u" or German "ü" Karrigell means "cart" and strakell, any sort of engine that you don't know its name. Bot rhyme with "hell" ; a and r like in French, g like in goat Now you know 3 words of Breton ! Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: best small database?
Here are some pure-Python databases : - gadfly : an SQL engine, mature and well tested, works in memory so not fit for large data sets - SnakeSQL : another SQL engine, less mature I think and very slow when I tested it - KirbyBase : stores data in a single file ; uses a more Pythonic syntax (no SQL) ; no size limit but performance decreases very much with the size. It looked promising but the last version is more than 1 year old and the author seems to focus on the Ruby version now - buzhug : Pythonic syntax (uses list comprehensions or methods like create(), select() on the db object), much faster than all the above. I'm obviously biaised : I wrote it... - for a small set of data you could also try strakell, the recipe I published on the Python Cookbook : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496770 With less than 200 lines of code, it's a very fast in-memory db engine that also uses list comprehensions for requests : SQL : SELECT name FROM persons WHERE age > 20 strakell : [ r["name"] for r in persons if r["age"] > 20 ] You can also create an index : persons.create_index("age") and then use it like this : persons.age[20] = list of the records where age = 20 Other pure-Python databases : ZODB (probably overkill for a small database) and Durus (I didn't test it) As said in others answers, the inclusion of SQLite in the standard distribution might make pure-Python solutions less attractive Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: key not found in dictionary
Depending on what you want to do if the key doesn't exist, you might want to use the dictionary method get() : value = some_dict.get(key,default) sets value to some_dict[key] if the key exists, and to default otherwise Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: modify element of a list.
Hi, The most simple is to use the index of the element in the list : def setAttribute(self, desc, value): n = anObject(desc, value) for i,o in enumerate(self.Objects): if o.getDescription() == desc: self.Objects[i] = n return self.Objects.append(n) Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: reading specific lines of a file
If the line number of the first line is 0 : source=open('afile.txt') for i,line in enumerate(source): if i == line_num: break print line Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating multiple lists from one list
# first step : build a dictionary mapping the objects # to all possible ids alist = ['a.1','b.3','b.4','c.2','c.6','d.3'] elts = {} for item in alist: obj=item.split('.')[0] if elts.has_key(obj): elts[obj].append(item) else: elts[obj] = [item] # then build the Python code that will iterate # on all the possible values ks = elts.keys() ks.sort() p_code = '' for i,k in enumerate(ks): p_code += i*' ' + "for item%s in elts['%s']:\n" %(i,k) p_code += len(ks)*' '+'print ['+','.join([ "item%s" %i for i,k in enumerate(ks) ])+']' # print the code print p_code >for item0 in elts['a']: > for item1 in elts['b']: > for item2 in elts['c']: > for item3 in elts['d']: >print [item0,item1,item2,item3] # execute this code exec p_code >['a.1', 'b.3', 'c.2', 'd.3'] >['a.1', 'b.3', 'c.6', 'd.3'] >['a.1', 'b.4', 'c.2', 'd.3'] >['a.1', 'b.4', 'c.6', 'd.3'] It works, but there are probably more elegant ways to do it Just a question : in your message you say that 'a.1' and 'b.1' can not exist together, but in the example there are lists with both 'b.3' and 'd.3' : should such lists be filtered ? Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: a class variable question
Erik Max Francis wrote: > Note this only changes the attribute in the instance. If he wants it to > be changed for all other instances, he needs to change it in the class > with:: A._var1 = 1 Yes, but in the OP's code func1() is called by __init__ for every instance - which in fact makes declaring _var1 as a class attribute useless Anyway, I find that changing the class attribute by calling a method on an instance is a little confusing. I would rather set the class attribute like this : class A2: _var1 = 0 def getvarValue(self): return self._var1 a = A2() print a.getvarValue() >>> 0 A2._var1 = 0 # change class attribute print a.getvarValue() >>> 1 b = A2() print b.getvarValue() >>> 1 Or using a class method : class A3: _var1 = 0 @classmethod def func1(cls): cls._var1 = 1 def getvarValue(self): return self._var1 a = A3() print a.getvarValue() >>> 0 A3.func1() # change class attribute print a.getvarValue() >>> 1 b = A3() print b.getvarValue() >>> 1 Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: a class variable question
In func1, _var1 = 1 creates a local variable _var1 (local to the method), not an attribute of the instance. If you want an instance attribute you must specify the reference to the instance by self._var1 = 1 ; self must be passed as an attribute to func1 def func1(self): self._var1 = 1 Similarly, in getvarValue : def getvarValue(self): return self._var1 Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-loading updated modules
Instead of exiting the interpreter, you can use reload() : see the section "Built-in functions" in the library reference "reload( module) Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument). " Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you help me with the below code? Urgent!
[EMAIL PROTECTED] a écrit : > Hello, > > You're right about it but this is a simple code which tells my problem. > I need actually the frame itself for states and unfortunately > copy.copy(frame) throws an exception. Pickling also doesn't work. Do > you have any other idea? > > Thanks, > > Gokce. > In your original post you said you wanted to store local variables, but it seems that you need to store more information than this : could you specify which ones ? Since you can't copy the stack frame, maybe you can copy only the attributes you need Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you help me with the below code? Urgent!
This is because in "states" you store a reference to frame.f_locals, not the value it takes. When you print states, all the items are the same reference to the same object and have the same value If you want to store the values at each cycle you should store a copy of frame.f_locals, which will give you a different object After import sys add the line : import copy and instead of states.append(frame.f_locals) write states.append(copy.copy(frame.f_locals)) Another example of this side-effect of storing references and not values : Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> states = [] >>> x = [0] >>> for i in range(10): ... x[0] = i ... states.append(x) ... >>> print states [[9], [9], [9], [9], [9], [9], [9], [9], [9], [9]] >>> Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Search substring in a string and get index of all occurances
mystring = 'John has a really nice powerbook.' substr = ' ' # space pos = 0 indices = [] while True: i = mystring.find(substr,pos) if i==-1: break indices.append(i) pos = i+1 print indices > [4, 8, 10, 17, 22] Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: New Karrigel page in Wikipedia
No, in the document root you create a folder "app1" and put all the files for the first application in it, and a folder "app2" for the second application For http://foo.example.com/app1 the server will search for an index file in this directory and serve it. You can also specify the script you want : http://foo.example.com/app1/default.py. Same thing for app2 of course. Absolutely no need to start two instances of the server on different ports Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: New Karrigel page in Wikipedia
The web server in Karrigell is actually application-independant. An application is a set of scripts or static files, generally stored in the same directory ; the server parses the http requests, searches for a file matching this request, processes the file according to its extension and sends the response For instance, the distribution provides a number of demo applications (a calendar, a wiki server, a forum etc) that can be all used when you start the server If you want to add a new application you just have to add the files, it will run without having to restart the server ; if you modify a script with a text editor, you see the result of the change the next time you reload the page Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: New Karrigel page in Wikipedia
Ok, thanks for the information. I have rewritten the page in a more neutral way and removed the tutorial-like part, I'll put in in wikibooks -- http://mail.python.org/mailman/listinfo/python-list
Re: New Karrigel page in Wikipedia
I added an entry in Wikipedia for information, just like other Python web frameworks have already done. If the style doesn't fit Wikipedia's I'm sorry and willing to learn how to improve it ; the reason I read was "Obvious, if elaborate, link spam. Really should be speedied, but I can't find a CSD that fits this". I don't really understand why it's called a spam, I don't know what a CSD is and I don't know either who deleted the prod template, not me anyway. I'll take wikipedia people's advice into account anyway -- http://mail.python.org/mailman/listinfo/python-list
Re: python library for web discussions
Take a look at Karrigell (http://www.karrigell.com), it has a built-in forum application Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Too Many if Statements?
This is because Python has a hidden mechanism to detect programs generated by Perl scripts, and make them crash with no explanation Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Server side newbie
swisscheese a écrit : > I have a simple python desktop app with several edit controls and a > couple of buttons. It just does some math. What's the simplest way to > make it a server-side app so visitors to my site can run the app via > their browser? > Among the many web frameworks for Python, Karrigell is probably the easiest to get started with You can check out a recent review on devshed : http://www.devshed.com/c/a/Python/Karrigell-for-Python/ It says : "Python novices won't find any obstacles when working with Karrigell, and Python experts won't feel too limited" Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Which Python web framework is most like Ruby on Rails?
Yes, there is a clear winner : "python zope" = 3.950.000 Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Which Python web framework is most like Ruby on Rails?
Just to add some more confusion to the discussion, here is what I've found about other web frameworks : CherryPy : BSD Django : BSD Jonpy : Python licence Quixote : CNRI Skunkweb : GPL or BSD Snakelets : MIT Subway : ? + licence of the components PythonWeb : LGPL (will consider BSD-Style or Python if LGPL is a problem) Turbogears : MIT + licence of the components Twisted : LGPL Webware : Python licence Zope : ZPL (Zope Public Licence) There doesn't seem to be an obvious choice, but the GPL isn't used much here Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Which Python web framework is most like Ruby on Rails?
In Karrigell the scripts are executed in a namespace prepared by the framework, with HTTP environment, form data, the functions and exceptions for authentication, session management, redirection etc. I suppose that this falls into the first category above, "modules (that) are designed to run linked together in a shared address space" ; the link between the framework and the scripts is certainly much tighter than between a web server and a CGI script Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Which Python web framework is most like Ruby on Rails?
I definitely don't want to invent another licence, there are enough of them already ! Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Which Python web framework is most like Ruby on Rails?
Hello all, I am Karrigell's author. I have chosen the GPL licence almost at random (I saw that the Python licence was GPL-compatible), so I don't mind switching to another Open Source licence if the GPL is liable to cause problems. Which one would you advice : BSD ? Python licence ? another ? Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
"0 in [True,False]" returns True
Hi all, In some program I was testing if a variable was a boolean, with this test : if v in [True,False] My script didn't work in some cases and I eventually found that for v = 0 the test returned True So I changed my test for the obvious "if type(v) is bool", but I still find it confusing that "0 in [True,False]" returns True By the way, I searched in the documentation what "obj in list" meant and couldn't find a precise definition (does it test for equality or identity with one of the values in list ? equality, it seems) ; did I miss something ? Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: strip not working on strings?
[EMAIL PROTECTED] a écrit : > I'm using Python 2.3.5 and when I type the following in the interactive > prompt I see that strip() is not working as advertised: > > s = 'p p:p' s.strip(' :') > > 'p p:p' > > Is this just me or does it not work? I want to get rid of all ' ' and > ':' in the string. I've checked the doc and from what I can tell this > is what strip() is supposed to do. Thanks for any help. > strip(chars) "returns a copy of the string with leading and trailing characters removed", that is, at the beginning and at the end of the string You can use this to remove the specified characters : for char in chars: s.replace(char,'') Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: which feature of python do you like most?
[EMAIL PROTECTED] a écrit : > > what is the thing that python makes you happy? > I discovered Python 5 years ago and I remember very well that what attracted me first was indentation. I had learnt JavaScript and rudiments of Java and couldn't decide on a consistent way of indenting my code, so it looked rather ugly and difficult to read. The first Python programs I saw struck me for the beauty of their graphical design (the use of lowercase letters also counts) As a learned the language itself I was attracted for the same reasons as the ones already given (simplicity, built-in types, list comprehensions...), but I still feel the same aesthetic pleasure every time I open a Python program to work on it Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlstring -- a library to build a SELECT statement
[EMAIL PROTECTED] a écrit : > > > My solution is sqlstring. A single-purpose library: to create SQL > statement objects. These objects (such as sqlstring.Select), represent > complex SQL Statements, but as Python objects. The benefit is that you > can, at run-time, "build" the statement pythonically, without > getting bogged down in String Manipulation. The theory is that once in > use, things that were complex (string magic) become simpler, and allow > the program to worry about higher-level issues. > With the same starting point - I don't like writing SQL strings inside Python code either - I have tested a different approach : use the Python list comprehension / generator expression syntax for the select requests I have published a recipe on the Python Cookbook : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442447 For instance : s = query(r.name for r in planes if r.speed > 500) for item in s: print s query is a class whose instances are created with the generator expression as argument. The matching SQL request is built in the __init__ method, here : SELECT r.name FROM planes AS r WHERE r.speed > 500 On two tables : s=query(r.name for r in planes for c in countries if r.country == c.country and c.continent == 'Europe') is translated into : SELECT r.name FROM countries AS c ,plane AS r WHERE (r.country = c.country AND c.continent = 'Europe') For the moment the implementation is not very elegant, especially for getting the source code of the generator expression (it would be nice if they had an attribute for that !), and I'm not sure if it could work for all the forms of the SELECT syntax. But it should cover at least the most usual kinds of requests, with a Pythonic syntax Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Concurrent access behind an asynchronous server
Sorry if the question seems naive, but is there a risk of concurrent accesses to a database if it is accessed only by scripts called by requests to an asynchronous server ? I have the same question for a server built on the non-threaded version of SocketServer.TCPServer A+ Pierre -- http://mail.python.org/mailman/listinfo/python-list
Strange os.path.exists() behaviour
os.path.exists(path) returns True if "path" exists But on Windows it also returns True for "path" followed by any number of dots : Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.exists('Lib/os.py') True# expected >>> os.path.exists('Lib/os.py.') True# unexpected >>> os.path.exists('Lib/os.py.') True# unexpected >>> Is there a reason for this ? Is there a test that returns True only for the really existing path ? Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Declaring variables from a list
You can use the built-in statement exec (http://www.python.org/doc/2.4.1/ref/exec.html) : # Blob = ['Var1', 'Var2', 'vAR3'] # i = 5 # for listitems in Blob: # i += 1 # exec('%s = i' %listitems) # # print Var1, Var2, vAR3 Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Web application toolkit recommendation?
[EMAIL PROTECTED] a écrit : I have looked briefly at Karrigell. does it support user logins? S Yes, you can take a look at the "portal" demo to see how it works Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with tkinter
Instead of indexing self.lab by strings, you can index them by the attributes themselves : self.lab[self.i], and change line 23 into for var in (self.s, self,i) For your example, I wouldn't have used the "text" option in the definition of the labels, then "textvariable" in the callback method (procedi) ; I would have used only "text" and no IntVar or StringVar, just an integer and a string : class MiaApp: def __init__(self, genitore): self.mioGenitore = genitore self.i = 42 self.s = "Baobab" self.lab = {} self.lab[self.i] = Label(self.mioGenitore) self.lab[self.i].configure(width = 30, relief = RIDGE, text = "[vuota]") self.lab[self.i].pack() self.lab[self.s] = Label(self.mioGenitore) self.lab[self.s].configure(width = 30, relief = RIDGE, text = "[vuota]") self.lab[self.s].pack() self.but = Button(self.mioGenitore) self.but.configure(text = "Vai!", command = self.procedi) self.but.pack() def procedi(self): for var in (self.i, self.s): self.lab[var].configure(text = var) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Widget geometry ?
PGMoscatt a écrit : Hi All, I am trying to create a dialog which will have a number of components but having trouble with the placement of various widgets. For example, in my code below you will see I am trying to insert alabel but I want the label to be in the top-left of the dialog but it dosen't want to go there. What am I doing wrong ? Pete from Tkinter import * class show_settings_dialog: def __init__(self,parent): top = self.top = Toplevel(parent) top.title("General Settings...") top["height"]=300 top["width"]=300 top.pack_propagate(0) l1 = Label(top,text="User Name:").grid(row=0, sticky=W) b = Button(top,text="Ok",command=self.ok) b.pack(pady=40) def ok(self): self.top.destroy() You are mixing pack() and grid() to place widgets in the same container. Try doing b.grid(row=0,column=1) instead Regards Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter and Text() widget interactivity ?
Tonino a écrit : Hi, I have a small Tkinter app that gets data from a socket connection to a "server". The app has a Text() widget to display the info that it gets from the socket connection. I have the ability to stop the text at any point. What I want to be able todo is select a line from the Text() window and double click or whatever on it to open a new window with that selected text as a paramater to the new window. The app is a network sniffer and I want to be able to select a line from the Text() window and run a decode on the data from the sniffer. any help and pointers would help. I have no idea of what to search for ;) Thanks Here is an example of what you can do : # from Tkinter import * # # def action(event): # begin,end=event.widget.tag_ranges(SEL) # selected_text=event.widget.get(begin,end) # new_window = Toplevel(root) # n_text = Text(new_window) # n_text.pack() # n_text.insert(END,selected_text) # # root=Tk() # t=Text(root) # t.pack() # t.tag_bind(SEL,"",action) # t.insert(END,"Sweetness, sweetness I was only joking when I said\n") # t.insert(END,"By rights you should be bludgeoned in your bed") # # root.mainloop() In a Text widget you can add event bindings to tags, the selected text has the built-in tag SEL. I don't think you can bind the event to it because double-clicking on a text widget selects the word the cursor is on ; here I use (left click) but you can use other events In the function "action" the widget where the event occured is event.widget (the Text widget). Its method tag_ranges returns the beginning and end of the text with the specified tag (here SEL), then you get the selected text by the method get() of the text widget This is explained in "An introduction to Tkinter" by Fredrik Lundh, in the chapter "The Text Widget" http://www.pythonware.com/library/tkinter/introduction/ Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: intersection of 2 list of pairs
Another method is to build two sets of sets, one for E1 and one for E2, then make the intersection of these sets - with Python 2.3 >>> E1=[('a','g'),('r','s')] >>> E2=[('g','a'),('r','q'),('f','h')] >>> from sets import Set,ImmutableSet >>> f=Set([ImmutableSet(s) for s in E1])& Set([ImmutableSet(s) for s in E2]) >>> [tuple(x) for x in f] [('a', 'g')] - with Python 2.4 >>> E1=[('a','g'),('r','s')] >>> E2=[('g','a'),('r','q'),('f','h')] >>> f=set([frozenset(s) for s in E1]) & set([frozenset(s) for s in E2]) >>> [tuple(x) for x in f] [('a', 'g')] You must use ImmutableSet or frozenset to be able to create a set of sets Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: recommended way of generating HTML from Python
Here are a couple of pointers. I agree with Michele that it would be nice to have some kind of standardization. Maybe this would be worth a post to the Web-SIG ? - I posted a 70-line recipe on the Python Cookbook, a sort of poor man's HTMLGen called HTMLTags http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366000 with a syntax like this : # print HTML( HEAD(TITLE('Test document')) + #BODY(H1('This is a test document')+ #TEXT('First line')+BR()+ #TEXT('Second line'))) The use of addition allows for shortcuts like print Sum([ TR(TD(i)+TD(i*i)) for i in range(100) ]) where Sum works like the built-in sum, but sum only works for numbers apparently - in the Cookbook someone mentioned the HyperText package, published in 2000 by Andy Dustman : http://dustman.net/andy/python/HyperText/ It uses this syntax : # print TABLE( #TR((TH('SPAM'), TH('EGGS')), #TR(TD('foo','bar', colspan=2)) # ) The package also handles XML, SGML etc. - I wrote to Andy and he said there was also Living Logic's XIST : http://www.livinglogic.de/Python/xist/index.html An example taken from the site : #node = xsc.Frag( # xml.XML10(), # html.DocTypeXHTML10transitional(), # html.html( # html.head( # meta.contenttype(), # html.title("Example page") # ), # html.body( # html.h1("Welcome to the example page"), # html.p( #"This example page has a link to the ", #html.a("Python home page", href="http://www.python.org/";), #"." # ) # ) # ) # ) # # print node.conv().asBytes(encoding="us-ascii") -- http://mail.python.org/mailman/listinfo/python-list
Re: Probably over my head... Trying to get Font Names
"Samantha" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... > I am attempting to extract the Font Names from the installed windows fonts. > I am having a heck of a time getting these rather than the file names. > Examples can be seen by going to Control Panel > Fonts > > Any help or direction is appreciated. > S Try this : Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import Tk >>> import tkFont >>> root=Tk() >>> print tkFont.families(root) -- http://mail.python.org/mailman/listinfo/python-list