Re: [Tutor] Extracting xml text
Hello, The following is an example which works for me to count opening tags in a xml doc, if it can help: # -*- coding: iso-8859-1 -*- import sys from xml.parsers.expat import ParserCreate n = 0 def start_element(name, attrs): # callback declaration global n n += 1 parser = ParserCreate() # création du parser parser.StartElementHandler = start_element # initialization parser.ParseFile(file(sys.argv[1])) # get the input file print '%d opening tags' % n Regards Karim France On 06/20/2010 08:03 AM, T.R. D. wrote: xml strings and so far it looks like the xml.parsers.expat is the way to go but I'm not quite sure how it works. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extracting xml text
In fact you must initialize the handler before parsing the xml doc and it should work. Regards Karim France On 06/20/2010 10:12 AM, Karim wrote: Hello, The following is an example which works for me to count opening tags in a xml doc, if it can help: # -*- coding: iso-8859-1 -*- import sys from xml.parsers.expat import ParserCreate n = 0 def start_element(name, attrs): # callback declaration global n n += 1 parser = ParserCreate() # création du parser parser.StartElementHandler = start_element # initialization parser.ParseFile(file(sys.argv[1])) # get the input file print '%d opening tags' % n Regards Karim France On 06/20/2010 08:03 AM, T.R. D. wrote: xml strings and so far it looks like the xml.parsers.expat is the way to go but I'm not quite sure how it works. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extracting xml text
Hello Stefan, I know you are promoting Etree and I am very interesting in it. Is there any chance to have it integrated in future standard Python version? Regards Karim On 06/20/2010 10:14 AM, Stefan Behnel wrote: T.R. D., 20.06.2010 08:03: I'm trying to parse a list of xml strings and so far it looks like the xml.parsers.expat is the way to go but I'm not quite sure how it works. I'm trying to parse something similar to the following. I'd like to collect all headings and bodies and associate them in a variable (dictionary for example). How would I use the expat class to do this? Well, you *could* use it, but I *would* not recommend it. :) Tove Jani Reminder Don't forget me this weekend! Jani Tovi Reminder 2 Don't forget to bring snacks! Use ElementTree's iterparse: from xml.etree.cElementTree import iterparse for _, element in iterparse("the_file.xml"): if element.tag == 'note': # find text in interesting child elements print element.findtext('heading'), element.findtext('body') # safe some memory by removing the handled content element.clear() iterparse() iterates over parser events, but it builds an in-memory XML tree while doing so. That makes it trivial to find things in the stream. The above code receives an event whenever a tag closes, and starts working when the closing tag is a 'note' element, i.e. when the complete subtree of the note element has been parsed into memory. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] elif statement
Hello, This code works for me: >>> x=3 >>> if x==0: ... print "x is 0" ... elif x&1 ==1: ... print "x is a odd number" ... elif x&1==0: ... print "x is a even number" ... x is a odd number So I think you copied by error the string '-- Line 6' in you example given that has nothing to do with the rest of the code. Regards Karim On 08/11/2010 03:34 AM, Sudarshana Banerjee wrote: print "x is a even number" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Executing Python from TCL
Hello Tutors, I want to know if there are modules or whatever to execute python functions inside TCL. These functions should returns python lists as TCL lists and Python dictionary as TCL Hash tables. Existing (opensource) tools, packages are welcome! I want to avoid to do it myself (anyway I don't have any idea how to do it :o) ) In fact, I develop parser for xml using xml.etree.ElementTree and another team which develop in TCL need to access it via an API I should do. Great Challenge. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing Python from TCL
Hello Alan, I want to take benefit of xml.etree.ElementTree and xml.etree.CElementTree, which are very good and do most of the job for me (create automatically database with lists and dictionary for me). My point is to do a same API used by team developing with Python and another team developing in TCL. I want to facilitate the reuse and make everybody happy (no war between the 2 languages supporters) though for me Python is largely superior. Anyway, you're right I found what I needed at: http://sourceforge.net/projects/elmer/files/elmer/elmer1.1.5/elmer1.1.5.tar.gz/download This is the open source Elmer distribution. Thanks Karim On 08/12/2010 02:13 AM, Alan Gauld wrote: "Karim" wrote I want to know if there are modules or whatever to execute python functions inside TCL. Not that I know of, unless Google tells you something different. You can of course call Python programs from Tcl and vice-versa. If you use the Java versions of both you might succeed. Or you could wrap your parser as a separate server process and expose it as a Web service or XML RPC... But given the wealth of xml parsers available for Tcl I'm surprised that they need yours... These functions should returns python lists as TCL lists and Python dictionary as TCL Hash tables. You could probably do some C level integration using Boost or SWIG or somesuch but I doubt the benefit would be worth it. HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Executing Python from TCL
Thanks Alan, For clarify that. The speed is not an issue people just need config files generated from xml to feed EDA simulations and validations tools. Karim On 08/12/2010 09:39 AM, Alan Gauld wrote: "Karim" wrote Anyway, you're right I found what I needed at: http://sourceforge.net/projects/elmer/files/elmer/elmer1.1.5/elmer1.1.5.tar.gz/download This is the open source Elmer distribution. OK, glad you found something and I'm sure it will be worth a try. But I'm pretty sure it will have to embed the Python interpreter so that the Tcl interpreter will call the python interpreter to execute the parser. That could lead to a significant slow down of your code. If speed is not a high priority you may get away with it. At least it should prove the concept and design of the app. But you may still find you need to use a native Tcl parser if speed is an issue. (Then again, if speed was a big issue you probably wouldn't be working in Tcl or even Python!) HTH ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Elementtree and pretty printing in Python 2.7
Sorry wrong import! from xml.minidom import parseString from xml.etree import ElementTree Karim On 08/22/2010 05:24 PM, Karim wrote: Hello Jerry, Tricky solution using minidom (standard) Not tested: import ElementTree import minidom def prettyPrint(element): txt = ElementTree.tostring(element) print minidom.parseString(txt).toprettyxml() Regards Karim On 08/22/2010 04:51 PM, Jerry Hill wrote: On Fri, Aug 20, 2010 at 3:49 AM, Knacktus wrote: Hi guys, I'm using Python 2.7 and the ElementTree standard-lib to write some xml. My output xml has no line breaks! So, it looks like that: instead of something like this: I'm aware of lxml which seems to have a pretty print option, but I would prefer to use the standard-lib ElementTree which seems not to have a feature like this. Do I miss something using the ElementTree-lib or is it bug? Neither, as far as I know. The XML you get is perfectly valid XML. If you want to pretty print it, there's a recipe here: http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think it's been included in the standard library yet. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Elementtree and pretty printing in Python 2.7
Hello Jerry, Tricky solution using minidom (standard) Not tested: import ElementTree import minidom def prettyPrint(element): txt = ElementTree.tostring(element) print minidom.parseString(txt).toprettyxml() Regards Karim On 08/22/2010 04:51 PM, Jerry Hill wrote: On Fri, Aug 20, 2010 at 3:49 AM, Knacktus wrote: Hi guys, I'm using Python 2.7 and the ElementTree standard-lib to write some xml. My output xml has no line breaks! So, it looks like that: instead of something like this: I'm aware of lxml which seems to have a pretty print option, but I would prefer to use the standard-lib ElementTree which seems not to have a feature like this. Do I miss something using the ElementTree-lib or is it bug? Neither, as far as I know. The XML you get is perfectly valid XML. If you want to pretty print it, there's a recipe here: http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think it's been included in the standard library yet. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Retriving previous user inputs in a gui
Hello All, I am figuring this out. I want a sort of file who store values entered previously in a gui. Th e next time the user launch his gui in the same directory the gui load the previous value from this file. Is there any modules in Tkinter for that? I suppose the file could be in xml format or whatever? pyGTK solution is welcome too! Even if I prefered to use the standard package. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retriving previous user inputs in a gui
Thank you Alan for your answer. In fact I want to do it in python format. I want to source it (I will declare it each input as a python variable). I don't want to parse it. I just want to source it like an external file in bash for example. Is there a way to not use string evaluation. But really load it as python setting file inside python program. PS: ConfigParser, hum very good , this could be of use for other part... Karim On 08/24/2010 08:03 PM, Alan Gauld wrote: "Karim" wrote I am figuring this out. I want a sort of file who store values entered previously in a gui. Thats easy enough - have you succeeded with this bit - check the file with a text editor... Th e next time the user launch his gui in the same directory the gui load the previous value from this file. Again thats pretty easy, did you get this working - create the file with a text editior? Is there any modules in Tkinter for that? No, Tkinter is for building GUIs. Python core language includes functions for reading and writing to files. Can you do this outside a GUI? Write a program to read the users name and save it to a file. Write a program to read the file and print the name it finds. Write a program that says Hello if it finds a name and asks for a name if it doesn't. Now translate that to your GUI. suppose the file could be in xml format or whatever? Yes, it could be in whatever. CSV, XML, ConfigParser or even plain text. HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retriving previous user inputs in a gui
Ok I find a solution (need to test it) that seems correct: Suppose we have a python file mySourceFile with this setting: EntryTextName = "myName" EntryTextMail = "mym...@gmail.com" In the calling script or main python file we could define a function sourceConfigGui as follow: def sourceConfigGui(mySourceFile,path_to_mysourcefile): import mySourceFile import sys sys.path.append(path_to_mysourcefile) If you have any other solution to source a external py file let me know. Regards On 08/24/2010 08:21 PM, Karim wrote: Thank you Alan for your answer. In fact I want to do it in python format. I want to source it (I will declare it each input as a python variable). I don't want to parse it. I just want to source it like an external file in bash for example. Is there a way to not use string evaluation. But really load it as python setting file inside python program. PS: ConfigParser, hum very good , this could be of use for other part... Karim On 08/24/2010 08:03 PM, Alan Gauld wrote: "Karim" wrote I am figuring this out. I want a sort of file who store values entered previously in a gui. Thats easy enough - have you succeeded with this bit - check the file with a text editor... Th e next time the user launch his gui in the same directory the gui load the previous value from this file. Again thats pretty easy, did you get this working - create the file with a text editior? Is there any modules in Tkinter for that? No, Tkinter is for building GUIs. Python core language includes functions for reading and writing to files. Can you do this outside a GUI? Write a program to read the users name and save it to a file. Write a program to read the file and print the name it finds. Write a program that says Hello if it finds a name and asks for a name if it doesn't. Now translate that to your GUI. suppose the file could be in xml format or whatever? Yes, it could be in whatever. CSV, XML, ConfigParser or even plain text. HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retriving previous user inputs in a gui
Correction indents disappear (sic !) and lines are inverted (my mistake too) :o): def sourceConfigGui(mySourceFile,path_to_mysourcefile): import sys sys.path.append(path_to_mysourcefile) import mySourceFile Karim On 08/24/2010 09:28 PM, Karim wrote: Ok I find a solution (need to test it) that seems correct: Suppose we have a python file mySourceFile with this setting: EntryTextName = "myName" EntryTextMail = "mym...@gmail.com" In the calling script or main python file we could define a function sourceConfigGui as follow: def sourceConfigGui(mySourceFile,path_to_mysourcefile): import mySourceFile import sys sys.path.append(path_to_mysourcefile) If you have any other solution to source a external py file let me know. Regards On 08/24/2010 08:21 PM, Karim wrote: Thank you Alan for your answer. In fact I want to do it in python format. I want to source it (I will declare it each input as a python variable). I don't want to parse it. I just want to source it like an external file in bash for example. Is there a way to not use string evaluation. But really load it as python setting file inside python program. PS: ConfigParser, hum very good , this could be of use for other part... Karim On 08/24/2010 08:03 PM, Alan Gauld wrote: "Karim" wrote I am figuring this out. I want a sort of file who store values entered previously in a gui. Thats easy enough - have you succeeded with this bit - check the file with a text editor... Th e next time the user launch his gui in the same directory the gui load the previous value from this file. Again thats pretty easy, did you get this working - create the file with a text editior? Is there any modules in Tkinter for that? No, Tkinter is for building GUIs. Python core language includes functions for reading and writing to files. Can you do this outside a GUI? Write a program to read the users name and save it to a file. Write a program to read the file and print the name it finds. Write a program that says Hello if it finds a name and asks for a name if it doesn't. Now translate that to your GUI. suppose the file could be in xml format or whatever? Yes, it could be in whatever. CSV, XML, ConfigParser or even plain text. HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retriving previous user inputs in a gui
after tests I get the following: >>> import params >>> dir(params) ['EntryTextMail', 'EntryTextName', '__builtins__', '__doc__', '__file__', '__name__', '__package__'] >>> params.EntryTextName 'myName' >>> params.EntryTextMail 'mym...@gmail.com' But the file to import should have '.py' extension (.py) (if there is a way to avoid that I wanted to use a 'hidden' file kind of ".config" , I can create a dynamical link to that file with .py then import it and at last delete the symbolic link). I should do a small class for that to reuse it. At first I tried to access it as variables instead of using .variable. I learnt something here! Regards Karim On 08/24/2010 09:38 PM, Karim wrote: Correction indents disappear (sic !) and lines are inverted (my mistake too) :o): def sourceConfigGui(mySourceFile,path_to_mysourcefile): import sys sys.path.append(path_to_mysourcefile) import mySourceFile Karim On 08/24/2010 09:28 PM, Karim wrote: Ok I find a solution (need to test it) that seems correct: Suppose we have a python file mySourceFile with this setting: EntryTextName = "myName" EntryTextMail = "mym...@gmail.com" In the calling script or main python file we could define a function sourceConfigGui as follow: def sourceConfigGui(mySourceFile,path_to_mysourcefile): import mySourceFile import sys sys.path.append(path_to_mysourcefile) If you have any other solution to source a external py file let me know. Regards On 08/24/2010 08:21 PM, Karim wrote: Thank you Alan for your answer. In fact I want to do it in python format. I want to source it (I will declare it each input as a python variable). I don't want to parse it. I just want to source it like an external file in bash for example. Is there a way to not use string evaluation. But really load it as python setting file inside python program. PS: ConfigParser, hum very good , this could be of use for other part... Karim On 08/24/2010 08:03 PM, Alan Gauld wrote: "Karim" wrote I am figuring this out. I want a sort of file who store values entered previously in a gui. Thats easy enough - have you succeeded with this bit - check the file with a text editor... Th e next time the user launch his gui in the same directory the gui load the previous value from this file. Again thats pretty easy, did you get this working - create the file with a text editior? Is there any modules in Tkinter for that? No, Tkinter is for building GUIs. Python core language includes functions for reading and writing to files. Can you do this outside a GUI? Write a program to read the users name and save it to a file. Write a program to read the file and print the name it finds. Write a program that says Hello if it finds a name and asks for a name if it doesn't. Now translate that to your GUI. suppose the file could be in xml format or whatever? Yes, it could be in whatever. CSV, XML, ConfigParser or even plain text. HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retriving previous user inputs in a gui
Thanks Alan for you advice! Our environment is secured because the program is only for internal use. We are supporting electronic designers. Nobody at work will write delete codes inside (I hope). But, sure, I will check configParser module. I wanted a straight forward config file because for TCL/TK GUI .config file is already existing in TCL format that executing same syntax '*set myvar myvar_value*'. I wanted to recreate this mechanism for python gui. Thanks to point out this security issue. Is there any equivalent to JAVACC in python (or lex yacc) to create grammary for config or format file? Regards Karim On 08/25/2010 01:57 AM, Alan Gauld wrote: "Karim" wrote >>> import params >>> dir(params) ['EntryTextMail', 'EntryTextName', '__builtins__', '__doc__', But the file to import should have '.py' extension (.py) (if there is a way to avoid that I wanted to use a 'hidden' file kind of ".config" , You can exec a file and you can read the file into a string as a variable then exec the string. BUT doing this is a huge security risk since anyone can put any kind of arbitrary code in your config file and you will blindly execute it. That's why config files are generally not executable code but some kind of data format - it's much safer and very little extra work. At first I tried to access it as variables instead of using .variable. I learnt something here! Any time you import a module you need to use the module name to access its contents - or use the from moo import * format, but that introduces even more risk! I strongly recommend that you think again and use a data format config file. HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such file or directory
If it is in the sys.path you should import it: *import ex1*. Then execute something like *ex1.main()* if you did a main(). Other python */ex.py* should world. Regards Karim On 08/25/2010 05:22 AM, Carter Danforth wrote: Hi everyone, This is my first email to group - I'm just starting to pick up Python and I'm going through the exercises in Zed Shaw's "Learn Python the Hard Way" ebook. Anyhow, I can't seem to be executing any files in terminal for some reason, in this case the file ex1.py: C:\Users\Carter Danforth\python ex1.py python: can't open file 'ex1.py': [Errno 2] No such file or directory ex1.py is located in "pythonpractice" on my desktop and I've updated the modules, here's the output from sys.path: ['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Users\\Carter Danforth\\Desktop\\pythonpractice', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] And the environmental variable is set to have python on my path: C:\Users\Carter Danforth>python Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> I'm not sure why I keep getting this error message and why I'm not able to execute any .py files. Any help would be great appreciated. Carter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] What Design Pattern for Document class (NOT URGENT)
Hello All, I want to build some classes by optimizing their design. But I want to keep quite 'simples'. I have a XML document which represents let's say some rules (id, description, value). My first idea is to create an *docrules* class which holds my document. This class will use 2 other instances from 2 respectives classes reader and writer. The main method of reader is get(). The main method of writer is write(). To resume I have: -- --- - docrules --- reader - -- --- - filename - - file - - --- - - - get() - - ------ -- - - - ---writer- - file - - write() - The *docrules* will do the parsing (*xml.etree* very effective) and create the reader and the writer instance. I want to create 2 others classes (or more) more specific which have more the knowledge about the XML documents structures. *SpecificRuleReader*, *SpecificRuleWriter* which are deriving resp. from Reader and Writer which hold resp. *getSpecificRules*() (use of get('/tag1/tag2/tag3/specificTagRules') and a* writeSpecificRules*(): - - reader writer - - ^ ^ || --- --- *SpecificRuleReader* *SpecificRulesWriter* --- --- *getSpecificRules*() *writeSpecificRules()* -- My purpose is to separate as far as possible XML representation from core classes. I will have certainly more SpecificrulesReader/Writer classes becauses the document is huge and several discipline rules will be adressed. I don't want necessarily have 2 big classes which know everything about XML document because I will have too many methods. So, for if anybody has this kind of experience or any design pattern idea, I will be enchanté. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pythonpath
On 11/01/2010 10:41 PM, Chris King wrote: Dear Tutors, When I try to import a module, how can I make it look in certain directories for them easily. Sincerely, Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hello, PYTHONPATH environment variable set to /path/to/you/libs. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Too different 2.6 vs 2.7?
Hello Jorge, I have Ubuntu 10.04 LTS and get the same issue. I installed 2.7 version manually in another place using -prefix option. It works as long as you are pointing to the correct bin (python2.7) and the local lib/ installation (PYTHONPATH) from python 2.7. Regards Karim On 11/08/2010 09:44 PM, Jorge Biquez wrote: Hello all. Newbie question. Are there really BIG differences between version 2.6 and 2.7? Under my ubuntu configuration I can not install version 2.7, searching the why, but the version 2.6 is maintained and installed by the ubuntu software center. As a newby , trying to learn all the features of all the libraries. Will I miss TOO much if I stay under version 2.6? Or it will be better to stay under 2.7 (in that case under Windows XP) Thanks in advance for your comments. Jorge Biquez ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python module structure & directories
Hello, I use to have it under src/lib as follow: src/lib/python src/lib/tcl src/lib/c All *.py modules are in src/lib/python with all the possible modules hierarchy. Then, At build time I copy lib root directory in the install. (with all C code compiled). Then the startup bin executable do the following as Alan said: *if ! echo $PYTHON | grep "/lib" > /dev/null ; then export PYTHONPATH="/lib:${PYTHONPATH}" fi* The conditional statement is here just to not overload the environment variable. Best Regards Karim On 11/25/2010 02:23 AM, Alan Gauld wrote: "Judy Chen" wrote I am very new to Python, I worked on C/C++ before. I would like to know is it a good practice to put Python development code under ../src/UI/foo.py ../src/businesslogic/bar.py, etc. Thats fine, especially if its a big project. src means source code and python is a type of source just as C is. or should we eliminate "src' directory since it is not pythonic, or it very C/C++ like. Who says its not pythonic? src is a perfectly common name to use on Unix type systems for all types of source code. I was told that the above directory/file structure does not apply to Python, since Python's source code are objects. The source code is not really an object but becaiuse you can import any python file as a module, and modules are objects (once they are loaded) you might get away with saying that. But really, python source files are no different to any other source files when it comes to organising your file system for a project. Are there any standard for how Python source code to be structured? Not that I'm aware of. There are some standards for how to create packages which might restrict things a little but oprovided you have your PYHONPATH set up tio find the modules all should be well. And you might want to create a build script that moves the modules from src to lib in the production file system. But on a project, especially one with multiple programming languages, having all source files in one place is a definite plus IMHO. Another thing to do would be take a look at some of the Python projects on Sourceforge - DIA for example. See how they structure their code. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python module structure & directories
Another possibility is to place you python library in the site package of your network installation, namely for my computer: *$HOME/build/python/src/Python-2.7.1rc1/Lib/site-packages* I build the latest release of python (rc1). But At build time I believe that the path to the libraries is hard-coded somewhere. Indeed, I provide the python v2.7.1rc1 package along with my application and I use PYTHONPATH to overcome this fact and point to the libraries of v2.7.1rc1 and PATH for python exec. Like that I am independent of the version of python present on a particular machine. Best Regards Karim On 11/25/2010 02:23 AM, Alan Gauld wrote: "Judy Chen" wrote I am very new to Python, I worked on C/C++ before. I would like to know is it a good practice to put Python development code under ../src/UI/foo.py ../src/businesslogic/bar.py, etc. Thats fine, especially if its a big project. src means source code and python is a type of source just as C is. or should we eliminate "src' directory since it is not pythonic, or it very C/C++ like. Who says its not pythonic? src is a perfectly common name to use on Unix type systems for all types of source code. I was told that the above directory/file structure does not apply to Python, since Python's source code are objects. The source code is not really an object but becaiuse you can import any python file as a module, and modules are objects (once they are loaded) you might get away with saying that. But really, python source files are no different to any other source files when it comes to organising your file system for a project. Are there any standard for how Python source code to be structured? Not that I'm aware of. There are some standards for how to create packages which might restrict things a little but oprovided you have your PYHONPATH set up tio find the modules all should be well. And you might want to create a build script that moves the modules from src to lib in the production file system. But on a project, especially one with multiple programming languages, having all source files in one place is a definite plus IMHO. Another thing to do would be take a look at some of the Python projects on Sourceforge - DIA for example. See how they structure their code. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Package loading
Hello every one, I created a package with the following structure: * ops/ o __init__.py o tcl/ + __init__.py + pythontcl.py > *python -c "import sys; print sys.path; import ops.tcl.pythontcl"* ['', '/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.5-py2.6.egg', '*/home/karim/build/UML2PDK/lib/python*', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages'] /*home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:109: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import unittest /home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:110: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import sys* At the lines I import standard modules sys and unittest I get these non-sense warning (my consideration) though I added the top package root, namely, */home/karim/build/UML2PDK/lib/python. The programesecute correctly but I alaways get this nerving warning. *Any idea will be welcome!* :-) *Regards Karim* * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Package loading
On 11/29/2010 09:15 PM, Karim wrote: Hello every one, I created a package with the following structure: * ops/ o __init__.py o tcl/ + __init__.py + pythontcl.py > *python -c "import sys; print sys.path; import ops.tcl.pythontcl"* ['', '/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.5-py2.6.egg', '*/home/karim/build/UML2PDK/lib/python*', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages'] /*home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:109: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import unittest /home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:110: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import sys* At the lines I import standard modules sys and unittest I get these non-sense warning (my consideration) though I added the top package root, namely, */home/karim/build/UML2PDK/lib/python. The programesecute correctly but I alaways get this nerving warning. *Any idea will be welcome!* :-) *Regards Karim* * I believed I know why: Traceback (most recent call last): File "", line 1, in File "/home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py", line 119, in print sys.modules[__package__] KeyError: 'pythontcl' It is due to method determine parent in class ModuleImporter. I don't know why sys.modules has the key 'ops.tcl.pythontcl' and this class search for the key module 'pythontcl'. Big mess between relative path or whatever. Any idea to fix that? Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Package loading
On 11/30/2010 12:58 AM, Karim wrote: On 11/29/2010 09:15 PM, Karim wrote: Hello every one, I created a package with the following structure: * ops/ o __init__.py o tcl/ + __init__.py + pythontcl.py > *python -c "import sys; print sys.path; import ops.tcl.pythontcl"* ['', '/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.5-py2.6.egg', '*/home/karim/build/UML2PDK/lib/python*', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages'] /*home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:109: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import unittest /home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:110: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import sys* At the lines I import standard modules sys and unittest I get these non-sense warning (my consideration) though I added the top package root, namely, */home/karim/build/UML2PDK/lib/python. The programesecute correctly but I alaways get this nerving warning. *Any idea will be welcome!* :-) *Regards Karim* * I believed I know why: Traceback (most recent call last): File "", line 1, in File "/home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py", line 119, in print sys.modules[__package__] KeyError: 'pythontcl' It is due to method determine parent in class ModuleImporter. I don't know why sys.modules has the key 'ops.tcl.pythontcl' and this class search for the key module 'pythontcl'. Big mess between relative path or whatever. Any idea to fix that? Karim Ok fixed. I must not set the special variable __name__. I set it for pydoc docstrings. Now the __name__ is automatically set to 'ops.tcl.pythontcl' and __package__ is set correctly to 'ops.tcl'. Kind Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] The Template Pattern
Hello all, I am seeking for information about the template pattern applied to python. Could you explain some implementation or anything else? it would be helpful. Regards Thanks a lot Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Template Pattern
On 12/13/2010 11:47 PM, Steven D'Aprano wrote: Karim wrote: Hello all, I am seeking for information about the template pattern applied to python. Could you explain some implementation or anything else? it would be helpful. Design patterns are means to an end, not an end in themselves. You shouldn't say "I want to use the template pattern", you should say "I want to solve this problem, what solution is appropriate?" and then only use the template pattern if it is appropriate. Steven, thank you for answering ;o) I don't want to use this pattern absolutely. But I discussed this topic with a C++ programmer. He wanted to translate part of C++ code in python that implements this pattern in C++. I already have implemented a Strategy pattern in python to read different file format into my database and generate different output format file like the code below: class Input(object): """The basic Input class, leaving out the details of the algorithm.""" def __init__( self, strategy ): self.strategy = strategy self.lastRead = None def read(self, filePath): """Load into database memory an input file. @arg: filePath - string - The input file path. @return: The created database object. """ self.lastRead = self.strategy.read() return self.lastRead class InputStrategy( object ): """This InputStrategy class is an abstract interface to various read strategy objects. """ def read(self, filePath): """Abstract method to load into database memory an input file. @arg: filePath - string - The input file path. @return: The created database object. """ raise NotImplementedError By the way, I use NotImplementedError in my abstract method of the abstract class. You are using TypeError exception. Is there a general rule for that? NotImplementedError is ok? I knew from Java experience that template method pattern is only a kind of particular case of Stategy where you delegate parts of algorithm by abstract methods overriding. Indeed the base class implements some common features and let derived classes implement particular parts by polymorphism. Now with your example, I don't understand why he had problems to implement from C++ ? Or perhaps is he mixing it with C++ feature template ?! In any case, the template design pattern is one of the simpler design patterns. Here's an example, adapted from Wikipedia's article on the Template Method Pattern: class AbstractGame: """An abstract class that is common to several games in which players play against the others, but only one is playing at a given time. """ def __init__(self, *args, **kwargs): if self.__class__ is AbstractGame: raise TypeError('abstract class cannot be instantiated') def playOneGame(self, playersCount): self.playersCount = playersCount self.initializeGame() j = 0 while not self.endOfGame(): self.makePlay(j) j = (j + 1) % self.playersCount self.printWinner() def initializeGame(self): raise TypeError('abstract method must be overridden') def endOfGame(self): raise TypeError('abstract method must be overridden') def makePlay(self, player_num): raise TypeError('abstract method must be overridden') def printWinner(self): raise TypeError('abstract method must be overridden') Now to create concrete (non-abstract) games, you subclass AbstractGame and override the abstract methods. class Chess(AbstractGame): def initializeGame(self): # Put the pieces on the board. ... def makePlay(player): # Process a turn for the player ... etc. One more Thanks for you example Steven! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Template Pattern
Hello Steven, Could take some time when possible to answer to my follow-up question? Thank you! Cheers Karim On 12/14/2010 12:19 AM, Karim wrote: On 12/13/2010 11:47 PM, Steven D'Aprano wrote: Karim wrote: Hello all, I am seeking for information about the template pattern applied to python. Could you explain some implementation or anything else? it would be helpful. Design patterns are means to an end, not an end in themselves. You shouldn't say "I want to use the template pattern", you should say "I want to solve this problem, what solution is appropriate?" and then only use the template pattern if it is appropriate. Steven, thank you for answering ;o) I don't want to use this pattern absolutely. But I discussed this topic with a C++ programmer. He wanted to translate part of C++ code in python that implements this pattern in C++. I already have implemented a Strategy pattern in python to read different file format into my database and generate different output format file like the code below: class Input(object): """The basic Input class, leaving out the details of the algorithm.""" def __init__( self, strategy ): self.strategy = strategy self.lastRead = None def read(self, filePath): """Load into database memory an input file. @arg: filePath - string - The input file path. @return: The created database object. """ self.lastRead = self.strategy.read() return self.lastRead class InputStrategy( object ): """This InputStrategy class is an abstract interface to various read strategy objects. """ def read(self, filePath): """Abstract method to load into database memory an input file. @arg: filePath - string - The input file path. @return: The created database object. """ raise NotImplementedError By the way, I use NotImplementedError in my abstract method of the abstract class. You are using TypeError exception. Is there a general rule for that? NotImplementedError is ok? I knew from Java experience that template method pattern is only a kind of particular case of Stategy where you delegate parts of algorithm by abstract methods overriding. Indeed the base class implements some common features and let derived classes implement particular parts by polymorphism. Now with your example, I don't understand why he had problems to implement from C++ ? Or perhaps is he mixing it with C++ feature template ?! In any case, the template design pattern is one of the simpler design patterns. Here's an example, adapted from Wikipedia's article on the Template Method Pattern: class AbstractGame: """An abstract class that is common to several games in which players play against the others, but only one is playing at a given time. """ def __init__(self, *args, **kwargs): if self.__class__ is AbstractGame: raise TypeError('abstract class cannot be instantiated') def playOneGame(self, playersCount): self.playersCount = playersCount self.initializeGame() j = 0 while not self.endOfGame(): self.makePlay(j) j = (j + 1) % self.playersCount self.printWinner() def initializeGame(self): raise TypeError('abstract method must be overridden') def endOfGame(self): raise TypeError('abstract method must be overridden') def makePlay(self, player_num): raise TypeError('abstract method must be overridden') def printWinner(self): raise TypeError('abstract method must be overridden') Now to create concrete (non-abstract) games, you subclass AbstractGame and override the abstract methods. class Chess(AbstractGame): def initializeGame(self): # Put the pieces on the board. ... def makePlay(player): # Process a turn for the player ... etc. One more Thanks for you example Steven! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
Hello Steven, I added the pipe char '|' to have a complete spinner! This would be set as a function for my wait routine installer. Thanks to share! Karim On 12/10/2010 09:51 PM, Steven D'Aprano wrote: Modulok wrote: List, Forgive me if I don't describe this well, I'm new to it: [snip description of a progress bar] Here's one way: import time, sys f = sys.stdout for i in range(20): time.sleep(1) # do some work f.write('=') f.flush() # make the change visible immediately else: f.write('\n') You might be able to get the same effect with print, but it's probably easier using sys.stdout directly. Here's another way, which *must* use stdout and not print. for i in range(20): percentage = i/20.0 spinner = '/-\\-'[i % 4] f.write("Progress: %5.2f%% %s %s>\r" % (percentage, spinner, '='*(i+1))) f.flush() time.sleep(1) else: f.write('\n') ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
I suppose we can do something like that (kind of pseudo code) to fully configure it: def doSomeStuff(*args): ... def progressBar( func, *args) import time, sys f = sys.stdout for i in range(20): func.__call__(args) f.write('=') f.flush() # make the change visible immediately else: f.write('\n') progressBar( doSomeStuff ) Cheers Karim On 12/18/2010 08:05 AM, Karim wrote: Hello Steven, I added the pipe char '|' to have a complete spinner! This would be set as a function for my wait routine installer. Thanks to share! Karim On 12/10/2010 09:51 PM, Steven D'Aprano wrote: Modulok wrote: List, Forgive me if I don't describe this well, I'm new to it: [snip description of a progress bar] Here's one way: import time, sys f = sys.stdout for i in range(20): time.sleep(1) # do some work f.write('=') f.flush() # make the change visible immediately else: f.write('\n') You might be able to get the same effect with print, but it's probably easier using sys.stdout directly. Here's another way, which *must* use stdout and not print. for i in range(20): percentage = i/20.0 spinner = '/-\\-'[i % 4] f.write("Progress: %5.2f%% %s %s>\r" % (percentage, spinner, '='*(i+1))) f.flush() time.sleep(1) else: f.write('\n') ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Template Pattern
Thanks a lot to point this out! Karim On 12/19/2010 04:33 AM, Steven D'Aprano wrote: Karim wrote: class InputStrategy( object ): """This InputStrategy class is an abstract interface to various read strategy objects. """ def read(self, filePath): """Abstract method to load into database memory an input file. @arg: filePath - string - The input file path. @return: The created database object. """ raise NotImplementedError By the way, I use NotImplementedError in my abstract method of the abstract class. You are using TypeError exception. Is there a general rule for that? NotImplementedError is ok? For abstract methods that should be overridden by a subclass, I would use NotImplementedError, as you do. That is a clear convention for saying "this method must be overridden". But __init__ is a special case. The __init__ method isn't merely not implemented. It *is* implemented, and it does two jobs: it performs any common initialization for the class and all subclasses, and it also prevents the AbstractCLass from being instantiated. class AbstractClass: def __init__(self, *args): if type(self) is AbstractClass: raise TypeError # do common initialization here Trying to instantiate an AbstractClass is always an error: instance = AbstractClass(args) and the error is a *type* error -- you are trying to instantiate a type that can't be. Python already does that, with the singletons None, NotImplemented (different from NotImplementedError!), and Ellipsis: >>> type(None)() Traceback (most recent call last): File "", line 1, in TypeError: cannot create 'NoneType' instances TypeError means you have an error in your code. NotImplementedError means the code is incomplete. I knew from Java experience that template method pattern is only a kind of particular case of Stategy where you delegate parts of algorithm by abstract methods overriding. Indeed the base class implements some common features and let derived classes implement particular parts by polymorphism. Now with your example, I don't understand why he had problems to implement from C++ ? Or perhaps is he mixing it with C++ feature template ?! You'd have to ask him. Maybe he's just not a very good programmer, or was having a bad day. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] xml.etree.ElementTree.parse() against a XMLShema file
Hello all, Is somebody has an example of the way to parse an xml file against a "grammary" file.xsd. The default parser is checking closing tags and attributes but I would like to validate a XSD file. I use the module ElementTree. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] xml.etree.ElementTree.parse() against a XMLShema file
On 12/22/2010 07:07 PM, Karim wrote: Is somebody has an example of the way to parse an xml file against a "grammary" file.xsd. I found this: http://www.velocityreviews.com/forums/t695106-re-xml-parsing-with-python.html Stefan is it still true the limitation of etree in python 2.7.1 ? Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] xml.etree.ElementTree.parse() against a XMLShema file
Thanks Stefan for answering. That's what I come up with. Using lxml (except for the different import) will be fully compliant with the ET code. Do I have to adapt it? I saw your fantastic benchmarks! Why the hell lxml is not integrated into the stdlib. I thought they put in it things which works at best for python interest ? Regards Karim On 12/22/2010 09:56 PM, Stefan Behnel wrote: Karim, 22.12.2010 19:28: On 12/22/2010 07:07 PM, Karim wrote: Is somebody has an example of the way to parse an xml file against a "grammary" file.xsd. I found this: http://www.velocityreviews.com/forums/t695106-re-xml-parsing-with-python.html Stefan is it still true the limitation of etree in python 2.7.1 ? Yes, ElementTree (which is in Python's stdlib) and lxml.etree are separate implementations. If you want validation, use the lxml package. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] xml.etree.ElementTree.parse() against a XMLShema file
On 12/22/2010 10:32 PM, Stefan Behnel wrote: Karim, 22.12.2010 22:09: Using lxml (except for the different import) will be fully compliant with the ET code. Do I have to adapt it? There are certain differences. http://codespeak.net/lxml/compatibility.html This page hasn't been changed for ages, but it should still be mostly accurate. I will have a look. Anyway, I must delivered my current version. I got 300 lines of codes which should be easily translated for the improved future version. I saw your fantastic benchmarks! Why the hell lxml is not integrated into the stdlib. I thought they put in it things which works at best for python interest ? I proposed it but it was rejected with the argument that it's a huge dependency and brings in two large C libraries that will be hard to control for future long-term maintenance. I think that's a reasonable objection. One can never says never... They will reconsider it I think. Thanks for your support! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamically generated classes
Hello Alan, You mentioned the facade pattern. Could you please provide a basic simple implementation of this pattern in python? Regards Karim On 12/23/2010 10:13 AM, Alan Gauld wrote: "Rasjid Wilcox" wrote I've been playing with dynamically generated classes. In particular: class ClassMaker(object): def __init__(maker_self, name): maker_self.name = name # class Foo(object): def __init__(self): self.parent = maker_self def whoami(self): print 'I am a Foo instance made by %s' % self.parent.name maker_self.Foo = Foo I'd probably just define the classes in a module rather than in the init method itself. Then pass the required class to the parent init as an argument. But the example code doesn't give enough clue as to how these classes will be used to be sure that will suit your need. a = ClassMaker('Alice') af = a.Foo() ab = a.Bar() af.whoami() I am a Foo instance made by Alice ab.whoami() I am a Bar instance made by Alice a.Foo is b.Foo False The actual use case is a system where there are multiple databases of essentially the same form, where a is database A, and b is database B, and Foo and Bar represent tables in both the databases. Unless you are actually building a database it would be unusual to have a class represent a table, a table normally represents a class - ie its not a two way relation - or the class uses a table to populate attributes. But again we have no clues about what the classes actually do - its normally the methods of the class that define its usage... the Foo table in database A, and bf would be the Foo table in database B. That sounds like you may be trying to create a facade pattern? My question is: is there a better way? Based on my playing with the above, it all seems to do what I want. My only concern is that I've not seen this idiom before, and perhaps there is a simpler or more standard way? I think it will do what you want but I wouldn't bother putting the class definitions inside the init - unless there is a good reason. At the very least I would create two factory methods which are called by init. That would allow you to reset the classes if needed too. class A: def __init__(self, name): self.foo = makeFoo() self.bar = makeBar() def makeFoo(self): class Foo: pass return Foo def makeBar(self): class Bar: pass reurn Bar But I still think its much more flexible to define the classes in a separate module: import foo, bar class A: def __init__(self,foo,bar): self.foo = foo self.bar = bar a = A(foo.Foo(A),bar.Bar(A)) # pass A so Foo/Bar know their parent You can then extend the use of A without changing A by defining new derivatives of Foo and Bar (as you use new databases for example) HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamically generated classes
Thanks for the link. I use Adapter already for java to align to different interface. I was curious about the facade implementation. Regards Karim On 12/23/2010 01:25 PM, Alan Gauld wrote: "Karim" wrote You mentioned the facade pattern. Could you please provide a basic simple implementation of this pattern in python? Not without spending more time than I have available. But you can read about it on wikipedia, including Java example code. However I think I actually should have said an Adaptor pattern rather than a Facade... http://en.wikipedia.org/wiki/Adapter_pattern HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dynamically generated classes
On 12/23/2010 10:13 AM, Alan Gauld wrote: "Rasjid Wilcox" wrote I've been playing with dynamically generated classes. In particular: class ClassMaker(object): def __init__(maker_self, name): maker_self.name = name # class Foo(object): def __init__(self): self.parent = maker_self def whoami(self): print 'I am a Foo instance made by %s' % self.parent.name maker_self.Foo = Foo I'd probably just define the classes in a module rather than in the init method itself. Then pass the required class to the parent init as an argument. But the example code doesn't give enough clue as to how these classes will be used to be sure that will suit your need. a = ClassMaker('Alice') af = a.Foo() ab = a.Bar() af.whoami() I am a Foo instance made by Alice ab.whoami() I am a Bar instance made by Alice a.Foo is b.Foo False The actual use case is a system where there are multiple databases of essentially the same form, where a is database A, and b is database B, and Foo and Bar represent tables in both the databases. Unless you are actually building a database it would be unusual to have a class represent a table, a table normally represents a class - ie its not a two way relation - or the class uses a table to populate attributes. But again we have no clues about what the classes actually do - its normally the methods of the class that define its usage... the Foo table in database A, and bf would be the Foo table in database B. That sounds like you may be trying to create a facade pattern? My question is: is there a better way? Based on my playing with the above, it all seems to do what I want. My only concern is that I've not seen this idiom before, and perhaps there is a simpler or more standard way? I think it will do what you want but I wouldn't bother putting the class definitions inside the init - unless there is a good reason. At the very least I would create two factory methods which are called by init. That would allow you to reset the classes if needed too. class A: def __init__(self, name): self.foo = makeFoo() self.bar = makeBar() def makeFoo(self): class Foo: pass return Foo def makeBar(self): class Bar: pass reurn Bar But I still think its much more flexible to define the classes in a separate module: import foo, bar class A: def __init__(self,foo,bar): self.foo = foo self.bar = bar a = A(foo.Foo(A),bar.Bar(A)) # pass A so Foo/Bar know their parent You can then extend the use of A without changing A by defining new derivatives of Foo and Bar (as you use new databases for example) HTH, By the way Alan your solution is simple and beautiful! I like this kind of flexible design. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Try except really better than if?
Hello all, I am using more and more try except statement. But I discussed with a very experienced C++ programmer. And he told me that at least in C++ using too many try -catch statements are making the code slower. And it should does the same for python (C implementation). My simple question: Is this true? And why using try-except is indeed encouraged to code as a pythonista? Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Try except really better than if?
Thank you Steven, Modulok and Alan for your precious and detailed explanations! I understood that I must not overuse try-except statement and usually when the exception could happen exceptionally. By the way I have this piece of code using elementTree standard module and according to Alan this is bad code I guess: *try: devdb.setDescription(dev.attrib['description']) except KeyError: pass try: devdb.setSymbolName(dev.attrib['symbolName']) except KeyError: pass try: devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList']) except KeyError: pass try: devdb.setLayoutName(dev.attrib['layoutName']) except KeyError: pass try: devdb.setLayoutType(dev.attrib['layoutType']) except KeyError: pass * In fact elementTree *attrib* dictionary attributes could not have optionally xml attribute (depending on my xml input file). Indeed to test existence I try to execute *dev.attrib['//'*]. But I can't use only one except because the other settings could not be processed if one given optional xml attribute is not present (except will be raised). I must did it for each possible attribute. Do you have an alternative or my way is ok? I know there is no special case which is enough special to break the rule ;o) Regards Karim On 01/10/2011 03:10 AM, Alan Gauld wrote: ctions are slower than static functions, but that ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Try except really better than if?
Thanks Alan this reassures me! Regards Karim On 01/10/2011 10:39 AM, ALAN GAULD wrote: By the way I have this piece of code using elementTree standard module and according to Alan this is bad code I guess: Which just proves there are no absolute rules in programming :-) *try: devdb.setDescription(dev.attrib['description']) except KeyError: pass try: devdb.setSymbolName(dev.attrib['symbolName']) except KeyError: pass try: devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList']) except KeyError: pass try: devdb.setLayoutName(dev.attrib['layoutName']) except KeyError: pass try: devdb.setLayoutType(dev.attrib['layoutType']) except KeyError: pass * Since you just use pass to ignore the error then you are kind of forced to do it this way. Its not bad each statement has to be treated individually, it is not a block where all the statements must pass or fail as a unit. > Do you have an alternative or my way is ok? This would also be a valid case for an if/else check but in readability terms I think try/except still wins because the handler is only a pass. If it were more complex I'd probably opt for if/else. I know there is no special case which is enough special to break the rule ;o) I'm not sure I agree. In programming you can usually find a special case that validly breaks any "rule"! Even "Don't use goto!" :-) HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Try except really better than if?
Steven many thanks for this useful hint! I will modify my code. Many thanks! Regards Karim On 01/10/2011 11:32 AM, Steven D'Aprano wrote: Karim wrote: Thank you Steven, Modulok and Alan for your precious and detailed explanations! I understood that I must not overuse try-except statement and usually when the exception could happen exceptionally. By the way I have this piece of code using elementTree standard module and according to Alan this is bad code I guess: *try: devdb.setDescription(dev.attrib['description']) except KeyError: pass [...] Whenever you have very similar code repeated many times, you should consider factoring out the common code into a helper function. Something like this: def try_or_pass(key): attr_name = 'set' + key[0].upper() + key[1:] try: getattr(devb, attr_name)(dev.attrib[key]) except KeyError: pass try_or_pass('description') try_or_pass('symbolName') etc. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Equality of numbers and Strings
Hello All, I am not a beginner in Python language but I discovered a hidden property of immutable elements as Numbers and Strings. s ='xyz' >>> t = str('xyz') >>> id(s) == id(t) True Thus if I create 2 different instances of string if the string is identical (numerically). I get the same object in py db. It could be evident but if I do the same (same elements) with a list it will not give the same result. Is-it because of immutable property of strings and numbers? Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equality of numbers and Strings
Many thanks Emile, Bob, Stefan, Wesley! Now, I see now that the point is more related to implementation details and optimization instead of a true property. But it could mistaken people not aware. Regards Karim On 01/10/2011 06:56 PM, Stefan Behnel wrote: Karim, 10.01.2011 17:07: I am not a beginner in Python language but I discovered a hidden property of immutable elements as Numbers and Strings. s ='xyz' >>> t = str('xyz') >>> id(s) == id(t) True Thus if I create 2 different instances of string if the string is identical (numerically). I get the same object in py db. It could be evident but if I do the same (same elements) with a list it will not give the same result. Is-it because of immutable property of strings and numbers? AFAIR, all string literals in a module are interned by the CPython compiler, and short strings that look like identifiers are also interned (to speed up dictionary lookups, e.g. for function names). So you will get identical objects in these cases, although it's not a good idea to rely on this as it's an implementation detail of the runtime. And the second thing that you can observe here is that str() never copies a string you pass in, which is reasonable behaviour for immutable objects. Thus if I create 2 different instances of string if the string is identical (numerically). There's no such thing as "numerically identical" strings. It's enough to say that they are identical as opposed to equal. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to insert a quit-Button in a Tkinter class?
Hello, Inherit from Frame see below: from Tkinter import * class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createLabel() self.createButton() def createLabel(self): self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app = App() app.master.title("Clock Time!") app.mainloop() Regards Karim On 01/12/2011 08:41 PM, Enih Gilead wrote: Hi, all ! I've being strugling a lot trying to insert (just as exemple) a quit-Button in a Tkinter class App with no success... What I get is the clock runing ok, but, the App simply ignores the quit-Button... Why? _*Remark*_: I took this minimalist digital clock just to illustrate the "bad :-)" class behavior, but it didn't work in any other Apps I tried. I searched a lot (indeed!) in the net but I couldn't find the reason. Could any of you tell me, please, _*what's the problem?*_ Thanks, enihgil ### import Tkinter import time class App(): def __init__(self): self.root = Tkinter.Tk() self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app=App() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to insert a quit-Button in a Tkinter class?
Hello, Inherit from Frame see below: from Tkinter import * class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createLabel() self.createButton() def createLabel(self): self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app = App() app.master.title("Clock Time!") app.mainloop() Regards Karim On 01/12/2011 08:41 PM, Enih Gilead wrote: Hi, all ! I've being strugling a lot trying to insert (just as exemple) a quit-Button in a Tkinter class App with no success... What I get is the clock runing ok, but, the App simply ignores the quit-Button... Why? _*Remark*_: I took this minimalist digital clock just to illustrate the "bad :-)" class behavior, but it didn't work in any other Apps I tried. I searched a lot (indeed!) in the net but I couldn't find the reason. Could any of you tell me, please, _*what's the problem?*_ Thanks, enihgil ### import Tkinter import time class App(): def __init__(self): self.root = Tkinter.Tk() self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app=App() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to insert a quit-Button in a Tkinter class?
/_Sorry my mistake in createLabel() method:_/ self.label = Label(text="") instead of : self.label = *Tkinter*.Label(text="") On 01/12/2011 09:23 PM, Karim wrote: Hello, Inherit from Frame see below: from Tkinter import * class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createLabel() self.createButton() def createLabel(self): self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app = App() app.master.title("Clock Time!") app.mainloop() Regards Karim On 01/12/2011 08:41 PM, Enih Gilead wrote: Hi, all ! I've being strugling a lot trying to insert (just as exemple) a quit-Button in a Tkinter class App with no success... What I get is the clock runing ok, but, the App simply ignores the quit-Button... Why? _*Remark*_: I took this minimalist digital clock just to illustrate the "bad :-)" class behavior, but it didn't work in any other Apps I tried. I searched a lot (indeed!) in the net but I couldn't find the reason. Could any of you tell me, please, _*what's the problem?*_ Thanks, enihgil ### import Tkinter import time class App(): def __init__(self): self.root = Tkinter.Tk() self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app=App() ___ Tutor maillist -tu...@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question
Hello, "You can even use a StringVar as the checkbutton's variable, and supply string values for the offvalue and onvalue. Here's an example: self.spamVar = StringVar() self.spamCB = Checkbutton ( self, text="Spam?", variable=self.spamVar, onvalue="yes", offvalue="no" ) If this checkbutton is on, self.spamVar.get() will return the string "yes"; if the checkbutton is off, that same call will return the string "no". Furthermore, your program can turn the checkbutton on by calling .set("yes")." Regards Karim On 01/12/2011 05:55 PM, Stinson, Wynn A Civ USAF AFMC 556 SMXS/MXDED wrote: Can someone give me some sample code to use to determine if a checkbox has been selected using Tkinter? thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] module to parse XMLish text?
Hello, *from xml.etree.ElementTree import ElementTree _/#Parsing:/_ doc = ElementTree() doc.parse(xmlFile) * /_*#Find tag element:*_/ *doc.find('mytag')* *_/#iteration over tag element:/_ lname = [] for lib in doc.iter('LibTag'): libName = lib.attrib['name'] lname.append(libName) * Regards Karim On 01/14/2011 03:55 AM, Terry Carroll wrote: Does anyone know of a module that can parse out text with XML-like tags as in the example below? I emphasize the "-like" in "XML-like". I don't think I can parse this as XML (can I?). Sample text between the dashed lines:: - Blah, blah, blah SOMETHING ELSE SOMETHING DIFFERENT - I'd like to be able to have a dictionary (or any other structure, really; as long as I can get to the parsed-out pieces) that would look smoothing like: {"BING" : "ZEBRA", "BANG" : "ROOSTER" "BOOM" : "GARBONZO BEAN" "BLIP" : "SOMETHING ELSE" "BASH" : "SOMETHING DIFFERENT"} The "Blah, blah, blah" can be tossed away, for all I care. The basic rule is that the tag either has an operand (e.g., ZEBRA>), in which case the name is the first word and the content is everything else that follows in the tag; or else the tag has no operand, in which case it is matched to a corresponding closing tag (e.g., SOMETHING ELSE), and the content is the material between the two tags. I think I can assume there are no nested tags. I could write a state machine to do this, I suppose, but life's short, and I'd rather not re-invent the wheel, if there's a wheel laying around somewhere. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] end parameter in 2.7.1?
IN 3.1 for print(): >>> print('hello', end =' ') hello>>> It suppress the newline character. On 01/15/2011 07:05 PM, Emile van Sebille wrote: On 1/15/2011 9:35 AM Bill DeBroglie said... Twice in two days...! Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which is using Python 3.1. The author uses the end parameter What's an 'end' parameter? Emile in numerous programs but this doesn't seem to translate to 2.7. Any advice as to how I can specify the final string of the print function? Thank you, bdb ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] module to parse XMLish text?
Hello, I did not see the XML code in details before I gave the code with ElementTree. In fact with unclosing tags you will get errors at parse time and it will give you the location of errors. You could use the module from Stefan which is way way superior than ElementTree which can validate against DTD or XSD and many many other features (speed, etc...) Regards Karim On 01/15/2011 07:53 AM, Stefan Behnel wrote: Wayne Werner, 15.01.2011 03:25: On Fri, Jan 14, 2011 at 4:42 PM, Terry Carroll wrote: On Fri, 14 Jan 2011, Karim wrote: from xml.etree.ElementTree import ElementTree I don't think straight XML parsing will work on this, as it's not valid XML; it just looks XML-like enough to cause confusion. It's worth trying out - most (good) parsers "do the right thing" even when they don't have strictly valid code. I don't know if xml.etree is one, but I'm fairly sure both lxml and BeautifulSoup would probably parse it correctly. They wouldn't. For the first tags, the text values would either not come out at all or they would be read as attributes and thus loose their order and potentially their whitespace as well. The other tags would likely get parsed properly, but the parser may end up nesting them as it hasn't found a closing tag for the previous tags yet. So, in any case, you'd end up with data loss and/or a structure that would be much harder to handle than the (relatively) simple file structure. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] What is __weakref__ ?
Hello, I am wondering what is this special class attribut. I know __dict__, slots. I use slots = [] when I want to use a read only class. But is anyone could explain with a little example the use of __weakref__? Regards karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Why super does not work !
Hello, I implemented Observer DP on a listbox (Tkinter) as follows and I don't understand why super() is not working and Observable.__init__(self) is working, cf below: class ListObservable(Listbox, Observable): """Creation de widget Listbox""" def __init__(self): super(ListObservable, self).__init__() #Observable.__init__(self) self._value = None self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys( self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') self.liste.grid(row=0, column=1, sticky=N+S+W) self.liste.bind('', self.onSelect) _The error is:_ Traceback (most recent call last): File "./observerAppliGraphique.py", line 118, in app=App() File "./observerAppliGraphique.py", line 37, in __init__ self.sujet.attach(self.nom) File "/home/karim/guiObserver/observable.py", line 11, in attach self._observers.append(observer) AttributeError: 'ListObservable' object has no attribute '_observers' And the Observable class is: class Observable(object): """Sujet a observer""" def __init__(self): self._observers = [] print('constructeur observable') def attach(self, observer): """Attache un nouvel observateur""" self._observers.append(observer) def detach(self, observer): """Retire un nouvel observateur""" self._observers.remove(observer) def notify(self): """Avertit tous les observateurs que l'observable change d'etat""" for observer in self._observers: observer.update() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why super does not work !
Thanks Izz, Luke, Steven and Alan! That's I figured out with MI and super. Steven I understand the point to have Listbox contains a Listbox. Before the code was in App class and I extracted it to do an outside class making the mistake. But magic of Python it's working (but I know it's awful). The code is working but I am not totally happy because of many EntryObserver almost identical objects (except from update and grid() options) Is it possible to simplify this structure? Regards Karim The rest of the code is below: #!/usr/bin/env python2.7 """Module ObserverGraphique.py Une implementation du design pattern Observer. """ from Tkinter import * from observable import Observable from observer import AbstractObserver data_base = { 'Employe1': ['Joel', 'Durant', '0623'], 'Employe2': ['Marc', 'Donce', '0624'], 'Employe3': ['George', 'Roux','0625'], 'Employe4': ['Alain', 'Richard', '0626'] } __all__ = ['App', 'ListObservable', 'Entry1Observer', 'Entry2Observer', 'Entry3Observer'] class App(Frame): """Application graphique avec Tkinter implementant un Observer Design Pattern.""" def __init__(self, master=None): Frame.__init__(self, master) self.master.title("Exemple : Observer Design Pattern") self.grid() self.createLabels() self.createObservable() self.createObservers() self.registerObservers() def createLabels(self): """Creation de widgets Label""" self.label1 = Label(text="Nom :") self.label2 = Label(text="Prenom :") self.label3 = Label(text="Poste :") self.label1.grid(row=1, column=1, sticky=W) self.label2.grid(row=2, column=1, sticky=W) self.label3.grid(row=3, column=1, sticky=W) def createObservable(self): """Creation de la listBox observable.""" self.sujet = ListObservable() def createObservers(self): """Creation des champs d'entre texte observateurs de la liste.""" self.nom= Entry1Observer(self.sujet) self.prenom = Entry2Observer(self.sujet) self.poste = Entry3Observer(self.sujet) def registerObservers(self): """Enregistrement des observateurs.""" self.sujet.attach(self.nom) self.sujet.attach(self.prenom) self.sujet.attach(self.poste) class ListObservable(Listbox, Observable): """Creation de widget Listbox""" def __init__(self): #super(ListObservable, self).__init__() Observable.__init__(self) self._value = None self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys( self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') self.liste.grid(row=0, column=1, sticky=N+S+W) self.liste.bind('', self.onSelect) self.liste.selection_set(0) def onSelect(self, e): if not self.liste.curselection(): self.setValue(0) else: self.setValue(self.liste.get(self.liste.curselection())) self.notify() def setValue(self, select): self._value = select def getValue(self): return self._value class Entry1Observer(Entry, AbstractObserver): """Creation de widget Entry 1""" def __init__(self, sujet=None): #super(Entry1Observer, self).__init__(sujet) AbstractObserver.__init__(self, sujet) self.text = StringVar() self.entry = Entry(textvariable=self.text) self.entry.grid(row=1, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][1]) print a class Entry2Observer(Entry, AbstractObserver): """Creation de widget Entry 2""" def __init__(self, sujet=None): AbstractObserver.__init__(self, sujet) self.text = StringVar() self.entry = Entry(textvariable=self.text) self.entry.grid(row=2, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][0]) class Entry3Observer(Entry, AbstractObserver): """Creation de widget Entry""" def __init__(self, sujet=None): AbstractObserver.__init__(self, sujet) self.text = StringVar() self.entry = Entry(textvariable=self.text) self.entry.grid(row=3, column=2) def up
Re: [Tutor] Why super does not work !
By the way Tkinter does not support super() seems to be an 'old style' class, this is perhaps the raison why MI does not work in this context: *Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter.Frame Traceback (most recent call last): File "", line 1, in ImportError: No module named Frame >>> from Tkinter import Frame >>> class App(Frame): ... def __init__(self): ... super(App, self).__init__() ... >>> a=App() Traceback (most recent call last): File "", line 1, in File "", line 3, in __init__ TypeError: must be type, not classobj >>> * Steven, I corrected my code (even if I have a double Inheritance which is ok in this context): * class ListObservable(Listbox, Observable): def __init__(self): Observable.__init__(self) self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys( Listbox.__init__(self, listvariable=self.listeContenu, selectmode='single') self.grid(row=0, column=1, sticky=N+S+W) self.bind('<>', self.onSelect) self._value = None def onSelect(self, e): if not self.curselection(): self.setValue(0) else: self.setValue(self.get(self.curselection())) self.notify() def setValue(self, select): self._value = select def getValue(self): return self._value class Entry1Observer(Entry, AbstractObserver): def __init__(self, sujet=None): AbstractObserver.__init__(self, sujet) self.text = StringVar() Entry.__init__(self, textvariable=self.text) self.grid(row=2, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][0])* I still need a advice about the possible improvement specially for Entry observer object. Regards Karim On 01/18/2011 07:31 AM, Karim wrote: Thanks Izz, Luke, Steven and Alan! That's I figured out with MI and super. Steven I understand the point to have Listbox contains a Listbox. Before the code was in App class and I extracted it to do an outside class making the mistake. But magic of Python it's working (but I know it's awful). The code is working but I am not totally happy because of many EntryObserver almost identical objects (except from update and grid() options) Is it possible to simplify this structure? Regards Karim The rest of the code is below: #!/usr/bin/env python2.7 """Module ObserverGraphique.py Une implementation du design pattern Observer. """ from Tkinter import * from observable import Observable from observer import AbstractObserver data_base = { 'Employe1': ['Joel', 'Durant', '0623'], 'Employe2': ['Marc', 'Donce', '0624'], 'Employe3': ['George', 'Roux','0625'], 'Employe4': ['Alain', 'Richard', '0626'] } __all__ = ['App', 'ListObservable', 'Entry1Observer', 'Entry2Observer', 'Entry3Observer'] class App(Frame): """Application graphique avec Tkinter implementant un Observer Design Pattern.""" def __init__(self, master=None): Frame.__init__(self, master) self.master.title("Exemple : Observer Design Pattern") self.grid() self.createLabels() self.createObservable() self.createObservers() self.registerObservers() def createLabels(self): """Creation de widgets Label""" self.label1 = Label(text="Nom :") self.label2 = Label(text="Prenom :") self.label3 = Label(text="Poste :") self.label1.grid(row=1, column=1, sticky=W) self.label2.grid(row=2, column=1, sticky=W) self.label3.grid(row=3, column=1, sticky=W) def createObservable(self): """Creation de la listBox observable.""" self.sujet = ListObservable() def createObservers(self): """Creation des champs d'entre texte observateurs de la liste.""" self.nom= Entry1Observer(self.sujet) self.prenom = Entry2Observer(self.sujet) self.poste = Entry3Observer(self.sujet) def registerObservers(self): """Enregistrement des observateurs.""" self.sujet.attach(self.nom) self.sujet.attach(self.prenom) self.sujet.attach(self.
Re: [Tutor] What is __weakref__ ?
Hello Steven, (1) slots = [] doesn't do anything special. You have misspelled __slots__. Yes sorry my mistake :-[ (2) Classes don't become read only just because you add __slots__ to them. All you prevent is adding extra attributes, and why would you wish to do that? I know this is ugly but until now it is the only way (with this side effect) I found to declare Enums class that I _understand_: *class CategoryType(object): """Implements the enumeration and prevent associated newly created instances to redefine enums value via special class variable '__slots__' definition. It makes also, instances have no attributes at all. """ __slots__ = () TRANSISTOR, MOS, BIPOLAR, CAPACITOR, RESISTOR, DIODE, ESD, PAD, \ COMPARATOR, OPAMP, ADC, DAC, PLL, OTHER = range(14) def toString ( self, litteral ): """Convert the litteral integer number to its associated string representation.""" if litteral == self.TRANSISTOR: return 'transistor' elif litteral == self.MOS: return 'mos' elif litteral == self.BIPOLAR:* [...] I discovered recently that I could configure __setattr__(self, name, value) by raising AttributeError to prevent to set up a new attribute value. Or use an conditional statement to avoid to define it twice. If you have good advice for enum (I hope I could understand) you welcome ;-) . Thus I use __slots__, __dict__ (in __setattr__) and I wanted to about much for __weakref__ Have you read the Fine Manual? http://docs.python.org/reference/datamodel.html#slots In fact, I already read that. But I am searching for doc about what is a weak reference. >>> class K1(object): ... __slots__ = [] # Don't support weak-refs. ... >>> class K2(object): ...__slots__ = '__weakref__' # Do support weak-refs. ... >>> import weakref >>> k1 = K1() >>> k2 = K2() >>> weakref.ref(k1) Traceback (most recent call last): File "", line 1, in TypeError: cannot create weak reference to 'K1' object >>> weakref.ref(k2) Same thing I don't know what to do with this object weakref :-[ as I don't know its meaning. That was my true question in fact; Regards ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is __weakref__ ?
Hello Bob, Thanks for this better and simple approach! To be perfect I would like to be able to do. >>> type = CategoryType() >>> type.TRANSISTOR 0 I will use your enums declaration and the range part to use as keys for enums. And I will raise a KeyError in toString() to handle invalid litteral. Thanks! Regards Karim On 01/18/2011 02:24 PM, bob gailer wrote: On 1/18/2011 8:08 AM, Karim wrote: I know this is ugly but until now it is the only way (with this side effect) I found to declare Enums class that I _understand_: *class CategoryType(object): """Implements the enumeration and prevent associated newly created instances to redefine enums value via special class variable '__slots__' definition. It makes also, instances have no attributes at all. """ __slots__ = () TRANSISTOR, MOS, BIPOLAR, CAPACITOR, RESISTOR, DIODE, ESD, PAD, \ COMPARATOR, OPAMP, ADC, DAC, PLL, OTHER = range(14) def toString ( self, litteral ): """Convert the litteral integer number to its associated string representation.""" if litteral == self.TRANSISTOR: return 'transistor' elif litteral == self.MOS: return 'mos' elif litteral == self.BIPOLAR:* [...] IMHO this just cries out for a dictionary: class CategoryType(object): __slots__ = () enums = { 0: 'transistor', 1: 'mos', ... } def toString(self, literal): """Convert the literal integer number to its associated string representation.""" return self.enums[literal] Note this does not handle invalid literal. If you are happy with range 14) you could alternatively use a list: enums = ['transistor, 'mos', ...] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is __weakref__ ?
On 01/18/2011 03:38 PM, bob gailer wrote: def __getattr__(self, name): return self.enums[name] Note this does not handle the upper/lower case issue. Thanks for the trick! works perfect! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why super does not work !
On 01/17/2011 11:36 PM, Dave Angel wrote: On 01/-10/-28163 02:59 PM, Karim wrote: Hello, I implemented Observer DP on a listbox (Tkinter) as follows and I don't understand why super() is not working and Observable.__init__(self) is working, cf below: class ListObservable(Listbox, Observable): """Creation de widget Listbox""" def __init__(self): super(ListObservable, self).__init__() #Observable.__init__(self) self._value = None self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys( self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') self.liste.grid(row=0, column=1, sticky=N+S+W) self.liste.bind('', self.onSelect) _The error is:_ Traceback (most recent call last): File "./observerAppliGraphique.py", line 118, in app=App() File "./observerAppliGraphique.py", line 37, in __init__ self.sujet.attach(self.nom) File "/home/karim/guiObserver/observable.py", line 11, in attach self._observers.append(observer) AttributeError: 'ListObservable' object has no attribute '_observers' And the Observable class is: class Observable(object): """Sujet a observer""" def __init__(self): self._observers = [] print('constructeur observable') def attach(self, observer): """Attache un nouvel observateur""" self._observers.append(observer) def detach(self, observer): """Retire un nouvel observateur""" self._observers.remove(observer) def notify(self): """Avertit tous les observateurs que l'observable change d'etat""" for observer in self._observers: observer.update() Just looking at what you supply, I'd suppose that ListBox doesn't correctly call super() in its own __init__() method. So I took a look at Tkinter.py, and sure enough, it just calls its own direct parent, Widget.l super() only works if all the classes you use are done consistently. DaveA Thanks for this precision! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is __weakref__ ?
Thanks for the links Steven! Regards Karim On 01/18/2011 10:49 PM, Steven D'Aprano wrote: Karim wrote: Same thing I don't know what to do with this object weakref :-[ as I don't know its meaning. That was my true question in fact; http://mindtrove.info/python-weak-references/ http://www.doughellmann.com/PyMOTW-ja/weakref/index.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help listing directory timestamps and deleting directories
Hello, Also working w/o external module just the standard one: *>>> import datetime >>> remove_after = datetime.datetime.now() - datetime.timedelta(days=31) >>> remove_after datetime.datetime(2010, 12, 24, 23, 21, 10, 11315) * Regards Karim On 01/24/2011 08:02 PM, Vince Spicer wrote: On Mon, Jan 24, 2011 at 11:25 AM, bsd...@gmail.com <mailto:bsd...@gmail.com> mailto:bsd...@gmail.com>> wrote: Hi, hoping for some help here. I've been trying to write a python script (complete newb) and have spent several days trying to get this right with no success. I am trying to list timestamps in a directory and if they are older than x amount of days delete the directories. It seems that in my for loop it is only evaluating the last timestamp of the last directory and using that timestamp to make the deletion decision. I realize that this script isn't going to delete the directories with evaluate as true but I haven't been able to get that far yet... ###start script## ###Modules### import os import time ###Global Variables### curr_t = time.time() days = 2629743 #2629743 is 30 days in epoch time. directory=os.path.join("/home", "userid", "python") for r,d,f in os.walk(directory): for dir in d: timestamp = os.path.getmtime(os.path.join(r,dir)) ## It seems that the below "if" statement is only comparing the timestamp of the last directory that this variable lists. print timestamp if curr_t - days < timestamp: I am expecting this statement to compare each timestamp of the "directory" variable and print out if it should be deleted or not. print "Your file will be deleted" else: print "File will NOT be deleted..." ###end of script# Thank you for your time! ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor First off, I would recommend using dates and not times, this can help make things clearer when dealing with dates, also the dateutil module can make date math a lot simpler (easy_install dateutil) from datetime import datetime from dateutil.relativedelta import relativedelta remove_after = datetime.now() - relativedelta(days=31) # exactly 1 month prior to today check_dir = "/path/to/whatever" for r,d,f in os.walk(check_dir): for dir in d: loc = os.path.join(r,dir) last_modified = datetime.fromtimestamp(os.path.getmtime(loc)) if last_modifed < remove_after: print "delete old directory", loc else: print "keep recently modified", loc Hope this helps, Vince Spicer Developer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] The trap of the year
Hello All, Just to share on rageous bug I encounter where 2 lists which "should" to be different (same id) because hold by different instances of the same class are not in fact DIFFERENT, see below: >>> class Device(): ... def __init__(self, parameters=[]): ... self.parameters = parameters ... def param(self): ... print(id(self.parameters)) ... >>> a=Device() >>> b=Device() >>> a.param() 140559202956568 >>> b.param() 140559202956568 When I discovered that I was puzzled because at the prompt: >>> a = [] >>> b = [] >>> id(a) 140559202956496 >>> id(b) 140559202957000 I am not really understanding why my init in the class made it refers to the same list object. What is the difference with 2nd example directly at the prompt? By the way, this one is ok: >>> class Device(): ... def __init__(self,parameters=None): ... self.parameters = None ... self.parameters = [] ... def param(self): ... print(id(self.parameters)) ... >>> a=Device() >>> b=Device() >>> b.param() 140559202956496 >>> a.param() 140559202956568 Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
If I understand a little bit what happen in: def __init__(self, parameters=[]): [...] The list argument is built before instance creation and indeed constructor execution. So this is the same list instance of constructor parameter for all new instance creation. For me it was a bad surprise! I never see warning about this fact in any books before. Regards Karim On 01/25/2011 10:08 PM, Izz ad-Din Ruhulessin wrote: Or the internal memory id or whatever it's called. 2011/1/25 Izz ad-Din Ruhulessin <mailto:izzaddin.ruhules...@gmail.com>> I think it has something to do with the physical id of the object 2011/1/25 Karim mailto:karim.liat...@free.fr>> Hello All, Just to share on rageous bug I encounter where 2 lists which "should" to be different (same id) because hold by different instances of the same class are not in fact DIFFERENT, see below: >>> class Device(): ... def __init__(self, parameters=[]): ... self.parameters = parameters ... def param(self): ... print(id(self.parameters)) ... >>> a=Device() >>> b=Device() >>> a.param() 140559202956568 >>> b.param() 140559202956568 When I discovered that I was puzzled because at the prompt: >>> a = [] >>> b = [] >>> id(a) 140559202956496 >>> id(b) 140559202957000 I am not really understanding why my init in the class made it refers to the same list object. What is the difference with 2nd example directly at the prompt? By the way, this one is ok: >>> class Device(): ... def __init__(self,parameters=None): ... self.parameters = None ... self.parameters = [] ... def param(self): ... print(id(self.parameters)) ... >>> a=Device() >>> b=Device() >>> b.param() 140559202956496 >>> a.param() 140559202956568 Karim ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
Hello Bob, I know this fact for function but in this case this is not a function but a constructor method of a class. The impact is not the same because all instance share the same argument parameter.This a kind of singleton argument :-) . I believed that the constructor will create each time a new argument init. Regards Karim On 01/25/2011 10:20 PM, bob gailer wrote: *values are evaluated when th* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
On 01/25/2011 10:12 PM, Jerry Hill wrote: On Tue, Jan 25, 2011 at 3:41 PM, Karim <mailto:karim.liat...@free.fr>> wrote: I am not really understanding why my init in the class made it refers to the same list object. What is the difference with 2nd example directly at the prompt? See http://effbot.org/zone/default-values.htm -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Thanks for the link jerry! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
Yes you're right. But the class and instance thing made me believe the context would be different. Error of judgment. Regards Karim On 01/25/2011 10:57 PM, Corey Richardson wrote: On 01/25/2011 04:28 PM, Karim wrote: Hello Bob, I know this fact for function but in this case this is not a function but a constructor method of a class. To be pedantic, a method _is_ a function, just under the umbrella of a class, with it's parent object being passed to it. ~Corey The impact is not the same because all instance share the same argument parameter.This a kind of singleton argument :-) . I believed that the constructor will create each time a new argument init. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] placing widgets
On 01/25/2011 10:31 PM, W S wrote: hi, i have written some Tk/Python code to do a few simple tasks, and am having trouble with my combobox placement on the frame. is there a way to more explicitly place it other than: This method does not give a lot of control xx=apply(OptionMenu,(self,TCase)+tuple(TestCase)) xx.grid(row=1, sticky=E+W) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor with grid you have row and column attribute. Plus you can create several Frames and place your widget in it if you want more specific placements. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
Thanks for the tip Steven. Regards Karim On 01/26/2011 12:39 AM, Steven D'Aprano wrote: Karim wrote: Hello Bob, I know this fact for function but in this case this is not a function but a constructor method of a class. Methods *are* functions. (Technically, they are lightweight wrappers around functions.) They are treated exactly the same by Python. The "constructor method" __init__ is treated not special. You can easily see this by printing the function from *inside* the class, before it gets wrapped by the class machinery: >>> class Test: # From Python 3, Python 2 may be a bit different. ... def __init__(myname, arg=[]): ... pass ... print(__init__) ... print(__init__.__defaults__) ... ([],) And there you can clearly see the list used as a default value. It is a little bit harder from outside, because the function is wrapped in a method-wrapper, but not that hard: >>> instance = Test() >>> instance.__init__.__func__ >>> instance.__init__.__func__.__defaults__ ([],) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
After one 2 months of python intensive development. I made this init defaults error in my db classes constructors... Shame on me :-[ Steven ! Your example shows me obvious. Regards Karim On 01/26/2011 12:33 AM, Steven D'Aprano wrote: Karim wrote: Hello All, Just to share on rageous bug I encounter where 2 lists which "should" to be different (same id) because hold by different instances of the same class are not in fact DIFFERENT, see below: I think you are confused. If the two lists have the same ID, they should be the same, not different. >>> class Device(): ... def __init__(self, parameters=[]): ... self.parameters = parameters This creates a list ONCE, when the method is created, and then uses that same list over and over again. Consider this: >>> import time >>> now = time.ctime() >>> now 'Wed Jan 26 10:05:31 2011' >>> def test(t=now): ... print(t) ... >>> test() Wed Jan 26 10:05:31 2011 >>> time.sleep(60); test() Wed Jan 26 10:05:31 2011 Are you surprised that time.ctime() only gets called *once*? I hope not -- I would expect that you consider this example obvious and not surprising. How about this instead? >>> def test2(t=time.ctime()): ... print(t) ... >>> test2() Wed Jan 26 10:09:10 2011 >>> time.sleep(60); test2() Wed Jan 26 10:09:10 2011 I hope that this also will not be surprising. time.ctime() is called once, when the function is created, and the result used as often as needed. It is no different when the default value is a list like []. The list is created once, and used each time the function is called. > When I discovered that I was puzzled because at the prompt: >>> a = [] >>> b = [] >>> id(a) 140559202956496 >>> id(b) 140559202957000 But this test is completely different. You create TWO lists, not one. A better test would be: >>> a = [] >>> b = a >>> id(a), id(b) (3083146668, 3083146668) I am not really understanding why my init in the class made it refers to the same list object. Because it only creates one list, when the method is defined, not each time the method is called. Only the *inside* of the method is executed each time the method is called, not the method definition. If you want something to be executed each time the method is called, you have to put it in the body of the method: >>> def test3(t=None): ... if t is None: t = time.ctime() ... print(t) ... >>> test3() Wed Jan 26 10:18:33 2011 >>> time.sleep(60); test3() Wed Jan 26 10:19:37 2011 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The trap of the year
Sorry Alan, When I read your tutorial I was probably blind... :-D I am going to re-read it. Regards Karim On 01/26/2011 01:30 AM, Alan Gauld wrote: "Karim" wrote If I understand a little bit what happen in: def __init__(self, parameters=[]): [...] The list argument is built before instance creation and indeed constructor execution. So this is the same list instance of constructor parameter for all new instance creation. Yes that is a feature of Pythons default argument mechanism. It has been discussed many times on this list and in the docs. As you discovered the best way to avoid it is use None as the default then create a new list inside the function if it is None. I never see warning about this fact in any books before. Its quite commonly warned against but until you get bitten the significance just passes you by! I bet if you look out for it now you'll see it often ebnough! HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class question
Hello, Design Patterns is the key for code reuse and problem solving. Indeed you have to separate your objects (classes) to use it. The god class is like a script with only one function: not very flexible and easy to debug. Program towards interface that means you have to use inheritance. Try to determine the objects you need for your problem and next step is how arrange it together (relational). Regards Karim On 01/26/2011 01:28 AM, Marc Tompkins wrote: On Tue, Jan 25, 2011 at 3:26 PM, Elwin Estle wrote: Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes? Seems to me like the one large class would be clearer in some ways. I have something I am trying to do that have somewhere in the neighborhood of 20 attributes that all relate together, however there are sort of "clumps" of attributes that have a sub-relationship to each other and I wondered if they should be their own class, but I am not sure, assuming that is a good idea, how these smaller classes might work together. I have only the foggiest notion of inheritance and I'd kind of like to stay away from that aspect of things until I get a better grasp of individual classes. For me, the question of one big class/multiple smaller classes comes down to reusability. If you find yourself writing the same code over and over again (or cutting/pasting big blocks of code), you should probably break up your classes. -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class question
Sure, but I come from java world and 1 inheritance is allowed but we can implement multiple interfaces. I like to use Abstract classes in Python then inherit and implement abstract method like in java (at least that's all I remember from Java experience). Indeed I was too direct everybody has the same style. Regards Karim On 01/26/2011 12:08 PM, Alan Gauld wrote: "Karim" wrote Program towards interface that means you have to use inheritance. Just to be picky, you can program by interface without using inheritance. Inheritance is only needed to implement interfaces in languages like C++. In Python (and other dynamically bound OOP languages) you can use polymorphism without inheritance. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class question
I know the the law of Murphy. But this one is a must-have.:-) Regards Karim * One way to reduce coupling is with the Law of Demeter: if you want your dog to walk, don't talk to your dog's legs. You will only confuse the dog and it won't get anywhere. http://en.wikipedia.org/wiki/Law_of_Demeter Hope this helps. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Print to std output with color
Hello all, Is there a simple way to print with color to stdout like the unix/linux example below: *print( '^[[1;31mThis is a warning!^[[0m' ) where <=> ^[ *I see thing with curses module. But is there an more simple object in other module to do the trick? Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print to std output with color
Thanks a lot Scott for the tip! Regards Karim On 01/26/2011 07:10 PM, Scott Nelson wrote: Curses is one way to go. Another is to use the PyWin32 module discussed in this thread: http://thread.gmane.org/gmane.comp.python.tutor/58450/focus=58454 Basically, here's a snippet of code that can get you started. This requires that you have the PyWin32 module installed (already installed by default if you use ActiveState's Python distribution for Windows). Using PyWin32 isn't for the faint of heart, but it does work. import win32console handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) print 'blue text' On Wed, Jan 26, 2011 at 11:10 AM, Karim <mailto:karim.liat...@free.fr>> wrote: Hello all, Is there a simple way to print with color to stdout like the unix/linux example below: *print( '^[[1;31mThis is a warning!^[[0m' ) where <=> ^[ *I see thing with curses module. But is there an more simple object in other module to do the trick? Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ Regards Karim ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print to std output with color
Thanks Alan! I will go there have a look. Regards Karim On 01/26/2011 07:24 PM, Alan Gauld wrote: "Karim" wrote Is there a simple way to print with color to stdout like the unix/linux example below: *print( '^[[1;31mThis is a warning!^[[0m' ) Not generically since stdout is a data stream which may not be printed (it could be spoken for example - how does the synthesiser interpret colour?) and the terminal may have a colour scheme that makes your output invisible! Also different terminals have different capabilities, many do not support colour but do support bold/italic/underline etc. Thats why curses exists, it does a best endeavours attempt at rendering what you want but reverts to defaults for cases where it is not supported. but even curses is not able to work with all terminals - for example line oriented terminals/teletypes. *I see thing with curses module. But is there an more simple object in other module to do the trick? Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ There are some attempts at providing easier terminal control functions. The effbot did one I seem to recall http://effbot.org/zone/console-handbook.htm That might suffice for you? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print to std output with color
That's what I figured out at effbot website. Thanks for the additional link Alan! Regards Karim On 01/26/2011 07:27 PM, Alan Gauld wrote: "Karim" wrote Is there a simple way to print with color to stdout like the unix/linux example below: *print( '^[[1;31mThis is a warning!^[[0m' ) I should have said the effbot solution (and WConio) are only for Windows. On Linux I think you are pretty well stuck with curses. I did find a simplified curses library here: http://nadiana.com/python-curses-terminal-controller HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter, create widgets during runtime?
I never did that but this is python! You can create anything you want at runtime! Make a factory method in you gui class which inherit from Frame or whatever container code below is testing: >>> from Tkinter import * >>> class gui(Frame): ... def __init__(self, master=None): ... Frame.__init__(self, master) ... self.pack() ... def createLabels(self): ... labels = [] ... for i in range(4): ... labelName = "myLabel_{0}".format(i) ... labels.append(Label(master=self, text="this is label " + labelName)) ... for label in labels: ... label.pack() ... >>> a=gui() >>> a.createLabels() self is the instance of your inherited Frame or else container. Regards Karim On 01/27/2011 01:15 PM, Elwin Estle wrote: From the lack of replies...I am guessing that this can't be done. Tho I just realized I had a typo in part of it. The line that reads: "Is there a way to do something like this in Tkinter? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above?" ...should have said, "Or am I correct in guessing tat if it IS possible, it is probably more..." --- On *Wed, 1/26/11, Elwin Estle //* wrote: From: Elwin Estle Subject: [Tutor] tkinter, create widgets during runtime? To: tutor@python.org Date: Wednesday, January 26, 2011, 12:21 PM With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code. i.e., something like: for {set i 0} {$i <= 5} {incr i} { label .myLabel_$i -text "this is label myLabel_$i" pack .myLabel_$i } ...which will generate five labels from "myLabel_0" to "myLabel_5". Useful if you need a varying number of widgets, or a series of "incremental" widgets. Is there a way to do something like this in Tkinter? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above? -Inline Attachment Follows- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter, create widgets during runtime?
Hello Wayne, I provided a complete example see the mail above, pretty similar to yours. Regards Karim On 01/27/2011 04:54 PM, Wayne Werner wrote: On Wed, Jan 26, 2011 at 11:21 AM, Elwin Estle mailto:chrysalis_reb...@yahoo.com>> wrote: With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code. i.e., something like: for {set i 0} {$i <= 5} {incr i} { label .myLabel_$i -text "this is label myLabel_$i" pack .myLabel_$i } for x in xrange(5): Label(root, text="This is label %d" %x).pack() will generate the labels. You can't put the variable names in the local namespace without some tricksy methods. You could, however, have a dict labels and just do labels[x] = Label(root, text="blah") labels[x].pack() HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter, create widgets during runtime?
Sorry, I forgot to update continuously the Frame: >>> app.mainloop() Karim On 01/27/2011 02:59 PM, Karim wrote: I never did that but this is python! You can create anything you want at runtime! Make a factory method in you gui class which inherit from Frame or whatever container code below is testing: >>> from Tkinter import * >>> class gui(Frame): ... def __init__(self, master=None): ... Frame.__init__(self, master) ... self.pack() ... def createLabels(self): ... labels = [] ... for i in range(4): ... labelName = "myLabel_{0}".format(i) ... labels.append(Label(master=self, text="this is label " + labelName)) ... for label in labels: ... label.pack() ... >>> a=gui() >>> a.createLabels() self is the instance of your inherited Frame or else container. Regards Karim On 01/27/2011 01:15 PM, Elwin Estle wrote: From the lack of replies...I am guessing that this can't be done. Tho I just realized I had a typo in part of it. The line that reads: "Is there a way to do something like this in Tkinter? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above?" ...should have said, "Or am I correct in guessing tat if it IS possible, it is probably more..." --- On *Wed, 1/26/11, Elwin Estle //* wrote: From: Elwin Estle Subject: [Tutor] tkinter, create widgets during runtime? To: tutor@python.org Date: Wednesday, January 26, 2011, 12:21 PM With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code. i.e., something like: for {set i 0} {$i <= 5} {incr i} { label .myLabel_$i -text "this is label myLabel_$i" pack .myLabel_$i } ...which will generate five labels from "myLabel_0" to "myLabel_5". Useful if you need a varying number of widgets, or a series of "incremental" widgets. Is there a way to do something like this in Tkinter? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above? -Inline Attachment Follows- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist -Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter, create widgets during runtime?
Sorry, I forgot to update continuously the Frame: >>> a.mainloop() Karim On 01/27/2011 02:59 PM, Karim wrote: I never did that but this is python! You can create anything you want at runtime! Make a factory method in you gui class which inherit from Frame or whatever container code below is testing: >>> from Tkinter import * >>> class gui(Frame): ... def __init__(self, master=None): ... Frame.__init__(self, master) ... self.pack() ... def createLabels(self): ... labels = [] ... for i in range(4): ... labelName = "myLabel_{0}".format(i) ... labels.append(Label(master=self, text="this is label " + labelName)) ... for label in labels: ... label.pack() ... >>> a=gui() >>> a.createLabels() self is the instance of your inherited Frame or else container. Regards Karim On 01/27/2011 01:15 PM, Elwin Estle wrote: From the lack of replies...I am guessing that this can't be done. Tho I just realized I had a typo in part of it. The line that reads: "Is there a way to do something like this in Tkinter? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above?" ...should have said, "Or am I correct in guessing tat if it IS possible, it is probably more..." --- On *Wed, 1/26/11, Elwin Estle //* wrote: From: Elwin Estle Subject: [Tutor] tkinter, create widgets during runtime? To: tutor@python.org Date: Wednesday, January 26, 2011, 12:21 PM With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code. i.e., something like: for {set i 0} {$i <= 5} {incr i} { label .myLabel_$i -text "this is label myLabel_$i" pack .myLabel_$i } ...which will generate five labels from "myLabel_0" to "myLabel_5". Useful if you need a varying number of widgets, or a series of "incremental" widgets. Is there a way to do something like this in Tkinter? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above? -Inline Attachment Follows- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist -Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] small ElementTree problem
id is a tag so it is a OBJECT Element with attributes accessible by dictionnary x.attrib[key] and x.text for tag content text. canonical string representation of your Element object: Obj.id :>composite pattern. For result use iterator as below (not tested but should be ok): *_/#Parsing:/_ doc = ElementTree() doc.parse(xmlFile)* *_/#iteration over tag element:/_ ids = [] names =[] for result in doc.iter('result'): idElem = result.find('id') *** nameElem = result.find('name')** * ids.append(idElem.text) names.append(nameElement.text) final = zip(ids, names) * You are not obliged to provide the full XPATH. Etree search for you. Regards Karim On 01/27/2011 11:23 PM, Alex Hall wrote: Hi all, I am using, and very much enjoying, the ElementTree library. However, I have hit a problem. Say I have something along the lines of: Message from Service 1.0 1 result 1 2 result 2 In my ResultSet class, I parse this to get the text of elements like message or version. Then, I use root.findall("list/result") and iterate over the result, passing to a second function which parses the passed-in elements into Result objects. For example: all=root.findall("list/result") for i in all: self.mylist.append(Obj().parse(i)) In Obj.parse(), the element passed in is treated like this: def parse(data): root=data.getroot() self.id=root.find("id").text self.name=root.find("name).text Printing the results of the above through Obj.id or Obj.name gives me odd behavior: print Obj.id :>None What is going on? Does the root change when I call find()? Why would an Element object get used when I clearly say to use the text of the found element? TIA. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Accessing a secured webpage
Hello, I want to create a client to access a webpage. But when I access it interactively there is a dialog box which ask for login and password. I want to access it in batch via python but I could only found a basic example: ||#||!/bin/env|| ||python| |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| |import| urllib2 reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) xhtmldata|=| reponse.|read|() |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) | I want to provide login and password via python code. The web adress is like http://website.com:8081/ddts/ddts_main. If you have link it is welcome! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing a secured webpage
Vince I saw your answer on the related subject fron October 2010 : *Re: [Tutor] Requesting restricted URL (further authentication requested)*. Thanks Karim On 01/28/2011 11:05 PM, Vince Spicer wrote: You may want to look at httplib2 http://code.google.com/p/httplib2/ This great module makes auth very simple Vince On Fri, Jan 28, 2011 at 3:54 PM, Karim <mailto:karim.liat...@free.fr>> wrote: Hello, I want to create a client to access a webpage. But when I access it interactively there is a dialog box which ask for login and password. I want to access it in batch via python but I could only found a basic example: ||#||!/bin/env|| ||python| |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| |import| urllib2 reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) xhtmldata|=| reponse.|read|() |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) | I want to provide login and password via python code. The web adress is like http://website.com:8081/ddts/ddts_main. If you have link it is welcome! Regards Karim ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Vince Spicer Developer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing a secured webpage
Thanks Ian! This is a simple one! I found this other way said more flexible, I must check it too: *import urllib class myURLOpener(urllib.FancyURLopener): def setpasswd(self, user, passwd): self.__user = user self.__passwd = passwd def prompt_user_passwd(self, host, realm): return self.__user, self.__passwd urlopener = myURLOpener() urlopener.setpasswd("mulder", "trustno1")* Basically, we must subclass **urllib.FancyURLopener** and override **prompt_user_passwd(). **Regards Karim ** ** On 01/28/2011 11:15 PM, ian douglas wrote: If it's HTTP basic_auth, you could try this method too: http://username:passw...@domain.com/page.html On 01/28/2011 01:54 PM, Karim wrote: Hello, I want to create a client to access a webpage. But when I access it interactively there is a dialog box which ask for login and password. I want to access it in batch via python but I could only found a basic example: ||#||!/bin/env|| ||python| |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| |import| urllib2 reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) xhtmldata|=| reponse.|read|() |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) | I want to provide login and password via python code. The web adress is like http://website.com:8081/ddts/ddts_main. If you have link it is welcome! Regards Karim ___ Tutor maillist -Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Tuples
Hello, for x, y in t: print x*y Regards Karim On 01/30/2011 10:29 AM, Becky Mcquilling wrote: I'm fairly new to python and I am trying to do some math with tuples. If I have a tuple: t =( (1000, 2000), (2, 4), (25, 2)) I want to loop through and print out the results of the multiplying the two numbers like so: 1000 x 2000 2 x 4 etc. I'm not sure of the syntax for that. Any ideas? Becky ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] oops...sorry, just top posted again
Is this a SM forum ? Karim On 01/31/2011 04:05 PM, David Hutto wrote: On Mon, Jan 31, 2011 at 8:11 AM, Elwin Estle wrote: ...but I have an excuse. I had the thing saved in a drafts folder and just hit send without thinking about it. ...I'll just go super glue broken glass to my hands and sprinkle itching powder all over my body. Is that penance enough? Nah, You also have to appease the Python Gods with a virgin sacrifice down at the local volcano, or canyon like abyss...your pick.. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting a string
Hello, >>> "He is {what}".format(what="{wild}") 'He is {wild}' Regards Karim On 02/01/2011 09:44 AM, Becky Mcquilling wrote: Quick question to the group to solve an immediate problem and then if anyone has a dead simple reference on formatting strings it would be greatly appreciated as I'm finding this to be pretty confusing. Basically, I need to format a string as an example: " I want to insert wild in place of what and output the resulting text WITH the curly braces. This is not the actual code but is the idea of what I need to do. Thanks all, Becky ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting a string
Complete test copy & paste: karim@Requiem4Dream:~$ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "He is {what}".format(what="{wild}") 'He is {wild}' >>> I don't get the missing "." ?! Regards Karim On 02/01/2011 01:35 PM, col speed wrote: You're missing a "." that if your computer is the same as mine, looks like something left behind by a mosquito On 1 February 2011 18:33, Karim <mailto:karim.liat...@free.fr>> wrote: Hello, >>> "He is {what}".format(what="{wild}") 'He is {wild}' Regards Karim On 02/01/2011 09:44 AM, Becky Mcquilling wrote: Quick question to the group to solve an immediate problem and then if anyone has a dead simple reference on formatting strings it would be greatly appreciated as I'm finding this to be pretty confusing. Basically, I need to format a string as an example: " I want to insert wild in place of what and output the resulting text WITH the curly braces. This is not the actual code but is the idea of what I need to do. Thanks all, Becky ___ Tutor maillist -Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org <mailto:Tutor@python.org> To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] RE module is working ?
Hello, I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) Only one substitution..._But this is not the same REGEX._ And the count=2 does nothing. By default all occurrence shoul be substituted. * *On linux using my good old sed command, it is working with my '?' (0-1 match):* *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* \"\" *Indeed what's the matter with RE module!?* *Any idea will be welcome! Regards Karim* * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
Hello, Any news on this topic?O:-) Regards Karim On 02/02/2011 08:21 PM, Karim wrote: Hello, I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) Only one substitution..._But this is not the same REGEX._ And the count=2 does nothing. By default all occurrence shoul be substituted. * *On linux using my good old sed command, it is working with my '?' (0-1 match):* *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* \"\" *Indeed what's the matter with RE module!?* *Any idea will be welcome! Regards Karim* * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
Hello Steven, I am perhaps a poor tradesman but I have to blame my thunderbird tool :-P . Because expression = *' "" '* is in fact fact expression = ' "" '. The bold appear as stars I don't know why. I need to have escapes for passing it to another language (TCL interpreter). So I will rewrite it not _in bold_: $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = ' "" ' >>> re.subn(r'([^\\])?"', r'\1\\"', expression) But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) * On linux using my good old sed command, it is working with my '?' (0-1 match): $ echo ' "" ' | sed 's/\([^\\]\)\?"/\1\\"/g'* * \"\" For me linux/unix sed utility is trusty and is the reference. Regards Karim On 02/03/2011 11:43 AM, Steven D'Aprano wrote: Karim wrote: Hello, I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: You don't have to escape quotes. Just use the other sort of quote: >>> print '""' "" * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* No, I'm sorry, that's incorrect -- that gives a syntax error in every version of Python I know of, including version 2.7: >>> expression = *' "" '* File "", line 1 expression = *' "" '* ^ SyntaxError: invalid syntax So what are you really running? >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Likewise here. *r'...' is a syntax error, as is expression*) I don't understand what you are running or why you are getting the results you are. > *Indeed what's the matter with RE module!?* There are asterisks all over your post! Where are they coming from? What makes you think the problem is with the RE module? We have a saying in English: "The poor tradesman blames his tools." Don't you think it's more likely that the problem is that you are using the module wrongly? I don't understand what you are trying to do, so I can't tell you how to do it. Can you give an example of what you want to start with, and what you want to end up with? NOT Python code, just literal text, like you would type into a letter. E.g. ABC means literally A followed by B followed by C. \" means literally backslash followed by double-quote ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
I forget something. There is no issue with python and double quotes. But I need to give it to TCL script but as TCL is shit string is only delimited by double quotes. Thus I need to escape it to not have syntax error whith nested double quotes. Regards The poor tradesman On 02/03/2011 12:45 PM, Karim wrote: Hello Steven, I am perhaps a poor tradesman but I have to blame my thunderbird tool :-P . Because expression = *' "" '* is in fact fact expression = ' "" '. The bold appear as stars I don't know why. I need to have escapes for passing it to another language (TCL interpreter). So I will rewrite it not _in bold_: $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = ' "" ' >>> re.subn(r'([^\\])?"', r'\1\\"', expression) But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) * On linux using my good old sed command, it is working with my '?' (0-1 match): $ echo ' "" ' | sed 's/\([^\\]\)\?"/\1\\"/g'* * \"\" For me linux/unix sed utility is trusty and is the reference. Regards Karim On 02/03/2011 11:43 AM, Steven D'Aprano wrote: Karim wrote: Hello, I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: You don't have to escape quotes. Just use the other sort of quote: >>> print '""' "" * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* No, I'm sorry, that's incorrect -- that gives a syntax error in every version of Python I know of, including version 2.7: >>> expression = *' "" '* File "", line 1 expression = *' "" '* ^ SyntaxError: invalid syntax So what are you really running? >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Likewise here. *r'...' is a syntax error, as is expression*) I don't understand what you are running or why you are getting the results you are. > *Indeed what's the matter with RE module!?* There are asterisks all over your post! Where are they coming from? What makes you think the problem is with the RE module? We have a saying in English: "The poor tradesman blames his tools." Don't you think it's more likely that the problem is that you are using the module wrongly? I don't understand what you are trying to do, so I can't tell you how to do it. Can you give an example of what you want to start with, and what you want to end up with? NOT Python code, just literal text, like you would type into a letter. E.g. ABC means literally A followed by B followed by C. \" means literally backslash followed by double-quote ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
On 02/03/2011 02:15 PM, Peter Otten wrote: Karim wrote: I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) Only one substitution..._But this is not the same REGEX._ And the count=2 does nothing. By default all occurrence shoul be substituted. * *On linux using my good old sed command, it is working with my '?' (0-1 match):* *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* \"\" *Indeed what's the matter with RE module!?* You should really fix the problem with your email program first; Thunderbird issue with bold type (appears as stars) but I don't know how to fix it yet. afterwards it's probably a good idea to try and explain your goal clearly, in plain English. I already did it. (cf the mails queue). But to resume I pass the expression string to TCL command which delimits string with double quotes only. Indeed I get error with nested double quotes => That's the key problem. Yes. What Steven said ;) Now to your question as stated: if you want to escape two consecutive double quotes that can be done with s = s.replace('""', '\"\"') I have already done it as a workaround but I have to add another replacement before to consider all other cases. I want to make the original command work to suppress the workaround. but that's probably *not* what you want. Assuming you want to escape two consecutive double quotes and make sure that the first one isn't already escaped, You hit it !:-) this is my attempt: def sub(m): ... s = m.group() ... return r'\"\"' if s == '""' else s ... print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" \\" \"') That is not the thing I want. I want to escape any " which are not already escaped. The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have made regex on unix since 15 years). For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' '?' is not accepted Why? character which should not be an antislash with 0 or 1 occurence. This is quite simple. I am a poor tradesman but I don't deny evidence. Regards Karim \\\"" \\\"\" \"" \"\" \\\" \\" \" Compare that with $ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g' \\\"\" \\"\" \"\" \"\" " \\\" \\" Concerning the exception and the discrepancy between sed and python's re, I suggest that you ask it again on comp.lang.python aka the python-list mailing list where at least one regex guru will read it. Peter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
On 02/03/2011 11:20 PM, Dave Angel wrote: On 01/-10/-28163 02:59 PM, Karim wrote: On 02/03/2011 02:15 PM, Peter Otten wrote: Karim wrote: (snip> *Indeed what's the matter with RE module!?* You should really fix the problem with your email program first; Thunderbird issue with bold type (appears as stars) but I don't know how to fix it yet. The simple fix is not to try to add bold or colors on a text message. Python-tutor is a text list, not an html one. Thunderbird tries to accomodate you by adding the asterisks, which is fine if it's regular English. But in program code, it's obviously confuses things. While I've got you, can I urge you not to top-post? In this message, you correctly added your remarks after the part you were quoting. But many times you put your comments at the top, which is backwards. DaveA Sorry Dave, I will try and do my best to avoid bold and top-post in the future. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
On 02/03/2011 07:47 PM, Karim wrote: On 02/03/2011 02:15 PM, Peter Otten wrote: Karim wrote: I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) Only one substitution..._But this is not the same REGEX._ And the count=2 does nothing. By default all occurrence shoul be substituted. * *On linux using my good old sed command, it is working with my '?' (0-1 match):* *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* \"\" *Indeed what's the matter with RE module!?* You should really fix the problem with your email program first; Thunderbird issue with bold type (appears as stars) but I don't know how to fix it yet. afterwards it's probably a good idea to try and explain your goal clearly, in plain English. I already did it. (cf the mails queue). But to resume I pass the expression string to TCL command which delimits string with double quotes only. Indeed I get error with nested double quotes => That's the key problem. Yes. What Steven said ;) Now to your question as stated: if you want to escape two consecutive double quotes that can be done with s = s.replace('""', '\"\"') I have already done it as a workaround but I have to add another replacement before to consider all other cases. I want to make the original command work to suppress the workaround. but that's probably *not* what you want. Assuming you want to escape two consecutive double quotes and make sure that the first one isn't already escaped, You hit it !:-) this is my attempt: def sub(m): ... s = m.group() ... return r'\"\"' if s == '""' else s ... print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" \\" \"') That is not the thing I want. I want to escape any " which are not already escaped. The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have made regex on unix since 15 years). For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' '?' is not accepted Why? character which should not be an antislash with 0 or 1 occurence. This is quite simple. I am a poor tradesman but I don't deny evidence. Recall: >>> re.subn(r'([^\\])?"', r'\1\\"', expression) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group Found the solution: '?' needs to be inside parenthesis (saved pattern) because outside we don't know if the saved match argument will exist or not namely '\1'. >>> re.subn(r'([^\\]?)"', r'\1\\"', expression) (' \\"\\" ', 2) sed unix command is more permissive: sed 's/\([^\\]\)\?"/\1\\"/g' because '?' can be outside parenthesis (saved pattern but escaped for sed). \1 seems to not cause issue when matching is found. Perhaps it is created only when match occurs. MORALITY: 1) Behaviour of python is logic and I must understand what I do with it. 2) sed is a fantastic
Re: [Tutor] RE module is working ?
On 02/04/2011 02:36 AM, Steven D'Aprano wrote: Karim wrote: *Indeed what's the matter with RE module!?* You should really fix the problem with your email program first; Thunderbird issue with bold type (appears as stars) but I don't know how to fix it yet. A man when to a doctor and said, "Doctor, every time I do this, it hurts. What should I do?" The doctor replied, "Then stop doing that!" :) Yes this these words made me laugh. I will keep it in my funny box. Don't add bold or any other formatting to things which should be program code. Even if it looks okay in *your* program, you don't know how it will look in other people's programs. If you need to draw attention to something in a line of code, add a comment, or talk about it in the surrounding text. [...] That is not the thing I want. I want to escape any " which are not already escaped. The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have made regex on unix since 15 years). Mainly sed, awk and perl sometimes grep and egrep. I know this is the jungle. Which regex? Perl regexes? sed or awk regexes? Extended regexes? GNU posix compliant regexes? grep or egrep regexes? They're all different. In any case, I am sorry, I don't think your regex does what you say. When I try it, it doesn't work for me. [steve@sylar ~]$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \\"text\" I give you my word on this. Exact output I redid it: #MY OS VERSION karim@Requiem4Dream:~$ uname -a Linux Requiem4Dream 2.6.32-28-generic #55-Ubuntu SMP Mon Jan 10 23:42:43 UTC 2011 x86_64 GNU/Linux #MY SED VERSION karim@Requiem4Dream:~$ sed --version GNU sed version 4.2.1 Copyright (C) 2009 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, to the extent permitted by law. GNU sed home page: <http://www.gnu.org/software/sed/>. General help using GNU software: <http://www.gnu.org/gethelp/>. E-mail bug reports to: . Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. #MY SED OUTPUT COMMAND: karim@Requiem4Dream:~$ echo 'Some ""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"\" # THIS IS WHAT I WANT 2 CONSECUTIVES IF THE FIRST ONE IS ALREADY ESCAPED I DON'T WANT TO ESCAPED IT TWICE. karim@Requiem4Dream:~$ echo 'Some \""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"\" # BY THE WAY THIS ONE WORKS: karim@Requiem4Dream:~$ echo 'Some "text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"text\" # BUT SURE NOT THIS ONE NOT COVERED BY MY REGEX (I KNOW IT AND WANT ORIGINALY TO COVER IT): karim@Requiem4Dream:~$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \\"text\" By the way in all sed version I work with the '?' (0 or one match) should be escaped that's the reason I have '\?' same thing with save '\(' and '\)' to store value. In perl, grep you don't need to escape. # SAMPLE FROM http://www.gnu.org/software/sed/manual/sed.html |\+| same As |*|, but matches one or more. It is a GNU extension. |\?| same As |*|, but only matches zero or one. It is a GNU extension I wouldn't expect it to work. See below. By the way, you don't need to escape the brackets or the question mark: [steve@sylar ~]$ echo 'Some \"text"' | sed -re 's/([^\\])?"/\1\\"/g' Some \\"text\" For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' No it is not. Yes I know, see my latest post in detail I already found the solution. I put it again the solution below: #Found the solution: '?' needs to be inside parenthesis (saved pattern) because outside we don't know if the saved match argument #will exist or not namely '\1'. >>> re.subn(r'([^\\]?)"', r'\1\\"', expression) (' \\"\\" ', 2) The pattern you are matching does not do what you think it does. "Zero or one of not-backslash, followed by a quote" will match a single quote *regardless* of what is before it. This is true even in sed, as you can see above, your sed regex matches both quotes. \" will match, because the regular expression will match zero characters, followed by a quote. So the regex is correct. >>> match = r'[^\\]?"' # zero or one not-backslash followed by quote >>> re.search(match, r'aaa\"aaa').group() '"' Now watc
Re: [Tutor] RE module is working ?
On 02/04/2011 11:26 AM, Peter Otten wrote: Karim wrote: That is not the thing I want. I want to escape any " which are not already escaped. The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have made regex on unix since 15 years). Can the backslash be escaped, too? If so I don't think your regex does what you think it does. r'\\\"' # escaped \ followed by escaped " should not be altered, but: $ echo '\\\"' | sed 's/\([^\\]\)\?"/\1\\"/g' " # two escaped \ folloed by a " that is not escaped By the way you are right: I changed an I added sed command for the ' "" ': karim@Requiem4Dream:~$ echo 'prima " "' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \" \" karim@Requiem4Dream:~$ echo 'prima ""' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"\" karim@Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" karim@Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" Sorry, for the incomplete command. You pointed it out, many thanks Peter! Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RE module is working ?
By the way with your helper function algorithm Steven and Peter comments you made me think of this change: karim@Requiem4Dream:~$ echo 'prima " "' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \" \" karim@Requiem4Dream:~$ echo 'prima ""' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"\" karim@Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" karim@Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" Regards Karim On 02/04/2011 08:07 PM, Karim wrote: On 02/04/2011 02:36 AM, Steven D'Aprano wrote: Karim wrote: *Indeed what's the matter with RE module!?* You should really fix the problem with your email program first; Thunderbird issue with bold type (appears as stars) but I don't know how to fix it yet. A man when to a doctor and said, "Doctor, every time I do this, it hurts. What should I do?" The doctor replied, "Then stop doing that!" :) Yes this these words made me laugh. I will keep it in my funny box. Don't add bold or any other formatting to things which should be program code. Even if it looks okay in *your* program, you don't know how it will look in other people's programs. If you need to draw attention to something in a line of code, add a comment, or talk about it in the surrounding text. [...] That is not the thing I want. I want to escape any " which are not already escaped. The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have made regex on unix since 15 years). Mainly sed, awk and perl sometimes grep and egrep. I know this is the jungle. Which regex? Perl regexes? sed or awk regexes? Extended regexes? GNU posix compliant regexes? grep or egrep regexes? They're all different. In any case, I am sorry, I don't think your regex does what you say. When I try it, it doesn't work for me. [steve@sylar ~]$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \\"text\" I give you my word on this. Exact output I redid it: #MY OS VERSION karim@Requiem4Dream:~$ uname -a Linux Requiem4Dream 2.6.32-28-generic #55-Ubuntu SMP Mon Jan 10 23:42:43 UTC 2011 x86_64 GNU/Linux #MY SED VERSION karim@Requiem4Dream:~$ sed --version GNU sed version 4.2.1 Copyright (C) 2009 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, to the extent permitted by law. GNU sed home page: <http://www.gnu.org/software/sed/>. General help using GNU software: <http://www.gnu.org/gethelp/>. E-mail bug reports to: . Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. #MY SED OUTPUT COMMAND: karim@Requiem4Dream:~$ echo 'Some ""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"\" # THIS IS WHAT I WANT 2 CONSECUTIVES IF THE FIRST ONE IS ALREADY ESCAPED I DON'T WANT TO ESCAPED IT TWICE. karim@Requiem4Dream:~$ echo 'Some \""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"\" # BY THE WAY THIS ONE WORKS: karim@Requiem4Dream:~$ echo 'Some "text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"text\" # BUT SURE NOT THIS ONE NOT COVERED BY MY REGEX (I KNOW IT AND WANT ORIGINALY TO COVER IT): karim@Requiem4Dream:~$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \\"text\" By the way in all sed version I work with the '?' (0 or one match) should be escaped that's the reason I have '\?' same thing with save '\(' and '\)' to store value. In perl, grep you don't need to escape. # SAMPLE FROM http://www.gnu.org/software/sed/manual/sed.html |\+| same As |*|, but matches one or more. It is a GNU extension. |\?| same As |*|, but only matches zero or one. It is a GNU extension I wouldn't expect it to work. See below. By the way, you don't need to escape the brackets or the question mark: [steve@sylar ~]$ echo 'Some \"text"' | sed -re 's/([^\\])?"/\1\\"/g' Some \\"text\" For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' No it is not. Yes I know, see my latest post in detail I already found the solution. I put it again the solution below: #Found the solution: '?' needs
[Tutor] Accessing query results html frame
Hello All, I get from Steven an very useful link (void space) for http authentication. I added some codes to be able to POST FORM a query as I do it by clicking a query button to get a list of bug Id on a server. The problem is I get a html page which refers 2 frames. And I am interesting in one particular frame namely for example, http://{server}:{port}/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port). But this pages is created every times in a tmp directory each time with a different name. 1) How can I get the name of this page because with python the page resulting of my query is not mentionned (hidden like)? Interactively there are 3 frames but only this one is of interest for me. But no name of this page is visible in the main html page. Is there a method to get all the nested frames locations? 2) I can see this page interactively when I click on a submit query button. Do I need to add 'ACTION': "Query" in the query dictionnary to simulate a click for submission (type="submit" button) ? 3) Interactively I see that cgi arg NextForm is empty so I let it like that in my query and LastForm was set to "SavedQuery". I put the same value in my python code. Is this ok? import urllib import urllib2 server='dummy.com' port='8081' username = 'karim.liateni' password = 'dummy_pass' theurl = 'http://{server}:{port}/ddts/ddts_main'.format(server=server, port=port) #theurl = 'http://{server}:{port}:8081/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port) #MEMO: #ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> data = { 'NextForm': "", 'LastForm': "SavedQuery", 'prompted': "yes", 'class': "Development", 'personalQuery': "DKPV", 'REMOTE_USER': username, 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' "Development" \)", 'use_field_defs':"false", 'QueryName': "DKPV", 'QueryType': "personal", 'ACTION': "Query" } query = urllib.urlencode(data) request = urllib2.Request(theurl, query) passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) pagehandle = urllib2.urlopen(request) print(pagehandle.read()) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing query results html frame
Hello, In fact as found in the net: "The concept of browser frames is completely outside the scope of HTTP. However, browser frames are defined in HTML, and so is the target property on form elements: <form action="/somescript?x=y" method="POST" target="_top"> This will make the form submit to the _top frame, which means "use the full browser window" " That means that my post form: ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> has a target property to make the submit to the 'rightframe'. Any ideas how I can modified the code (I think the request data or whatever) below to access without knowing the temporary html file name generically. Regards Karim On 02/10/2011 07:12 PM, Karim wrote: Hello All, I get from Steven an very useful link (void space) for http authentication. I added some codes to be able to POST FORM a query as I do it by clicking a query button to get a list of bug Id on a server. The problem is I get a html page which refers 2 frames. And I am interesting in one particular frame namely for example, http://{server}:{port}/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port). But this pages is created every times in a tmp directory each time with a different name. 1) How can I get the name of this page because with python the page resulting of my query is not mentionned (hidden like)? Interactively there are 3 frames but only this one is of interest for me. But no name of this page is visible in the main html page. Is there a method to get all the nested frames locations? 2) I can see this page interactively when I click on a submit query button. Do I need to add 'ACTION': "Query" in the query dictionnary to simulate a click for submission (type="submit" button) ? 3) Interactively I see that cgi arg NextForm is empty so I let it like that in my query and LastForm was set to "SavedQuery". I put the same value in my python code. Is this ok? import urllib import urllib2 server='dummy.com' port='8081' username = 'karim.liateni' password = 'dummy_pass' theurl = 'http://{server}:{port}/ddts/ddts_main'.format(server=server, port=port) #theurl = 'http://{server}:{port}:8081/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port) #MEMO: #ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> data = { 'NextForm': "", 'LastForm': "SavedQuery", 'prompted': "yes", 'class': "Development", 'personalQuery': "DKPV", 'REMOTE_USER': username, 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' "Development" \)", 'use_field_defs':"false", 'QueryName': "DKPV", 'QueryType': "personal", 'ACTION': "Query" } query = urllib.urlencode(data) request = urllib2.Request(theurl, query) passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) pagehandle = urllib2.urlopen(request) print(pagehandle.read()) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor