From nuno.hespanhol at gmail.com Sun Mar 1 02:08:01 2009 From: nuno.hespanhol at gmail.com (Nuno Hespanhol) Date: Sun, 01 Mar 2009 01:08:01 +0000 Subject: [Tutor] What does the L at the end of a number means? Message-ID: <49A9DFF1.9040703@gmail.com> Hi. I have started learning phyton today! I was playing around with some large numbers (fibonacci series) and noticed that in some large calculations results have an "L" at the end of a number. Does this L stands for Large? Is there any way to disable this feature, so that all numbers are shown? Thanks for your time. From wescpy at gmail.com Sun Mar 1 02:22:36 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 28 Feb 2009 17:22:36 -0800 Subject: [Tutor] What does the L at the end of a number means? In-Reply-To: <49A9DFF1.9040703@gmail.com> References: <49A9DFF1.9040703@gmail.com> Message-ID: <78b3a9580902281722n453c41b3sa334ef984be74c95@mail.gmail.com> > I have started learning phyton today! > I was playing around with some large numbers (fibonacci series) > and noticed that in some large calculations results have an "L" at the end > of a number. > Does this L stands for Large? Is there any way to disable this feature, so > that all numbers are shown? hi, and welcome to Python! yes, the "L" can mean "large," but officially, it means "long". What version of Python are you using? The reason why i ask is because long integers have been rolled into the existing integer type and the "L" should no longer be showing up as it is being phased out since the 2.2 release. They are completely gone in 3.0. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From geoterium at gmail.com Sun Mar 1 02:43:25 2009 From: geoterium at gmail.com (George Wahid) Date: Sun, 1 Mar 2009 03:43:25 +0200 Subject: [Tutor] What does the L at the end of a number means? Message-ID: it means that it's type is "long". writing an expression makes python return its value, so writing 2**1000 will return a number that ends with L to show that it's a long integer. but writing "print 2**1000" will print the number without the L. I don't know if there is a way to disable this feature, but it's not present in python 3.0. From lie.1296 at gmail.com Sun Mar 1 03:31:03 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 01 Mar 2009 13:31:03 +1100 Subject: [Tutor] What does the L at the end of a number means? In-Reply-To: <49A9DFF1.9040703@gmail.com> References: <49A9DFF1.9040703@gmail.com> Message-ID: <49A9F367.7020803@gmail.com> Nuno Hespanhol wrote: > Hi. > I have started learning phyton today! > I was playing around with some large numbers (fibonacci series) > and noticed that in some large calculations results have an "L" at the > end of a number. > Does this L stands for Large? Is there any way to disable this feature, > so that all numbers are shown? > > Thanks for your time. "L" means it is "long integer". In the python interpreter, when you do something like this: >>> a it will actually call the __repr__ of a and print it. >>> print a.__repr__() while >>> print a will call __str__ of a and print it >>> print a.__str__() Python 2.x's long integer __repr__ adds an extra L to denote long integer, however the __str__ does not. From lie.1296 at gmail.com Sun Mar 1 03:31:03 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 01 Mar 2009 13:31:03 +1100 Subject: [Tutor] What does the L at the end of a number means? In-Reply-To: <49A9DFF1.9040703@gmail.com> References: <49A9DFF1.9040703@gmail.com> Message-ID: <49A9F367.7020803@gmail.com> Nuno Hespanhol wrote: > Hi. > I have started learning phyton today! > I was playing around with some large numbers (fibonacci series) > and noticed that in some large calculations results have an "L" at the > end of a number. > Does this L stands for Large? Is there any way to disable this feature, > so that all numbers are shown? > > Thanks for your time. "L" means it is "long integer". In the python interpreter, when you do something like this: >>> a it will actually call the __repr__ of a and print it. >>> print a.__repr__() while >>> print a will call __str__ of a and print it >>> print a.__str__() Python 2.x's long integer __repr__ adds an extra L to denote long integer, however the __str__ does not. From d.conca at gmail.com Sun Mar 1 10:36:25 2009 From: d.conca at gmail.com (Daniele) Date: Sun, 1 Mar 2009 10:36:25 +0100 Subject: [Tutor] modular program Message-ID: <537341c70903010136o168fc246r5687b1e5944eefb0@mail.gmail.com> Hi, I'd like to write a python program which can be easily extended by other people. Where can I find some "best practices" for writing modular programs? I thought about a txt file containing function calls that my program will parse and execute in order, or is it better just to execute every .py file in a certain "module" folder (I don't like this as modules could need to be executed in different moments)? Can any1 point me to a relatively simple program to look at? thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Mar 1 14:05:37 2009 From: srilyk at gmail.com (W W) Date: Sun, 1 Mar 2009 07:05:37 -0600 Subject: [Tutor] modular program In-Reply-To: <537341c70903010136o168fc246r5687b1e5944eefb0@mail.gmail.com> References: <537341c70903010136o168fc246r5687b1e5944eefb0@mail.gmail.com> Message-ID: <333efb450903010505y1faabbd2l77972a371aada599@mail.gmail.com> On Sun, Mar 1, 2009 at 3:36 AM, Daniele wrote: > Hi, > I'd like to write a python program which can be easily extended by other > people. Where can I find some "best practices" for writing modular programs? > I thought about a txt file containing function calls that my program will > parse and execute in order, or is it better just to execute every .py file > in a certain "module" folder (I don't like this as modules could need to be > executed in different moments)? Can any1 point me to a relatively simple > program to look at? Using classes is a pretty good idea. Then people can either "import daniele" or "from daniele import niftyClass". You can pretty much take a look at any of the modules in your python library directory. In the case of my linux box, that's /usr/lib/python2.5/ HTH, Wayne From roadierich at googlemail.com Sun Mar 1 16:13:26 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Sun, 1 Mar 2009 15:13:26 +0000 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Message-ID: 2009/2/28 Alan Gauld : > > "Richard Lovely" wrote > >> > Sorry, I should have pointed out that you will need to redefine >> > all your functions to accept a parameter. >> >> Always makes me smile when (experienced) people redesign the wheel... >> >> From the docs (http://www.python.org/doc/2.6/library/functools.html): >> >> "The partial() is used for partial function application which >> ?freezes? some portion of a function?s arguments and/or keywords >> resulting in a new object with a simplified signature." > > I'm not sure how you would use partial in this case, I still think you'd > need to add a parameter to the function definitions. partial would > remove the need for lambda in some of the other solutions though. > > But an interesting module that I've not seen before. Although since it was > only introduced in 2.5 I'm not surprised, I've been focussing more > on v3 lately rather than the new stuff in 2.5/2.6 (in fact I don't even > have 2.6 loaded yet and only have 2.5 on one PC...) > > Thanks for highlighting it. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Ooops... quoted the wrong message. That should have been quoting the message about lambdas... -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From alan.gauld at btinternet.com Sun Mar 1 18:10:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Mar 2009 17:10:21 -0000 Subject: [Tutor] modular program References: <537341c70903010136o168fc246r5687b1e5944eefb0@mail.gmail.com> Message-ID: "Daniele" wrote > I'd like to write a python program which can be easily extended by > other > people. Where can I find some "best practices" for writing modular > programs? Try reading wikipedia. Try looking under "modular", "coupling" and "cohesion" You could also try "Frameworks" > I thought about a txt file containing function calls that my program > will > parse and execute in order, or is it better just to execute every > .py file > in a certain "module" folder Erm, I don't know what you mean by that bit?! :-) A text file full of python functions is a module if you name it .py. You can then import it and use the functins therein. > I don't like this as modules could need to be executed in different > moments You don't normally execute modules, you use the executable functions within modules. (Although in the strictest sense functions are themselves a form of module.) > Can any1 point me to a relatively simple program to look at? You could look at the topic on modules and functins in my tutor. Or you could read the case study topic which uses modules Or if you can find the paper book version (in your local library?) you can read the Games Framework chapter which describes how to write a set of modules (using classes) that are explicitly designed to be extended rather than used as-is. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Sun Mar 1 19:04:56 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 01 Mar 2009 10:04:56 -0800 Subject: [Tutor] Converting "HH:MM:SS" to datetime Message-ID: <49AACE48.5020006@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sun Mar 1 19:15:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 1 Mar 2009 19:15:16 +0100 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: <49AACE48.5020006@sbcglobal.net> References: <49AACE48.5020006@sbcglobal.net> Message-ID: 2009/3/1 Wayne Watson : > Ok, how do I do what's mentioned in Subject? Googling for python and time gives as first result. http://www.doughellmann.com/PyMOTW/datetime/index.html Which covers all you need to know to solve this. Greets Sander From sander.sweers at gmail.com Sun Mar 1 19:16:42 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 1 Mar 2009 19:16:42 +0100 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: References: <49AACE48.5020006@sbcglobal.net> Message-ID: 2009/3/1 Sander Sweers : > > Googling for python and time gives as first result. Sorry this is not correct, ignore it. Greets Sander From cfuller084 at thinkingplanet.net Sun Mar 1 16:56:48 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 1 Mar 2009 09:56:48 -0600 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: <49AACE48.5020006@sbcglobal.net> References: <49AACE48.5020006@sbcglobal.net> Message-ID: <200903010956.49206.cfuller084@thinkingplanet.net> On Sunday 01 March 2009 12:04, Wayne Watson wrote: > Ok, how do I do what's mentioned in Subject? There's an inverse to the strftime() function, strptime(), also in the time module, that will do this. Cheers From marc.tompkins at gmail.com Sun Mar 1 19:36:26 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 1 Mar 2009 10:36:26 -0800 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: <49AACE48.5020006@sbcglobal.net> References: <49AACE48.5020006@sbcglobal.net> Message-ID: <40af687b0903011036wf0f8ebai248a29ca0f07ff9d@mail.gmail.com> On Sun, Mar 1, 2009 at 10:04 AM, Wayne Watson wrote: > Ok, how do I do what's mentioned in Subject? > One thing to be aware of - Python datetimes are just that: date + time. If you specify only the time, the date will be filled in with a default value - generally the beginning of the epoch for your particular platform. "datetime" objects (but not "time" objects!) have a method called "strptime" which does exactly what you want - you give it an input string and a format string to tell it how to interpret the input, and it returns a datetime object. Then you can remove the date portion and you're done: >>> import datetime >>> blah = datetime.datetime.strptime("13:01:15","%H:%M:%S") >>> blah datetime.datetime(1900, 1, 1, 13, 1, 15) >>> blah = blah.time() >>> blah datetime.time(13, 1, 15) The format string for strptime uses the same conventions as the strftime() function; they're generally not listed separately. Or you can hack the string into its component parts and create the time from a timetuple: (I'm including the mistakes I made along the way) >>> inDateStr = "13:01:15" >>> inHour = inDateStr[:2] >>> inHour '13' >>> inMin = inDateStr[4:6] >>> inMin '1:' >>> inMin = inDateStr[3:5] >>> inMin '01' >>> inSec = inDateStr[-2:] >>> inSec '15' >>> blah = datetime.time(inHour, inMin, inSec) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required >>> blah = datetime.time(int(inHour), int(inMin), int(inSec)) >>> blah datetime.time(13, 1, 15) >>> Hope that helps. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Mar 1 21:47:40 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 01 Mar 2009 12:47:40 -0800 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: References: <49AACE48.5020006@sbcglobal.net> Message-ID: <49AAF46C.5050907@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Mar 1 21:51:07 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 01 Mar 2009 12:51:07 -0800 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: <40af687b0903011036wf0f8ebai248a29ca0f07ff9d@mail.gmail.com> References: <49AACE48.5020006@sbcglobal.net> <40af687b0903011036wf0f8ebai248a29ca0f07ff9d@mail.gmail.com> Message-ID: <49AAF53B.7010304@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Mar 1 22:04:08 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 01 Mar 2009 13:04:08 -0800 Subject: [Tutor] Returning the IDLE Shell Window to Prompt Message-ID: <49AAF848.8030906@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Mar 1 22:18:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Mar 2009 16:18:04 -0500 Subject: [Tutor] Converting "HH:MM:SS" to datetime In-Reply-To: <49AAF53B.7010304@sbcglobal.net> References: <49AACE48.5020006@sbcglobal.net> <40af687b0903011036wf0f8ebai248a29ca0f07ff9d@mail.gmail.com> <49AAF53B.7010304@sbcglobal.net> Message-ID: <1c2a2c590903011318j6ddfb9b5w33b2ea67d452a925@mail.gmail.com> On Sun, Mar 1, 2009 at 3:51 PM, Wayne Watson wrote: > ??????? x = str(self.start_time) > ??????? set_loc_dict["start_time"] = > datetime.datetime.strptime(x,"%H:%M:%S") > > It seems like there should be a simpler way to wrestle this to datetime. You say self.start_time is a str, so there is no need to convert it, and no need for the helper variable. How about set_loc_dict["start_time"] = datetime.datetime.strptime(self.start_time,"%H:%M:%S") Kent From d.conca at gmail.com Sun Mar 1 22:44:01 2009 From: d.conca at gmail.com (Daniele) Date: Sun, 1 Mar 2009 22:44:01 +0100 Subject: [Tutor] Tutor Digest, Vol 61, Issue 3 In-Reply-To: References: Message-ID: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> > From:?W W > Subject:?Re: [Tutor] modular program >>Where can I find some "best practices" for writing modular programs? >> I thought about a txt file containing function calls that my program will >> parse and execute in order, or is it better just to execute every .py file >> in a certain "module" folder (I don't like this as modules could need to be >> executed in different moments)? > You can pretty much take a look at any of the modules in your python > library directory. In the case of my linux box, that's > /usr/lib/python2.5/ I'm sorry, I've realized I didn't explain my needs at all. I was a little influenced by drupal's definition of modules, which is completely different from python's. With module here I meant plug-in or extension: a piece of code written by someone else that can be easily (and automaticallly) integrated into my program. My program must provide the posibility to be extended without editing its code, just like mozilla's add-ons. From bgailer at gmail.com Sun Mar 1 22:53:24 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 01 Mar 2009 16:53:24 -0500 Subject: [Tutor] Tutor Digest, Vol 61, Issue 3 In-Reply-To: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> References: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> Message-ID: <49AB03D4.9040308@gmail.com> Daniele wrote: [snip] > With module here I meant plug-in or extension: a piece of code written > by someone else that can be easily (and automaticallly) integrated > into my program. > My program must provide the posibility to be extended without editing > its code, just like mozilla's add-ons. > > That would depend on the interface between your program and the extensions. Do you have a design for this? You might take a look at how to create a mozilla add-on for ideas on this. -- Bob Gailer Chapel Hill NC 919-636-4239 From dorseye at gmail.com Sun Mar 1 23:27:48 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Sun, 1 Mar 2009 15:27:48 -0700 Subject: [Tutor] Tutor Digest, Vol 61, Issue 3 In-Reply-To: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> References: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> Message-ID: Not sure if this is what you mean, but: Say you have the files efunc.py and trytry.py in the same folder. *The content of efunc.py is:* def funky(): print 'funkytown' *The content of trytry.py is:* import efunc efunc.funky() *Output would be:* name at ububox:~$ python trytry.py funkytown name at ububox:~$ trtry.py "easily and automatically" uses the code from efunc.py It calls the function funky(). Granted this is a prety silly example, but is that what you mean by using code written by someone else? You do this with modules all the time, like import os, import glob, etc. Any .py file imported into another .py file is a module, granted most of them are a bit more useful than efunc.py > I'm sorry, I've realized I didn't explain my needs at all. > I was a little influenced by drupal's definition of modules, which is > completely different from python's. > With module here I meant plug-in or extension: a piece of code written > by someone else that can be easily (and automaticallly) integrated > into my program. > My program must provide the posibility to be extended without editing > its code, just like mozilla's add-ons. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 1 23:53:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Mar 2009 22:53:15 -0000 Subject: [Tutor] Returning the IDLE Shell Window to Prompt References: <49AAF848.8030906@sbcglobal.net> Message-ID: "Wayne Watson" wrote > My Tkinter program can crash at this stage, and the shell window is > locked from text entry, and the GUI displayed. I can kill the window > by > using X in the corner, and responding to a few dialogs. There must > be another way. There are lots of ways to kill an errant program. You could use Task Manager for example. But none of them are clean. It's one of the perils of running a Tkinter program inside another Tkinter program (IDLE). That's why its always safer to test GUI programs, and especially TKinter programs outside of IDLE. Just double click your file in Windows Explorer (or run it from a DOS box if you have any print statements, or want to see the error traces) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 2 00:17:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Mar 2009 23:17:10 -0000 Subject: [Tutor] Tutor Digest, Vol 61, Issue 3 References: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> Message-ID: "Daniele" wrote > With module here I meant plug-in or extension: a piece of code > written > by someone else that can be easily (and automaticallly) integrated > into my program. OK, To do that you need to provide an intrerface in your code that the plug-in can use. That is to say you must call a documented set of functions/methods and then arrange your code such that the plugin can replace the default code. One way to do that in Python is to use a class which dedefines a set of methods which you call. The plugin writer can then either subclass that class or just write another class with the same interface. You can then read the file name and import the file as a module and assign the moduiles class to the class reference of your interface. Remember that in Python classes are objects too. Some pseudo-code class MyInterface: def foo(self): pass def getPluginName(): # get it from a config file, a folder or whatever # or return None plugIn = getPluginName(): if plugIn: p = imp.find_module(pth) # you'll need more work here! imp.load_module(pg, p) thePlugIn = pg.getInterface() else: thePlugin = MyInterface theInterface = thePlugin() theInterface.foo() # use default or plugin The plugin file looks like: #class that implements MyInterface class PlugIn: def foo(self): print ("i'm pluggged in") def getInterface(): return PlugIn There are many more tricks etc that tyou can do to industrialize that concept but it should be a start. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Mon Mar 2 00:38:17 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 01 Mar 2009 15:38:17 -0800 Subject: [Tutor] Returning the IDLE Shell Window to Prompt In-Reply-To: References: <49AAF848.8030906@sbcglobal.net> Message-ID: <49AB1C69.3030506@sbcglobal.net> An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Mar 2 03:31:56 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 1 Mar 2009 20:31:56 -0600 Subject: [Tutor] modular program In-Reply-To: References: Message-ID: <874864728E7B4E258BA023CD0FB645E7@AWA2> You can look at a site called UtilityMill (http://utilitymill.com/) that hosts user-defined Python code, and wraps it in an API to be used interactively through an HTML form, or programmatically over HTTP. I'm pretty sure that the author makes the source code available for this site. Also, you could look at a particular utility on UtilityMill, the Trading Strategy Evaluator (http://utilitymill.com/utility/trading_strategy_evaluator). This accepts a Python function in an HTML form text input field, and then runs that function as part of a trading simulation. (Since this a utility hosted within UtilityMill, the source code is publicly viewable.) -- Paul From sierra_mtnview at sbcglobal.net Mon Mar 2 07:40:01 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 01 Mar 2009 22:40:01 -0800 Subject: [Tutor] Maintaining the Same Variable Type--Tkinter Message-ID: <49AB7F41.4060000@sbcglobal.net> An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon Mar 2 09:12:49 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 02 Mar 2009 19:12:49 +1100 Subject: [Tutor] Tutor Digest, Vol 61, Issue 3 In-Reply-To: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> References: <537341c70903011344q5a325692xa88d04928744b46d@mail.gmail.com> Message-ID: Daniele wrote: >> From: W W >> Subject: Re: [Tutor] modular program > >>> Where can I find some "best practices" for writing modular programs? >>> I thought about a txt file containing function calls that my program will >>> parse and execute in order, or is it better just to execute every .py file >>> in a certain "module" folder (I don't like this as modules could need to be >>> executed in different moments)? > >> You can pretty much take a look at any of the modules in your python >> library directory. In the case of my linux box, that's >> /usr/lib/python2.5/ > > I'm sorry, I've realized I didn't explain my needs at all. > I was a little influenced by drupal's definition of modules, which is > completely different from python's. > With module here I meant plug-in or extension: a piece of code written > by someone else that can be easily (and automaticallly) integrated > into my program. > My program must provide the posibility to be extended without editing > its code, just like mozilla's add-ons. It heavily depends on the design of the main program. The simplest way to have a plug-in system is probably having user writes python modules which your program will import and call a certain agreed function. for example mainprogram.py: um_name = raw_input('Enter usermodule's filename: ') um = __import__(um_name) um.run() usermodule.py: def run(): # do initializations required to install the module From d.conca at gmail.com Mon Mar 2 10:07:12 2009 From: d.conca at gmail.com (Daniele) Date: Mon, 2 Mar 2009 10:07:12 +0100 Subject: [Tutor] [Edited] Plug-in enabled Program Message-ID: <537341c70903020107r747bda4bvc8a0c0360ac2955b@mail.gmail.com> > ---------- Messaggio inoltrato ---------- > From:?"Alan Gauld" > To:?tutor at python.org > Subject:?Re: [Tutor] Tutor Digest, Vol 61, Issue 3 > > OK, To do that you need to provide an intrerface in your code > that the plug-in can use. That is to say you must call a documented > set of functions/methods and then arrange your code such that the > plugin can replace the default code. Thank you Alan, that's what I wanted :) I've understood the idea, and I'll investigate it. The only doubt I have is how to adapt it to multiple plugins related to the same interface. Let's say my program downloads a file from a url and saves it in a local directory. One plugin could be written to add a prefix to the file name and another one to make the filename all-caps. In this case the same interface (let's call it "ManageFileName") should be used twice (or, in general, many times), and it's not simple to decide a priori how to merge the two actions. This lets me think about decorators, is that a possibility? Each user could write it's own decorator to the "setFileName()" method and the program will use them together. As I don't know decorators in python at all, I'm not sure this could work out, but it could be a nice push to start learning :) From alan.gauld at btinternet.com Mon Mar 2 11:59:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Mar 2009 10:59:40 -0000 Subject: [Tutor] [Edited] Plug-in enabled Program References: <537341c70903020107r747bda4bvc8a0c0360ac2955b@mail.gmail.com> Message-ID: "Daniele" wrote > have is how to adapt it to multiple plugins related to the same > interface. There are a few approaches. There is a design pattern (facade from memory) that allows this but you can also implement the plugin calls as a list of objects. So instead of calling theInteface.foo() you load a list full of all the interface obujects and run for if in the InterfaceList: if.foo() That will apply each plugin in the sequence loaded. That can of course result in one plugin wiping out the changes by another... but I don;t know of any way to avoid that. HTH, Alan G. From administrador.de.red at gmail.com Mon Mar 2 23:36:18 2009 From: administrador.de.red at gmail.com (Network Administrator) Date: Mon, 2 Mar 2009 16:36:18 -0600 Subject: [Tutor] Add elements to list and display it [Very newbie question] In-Reply-To: References: Message-ID: Thanks, Eric for your help! I appreciate your explanation about the reserved word "list" as well as the code you gently wrote to me. Now, I want to show everybody what I did: #!/usr/bin/env python ##################### # This function fills any given list # mylist = [] x = 0 while (x != 't2'): x = raw_input('Enter IP: ') mylist.append(x) mylist.pop() """ # Discontinued for i in mylist: print i """ # More useful to solve my particular problem. for i, v in enumerate(mylist): print i, v It works really fine to me. Thanks! I continue learning and making. Will. On Sat, Feb 28, 2009 at 1:36 AM, Eric Dorsey wrote: > Here is one possible implementation of your project. > > *Code:* > #Dont use list as a variable name, its one of the reserved words. > mylist = [] > > #realize any values captured here are strings > x = raw_input('Enter num or text: ') > mylist.append(x) > x = raw_input('Enter num or text: ') > mylist.append(x) > > #output the type of objects you've entered (hint: they'll always be > strings.. ;) > print type(mylist[0]) > print type(mylist[1]) > > #print the list of items > for i in mylist: > print i > > *When you run the program:* > Enter num or text: 27 > Enter num or text: Eric > > > 27 > Eric > > > On Fri, Feb 27, 2009 at 10:19 AM, Network Administrator < > administrador.de.red at gmail.com> wrote: > >> I am beggining to learn Python and I appreciate if you help me with this: >> >> "I want a piece of a program to request the user to input "elements" >> (numbers, text, etc) and store them into a list. Then, I want to display all >> the elements one-per-line." >> >> I started using this code: >> >> #!/usr/bin/env python >> ##################### >> # This function fills any given list >> # and display its content. >> # >> x = 0 # Variable "x" initiallized to zero, just >> because Python required it >> while (x != 't2' ): # On user's input "t2", no more input must be >> required >> list = [] # I start a zero-elements list >> x = raw_input('Enter your number or text: ') # Software >> asks for user's input. >> >> list.append(x) >> # User's input is append to the list "list" >> >> for x in list: # It asks to enter the list and... >> print x # print their elements. >> >> Unfortunately, this code fails to do what I expect. I notice that user's >> input is not being append to the list, so, when I require to print the >> elements of the list only "t2" is displayed. I don't know how to append >> elements to a list on user's input. >> >> I appreciate your clearence. >> >> Regards, >> >> >> Will. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Mar 3 00:22:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 2 Mar 2009 18:22:07 -0500 Subject: [Tutor] Add elements to list and display it [Very newbie question] In-Reply-To: References: Message-ID: <1c2a2c590903021522h62fe0b0s14de5af519eacab6@mail.gmail.com> On Mon, Mar 2, 2009 at 5:36 PM, Network Administrator wrote: > I appreciate your explanation about the reserved word "list" as well as the > code you gently wrote to me. Now, I want to show everybody what I did: > > #!/usr/bin/env python > ##################### > # This function fills any given list > # > mylist = [] > x = 0 > while (x != 't2'): > ??? x = raw_input('Enter IP: ') > ??? mylist.append(x) > mylist.pop() A little more straightforward, perhaps: mylist = [] while True: x = raw_input('Enter IP: ') if x == 't2': break mylist.append(x) Kent From juryef at yahoo.com Tue Mar 3 02:45:36 2009 From: juryef at yahoo.com (Judith Flores) Date: Mon, 2 Mar 2009 17:45:36 -0800 (PST) Subject: [Tutor] Difference in minutes between two time stamps Message-ID: <938340.46544.qm@web34703.mail.mud.yahoo.com> Hello, I can't seem to figure out the syntax to calculate the difference in minutes between two time stamps. I already read the documentation about datetime and time modules, but I was unable to implement the code. My code will be fed with two timestamps (as styrings): start="09:35:23" end="10:23:00" Could someone guide me on how to calculate the difference in minutes between both stamps? Your help is very much appreciated. Thank you, Judith From john at fouhy.net Tue Mar 3 02:53:48 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Mar 2009 14:53:48 +1300 Subject: [Tutor] Difference in minutes between two time stamps In-Reply-To: <938340.46544.qm@web34703.mail.mud.yahoo.com> References: <938340.46544.qm@web34703.mail.mud.yahoo.com> Message-ID: <5e58f2e40903021753v5cc5ac99m687cfc4262fec2b2@mail.gmail.com> 2009/3/3 Judith Flores : > > Hello, > > ? I can't seem to figure out the syntax to calculate the difference in minutes between two time stamps. I already read the documentation about datetime and time modules, but I was unable to implement the code. > > My code will be fed with two timestamps (as styrings): > > start="09:35:23" > end="10:23:00" > > ? ?Could someone guide me on how to calculate the difference in minutes between both stamps? You want to use the datetime.datetime.strptime() function to parse the timestamps. Although you will probably need to look at the time module to get the different codes -- the documentation isn't superbly organised in this area, I feel. Anyway, as a start: >>> import datetime >>> s = '09:35:23' >>> datetime.datetime.strptime(s, '%H:%M:%S') datetime.datetime(1900, 1, 1, 9, 35, 23) Can you figure out how to proceed from there? -- John. From cfuller084 at thinkingplanet.net Tue Mar 3 00:24:48 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 2 Mar 2009 17:24:48 -0600 Subject: [Tutor] Difference in minutes between two time stamps In-Reply-To: <938340.46544.qm@web34703.mail.mud.yahoo.com> References: <938340.46544.qm@web34703.mail.mud.yahoo.com> Message-ID: <200903021724.48700.cfuller084@thinkingplanet.net> Use time.strptime() to parse them into seconds since the start of epoch, and then an ordinary numeric subtraction will work. Cheers On Monday 02 March 2009 19:45, Judith Flores wrote: > Hello, > > I can't seem to figure out the syntax to calculate the difference in > minutes between two time stamps. I already read the documentation about > datetime and time modules, but I was unable to implement the code. > > My code will be fed with two timestamps (as styrings): > > start="09:35:23" > end="10:23:00" > > Could someone guide me on how to calculate the difference in minutes > between both stamps? > > Your help is very much appreciated. > > Thank you, > > Judith > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sierra_mtnview at sbcglobal.net Tue Mar 3 04:54:56 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 02 Mar 2009 19:54:56 -0800 Subject: [Tutor] What is this [] construction? Message-ID: <49ACAA10.6060700@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Mar 3 04:56:47 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Mar 2009 16:56:47 +1300 Subject: [Tutor] What is this [] construction? In-Reply-To: <49ACAA10.6060700@sbcglobal.net> References: <49ACAA10.6060700@sbcglobal.net> Message-ID: <5e58f2e40903021956u11f64313xbe474f0fcbdd6fe4@mail.gmail.com> 2009/3/3 Wayne Watson : > What is this: d = [ int(x) for x in s.split(":") ] It's a list comprehension: http://docs.python.org/tutorial/datastructures.html#list-comprehensions -- John. From andreengels at gmail.com Tue Mar 3 08:18:56 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 3 Mar 2009 08:18:56 +0100 Subject: [Tutor] What is this [] construction? In-Reply-To: <49ACAA10.6060700@sbcglobal.net> References: <49ACAA10.6060700@sbcglobal.net> Message-ID: <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson wrote: > What is this: d = [ int(x) for x in s.split(":") ] > I see in the program I'm looking at, the [] construction can be much more > complicated, as in: > ?????? self.recent_events = [ event for event in self.recent_events > ?????????????????????????????? if os.path.exists(event) and > ?????????????????????????????? (time.time() - os.path.getmtime(event)) < > 3600.0 ] That's called list comprehension. The notation [f(x) for x in A if p(x)] means: Form a list in the following way: Start with an empty list. Then go through A, and for each x in A, if p(x) is true, add f(x) to the list. d = [f(x) for x in A if p(x)] is equivalent to: d = [] for x in A: if p(x): d.append(f(x)) Your first example had no p(x) defined, which means that it's done for all x, that is: [ int(x) for x in s.split(":") ] means: The list, formed by taking int(x) for all x in the result of s.split(":"). It is almost English, really... [f(x) for x in A if p(x)] means: f(x) for all x in A for which p(x) holds. -- Andr? Engels, andreengels at gmail.com From marc.tompkins at gmail.com Tue Mar 3 09:26:30 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 3 Mar 2009 00:26:30 -0800 Subject: [Tutor] What is this [] construction? In-Reply-To: <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> References: <49ACAA10.6060700@sbcglobal.net> <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> Message-ID: <40af687b0903030026v35e2ed7dy638a8ba99d552401@mail.gmail.com> On Mon, Mar 2, 2009 at 11:18 PM, Andre Engels wrote: > On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson > wrote: > > self.recent_events = [ event for event in self.recent_events > > if os.path.exists(event) and > > (time.time() - os.path.getmtime(event)) < > > 3600.0 ] > In this example, we'll step through self.recent_events - which apparently is a list of filenames - and call each item we come across "event". That's the "for event in self.recent_events" part. If the filename corresponds to an actual file ("if os.path.exists(event)") AND that file has been modified less than an hour ago (the difference between the current time and the file's modification time is less than 3,600 seconds), then we add "event" to the list we're building and move on to the next "event" until we're done. At the end, we call our new list self.recent_events, which replaces the list we were looping through a moment ago. Chances are it's a bit shorter now. List comprehensions will make your head hurt the first few dozen times you encounter them. After that, they become easier to use than the longer for-loop structure they replace - as Andr? pointed out, they read almost like English. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandertelford at gmail.com Tue Mar 3 11:36:52 2009 From: alexandertelford at gmail.com (Alexander Telford) Date: Tue, 3 Mar 2009 10:36:52 +0000 Subject: [Tutor] Touchscreen GUI for PyKaraoke - Job in London In-Reply-To: <634ea5210903030232j78717007t9c54a8feda969d95@mail.gmail.com> References: <634ea5210903030232j78717007t9c54a8feda969d95@mail.gmail.com> Message-ID: <634ea5210903030236n7fb20a0en4520ead7be9af776@mail.gmail.com> Hi, I am looking for someone to write a touchscreen GUI for PyKaraoke ( http://www.kibosh.org/pykaraoke/). Looking for someone based in or around London with a lot of experience of Python and Linux who willl be able to complete this project quickly. Knowledge of sound and video processing on Linux a bonus. Please contact me for further details. Thanks, Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerard.kelly at uqconnect.edu.au Tue Mar 3 10:05:21 2009 From: gerard.kelly at uqconnect.edu.au (Mr Gerard Kelly) Date: Tue, 3 Mar 2009 09:05:21 +0000 Subject: [Tutor] animation with Tkinter canvas Message-ID: <3F23748B015E23448EDE65E6411239F115223DD1A6@BL2PRD0101MB010.prod.exchangelabs.com> Hello, I am attempting to make a simple animation of a vibrating string using Tkinter canvas. I haven't been able to find much information on how to do it. I have my data of position x on the string at time t. I can plot it with Tkinter showing the string for all times at once: width=1500 height=300 root = Tk() root.title("SinWave") canvas = Canvas(width=width,height=height,bg='white') linecoords=[] for i in range(mi): for j in range(ni): linecoords.append(width*x[j]) linecoords.append(height*(1/2+U[i,j])) canvas.create_line(linecoords,fill='black') root.update() canvas.pack() mainloop() Now I know that to get animation involves a root.update() and a root.update_idletasks() somewhere but I can't figure out how to use these! Thank you for your help. -Gerard. From srilyk at gmail.com Tue Mar 3 13:02:07 2009 From: srilyk at gmail.com (W W) Date: Tue, 3 Mar 2009 06:02:07 -0600 Subject: [Tutor] animation with Tkinter canvas In-Reply-To: <3F23748B015E23448EDE65E6411239F115223DD1A6@BL2PRD0101MB010.prod.exchangelabs.com> References: <3F23748B015E23448EDE65E6411239F115223DD1A6@BL2PRD0101MB010.prod.exchangelabs.com> Message-ID: <333efb450903030402s38d43aafu615eb4ef0ce5b8aa@mail.gmail.com> On Tue, Mar 3, 2009 at 3:05 AM, Mr Gerard Kelly wrote: > Hello, I am attempting to make a simple animation of a vibrating string using Tkinter canvas. > I haven't been able to find much information on how to do it. > I have my data of position x on the string at time t. I can plot it > with > root.update() > > canvas.pack() > mainloop() > > > Now I know that to get animation involves a root.update() and a root.update_idletasks() somewhere but I can't figure out how to use these! You don't have to use root.update. If you're drawing items on a canvas you can delete them later. 34: for x in xrange(0, 10): 35: y = c.create_line(0,0, x*x, x*x) 36: time.sleep(.5) 37: c.update_idletasks() #Force redraw 38: c.delete(y) Try those 5 lines and see if it works for you. HTH, Wayne From timomlists at gmail.com Tue Mar 3 18:18:24 2009 From: timomlists at gmail.com (Timo) Date: Tue, 03 Mar 2009 18:18:24 +0100 Subject: [Tutor] Shelve: remove dictionary from list Message-ID: <49AD6660.8040007@gmail.com> Hello all, I'm using the Shelve module to store dictionaries in a list as a value of a key. So: key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] The problem is I can't remove a dictionary from the list. import shelve s = shelve.open('file') try: for index, value in enumerate(s['key']): if value['keyA'] == 1 and value['keyB'] == 2: del value[index] finally: s.close() If I do some printing in between, I can see the dictionary actually gets removed, but doesn't get saved. Any ideas why? From kent37 at tds.net Tue Mar 3 19:36:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Mar 2009 13:36:05 -0500 Subject: [Tutor] Shelve: remove dictionary from list In-Reply-To: <49AD6660.8040007@gmail.com> References: <49AD6660.8040007@gmail.com> Message-ID: <1c2a2c590903031036r67e2920fo9bd0d3d23960d1ed@mail.gmail.com> On Tue, Mar 3, 2009 at 12:18 PM, Timo wrote: > Hello all, I'm using the Shelve module to store dictionaries in a list as a > value of a key. > > So: > > key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] > > The problem is I can't remove a dictionary from the list. > > > import shelve > > s = shelve.open('file') > try: > ? for index, value in enumerate(s['key']): > ? ? ? if value['keyA'] == 1 and value['keyB'] == 2: > ? ? ? ? ? del value[index] > finally: > ? s.close() > > > If I do some printing in between, I can see the dictionary actually gets > removed, but doesn't get saved. Any ideas why? >From the shelve docs: By default, mutations to persistent-dictionary mutable entries are not automatically written back. If the optional writeback parameter is set to True, all entries accessed are cached in memory, and written back at close time; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated). In other words, by default, shelve does not know about changes you make to mutable values. You can either - open the shelve with writeback=True - explicitly store the modified value back into the shelve: key = s['key'] # modify key s['key'] = key s.close() Kent From sierra_mtnview at sbcglobal.net Tue Mar 3 20:54:13 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 11:54:13 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables Message-ID: <49AD8AE5.9040607@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Mar 3 21:22:15 2009 From: srilyk at gmail.com (W W) Date: Tue, 3 Mar 2009 14:22:15 -0600 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: <49AD8AE5.9040607@sbcglobal.net> References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: <333efb450903031222k4e44841cr8215a1cb63e44859@mail.gmail.com> On Tue, Mar 3, 2009 at 1:54 PM, Wayne Watson wrote: > > BTW, the Quit function is original but doesn't kill the window when Quit is > used. What fixes that? For more bonus points, it seems as though the try > statement in the dialog should really bring up an "Error" dialog saying > something is wrong, when an invalid entry occurs. No need to construct an > error dialog for me, but I'd be curious how it might be handled. > For the error dialog you can easily use tkMessageBox: just import tkMessageBox and then use this: In [2]: tkMessageBox.showerror('Some Error', 'An Error occurred!') Out[2]: 'ok' If you're expecting a specific error you can use try: #some statements except SpecificError: #Handle the error In this case (at least the block I looked at) it's just printing to the command line. You can handle it using any one of the message boxes or creating your own. > ??? def Quit(self): > ??????? self.running = False > ??????? self.master.quit() > You could also try self.master.destroy() when I tried: from Tkinter import * root = Tk() root.quit() in an ipython session. It didn't close my root window but the destroy method did. HTH, Wayne From timmichelsen at gmx-topmail.de Tue Mar 3 21:41:06 2009 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 03 Mar 2009 21:41:06 +0100 Subject: [Tutor] Difference in minutes between two time stamps In-Reply-To: <5e58f2e40903021753v5cc5ac99m687cfc4262fec2b2@mail.gmail.com> References: <938340.46544.qm@web34703.mail.mud.yahoo.com> <5e58f2e40903021753v5cc5ac99m687cfc4262fec2b2@mail.gmail.com> Message-ID: >>>> import datetime >>>> s = '09:35:23' >>>> datetime.datetime.strptime(s, '%H:%M:%S') > datetime.datetime(1900, 1, 1, 9, 35, 23) > > Can you figure out how to proceed from there? In case she doesn't know: import datetime as dt start="09:35:23" end="10:23:00" start_dt = dt.datetime.strptime(start, '%H:%M:%S') end_dt = dt.datetime.strptime(end, '%H:%M:%S') diff.seconds/60 From timmichelsen at gmx-topmail.de Tue Mar 3 22:10:52 2009 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 03 Mar 2009 22:10:52 +0100 Subject: [Tutor] Difference in minutes between two time stamps In-Reply-To: References: <938340.46544.qm@web34703.mail.mud.yahoo.com> <5e58f2e40903021753v5cc5ac99m687cfc4262fec2b2@mail.gmail.com> Message-ID: > >>>> import datetime >>>>> s = '09:35:23' >>>>> datetime.datetime.strptime(s, '%H:%M:%S') >> datetime.datetime(1900, 1, 1, 9, 35, 23) >> >> Can you figure out how to proceed from there? > In case she doesn't know: > > import datetime as dt > start="09:35:23" > end="10:23:00" > > start_dt = dt.datetime.strptime(start, '%H:%M:%S') > > end_dt = dt.datetime.strptime(end, '%H:%M:%S') I forgot to paste in between: diff = (end_dt - start_dt) > diff.seconds/60 From sierra_mtnview at sbcglobal.net Tue Mar 3 22:53:19 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 13:53:19 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: <333efb450903031222k4e44841cr8215a1cb63e44859@mail.gmail.com> References: <49AD8AE5.9040607@sbcglobal.net> <333efb450903031222k4e44841cr8215a1cb63e44859@mail.gmail.com> Message-ID: <49ADA6CF.6030107@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 4 00:14:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Mar 2009 23:14:07 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: "Wayne Watson" wrote > see my post of yesterday, "Maintaining the Same Variable > Type--Tkinter", > went over like a lead balloon. :-) Yeah, I had no idea what you meant :-) > I've heavily modified the original code to accept a config file, > and set up variable to initialize the widgets, trying to bridge > some code in the Enter_Data_Dialog and Set_Enter_Data > objects control variable code is where the trouble lays Yep, and part of it is the attempt to create variables dynamically. It's so much easier if you use a dictionary or a list of name,value tuples. > The code below puts up a window with one menu and two > submenus items, Enter Data, and Exit. Select Enter Data > and put in an integer number. It all works fine. It works with hard coded variable names. Trying to use dynamic variable names will be much trickier! > Basically, what I want to do is eliminate code like > dialog.anumberVar.get() and replace it by constructing the > appropriate names for the config file. If you used a list of variables you could replace it with self.varList[0][1] = dialog.myVar.get() In this case, the config file might contain: > anumber = 123 and you store that as varList.append( (varname, varValue) ) If there is only one variable at a time you could just use the tuple of course: self.myVar = (varname, varValue) Then the dialog return becomes: self.myVar[1] = dialog.myVar.get() You also need to make the dialog smart enough to read the name of the variable (myVar[0]) and set the label accordingly... If you use dynamic variables you will need to pass in the variable name and then use getattr to retrieve the value. Or pass name and value - which sounds a lot like a tuple? The problem with trying to create actual variables is that the rest of yor code must become psychic (or very complex) to figure out what variable to use. Or you write a lott of near identical code to handle every possible variable name! > BTW, the Quit function is original but doesn't kill the window > when Quit is used. What fixes that? Brute force you can use sys.exit()! But more normally you can use what you have used, so I'm not sure why its not working! > For more bonus points, it seems as though the try statement > in the dialog should really bring up an "Error" dialog saying > something is wrong, when an invalid entry occurs. You can use the standard 'showerror' or 'showwarning' dialogs for that: http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm Finally I note the use of eval() to evaluate the user input. That is bad, bad bad. And looks like there is no need since after eval'ing you then use int(). You should be able to use int() directly on the input and handle any ValueError exceptions etc to catch bad input. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Mar 4 00:15:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Mar 2009 23:15:42 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: "Wayne Watson" wrote > > BTW, the Quit function is original but doesn't kill the window when > Quit is used. Does that include running from the command console? Is this another IDLE/Tkinter issue maybe? Alan G. From alan.gauld at btinternet.com Wed Mar 4 00:21:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Mar 2009 23:21:53 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net><333efb450903031222k4e44841cr8215a1cb63e44859@mail.gmail.com> <49ADA6CF.6030107@sbcglobal.net> Message-ID: > destroy() took care of it, but I wonder what advantage there was to > Quit()? destroy destroys the widget, quit exits the main loop. destroying the top level widget usually causes the mainloop; to die too so the end result is the same (provided you have no non-modal dialogs open?). HTH, Alan G. From alan.gauld at btinternet.com Wed Mar 4 00:26:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Mar 2009 23:26:09 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Comments? > class IntVar_GUI: I just noticed the name of the class. This kind of implies that you are intending writing GUIs for each data type? That shouldn't be necessary since the inputs will be strings in each case. You only need to call the appropriate conversion function when you pull the data back from the input dialog. The exception might be if you want a different inpuit mechanism - like a drop down list or radio button. In that case the number of GUIs you write is determined by the number of input mechanisms used not the number of data types... Hopefully the mechanism list is shorter than the data type list! Just a thought. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Wed Mar 4 01:17:38 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 16:17:38 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: <49ADC8A2.4050409@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 4 01:34:19 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 16:34:19 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: <49ADCC8B.60707@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-203.jpg Type: image/jpeg Size: 15206 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed Mar 4 01:42:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 00:42:05 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> <49ADCC8B.60707@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Note though the use of control variables like IntVar, etc. FWIW. Personally I never use those "convenience" features of Tk. I prefer to explicitly set and get them myself. Alan G From sierra_mtnview at sbcglobal.net Wed Mar 4 01:42:25 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 16:42:25 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: <49ADCE71.7080706@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 4 01:46:30 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 16:46:30 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: References: <49AD8AE5.9040607@sbcglobal.net> <49ADCC8B.60707@sbcglobal.net> Message-ID: <49ADCF66.6020508@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 4 03:16:27 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 03 Mar 2009 18:16:27 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: <49ADCE71.7080706@sbcglobal.net> References: <49AD8AE5.9040607@sbcglobal.net> <49ADCE71.7080706@sbcglobal.net> Message-ID: <49ADE47B.2010309@sbcglobal.net> An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Wed Mar 4 04:01:36 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 04 Mar 2009 14:01:36 +1100 Subject: [Tutor] What is this [] construction? In-Reply-To: <40af687b0903030026v35e2ed7dy638a8ba99d552401@mail.gmail.com> References: <49ACAA10.6060700@sbcglobal.net> <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> <40af687b0903030026v35e2ed7dy638a8ba99d552401@mail.gmail.com> Message-ID: Marc Tompkins wrote: > List comprehensions will make your head hurt the first few dozen times > you encounter them. After that, they become easier to use than the > longer for-loop structure they replace - as Andr? pointed out, they read > almost like English. I have to disagree, I immediately fell in love with list comprehension when I first meet them. From marc.tompkins at gmail.com Wed Mar 4 04:18:44 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 3 Mar 2009 19:18:44 -0800 Subject: [Tutor] What is this [] construction? In-Reply-To: References: <49ACAA10.6060700@sbcglobal.net> <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> <40af687b0903030026v35e2ed7dy638a8ba99d552401@mail.gmail.com> Message-ID: <40af687b0903031918t37509cb0x7a738804ad061fd9@mail.gmail.com> On Tue, Mar 3, 2009 at 7:01 PM, Lie Ryan wrote: > Marc Tompkins wrote: > > List comprehensions will make your head hurt the first few dozen times > >> you encounter them. After that, they become easier to use than the longer >> for-loop structure they replace - as Andr? pointed out, they read almost >> like English. >> > I have to disagree, I immediately fell in love with list comprehension when > I first meet them. > OK, I over-generalized. They made MY head hurt at first. Now I love them. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From clsdaniel at gmail.com Wed Mar 4 06:08:10 2009 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 3 Mar 2009 22:08:10 -0700 Subject: [Tutor] Code documentation Message-ID: <4fae7dfa0903032108k6540a5a5g6eb24e51fff819f0@mail.gmail.com> Hello list, I have been coding in python a short while and I have been wondering which approach should I take on documentation (API docs) for a python library I have been working on, there is currently code docstrings, docstrings with some markup (epydoc, etc), or external programs such as Sphinx (reStructuredText markup). In your experience which way is the best or what advantages/disadvantages do you see (experienced) with each approach that you are familiar. Thanks! From dorseye at gmail.com Wed Mar 4 06:43:22 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Tue, 3 Mar 2009 22:43:22 -0700 Subject: [Tutor] Convert XML codes to "normal" text? Message-ID: *So here is my program, I'm pulling some information off of my Snipt feed .. * import feedparser d = feedparser.parse('http://snipt.net/dorseye/feed') x=0 for i in d['entries']: print d['entries'][x].title print d['entries'][x].summary print x+=1 *Output* Explode / Implode List >>> V = list(V) >>> V ['s', 'p', 'a', 'm', 'm', 'y'] >>> V = ''.join(V) >>> V 'spammy' >>> I know, for example, that the > code means >, but what I don't know is how to convert it in all my data to show properly? In all the feedparser examples it just smoothly has the output correct (like in one the data was whatever and it had the special characters just fine.) I didn't notice any special call on their feedparser.parse() and I can't seem to find anything in the feedparser documentation that addresses this. Has anyone run into this before? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Wed Mar 4 07:27:29 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 04 Mar 2009 17:27:29 +1100 Subject: [Tutor] Convert XML codes to "normal" text? In-Reply-To: References: Message-ID: Eric Dorsey wrote: > _So here is my program, I'm pulling some information off of my Snipt > feed .._ > I know, for example, that the > code means >, but what I don't know > is how to convert it in all my data to show properly? In all the > feedparser examples it just smoothly has the output correct Why not str.replace()? mystring = mystring.replace('>', '>') > (like in one > the data was whatever and it had the special characters > just fine.) I didn't notice any special call on their feedparser.parse() > and I can't seem to find anything in the feedparser documentation that > addresses this. Has anyone run into this before? Thanks! It's because > is not the same as >. > is HTML escape sequence for >, which means browser would substitute them to a real > instead of considering it as part of html tags. From orsenthil at gmail.com Wed Mar 4 08:01:04 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Wed, 4 Mar 2009 12:31:04 +0530 Subject: [Tutor] Convert XML codes to "normal" text? In-Reply-To: References: Message-ID: <7c42eba10903032301k70cc7f0bx89d75c5908381776@mail.gmail.com> On Wed, Mar 4, 2009 at 11:13 AM, Eric Dorsey wrote: > I know, for example, that the > code means >, but what I don't know is > how to convert it in all my data to show properly? I Feedparser returns the output in html only so except html tags and entities in the output. What you want is to Unescape HTML entities ( http://effbot.org/zone/re-sub.htm#unescape-html ) import feedparser import re, htmlentitydefs def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) d = feedparser.parse('http://snipt.net/dorseye/feed') x=0 for i in d['entries']: print unescape(d['entries'][x].title) print unescape(d['entries'][x].summary) print x+=1 HTH, Senthil From alan.gauld at btinternet.com Wed Mar 4 08:56:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 07:56:02 -0000 Subject: [Tutor] What is this [] construction? References: <49ACAA10.6060700@sbcglobal.net> <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> Message-ID: "Andre Engels" wrote >> What is this: d = [ int(x) for x in s.split(":") ] > That's called list comprehension. The notation > [f(x) for x in A if p(x)] > means: > Form a list in the following way: For Wayne's benefit... You will also find a similar construction in parens called a generator expression (like tuoles the parens aren't always necessary but usually help). That produces an iterable that you can loop over without actually creating a list per se. ie you can write: >>> foo = [1,2,3,4] >>> for n in (x for x in foo if x % 2): ... print n ... 1 3 In Python v3 list comprehensions and generator expressions have been "merged" in that putting a GE inside [] has the same effect as a LC. In practice this makes little or no difference to the programmer its just how Python handles it behind the scenes. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From alan.gauld at btinternet.com Wed Mar 4 08:58:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 07:58:33 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> <49ADCE71.7080706@sbcglobal.net> <49ADE47B.2010309@sbcglobal.net> Message-ID: "Wayne Watson" wrote > One starts it by double clicking on the py file. And just to be clear, it exits OK when you run it that way? I would expect so since that's the normal way to run a Tkinter program. IDLE is only intended to be a development tool not a runtime program. > Nope. I just tried it. It works fine from there. > >> Does that include running from the command console? Alan G. From alan.gauld at btinternet.com Wed Mar 4 09:01:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 08:01:27 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> <49ADCC8B.60707@sbcglobal.net> <49ADCF66.6020508@sbcglobal.net> Message-ID: "Wayne Watson" wrote > There's another way? Sure, just create normal Entry widgets and capture the input string and convert/assign it as you would a string captured from raw_input() in a console. No magic required. Its slightly more code but I find the auto assignment of values to variables catches me out sometimes so I prefer to keep it explicit. Alan G. From alan.gauld at btinternet.com Wed Mar 4 09:06:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 08:06:31 -0000 Subject: [Tutor] Code documentation References: <4fae7dfa0903032108k6540a5a5g6eb24e51fff819f0@mail.gmail.com> Message-ID: "Carlos Daniel Ruvalcaba Valenzuela" wrote > which approach should I take on documentation (API docs) for a > python > library I have been working on, there is currently code docstrings, docstrings are the minimum since they show up on help() > docstrings with some markup (epydoc, etc), or external programs such > as Sphinx (reStructuredText markup). Personally I never use these. I use help() in the first instance and failing that go to the html module docs. > In your experience which way is the best or what > advantages/disadvantages do you see (experienced) with each approach > that you are familiar. Fancy markup is a wasted luxury so far as I am concerned. The most important documentation is the signature of the function ie the bit that looks like: int(x[, base]) -> integer Provided the function and params have descriptive names then 90% of the time thats all I need! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Wed Mar 4 12:35:54 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 04 Mar 2009 22:35:54 +1100 Subject: [Tutor] Code documentation In-Reply-To: References: <4fae7dfa0903032108k6540a5a5g6eb24e51fff819f0@mail.gmail.com> Message-ID: Alan Gauld wrote: >> In your experience which way is the best or what >> advantages/disadvantages do you see (experienced) with each approach >> that you are familiar. > > Fancy markup is a wasted luxury so far as I am concerned. Not to mention that using non-docstring documentation breaks help(), and using fancy markups might clutter help(). From kent37 at tds.net Wed Mar 4 13:33:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Mar 2009 07:33:48 -0500 Subject: [Tutor] What is this [] construction? In-Reply-To: References: <49ACAA10.6060700@sbcglobal.net> <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> Message-ID: <1c2a2c590903040433u5dfc51a8k8e7e2bb169dac77a@mail.gmail.com> On Wed, Mar 4, 2009 at 2:56 AM, Alan Gauld wrote: > In Python v3 list comprehensions and generator expressions have been > "merged" in that putting a GE inside [] has the same effect as a LC. In > practice this makes little or no difference to the programmer its just how > Python handles it behind the scenes. ?? Python 3.0.1 (r301:69556, Feb 14 2009, 22:08:17) >>> [x*x for x in range(3)] [0, 1, 4] >>> [(x*x for x in range(3))] [ at 0x6779b8>] I think you mean this (from http://docs.python.org/3.0/whatsnew/3.0.html): Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope. Kent From kent37 at tds.net Wed Mar 4 13:41:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Mar 2009 07:41:53 -0500 Subject: [Tutor] Code documentation In-Reply-To: References: <4fae7dfa0903032108k6540a5a5g6eb24e51fff819f0@mail.gmail.com> Message-ID: <1c2a2c590903040441g276dcfe1nb036857bfc52d287@mail.gmail.com> On Wed, Mar 4, 2009 at 3:06 AM, Alan Gauld wrote: > > "Carlos Daniel Ruvalcaba Valenzuela" wrote > >> which approach should I take on documentation (API docs) for a python >> library I have been working on, there is currently code docstrings, > > docstrings are the minimum since they show up on help() > >> docstrings with some markup (epydoc, etc), or external programs such >> as Sphinx (reStructuredText markup). epydoc is good for creating a bare-bones API document. It gives a high-level view with links around the code and, optionally, to the source. Its usefulness depends a lot on how good your doc strings are. It can work with plain doc strings or you can mark them up to make a richer API document at the expense of less readable help() text. Sphinx seems to be the tool of choice for creating narrative docs for Python projects. It is probably a good choice if you want to write more than just doc strings. > Personally I never use these. I use help() in the first instance and > failing that go to the html module docs. The Python html module docs are generated with Sphinx since 2.6. Kent From sierra_mtnview at sbcglobal.net Wed Mar 4 13:55:41 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 04 Mar 2009 04:55:41 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: References: <49AD8AE5.9040607@sbcglobal.net> <49ADCE71.7080706@sbcglobal.net> <49ADE47B.2010309@sbcglobal.net> Message-ID: <49AE7A4D.5080307@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 4 14:56:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 04 Mar 2009 05:56:23 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: References: <49AD8AE5.9040607@sbcglobal.net> <49ADCC8B.60707@sbcglobal.net> <49ADCF66.6020508@sbcglobal.net> Message-ID: <49AE8887.7020200@sbcglobal.net> An HTML attachment was scrubbed... URL: From neven.gorsic at gmail.com Wed Mar 4 15:06:07 2009 From: neven.gorsic at gmail.com (=?ISO-8859-2?B?TmV2ZW4gR29yuWnm?=) Date: Wed, 4 Mar 2009 15:06:07 +0100 Subject: [Tutor] wxPython vs PyQt Message-ID: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> Hi! I am about to begin to learn GUI programming with Python. What are pros and cons for PyQT and wxPython? I read that PyQT has PyQT Designer which makes GUI programming easier. Is it owned and supported by Nokia? What about wxPython? Boa Constructor is not developed any more ... Is there any program like QT Designer? I read also that none of them are even near as good as Delphi or VB. Is it really so? Thanks, Neven -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Wed Mar 4 17:47:59 2009 From: timomlists at gmail.com (Timo) Date: Wed, 04 Mar 2009 17:47:59 +0100 Subject: [Tutor] Shelve: remove dictionary from list In-Reply-To: <1c2a2c590903031036r67e2920fo9bd0d3d23960d1ed@mail.gmail.com> References: <49AD6660.8040007@gmail.com> <1c2a2c590903031036r67e2920fo9bd0d3d23960d1ed@mail.gmail.com> Message-ID: <49AEB0BF.5090908@gmail.com> Kent Johnson schreef: > On Tue, Mar 3, 2009 at 12:18 PM, Timo wrote: > >> Hello all, I'm using the Shelve module to store dictionaries in a list as a >> value of a key. >> >> So: >> >> key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] >> >> The problem is I can't remove a dictionary from the list. >> >> >> import shelve >> >> s = shelve.open('file') >> try: >> for index, value in enumerate(s['key']): >> if value['keyA'] == 1 and value['keyB'] == 2: >> del value[index] >> finally: >> s.close() >> >> >> If I do some printing in between, I can see the dictionary actually gets >> removed, but doesn't get saved. Any ideas why? >> > > From the shelve docs: > By default, mutations to persistent-dictionary mutable entries are not > automatically written back. If the optional writeback parameter is set > to True, all entries accessed are cached in memory, and written back > at close time; this can make it handier to mutate mutable entries in > the persistent dictionary, but, if many entries are accessed, it can > consume vast amounts of memory for the cache, and it can make the > close operation very slow since all accessed entries are written back > (there is no way to determine which accessed entries are mutable, nor > which ones were actually mutated). > > In other words, by default, shelve does not know about changes you > make to mutable values. You can either > - open the shelve with writeback=True > - explicitly store the modified value back into the shelve: > key = s['key'] > # modify key > s['key'] = key > s.close() > > Kent > Sorry, I should have known this myself since I do this to append data to it. Stupid mistake. Don't know why I didn't do this when deleting data. From alan.gauld at btinternet.com Wed Mar 4 20:28:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 19:28:50 -0000 Subject: [Tutor] What is this [] construction? References: <49ACAA10.6060700@sbcglobal.net><6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> <1c2a2c590903040433u5dfc51a8k8e7e2bb169dac77a@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> In Python v3 list comprehensions and generator expressions have >> been >> "merged" in that putting a GE inside [] has the same effect as a >> LC. > > I think you mean this (from > http://docs.python.org/3.0/whatsnew/3.0.html): Yeah, that's what I was thinking about but my memory played tricks and it doesn't say exactly what I thought it said! :-) Alan G From alan.gauld at btinternet.com Wed Mar 4 20:32:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 19:32:57 -0000 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables References: <49AD8AE5.9040607@sbcglobal.net> <49ADCC8B.60707@sbcglobal.net> <49ADCF66.6020508@sbcglobal.net> <49AE8887.7020200@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I'm not sure what normal is. Do you have an example, > Is this what you have in mind > ? > =================start > from Tkinter import * > master = Tk() > e = Entry(master) > e.pack() > e.focus_set() > > def callback(): > print e.get() > > b = Button(master, text="get", width=10, command=callback) > b.pack() > > mainloop() > ========================end Yes thats exactly what I had in mind. > This begs the question as to why one would use control variables at > all? > From a light reading of the subject, it seems as though they may > help > in certain circumstances of coupling. Yes, although you can still do it by hand. > One special quality of a control variable is that it can be shared > by a > number of different widgets, and the control variable can remember > all the widgets that are currently sharing it. This is fairly rare in my experience but it would be handy. But OTOH its sufficiently complex that I might prefer to make that complexity explicit so that I remember its there! HTH, Alan G. From alan.gauld at btinternet.com Wed Mar 4 20:37:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Mar 2009 19:37:55 -0000 Subject: [Tutor] wxPython vs PyQt References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> Message-ID: "Neven Gorsic" wrote > I read also that none of them are even near as good as Delphi or VB. > Is it > really so? I had a look around various GUII building tools for wxPython but none of them were near Delphi/VB standard. I've never used pyQT or even vanilla Qt so the idea of learning yet another GUI toolkit kept me away from that. FWIW The only Gui builder I got to work even half way decently was the one in SPE. But in practice I still just hand crank them... Its really not that much harder for the small scale stuff I do. If I had a big GUI project I suspect I'd build it in Delphi and call out to Python using COM or somesuch. Alan G. From dorseye at gmail.com Wed Mar 4 20:41:45 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 4 Mar 2009 12:41:45 -0700 Subject: [Tutor] Convert XML codes to "normal" text? In-Reply-To: <7c42eba10903032301k70cc7f0bx89d75c5908381776@mail.gmail.com> References: <7c42eba10903032301k70cc7f0bx89d75c5908381776@mail.gmail.com> Message-ID: Senthil, That worked like a charm, thank you for the help! Now my Snipt's are actually legible :) On Wed, Mar 4, 2009 at 12:01 AM, Senthil Kumaran wrote: > On Wed, Mar 4, 2009 at 11:13 AM, Eric Dorsey wrote: > > I know, for example, that the > code means >, but what I don't know is > > how to convert it in all my data to show properly? I > > Feedparser returns the output in html only so except html tags and > entities in the output. > What you want is to Unescape HTML entities ( > http://effbot.org/zone/re-sub.htm#unescape-html ) > > import feedparser > import re, htmlentitydefs > > def unescape(text): > def fixup(m): > text = m.group(0) > if text[:2] == "&#": > # character reference > try: > if text[:3] == "&#x": > return unichr(int(text[3:-1], 16)) > else: > return unichr(int(text[2:-1])) > except ValueError: > pass > else: > # named entity > try: > text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) > except KeyError: > pass > return text # leave as is > return re.sub("&#?\w+;", fixup, text) > > > d = feedparser.parse('http://snipt.net/dorseye/feed') > > x=0 > for i in d['entries']: > print unescape(d['entries'][x].title) > print unescape(d['entries'][x].summary) > print > x+=1 > > > > HTH, > Senthil > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Mar 4 20:54:48 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 4 Mar 2009 11:54:48 -0800 Subject: [Tutor] What is this [] construction? In-Reply-To: References: <49ACAA10.6060700@sbcglobal.net> <6faf39c90903022318u7ae955c3h865cc1d0b2f0ce11@mail.gmail.com> Message-ID: <40af687b0903041154y3d18ca0dnbdbf15b764fa4a7d@mail.gmail.com> On Tue, Mar 3, 2009 at 11:56 PM, Alan Gauld wrote: > > In Python v3 list comprehensions and generator expressions have been > "merged" in that putting a GE inside [] has the same effect as a LC. In > practice this makes little or no difference to the programmer its just how > Python handles it behind the scenes. > In Python 3000, lists comprehend YOU! (With apologies to Yakov Smirnoff...) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Mar 4 22:40:34 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 4 Mar 2009 22:40:34 +0100 Subject: [Tutor] Convert XML codes to "normal" text? In-Reply-To: References: Message-ID: 2009/3/4 Eric Dorsey : > d = feedparser.parse('http://snipt.net/dorseye/feed') > > x=0 > for i in d['entries']: > ??? print d['entries'][x].title > ??? print d['entries'][x].summary > ??? print > ??? x+=1 > > Output > > Explode / Implode List > >>> V = list(V) > I know, for example, that the > code means >, but what I don't know is > how to convert it in all my data to show properly? In all the feedparser What you are looking for is unescape from saxutils. Example: >>> from xml.sax.saxutils import unescape >>> unescape('>') '>' Greets Sander From cfuller at thinkingplanet.net Wed Mar 4 19:16:28 2009 From: cfuller at thinkingplanet.net (Chris Fuller) Date: Wed, 4 Mar 2009 12:16:28 -0600 Subject: [Tutor] wxPython vs PyQt In-Reply-To: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> Message-ID: <200903041216.29000.cfuller@thinkingplanet.net> There is a not-free GUI builder, wxDesigner, that isn't too bad (except for costing money). http://www.roebling.de The GLADE GUI builder for Gtk is very nice, however. http://www.pygtk.org/ For windows: http://gladewin32.sourceforge.net/ Cheers From kent37 at tds.net Wed Mar 4 23:17:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Mar 2009 17:17:33 -0500 Subject: [Tutor] wxPython vs PyQt In-Reply-To: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> Message-ID: <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> On Wed, Mar 4, 2009 at 9:06 AM, Neven Gor?i? wrote: > Hi! > > I am about to begin to learn GUI programming with Python. What are pros and > cons for PyQT and wxPython? > > I read that PyQT has PyQT Designer which makes GUI programming easier. Is it > owned and supported by Nokia? > What about wxPython? Boa Constructor is not developed any more ... Is there > any program like QT Designer? I've heard good things about Dabo, never tried it myself though. http://dabodev.com/ Kent From kent37 at tds.net Thu Mar 5 00:00:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Mar 2009 18:00:36 -0500 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: <49AD8AE5.9040607@sbcglobal.net> References: <49AD8AE5.9040607@sbcglobal.net> Message-ID: <1c2a2c590903041500x35b83374p50ac82f8fd1224aa@mail.gmail.com> On Tue, Mar 3, 2009 at 2:54 PM, Wayne Watson wrote: > I see my post of yesterday, "Maintaining the Same Variable Type--Tkinter", > went over like a lead balloon. :-) > (Note though the Myth Busters TV series successfully built and flew a lead > balloon.) > > Let's see if I can really simplify what I'm after. I've pulled the > essentials out of the original larger program I'm trying to modify. 2000 > lines down to 80. I've only added a few lines of my own, and changed the > menu and dialog content. Although I've heavily modified the original code to > accept a config file, and set up variable to initialize the widgets, trying > to bridge some code in the Enter_Data_Dialog and Set_Enter_Data objects > control variable code is where the trouble lays for completing the > modifications. > > The code below puts up a window with one menu and two submenus items,? Enter > Data, and Exit. Select Enter Data and put in an integer number. It all works > fine. Basically, what I want to do is eliminate code like > dialog.anumberVar.get() and replace it by constructing the appropriate names > for the config file. In this case, the config file might contain: > ??? anumber = 123 I've stayed out of this because I don't really understand what you are trying to do. But I *think* what you are looking for is a data-driven GUI. Rather than hard-coding a bunch of variable names and types, you want to build a gui based on a description of the data. Here is a program that might give you some ideas about how to abstract your problem. I don't expect it to exactly (or even closely) do what you want but maybe it will point you in a useful direction. The heart of it is the initial classes, which abstract the creation of a gui and retrieval of a typed value, and the 'values' list in class App, which is the definition of the values to display and their types. The gui can be extended with additional entry lines simply by adding more entries to the values list. Kent from Tkinter import * # These classes encapsulate creating a gui element and retrieving a typed value from it # The constructors create the elements, the get() methods return values class TextWidget(object): def __init__(self, master, label, row): Label(master, text=label).grid(row=row, sticky=W) self.entry = Entry(master) self.entry.grid(row=row, column=1) class StringWidget(TextWidget): def get(self): return self.entry.get() class IntWidget(TextWidget): def get(self): # This will blow up if the entry is not a valid integer # Better would be to validate or constrain the input value = self.entry.get() return int(value) if value else 0 class BoolWidget(object): def __init__(self, master, label, row): self.var = IntVar() cb = Checkbutton(master, text=label, variable=self.var) cb.grid(row=row, columnspan=2, sticky=W) def get(self): return bool(self.var.get()) class App: def __init__(self, master): # List of parameter name, parameter description, widget type values = [ ('name', 'Your name:', StringWidget), ('age', 'Your age:', IntWidget), ('subscribe', 'Send emails', BoolWidget), ] # Create the widgets row = 0 self.widgets = {} for name, desc, widget in values: self.widgets[name] = widget(master, desc, row) row += 1 # Button to print values Button(master, text="Show", command=self.show).grid(row=row) def show(self): for name, widget in self.widgets.items(): print name, type(widget.get()), widget.get() root = Tk() app = App(root) root.mainloop() From alan.gauld at btinternet.com Thu Mar 5 01:56:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Mar 2009 00:56:37 -0000 Subject: [Tutor] wxPython vs PyQt References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> Message-ID: "Kent Johnson" wrote > I've heard good things about Dabo, never tried it myself though. > http://dabodev.com/ I looked at Dabo but decided not to try it since it was yet another framework. Although it's based on wxPython they have layered their own widgets on top which is what the GUI Builder uses. (PythonCard fell into the same hole) But the web pages and writeup looked good and the forum seemed to be active and not all negative. Alan G From jfabiani at yolo.com Thu Mar 5 03:10:24 2009 From: jfabiani at yolo.com (johnf) Date: Wed, 4 Mar 2009 18:10:24 -0800 Subject: [Tutor] wxPython vs PyQt In-Reply-To: References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> Message-ID: <200903041810.24685.jfabiani@yolo.com> On Wednesday 04 March 2009 04:56:37 pm Alan Gauld wrote: > "Kent Johnson" wrote > > > I've heard good things about Dabo, never tried it myself though. > > http://dabodev.com/ > > I looked at Dabo but decided not to try it since it was yet another > framework. Although it's based on wxPython they have layered their > own widgets on top which is what the GUI Builder uses. (PythonCard > fell into the same hole) Yes, it's true that Dabo has wrapped (subclassed) most of the controls. The purpose of course was to provide developer ease of use. If you are building a real business app then I doubt there is anything better in the python world. I personally have used both VB and Delphi and see Dabo on the same level. With one exception - we have a beta GUI builder. Everything that has been done in Dabo is the very same things that all developers would be required to do if they access a database and associate fields to controls. BTW there is nothing stopping a Dabo developer from directly using wx controls. Dabo prevents nothing. So Alan, I don't see my work as falling into any hole. > > But the web pages and writeup looked good and the forum seemed > to be active and not all negative. > > Alan G -- John Fabiani From sierra_mtnview at sbcglobal.net Thu Mar 5 17:00:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Mar 2009 08:00:11 -0800 Subject: [Tutor] A Simple Tkinter Control Program--Slight Problem Message-ID: <49AFF70B.4060001@sbcglobal.net> Here's what I think the author meant in discussing a control variable sample program. ======================== from Tkinter import * v=StringVar() e = Entry(master, textvariable=v) e.pack() e.focus_set() v.set("a default value") s = v.get() mainloop() The problem is that Python objects with the msg: AttributeError: 'NoneType' object has no attribute 'tk' What corrects this? The full sample program below it runs fine: ======================= from Tkinter import * master = Tk() e = Entry(master) e.pack() e.focus_set() def callback(): print e.get() b = Button(master, text="get", width=10, command=callback) b.pack() mainloop() -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From sierra_mtnview at sbcglobal.net Thu Mar 5 17:36:55 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Mar 2009 08:36:55 -0800 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: <1c2a2c590903041500x35b83374p50ac82f8fd1224aa@mail.gmail.com> References: <49AD8AE5.9040607@sbcglobal.net> <1c2a2c590903041500x35b83374p50ac82f8fd1224aa@mail.gmail.com> Message-ID: <49AFFFA7.80606@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Mar 5 18:13:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Mar 2009 12:13:57 -0500 Subject: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables In-Reply-To: <49AFFFA7.80606@sbcglobal.net> References: <49AD8AE5.9040607@sbcglobal.net> <1c2a2c590903041500x35b83374p50ac82f8fd1224aa@mail.gmail.com> <49AFFFA7.80606@sbcglobal.net> Message-ID: <1c2a2c590903050913g2be10e48ybfaa8cdd66f54d0a@mail.gmail.com> On Thu, Mar 5, 2009 at 11:36 AM, Wayne Watson wrote: > It looks like your sample code code has the right idea, but the hang up with > the original code is getting entered values back to the main program and > available globally through it. The trick in your code, I think, is to get > the data back the user entered, and set the main program's global variables > (to mimic the original program). I'm stuck with the original concept of the > main code setting self.hourly_rate to the new value to, say, 15 in the > Dialog setup that calls the Dialog GUI. That is, when the Dialog returns, > the code must set self.hourly_rate to 15. I may not like that, but that's > the way the author designed it. I do not want to rewrite lots of code > because of it. So instead of the code after the return to the from Dialog > being hard coded, I need to construct executable statements from the list > above to do the job. This is not a big change from the code I wrote. Instead of printing the values, return a dict mapping names to values: return dict((name, widget.get()) for name, widget in self.widgets.items()) Then in the caller, use setattr() to set the attributes on self: for name, value in returned_values.items(): setattr(self, name, value) Kent From alan.gauld at btinternet.com Thu Mar 5 18:39:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Mar 2009 17:39:24 -0000 Subject: [Tutor] A Simple Tkinter Control Program--Slight Problem References: <49AFF70B.4060001@sbcglobal.net> Message-ID: "Wayne Watson" wrote Here's what I think the author meant in discussing a control variable sample program. ======================== from Tkinter import * v=StringVar() e = Entry(master, textvariable=v) AG >> No master defined... you need AG >> master = Tk() e.pack() e.focus_set() v.set("a default value") s = v.get() mainloop() AG>> and this should be master.mainloop() Alan G From amit.pureenergy at gmail.com Thu Mar 5 18:18:56 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Thu, 5 Mar 2009 22:48:56 +0530 Subject: [Tutor] Designing Tools/books Message-ID: Although this may not be the most appropriate place to ask this but i couldn't figure out where else i should be asking this question.I am getting habitual of starting projects and getting results quickly thanks to python .But I get stuck in documentation because i haven't asked the design questions through and through.Although my projects work for college because they are not large scale and do not require optimum quality control so this problem only seems to come during documentation but i believe this will be a pain when i do this professionally.So my question is please guide me to good internet resources ,books and tools that talk about design especially with python in mind. Also they follow Agile Software development model or any other latest development cycle used in the industry . -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 5 21:26:47 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Mar 2009 12:26:47 -0800 Subject: [Tutor] A Simple Tkinter Control Program--Slight Problem In-Reply-To: References: <49AFF70B.4060001@sbcglobal.net> Message-ID: <49B03587.700@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 5 23:19:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Mar 2009 22:19:32 -0000 Subject: [Tutor] Designing Tools/books References: Message-ID: "amit sethi" wrote > problem only seems to come during documentation but i believe this > will be a > pain when i do this professionally.So my question is please guide me > to good > internet resources ,books and tools that talk about design > especially with > python in mind. I don't know of any that focus strictly on design with Python but the principles of design are fairly laguage agnostic. Indeed a good test of a design is whether it is easily translated into another language, if not it is probably too low level! Design breaks down to a few core principles Try searching Wkipedia for terms like: cohesion, coupling, modularity, encapsulation, interface Follow the references accompanying those pages. Some types of problem lend themselves to formal methods, particularly state machines and logic dominated domains. Some standard books that are worth reading are: Design Patterns by the "Gang of Four" OO Design and Analysis by Grady Booch OO Design by Peter Coad - this one is greatlyy under rated IMHO Many people like Agile Sioftware Development by Robert Martin but personally I didn't like it much. Also worth considering is Writing Effective Usecases by Cockburn This is one I keep going back to and finding fresh insights each time. In an Agile world high level use cases are a great way of grouping development User Stories into deliverable and effective business scenarios Finally remember that design documents are not primarily written for the developers, they should be aimed primarily at the testers, trainers, project managers, operations and support teams. They are the people who actually read and use design documents. Developers create designs and maintainers read the code... > Also they follow Agile Software development model or any > other latest development cycle used in the industry . Agile is very effective on small projects. But then again almost anything is effective in small projects! As projects get bigger Agile breaks down and becomes a hindrance on really big projects. You can use Agile at the programmer level on a big project but you will likely need a more architectural focussed approach to pull it all together. Design is largely independent of the project management style used. The amount of documentation produced and its format is almost entirely driven by the project management style. Design != Documentation So a lot will depend on the kind of organisation you intend to work for, the kind of projects they do and other such factors. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From gerard.kelly at uqconnect.edu.au Fri Mar 6 02:38:07 2009 From: gerard.kelly at uqconnect.edu.au (Mr Gerard Kelly) Date: Fri, 6 Mar 2009 01:38:07 +0000 Subject: [Tutor] array and ndarray Message-ID: <3F23748B015E23448EDE65E6411239F1152252EAF1@BL2PRD0101MB010.prod.exchangelabs.com> I am trying to convert something using the old Numeric module to the numpy module. This is the code so far:: from __future__ import division import pygame, time, random, pygame.sndarray sample_rate = 44100 from numpy import * def sine_array(hz,peak,n_samples=sample_rate): length=sample_rate/hz omega=pi*2/length xvalues=arange(length)*omega sinarray=(peak*sin(xvalues).astype(int16)) sa=resize(sinarray,sample_rate) return sa def play_for(sample_array, ms): pygame.mixer.pre_init(sample_rate, -16, 1) pygame.init() sound = pygame.sndarray.make_sound(sample_array) sound.play(-1) pygame.time.delay(ms) sound.stop() def main(): pygame.mixer.pre_init(sample_rate, -16, 1) pygame.init() play_for(sine_array(440,4096), 4000) if __name__ == '__main__': main() My error is the following: Traceback (most recent call last): File "na.py", line 30, in if __name__ == '__main__': main() File "na.py", line 28, in main play_for(sine_array(440,4096), 4000) File "na.py", line 20, in play_for sound = pygame.sndarray.make_sound(sample_array) File "/usr/lib/python2.5/site-packages/pygame/sndarray.py", line 123, in make_sound return numericsnd.make_sound (array) TypeError: argument 1 must be array, not numpy.ndarray How could I modify this to get an array instead of an ndarray? From sierra_mtnview at sbcglobal.net Fri Mar 6 04:52:51 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Mar 2009 19:52:51 -0800 Subject: [Tutor] Misunderstanding the Entry Widget Message-ID: <49B09E13.7080402@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 6 09:22:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Mar 2009 08:22:09 -0000 Subject: [Tutor] Misunderstanding the Entry Widget References: <49B09E13.7080402@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Apparently Entry does not have a callback. Thats the magic of Control Variables. They automatically get populated when the user enters data into the Entry widget. But since Entry widgets are usually part if a form and there will be several of them its more useful to wait for the whole form to be complteed and then hit a Submit button. The button handler can then read all of the Entry fields using get() So you are right that there is no callback per se except for the auto settigh of control variables, but you can't trigger an action based on that. However you can of course bind an event to the Entry box such as keypress, mouse over etc. and the event can trigger an action, so in your example you could bind a carriage return keystroke to some action. See the event handling topic in my tutorial for an example of binding a specific key to an event. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Fri Mar 6 12:31:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 06:31:50 -0500 Subject: [Tutor] array and ndarray In-Reply-To: <3F23748B015E23448EDE65E6411239F1152252EAF1@BL2PRD0101MB010.prod.exchangelabs.com> References: <3F23748B015E23448EDE65E6411239F1152252EAF1@BL2PRD0101MB010.prod.exchangelabs.com> Message-ID: <1c2a2c590903060331pcb3962et54f814217fd9c113@mail.gmail.com> On Thu, Mar 5, 2009 at 8:38 PM, Mr Gerard Kelly wrote: > I am trying to convert something using the old Numeric module to the numpy module. > > This is the code so far:: > > from __future__ import division > > import pygame, time, random, pygame.sndarray > sample_rate = 44100 > > from numpy import * > > def sine_array(hz,peak,n_samples=sample_rate): > ?length=sample_rate/hz > ?omega=pi*2/length > ?xvalues=arange(length)*omega > ?sinarray=(peak*sin(xvalues).astype(int16)) > ?sa=resize(sinarray,sample_rate) > ?return sa > > def play_for(sample_array, ms): > ?pygame.mixer.pre_init(sample_rate, -16, 1) > ?pygame.init() > ?sound = pygame.sndarray.make_sound(sample_array) > ?sound.play(-1) > ?pygame.time.delay(ms) > ?sound.stop() > > def main(): > ?pygame.mixer.pre_init(sample_rate, -16, 1) > ?pygame.init() > ?play_for(sine_array(440,4096), 4000) > > if __name__ == '__main__': main() > > My error is the following: > > Traceback (most recent call last): > ?File "/usr/lib/python2.5/site-packages/pygame/sndarray.py", line 123, in make_sound > ? ?return numericsnd.make_sound (array) > TypeError: argument 1 must be array, not numpy.ndarray > > > How could I modify this to get an array instead of an ndarray? Do you still have Numeric installed and available? The docs for pygame.sndarray say, "Supported array systems are numeric numpy The default will be Numeric, if installed. Otherwise, numpy will be set as default if installed. If neither Numeric nor numpy are installed, the module will raise an ImportError. The array type to use can be changed at runtime using the use_arraytype() method, which requires one of the above types as string. " Judging from this, and the error coming from *numeric*snd.make_sound(), I think pygame is finding Numeric and expecting its arguments to be Numeric arrays. Try adding a call to pygame.sndarray.use_arraytype('numpy') before any other pygame calls. Kent From kent37 at tds.net Fri Mar 6 12:36:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 06:36:35 -0500 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: <49B09E13.7080402@sbcglobal.net> References: <49B09E13.7080402@sbcglobal.net> Message-ID: <1c2a2c590903060336k3d2aff46o7431b83867ee7dc3@mail.gmail.com> On Thu, Mar 5, 2009 at 10:52 PM, Wayne Watson wrote: > Apparently Entry does not have a callback. It seems as though it should. If > one enters data into it and presses Return, then it would be good to know > what the data is, so it can be used elsewhere. However, that's not the way > it works. One seems to need a button or some other widget to make it > happen*. So what's the game with it? You can bind a event to an Entry widget. Here is a simple example: from Tkinter import * def showText(evt): print 'Text is:', text.get('0.0', END) return 'break' # Prevent the event from propagating to the Text widget root = Tk() text = Text() # This line binds the showText handler to the key event text.bind('', showText) text.pack() root.mainloop() Kent From sierra_mtnview at sbcglobal.net Fri Mar 6 13:15:12 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 06 Mar 2009 04:15:12 -0800 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: References: <49B09E13.7080402@sbcglobal.net> Message-ID: <49B113D0.60005@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Mar 6 14:00:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 08:00:34 -0500 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: <49B113D0.60005@sbcglobal.net> References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net> Message-ID: <1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> On Fri, Mar 6, 2009 at 7:15 AM, Wayne Watson wrote: > Control variables. What is the difference between IntVar,? BooleanVar, > StringVar,? and DoubleVar? The difference is the type of value returned by get(). > For example, in the program below, it looks like > I get the same result usint IntVar or StringVar. It almost appears the usage > depends on what widget one uses: Entry, RadioButton, CheckBox, ... > > ===================begin========= > from Tkinter import * > # Use of control variables > > def mycallback(): > ??? print "User entered:" , e.get() > ??? print "Operationg by 2 gives: ", e.get()*2 Change the above to use v.get(). e.get() has nothing to do with the var. > master = Tk() > > v=StringVar() > #v=IntVar() > print v,type(v) Try this: print v, type(v), type(v.get()) Kent From norman at khine.net Fri Mar 6 13:56:03 2009 From: norman at khine.net (ski) Date: Fri, 06 Mar 2009 13:56:03 +0100 Subject: [Tutor] using re groups Message-ID: <49B11D63.2040607@khine.net> Hello, I have this: >>> import re >>> s = "Association of British Travel Agents (ABTA) No. 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive Travel & Meet. Association (ITMA)" >>> licenses = re.split("\n+", s) >>> licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') >>> for license in licenses: ... m = licenseRe.search(license) ... print m.group(1, 3) ... ('ABTA', '56542') ('ATOL', None) ('IATA', None) ('ITMA', None) What is the best way to also extract the affiliation name i.e: 'Association of British Travel Agents', 'Air Travel Organisation Licence' etc.. Thanks Norman From kent37 at tds.net Fri Mar 6 15:10:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 09:10:18 -0500 Subject: [Tutor] using re groups In-Reply-To: <49B11D63.2040607@khine.net> References: <49B11D63.2040607@khine.net> Message-ID: <1c2a2c590903060610u3dbb9c57o441b6261f36e58b@mail.gmail.com> On Fri, Mar 6, 2009 at 7:56 AM, ski wrote: > Hello, > I have this: > >>>> import re >>>> s = "Association of British Travel Agents (ABTA) No. 56542\nAir Travel >>>> Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive >>>> Travel & Meet. Association (ITMA)" >>>> licenses = re.split("\n+", s) >>>> licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') >>>> for license in licenses: > ... ? ? m = licenseRe.search(license) > ... ? ? print m.group(1, 3) > ... > ('ABTA', '56542') > ('ATOL', None) > ('IATA', None) > ('ITMA', None) > > What is the best way to also extract the affiliation name i.e: > > 'Association of British Travel Agents', > 'Air Travel Organisation Licence' I would add another group to the beginning of the re that matches everything before the first (, e.g. r'([^(]+)\(([A-Z]+)\)( No. (\d+))?' Kent From zstumgoren at gmail.com Fri Mar 6 17:08:48 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 6 Mar 2009 11:08:48 -0500 Subject: [Tutor] does id function return location of reference or the referenced object? Message-ID: Hi all, I've managed to think myself in circles and was hoping someone could help clarify the nature of the "id" function and references in general. I initially got confused while dealing with file objects, so I'll stick with that example. My question, based on the below tests in the ipython interpreter, is whether the id function is returning the location of the file object or the reference to that object (in this case, "f"). My hunch is that it's the memory location of the file object, but then I started thinking that everything in python is an object, so shouldn't there be a memory location for the variable name "f" as well? And are the below memory locations for that reference rather than the object itself? The examples below suggest (to me) that the memory address is for the file object itself. But I'm not familiar enough with python's internals to know if I'm misinterpreting the results and generally muddling the concepts. Any advice is greatly appreciated. Regards, Serdar <<>> In [26] f = open('class_test.py') In [27]: f Out[27]: In [28]: id(f) Out[28]: 139090712 In [29]: type(f) Out[29]: In [30]: 0x84a5b18 Out[30]: 139090712 <<>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 6 17:26:31 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 06 Mar 2009 08:26:31 -0800 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: <1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net> <1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> Message-ID: <49B14EB7.4050504@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Mar 6 17:36:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 11:36:24 -0500 Subject: [Tutor] does id function return location of reference or the referenced object? In-Reply-To: References: Message-ID: <1c2a2c590903060836x70de5baeq7d2709cdb9d0c235@mail.gmail.com> On Fri, Mar 6, 2009 at 11:08 AM, Serdar Tumgoren wrote: > Hi all, > > I've managed to think myself in circles and was hoping someone could help > clarify the nature of the "id" function and references in general. > > I initially got confused while dealing with file objects, so I'll stick with > that example.? My question, based on the below tests in the ipython > interpreter, is whether the id function is returning the location of the > file object or the reference to that object (in this case, "f"). My hunch is > that it's the memory location of the file object, but then I started > thinking that everything in python is an object, so shouldn't there be a > memory location for the variable name "f" as well? And are the below memory > locations for that reference rather than the object itself? In CPython, at least, the id is the memory location of the object. Variables are generally stored as dictionary entries. The string 'f' does have an address, but that is not what id(f) refers to. Python doesn't make any guarantees about this, it is an implementation detail. The docs for id() say, Return the ``identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.) Kent From zstumgoren at gmail.com Fri Mar 6 18:09:03 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 6 Mar 2009 12:09:03 -0500 Subject: [Tutor] does id function return location of reference or the referenced object? In-Reply-To: <1c2a2c590903060836x70de5baeq7d2709cdb9d0c235@mail.gmail.com> References: <1c2a2c590903060836x70de5baeq7d2709cdb9d0c235@mail.gmail.com> Message-ID: So can I ask what happens internally in python when you create open a file object in a loop without assigning that file object to a variable? E.g.: for line in open(file.py): print line In the above, is pythonimplicitly creating a reference to a file object and using that in the for loop? Or is something else going on under the hood? Either way, I figured that if you don't assign the file object to a variable, then the file object is trashed by python's garbage collection once the loop reaches end-of-file. Is the above a correct understanding? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Mar 6 18:18:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 12:18:31 -0500 Subject: [Tutor] does id function return location of reference or the referenced object? In-Reply-To: References: <1c2a2c590903060836x70de5baeq7d2709cdb9d0c235@mail.gmail.com> Message-ID: <1c2a2c590903060918m254d8393t7d791ce40a479608@mail.gmail.com> On Fri, Mar 6, 2009 at 12:09 PM, Serdar Tumgoren wrote: > So can I ask what happens internally in python when you create open a file > object in a loop without assigning that file object to a variable? > > E.g.: > > for line in open(file.py): > ?? print line > > In the above, is pythonimplicitly creating a reference to a file object and > using that in the for loop? Yes, a reference to a file object is stored in a temporary variable. > Or is something else going on under the hood? > Either way, I figured that if you don't assign the file object to a > variable, then the file object is trashed by python's garbage collection > once the loop reaches end-of-file. The file is closed when the temporary goes out of scope, not when the loop exits. This is probably at the end of the function that includes the loop. This is true in CPython anyway. There is no guarantee in the language of when an object is garbage collected and other implementations have different policies. Kent From kent37 at tds.net Fri Mar 6 18:53:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 12:53:07 -0500 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: <49B14EB7.4050504@sbcglobal.net> References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net> <1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> Message-ID: <1c2a2c590903060953i5a439f14o13c83c4028d85ffa@mail.gmail.com> On Fri, Mar 6, 2009 at 11:26 AM, Wayne Watson wrote: > I've just got to stop using one letter for variables, especially ones that > sound alike! :-) > > Other than v tracking every value change made, did I gain anything by using > it? It seems to me that control variables are of marginal use. I might have > thought they were necessary for use with scale widgets, but I'm looking at > an example that says otherwise. Can you easily construct a simple example > where they are absolutely necessary, or at least provide a situation where > they are necessary? You need a variable to get the state of a Checkbutton. Variables would be helpful if you had multiple controls displaying the same value. They might give a useful decoupling between the GUI and other clients of the data; they are a mini-model, in the Model-View-Controller sense. Kent From mustafa.cmpe at gmail.com Fri Mar 6 19:31:37 2009 From: mustafa.cmpe at gmail.com (mustafa akkoc) Date: Fri, 6 Mar 2009 20:31:37 +0200 Subject: [Tutor] print problem python Message-ID: <401fd82b0903061031k135d5401ncac370bb47f4af3c@mail.gmail.com> i start learning pyton language i want to print some thing but when i type : print "hello world" but it give an error like this SyntaxError: invalid syntax (, line 1) i am using python shell version 3.0.1 -- Mustafa Akkoc -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Fri Mar 6 19:39:49 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Fri, 06 Mar 2009 13:39:49 -0500 Subject: [Tutor] print problem python In-Reply-To: <401fd82b0903061031k135d5401ncac370bb47f4af3c@mail.gmail.com> References: <401fd82b0903061031k135d5401ncac370bb47f4af3c@mail.gmail.com> Message-ID: <49B16DF5.1020100@canterburyschool.org> In Python 3, you need to put ( ) around what you want to print, so it would be: >>> print("hello world") Cheers, Vern mustafa akkoc wrote: > i start learning pyton language i want to print some thing but when i > type : print "hello world" but it give an error like this > SyntaxError: invalid syntax (, line 1) > > i am using python shell version 3.0.1 > > -- > Mustafa Akkoc > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From sarah.l.harris at jpl.nasa.gov Sat Mar 7 01:05:01 2009 From: sarah.l.harris at jpl.nasa.gov (Harris, Sarah L) Date: Fri, 6 Mar 2009 16:05:01 -0800 Subject: [Tutor] image processing Message-ID: Could someone please let me know where I can find 'lots' of examples of image processing using python? Particularly MODIS and ASTER examples. Any feedback will be greatly appreciated. Regards Sarah -------------- next part -------------- An HTML attachment was scrubbed... URL: From sarah.l.harris at jpl.nasa.gov Sat Mar 7 01:03:22 2009 From: sarah.l.harris at jpl.nasa.gov (Harris, Sarah L) Date: Fri, 6 Mar 2009 16:03:22 -0800 Subject: [Tutor] memory error Message-ID: Hello, I am very much a beginner at programming. As a learning tool I am trying to extract multiple zipped files. I got it to work after looking at lots of other examples (see below for code) but because some of my files are quite large I end up with a 'Memory Error'. Is there a simple way to fix this? import zipfile, glob, os os.chdir('E:\\test1') from os.path import isfile fname=filter(isfile, glob.glob('*.zip')) for fname in fname: zipnames=filter(isfile, glob.glob('*.zip')) for zipname in zipnames: zf=zipfile.ZipFile(zipname, 'r') for zfilename in zf.namelist(): newFile=open(zfilename, 'wb') newFile.write(zf.read(zfilename)) newFile.close() zf.close() print 'done' Regards Sarah -------------- next part -------------- An HTML attachment was scrubbed... URL: From moron.oxy at gmail.com Sat Mar 7 02:16:00 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Sat, 7 Mar 2009 12:16:00 +1100 Subject: [Tutor] memory error In-Reply-To: References: Message-ID: <2096a7260903061716u629cf351ua19aa20a9023c0b8@mail.gmail.com> Hello, On Sat, Mar 7, 2009 at 11:03 AM, Harris, Sarah L wrote: > import zipfile, glob, os > os.chdir('E:\\test1') > from os.path import isfile > fname=filter(isfile, glob.glob('*.zip')) > for fname in fname: > ??? zipnames=filter(isfile, glob.glob('*.zip')) > ??? for zipname in zipnames: > ??????? zf=zipfile.ZipFile(zipname, 'r') > ??????? for zfilename in zf.namelist(): > ??????????? newFile=open(zfilename, 'wb') > ??????????? newFile.write(zf.read(zfilename)) > ??????????? newFile.close() > ??? zf.close() I assume this zf,close() call is indented one more level, so it's inline with the zf= zipfile.ZipFile(...) As for the memory error, zf.read(zfilename) returns the entire set of bytes based on the documentation of the archive member. There's this call: http://docs.python.org/library/zipfile.html#zipfile.ZipFile.open which returns a file-like object (http://docs.python.org/library/stdtypes.html#file-objects), in particular you can use read(num_bytes) on the returned file like object till you encounter EOF so you can do step-by-step reads (and writes) instead of reading the entire file into memory. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From emadnawfal at gmail.com Sat Mar 7 03:52:51 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 6 Mar 2009 21:52:51 -0500 Subject: [Tutor] glob in order of the file numbers Message-ID: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> Hi Tutors, suppose I have four files in the current directory: 1.temp, 2.temp, 3.temp, and 4.temp. I want to use glob, or anything else, to print the contents of the files in their respective orders, where the content of 1.temp gets printed, then 2.temp, then 3.temp, then 4.temp. I write the following, but it does not get me what I want: import glob for path in glob.iglob("*.temp"): infile = open(path) for line in infile: print line.strip() # This prints emad at emad-laptop:~/Desktop/TEMP$ python globbing.py This is four This is one This is two This is three Could somebody please tell me how to get the output in the right order? -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill at celestial.net Sat Mar 7 04:11:46 2009 From: bill at celestial.net (Bill Campbell) Date: Fri, 6 Mar 2009 19:11:46 -0800 Subject: [Tutor] glob in order of the file numbers In-Reply-To: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> References: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> Message-ID: <20090307031146.GA21676@ayn.mi.celestial.com> On Fri, Mar 06, 2009, Emad Nawfal (???? ????) wrote: > > Hi Tutors, > suppose I have four files in the current directory: 1.temp, 2.temp, > 3.temp, and 4.temp. I want to use glob, or anything else, to print the > contents of the files in their respective orders, where the content of > 1.temp gets printed, then 2.temp, then 3.temp, then 4.temp. > I write the following, but it does not get me what I want: > import glob > for path in glob.iglob("*.temp"): > infile = open(path) > for line in infile: > print line.strip() > # This prints > emad at emad-laptop:~/Desktop/TEMP$ python globbing.py > This is four > This is one > This is two > This is three > Could somebody please tell me how to get the output in the right > order? files = glob.glob('*.temp') files.sort() for file in files: ... Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 The pinnacle of open systems is: when moving from vendor to vendor, the design flaws stay the same. From orsenthil at gmail.com Sat Mar 7 04:15:54 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Sat, 7 Mar 2009 08:45:54 +0530 Subject: [Tutor] glob in order of the file numbers In-Reply-To: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> References: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> Message-ID: <7c42eba10903061915l42cfa40fl1c3caf44fb55717d@mail.gmail.com> 2009/3/7 Emad Nawfal (???? ????) : > import glob > for path in glob.iglob("*.temp"): > ??? infile = open(path) > ??? for line in infile: > ??? ??? print line.strip() import glob files = sorted(glob.glob("*.temp")) for each in files: print open(each).read() Note couple of things: - glob.glob - sorted to arranged in order. - just read() the fhandle to read the contents. -- Senthil From kent37 at tds.net Sat Mar 7 05:31:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 23:31:03 -0500 Subject: [Tutor] image processing In-Reply-To: References: Message-ID: <1c2a2c590903062031q4221b83dkd7032927baf6a6bf@mail.gmail.com> On Fri, Mar 6, 2009 at 7:05 PM, Harris, Sarah L wrote: > Could someone please let me know where I can find 'lots' of examples of > image processing using python? Particularly MODIS and ASTER examples. > Any feedback will be greatly appreciated. There is one complete example here: http://pyevolve.sourceforge.net/wordpress/?p=86 It might help if you gave us more information - what are MODIS and ASTER? What kind of image processing are you interested in? Do you know about PIL (Python Imaging Library)? It provides some basic image processing. Kent From kent37 at tds.net Sat Mar 7 05:34:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Mar 2009 23:34:13 -0500 Subject: [Tutor] glob in order of the file numbers In-Reply-To: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> References: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> Message-ID: <1c2a2c590903062034u3f48d1a0h536574252b38ba42@mail.gmail.com> On Fri, Mar 6, 2009 at 9:52 PM, Emad Nawfal (???? ????) wrote: > Hi Tutors, > suppose I have four files in the current directory: 1.temp, 2.temp, 3.temp, > and 4.temp. I want to use glob, or anything else, to print the contents of > the files in their respective orders, where the content of 1.temp gets > printed, then 2.temp, then 3.temp, then 4.temp. > I write the following, but it does not get me what I want: > > import glob > for path in glob.iglob("*.temp"): > ??? infile = open(path) > ??? for line in infile: > ??? ??? print line.strip() Since you know the file names, just build the names directly: for i in range(1, 5): path = '%s.temp' % i print open(path).read() Kent From alan.gauld at btinternet.com Sat Mar 7 10:04:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Mar 2009 09:04:36 -0000 Subject: [Tutor] Misunderstanding the Entry Widget References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> Message-ID: "Wayne Watson" wrote > > Can you easily construct a simple example where they are > absolutely necessary, or at least provide a situation where > they are necessary? I don't think you can. They are a convenience feature not a necessity. But the same can be said of standard dialogs, message boxes etc. You could build all of those from basic widgets but it woulfd be a pain. Sometimes Control variables save you some pain. Personally I don't bother with them much but others like them. Alan G From alan.gauld at btinternet.com Sat Mar 7 10:11:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Mar 2009 09:11:32 -0000 Subject: [Tutor] print problem python References: <401fd82b0903061031k135d5401ncac370bb47f4af3c@mail.gmail.com> Message-ID: "mustafa akkoc" wrote >i start learning pyton language i want to print some thing but when i >type : > print "hello world" but it give an error like this SyntaxError: > invalid > syntax (, line 1) > i am using python shell version 3.0.1 If you are new to programming as well as Pyton I recommend you get Python 2.6 rather than Python 3. Python 3 has a lot of changes and most of the beginners material hasn't caught up yet. It will be easier to get answers to your questions if you stick with v2.6 and then when comfortable with that move to v3 aand learn about the differences. Sometimes newest isn't the best. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emadnawfal at gmail.com Sat Mar 7 13:36:23 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 7 Mar 2009 07:36:23 -0500 Subject: [Tutor] glob in order of the file numbers In-Reply-To: <1c2a2c590903062034u3f48d1a0h536574252b38ba42@mail.gmail.com> References: <652641e90903061852yb4a7e7cwde8ea967a9ab5543@mail.gmail.com> <1c2a2c590903062034u3f48d1a0h536574252b38ba42@mail.gmail.com> Message-ID: <652641e90903070436m424de3bn4bf31c61ec1b4ae8@mail.gmail.com> On Fri, Mar 6, 2009 at 11:34 PM, Kent Johnson wrote: > On Fri, Mar 6, 2009 at 9:52 PM, Emad Nawfal (???? ????) > wrote: > > Hi Tutors, > > suppose I have four files in the current directory: 1.temp, 2.temp, > 3.temp, > > and 4.temp. I want to use glob, or anything else, to print the contents > of > > the files in their respective orders, where the content of 1.temp gets > > printed, then 2.temp, then 3.temp, then 4.temp. > > I write the following, but it does not get me what I want: > > > > import glob > > for path in glob.iglob("*.temp"): > > infile = open(path) > > for line in infile: > > print line.strip() > > Since you know the file names, just build the names directly: > > for i in range(1, 5): > path = '%s.temp' % i > print open(path).read() > > Kent > Thank you all for the solutions. I had figured out Kent's solution before, so thank you for letting me know that I did it right. So, glob just creates a list of the file names. Thank you all again. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Mar 7 13:51:15 2009 From: srilyk at gmail.com (W W) Date: Sat, 7 Mar 2009 06:51:15 -0600 Subject: [Tutor] print problem python In-Reply-To: References: <401fd82b0903061031k135d5401ncac370bb47f4af3c@mail.gmail.com> Message-ID: <333efb450903070451q7c03b4ew1f87f40b26bc9b36@mail.gmail.com> On Sat, Mar 7, 2009 at 3:11 AM, Alan Gauld wrote: > Python 3 has a lot of > changes and most of the beginners material hasn't caught > up yet. It will be easier to get answers to your questions if > you stick with v2.6 and then when comfortable with that move > to v3 aand learn about the differences. As far as I know, Snake Wrangling For Kids has been updated... that's the only one I know about. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi From kent37 at tds.net Sat Mar 7 14:38:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Mar 2009 08:38:37 -0500 Subject: [Tutor] print problem python In-Reply-To: <333efb450903070451q7c03b4ew1f87f40b26bc9b36@mail.gmail.com> References: <401fd82b0903061031k135d5401ncac370bb47f4af3c@mail.gmail.com> <333efb450903070451q7c03b4ew1f87f40b26bc9b36@mail.gmail.com> Message-ID: <1c2a2c590903070538g23b006c6g48ee7eca3bfcf40@mail.gmail.com> On Sat, Mar 7, 2009 at 7:51 AM, W W wrote: > On Sat, Mar 7, 2009 at 3:11 AM, Alan Gauld wrote: >> Python 3 has a lot of >> changes and most of the beginners material hasn't caught >> up yet. It will be easier to get answers to your questions if >> you stick with v2.6 and then when comfortable with that move >> to v3 aand learn about the differences. > > As far as I know, Snake Wrangling For Kids has been updated... that's > the only one I know about. I didn't know about that one! There is a list of Python 3.0 learning resources here: http://wiki.python.org/moin/Python3.0Tutorials Kent From andrefsp at gmail.com Sat Mar 7 16:35:05 2009 From: andrefsp at gmail.com (=?ISO-8859-1?Q?andr=E9_palma?=) Date: Sat, 07 Mar 2009 15:35:05 +0000 Subject: [Tutor] Pyusb: get data via USB sent from mouse Message-ID: <49B29429.6080806@gmail.com> Hi folks, I'm new on pyusb programming and to learn how to get data i'm trying to get data sent from my mouse. I've download a program called usbview( http://www.kroah.com/linux/usb/ ) to display the device descriptors of any USB device pluged to my computer. I made a peace of code that was supposed to get the data sent from my mouse but when i try to run it there is an error saying that the device is busy =S Code: ======================================================================================= import sys import usb import time import struct import array import math class DeviceDescriptor(object) : def __init__(self, vendor_id, product_id, interface_id) : self.vendor_id = vendor_id self.product_id = product_id self.interface_id = interface_id def getDevice(self) : busses = usb.busses() for bus in busses: for device in bus.devices : if device.idVendor == self.vendor_id : if device.idProduct == self.product_id : return device return None class PlugUSBDevice(object) : PLUG_VENDOR_ID = 0x1c4f # mouse vendor id PLUG_PRODUCT_ID = 0x0003 # mouse product id PLUG_INTERFACE_ID = 0 # mouse interface number PLUG_INTERRUPT_IN_EP = 0x81L # mouse end point address def __init__(self) : self.device_descriptor = DeviceDescriptor(PlugUSBDevice.PLUG_VENDOR_ID, PlugUSBDevice.PLUG_PRODUCT_ID, PlugUSBDevice.PLUG_INTERFACE_ID) self.device = self.device_descriptor.getDevice() self.handle = None def open(self) : self.device = self.device_descriptor.getDevice() self.handle = self.device.open() self.handle.claimInterface(self.device_descriptor.interface_id) def close(self) : self.handle.releaseInterface() def getDataPacket(self, bytesToGet) : return self.handle.interruptRead(PlugUSBDevice.PLUG_INTERRUPT_IN_EP, bytesToGet, 15) if __name__ == "__main__": device = PlugUSBDevice() device.open() print device.getDataPacket(4) The error: ************************************************************ File "readusb.py", line 61, in device.open() File "readusb.py", line 50, in open self.handle.claimInterface(self.device_descriptor.interface_id) usb.USBError: could not claim interface 0: Device or resource busy ************************************************************ ================================================================================================== What am i doing wrong? =S From sphennings at gmail.com Sat Mar 7 20:09:35 2009 From: sphennings at gmail.com (sphennings W.) Date: Sat, 7 Mar 2009 14:09:35 -0500 Subject: [Tutor] could someone explain why this happens to me. Message-ID: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> When I enter the following code into IDLE do both lists have the same value? How would I manipulate both lists separately? >>> List1=[1,2,3] >>> List2=List1 >>> List2.reverse() >>> print(List2) [3, 2, 1] >>> print(List1) [3, 2, 1] >>> List2.append(0) >>> print(List2) [3, 2, 1, 0] >>> print(List1) [3, 2, 1, 0] From emadnawfal at gmail.com Sat Mar 7 20:28:35 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 7 Mar 2009 14:28:35 -0500 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> Message-ID: <652641e90903071128v72626feaj24442634a41e433c@mail.gmail.com> On Sat, Mar 7, 2009 at 2:09 PM, sphennings W. wrote: > When I enter the following code into IDLE do both lists have the same > value? > How would I manipulate both lists separately? > > >>> List1=[1,2,3] > >>> List2=List1 > >>> List2.reverse() > >>> print(List2) > [3, 2, 1] > >>> print(List1) > [3, 2, 1] > >>> List2.append(0) > >>> print(List2) > [3, 2, 1, 0] > >>> print(List1) > [3, 2, 1, 0] > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > When you assign list2 to list1, you are just referencing the old list. Whatever you do either one, it will affect the other as well. The solution, to my limited knowledge, is to deep-copy the list, as illustrated here: >>> l1 = [1,2,3] >>> import copy >>> l2 = copy.deepcopy(l1) >>> l2 [1, 2, 3] >>> l1.reverse() >>> l1 [3, 2, 1] >>> l2 [1, 2, 3] >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Mar 7 20:32:16 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 07 Mar 2009 11:32:16 -0800 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> Message-ID: sphennings W. wrote: > When I enter the following code into IDLE do both lists have the same value? They way you've done it, both names List1 and List2 refer/point to the same list. Changes to one affect both. > How would I manipulate both lists separately? Assign them separately or use a copy form of assignment, eg List2 = List1[:] Note however that this form of copy doesn't copy nested structures and you'll have similar issues in that case. Look into deepcopy. Emile > >>>> List1=[1,2,3] >>>> List2=List1 >>>> List2.reverse() >>>> print(List2) > [3, 2, 1] >>>> print(List1) > [3, 2, 1] >>>> List2.append(0) >>>> print(List2) > [3, 2, 1, 0] >>>> print(List1) > [3, 2, 1, 0] > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From duakapil at gmail.com Sat Mar 7 20:36:38 2009 From: duakapil at gmail.com (Kapsicum) Date: Sun, 8 Mar 2009 01:06:38 +0530 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: <4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com> References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> <4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com> Message-ID: <4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> On Sun, Mar 8, 2009 at 12:39 AM, sphennings W. wrote: > When I enter the following code into IDLE do both lists have the same > value? > How would I manipulate both lists separately? > > >>> List1=[1,2,3] > >>> List2=List1 > >>> List2.reverse() > >>> print(List2) > [3, 2, 1] > >>> print(List1) > [3, 2, 1] > >>> List2.append(0) > >>> print(List2) > [3, 2, 1, 0] > >>> print(List1) > [3, 2, 1, 0] When you create an object and assign it to a variable, the variable only refers to the object and does not represent the object itself. If you want to make a copy of a list or such kinds of sequences , then you have to use the slicing operation to make a copy. If you just assign the variable name to another name, both of them will refer to the same object. List2=List1[ : ] Kapil Dua Mobile: +919711311052 -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Mar 7 20:47:40 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 7 Mar 2009 14:47:40 -0500 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: <4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> <4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com> <4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> Message-ID: <652641e90903071147q636445afw7c67ead81a5c5bce@mail.gmail.com> On Sat, Mar 7, 2009 at 2:36 PM, Kapsicum wrote: > > > On Sun, Mar 8, 2009 at 12:39 AM, sphennings W. wrote: > >> When I enter the following code into IDLE do both lists have the same >> value? >> How would I manipulate both lists separately? >> >> >>> List1=[1,2,3] >> >>> List2=List1 >> >>> List2.reverse() >> >>> print(List2) >> [3, 2, 1] >> >>> print(List1) >> [3, 2, 1] >> >>> List2.append(0) >> >>> print(List2) >> [3, 2, 1, 0] >> >>> print(List1) >> [3, 2, 1, 0] > > > When you create an object and assign it to a variable, the variable only > refers to the object > and does not represent the object itself. > > > If you want to make a copy of a list or such kinds of sequences , then you > have to use > the slicing operation to make a copy. If you just assign the variable name > to another name, > both of them will refer to the same object. > > List2=List1[ : ] > > > > Kapil Dua > Mobile: +919711311052 > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > This made me search, and I found another solution: if you use the list function as follows: >>> s = [1,2,3] >>> v = list(s) >>> s.reverse() >>> s [3, 2, 1] >>> v [1, 2, 3] >>> As a linguist, I would love to know what the difference between these things are: mycopy = original[:] mycopy = copy.deepcopy(original) mycopy = list(original) -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Mar 7 21:02:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Mar 2009 20:02:05 -0000 Subject: [Tutor] could someone explain why this happens to me. References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com><4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com><4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> <652641e90903071147q636445afw7c67ead81a5c5bce@mail.gmail.com> Message-ID: "Emad Nawfal (???? ????)" wrote > As a linguist, I would love to know what the difference between > these > things are: The differences are the same whether you are a linguist or not :-) (and yes I know my reading is incorrect grammaticallly but I couldn't resist it!) > mycopy = original[:] Returns a slice of the original list. In this case it so happens the slice is the full list. > mycopy = copy.deepcopy(original) calls the deepcopy function which traverses the original list and all nested structures explicitly copying the elements. > mycopy = list(original) Use the list type constructor to make a list out of its argument. It just so happens the argument in this case is a list. The end result is the same but the mechanisms (ie the code called) are quite different. It would be interesting to compare speeds, but I'm too lazy! I suspect deepcopy would be slowest but I'm not sure about the other two. Alan G. From emadnawfal at gmail.com Sat Mar 7 21:12:08 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 7 Mar 2009 15:12:08 -0500 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> <4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com> <4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> <652641e90903071147q636445afw7c67ead81a5c5bce@mail.gmail.com> Message-ID: <652641e90903071212m2fb2a183qf3ffb84cc3b81c05@mail.gmail.com> 2009/3/7 Alan Gauld > > "Emad Nawfal (???? ????)" wrote > > As a linguist, I would love to know what the difference between these >> things are: >> > > The differences are the same whether you are a linguist or not :-) > (and yes I know my reading is incorrect grammaticallly but I couldn't > resist it!) > > mycopy = original[:] >> > Returns a slice of the original list. In this case it so happens > the slice is the full list. > > mycopy = copy.deepcopy(original) >> > > calls the deepcopy function which traverses the original list > and all nested structures explicitly copying the elements. > > mycopy = list(original) >> > > Use the list type constructor to make a list out of its argument. > It just so happens the argument in this case is a list. > > The end result is the same but the mechanisms (ie the code called) > are quite different. It would be interesting to compare speeds, > but I'm too lazy! I suspect deepcopy would be slowest but I'm > not sure about the other two. > > Alan G. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks Alan, As a linguist, I appreciate your disambiiguation mechanism. Not all subscribers to this list are programmers, or know much about computer science. I know lots about formal thinking, but not about programming, and I always preface my questions with an expression that means: please give me a simple answer without so much jargon. Thanks for the explanation -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Mar 7 21:23:53 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 7 Mar 2009 21:23:53 +0100 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> <4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com> <4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> <652641e90903071147q636445afw7c67ead81a5c5bce@mail.gmail.com> Message-ID: 2009/3/7 Alan Gauld : >> mycopy = original[:] > > Returns a slice of the original list. In this case it so happens > the slice is the full list. > >> mycopy = list(original) > > Use the list type constructor to make a list out of its argument. > It just so happens the argument in this case is a list. Both not give the desired result with nested lists and this is why you have.. >> mycopy = copy.deepcopy(original) > > calls the deepcopy function which traverses the original list > and all nested structures explicitly copying the elements. copy.deepcopy :-) >>> import copy >>> list1 = [1,2] >>> list2 = [3.4] >>> list3 = [list1, list2] >>> list4 = list(list3) >>> list5 = list3[:] >>> list6 = copy.deepcopy(list3) >>> list1.append('a') >>> list1 [1, 2, 'a'] >>> list3 [[1, 2, 'a'], [3.3999999999999999]] >>> list4 [[1, 2, 'a'], [3.3999999999999999]] >>> list5 [[1, 2, 'a'], [3.3999999999999999]] >>> list6 [[1, 2], [3.3999999999999999]] Notice that list6 is the only list which does not have the appended a. Greets Sander From sierra_mtnview at sbcglobal.net Sun Mar 8 05:20:14 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Mar 2009 20:20:14 -0800 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> Message-ID: <49B3477E.50900@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Mar 8 05:54:30 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Mar 2009 20:54:30 -0800 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: <49B3477E.50900@sbcglobal.net> References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> Message-ID: <49B34F86.70003@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 8 10:11:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Mar 2009 09:11:58 -0000 Subject: [Tutor] Misunderstanding the Entry Widget References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Signature.htmlAnother thought occurred to me about this situation. > Suppose I have a dialog with two Entry objects in a dialog object > called TwoEntries: > entry1 = Entry(master, width=10).grid(row=4, column=1) > entry2 = Entry(master, width=10).grid(row=5, column=1) > and I do not use a StringVar to return the values entered. > Is it possible to reach inside TwoEntries, after returning from it, > and grab entry1 and 2? It would seem so if the call was > dialog=TwoEntries(...). Sure, just use x = dialog.entry1.get() y = dialog.entry2.get() There really is nothing special going on. > I have no idea of the history of these variables, but they have > very limited descriptions and examples. I assume because they have a very simple and specific purpose. There is probably more on them if you look at the original Tcl/Tk documentation. Remember Tkinter is just a wrapper arpund Tcl/Tkl and Tk has been around for a long time (20 years now) Alan G. From lie.1296 at gmail.com Sun Mar 8 12:59:30 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 08 Mar 2009 22:59:30 +1100 Subject: [Tutor] could someone explain why this happens to me. In-Reply-To: References: <142c835c0903071109vbbdcb06l708b0d4296ba811a@mail.gmail.com> <4d846e3e0903071133v4e1ad599p9a5bbbd5278aaf69@mail.gmail.com> <4d846e3e0903071136i1fc44911w8264642dd4afa91d@mail.gmail.com> <652641e90903071147q636445afw7c67ead81a5c5bce@mail.gmail.com> Message-ID: Sander Sweers wrote: > 2009/3/7 Alan Gauld : >>> mycopy = original[:] >> Returns a slice of the original list. In this case it so happens >> the slice is the full list. >> >>> mycopy = list(original) >> Use the list type constructor to make a list out of its argument. >> It just so happens the argument in this case is a list. > > Both not give the desired result with nested lists and this is why you have.. What is the desired result? Sometimes I might want to copy a list, but keep the referenced items the same. In which case I'd use the slice copying or list constructor copying. Any way, there is one unmentioned way to copy a list: listcopy = [x for x in mylist] though it might be slower and more verbose. From srilyk at gmail.com Sun Mar 8 14:34:47 2009 From: srilyk at gmail.com (W W) Date: Sun, 8 Mar 2009 07:34:47 -0600 Subject: [Tutor] Pyusb: get data via USB sent from mouse In-Reply-To: <49B29429.6080806@gmail.com> References: <49B29429.6080806@gmail.com> Message-ID: <333efb450903080634h7ea30339i39312132d59f20e3@mail.gmail.com> On Sat, Mar 7, 2009 at 9:35 AM, andr? palma wrote: > Hi folks, I'm new on pyusb programming and to learn how to get data i'm > trying ?to get ?data ?sent ?from ?my mouse. > I've download a program called usbview( http://www.kroah.com/linux/usb/ ) to > display the device descriptors of any USB device ?pluged ?to my ?computer. > I made a peace of code that was supposed to get the data sent from my mouse > but when i try to run it there is an error saying that the device is busy > ?=S I haven't used pyusb, but my guess is that because your window manager is using the device already that it can't get a lock on it. I've used pyserial for communicating with a USB device, but I've never tried communication with a mouse. HTH, Wayne From sierra_mtnview at sbcglobal.net Sun Mar 8 15:40:26 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 08 Mar 2009 07:40:26 -0700 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> Message-ID: <49B3D8DA.8060306@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 8 18:53:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Mar 2009 17:53:07 -0000 Subject: [Tutor] Misunderstanding the Entry Widget References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> <49B3D8DA.8060306@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Yep, when I bowed of programming long ago, I had Ousterhout's > (something like that) book, and finally sold it on Amazom 5 years > ago It was a good book in its day but is now well overdue an update. The book I'd recommend getting is Tcl/Tk in a Nutshell from O'Reilly Its only a reference but it covers Tk and Tix. There is hardly any Python docs for Tix although it is now part of the standard library. (Actually I think Tkinter needs an update too, there seem to be quite a few new Tk widgets that are not available in Tkinter... or is it just that they are not documented? I must have a poke around in v2.5... But the Nutshell seems to cover all the stuff that is in Tkinter) You can get a used Nutshell for around $6 via Amazon (and it covers expect too should you ever dabble with pyExpect). [ But note: for serious Tcl users the best book is Welsh's offering the Niutshell is just a reference that translates fairly easily to Tkinter/Tix] On Linux, I started using it in 1993 with RedHat 2 and Slackware 3. I dropped out for a spell then came back to it around Slackware 7 and Mandrake (now Mandriva) 3? But then I bought a Mac iBook and discovered cygwin and my current Linux box (Suse 9?) is lying idle. It only gets booted when I want to test some web things because it runs apache and Turbo Gears. Although I do now have an Asus Eee mini laptop with Linux and I'm using that to do some stuff now and then. Alan G. From mustafa.cmpe at gmail.com Sun Mar 8 18:56:15 2009 From: mustafa.cmpe at gmail.com (mustafa akkoc) Date: Sun, 8 Mar 2009 19:56:15 +0200 Subject: [Tutor] while loop problem Message-ID: <401fd82b0903081056h77328be4l12980f995dc80bbb@mail.gmail.com> hello i have syntax problem in this program #!/usr/bin/python # Filename: while.py number = 23 running = True while running : guess= input('Enter an integer : ') # it give a syntax error this line can you me ? if guess == number: print('Congratulations, you guessed it.') running = False # this causes the while loop to stop elif guess < number: print('No, it is a little higher than that.') else: print('No, it is a little lower than that.') else: print('The while loop is over.') # Do anything else you want to do here print('Done' -- Mustafa Akkoc -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 8 19:07:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Mar 2009 18:07:49 -0000 Subject: [Tutor] Misunderstanding the Entry Widget References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net><49B3D8DA.8060306@sbcglobal.net> Message-ID: "Alan Gauld" wrote >> Yep, when I bowed of programming long ago, I had Ousterhout's > It was a good book in its day but is now well overdue an update. And lo and behold, listed on Amazon is the 2nd edition due in August 2009! How's that for service :-) BTW I also noticed that there is also now an O'Reilly pocket reference which might be even more useful to Python Tkinter users than the Nutshell - smaller and cheaper and even more terse! Although it doesn't appear to cover Tix... Alan G. From alan.gauld at btinternet.com Sun Mar 8 19:16:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Mar 2009 18:16:15 -0000 Subject: [Tutor] while loop problem References: <401fd82b0903081056h77328be4l12980f995dc80bbb@mail.gmail.com> Message-ID: "mustafa akkoc" wrote > hello i have syntax problem in this program > #!/usr/bin/python > # Filename: while.py > number = 23 > running = True > > while running : > guess= input('Enter an integer : ') # it give a syntax error this > line can > you me ? Always post the full text of error messages please. It helps us a lot. Howevbder in this case I suspect the problem is that you do not seem to have indented the line under the while loop (although that may be due to email reformatting issues...) But that should say IndentationError not Syntax error? Also you don;t say what version of Python you are using. input() has changed slightly in v3... HTH, Alan G. From sierra_mtnview at sbcglobal.net Sun Mar 8 19:54:39 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 08 Mar 2009 11:54:39 -0700 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> <49B3D8DA.8060306@sbcglobal.net> Message-ID: <49B4146F.2080500@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 8 20:00:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Mar 2009 19:00:17 -0000 Subject: [Tutor] Misunderstanding the Entry Widget References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net><49B3D8DA.8060306@sbcglobal.net> Message-ID: "Alan Gauld" wrote > I think Tkinter needs an update too, there seem to be quite a few > new Tk widgets that are not available in Tkinter... or is it just > that > they are not documented? I must have a poke around in v2.5... I spoke too soon, its just the documentation needs an update the newer widgets are supported - at least paned window and Spinbox are, I didn't try any others. But you will need to look in the Tcl/Tk docs to find out how to use them! Here is the best site I know. It doesn't give Tkinter examples but does give Perl examples, which are pretty similar in style. http://www.tkdocs.com/tutorial/morewidgets.htm It also looks like we will get the new themed widgets in Python 2.7 and 3.1 which means Tkinter will no longer be the ugly duckling of Python GUI toolkits! Hooray! :-) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From wferguson1 at socal.rr.com Sun Mar 8 20:48:28 2009 From: wferguson1 at socal.rr.com (WM.) Date: Sun, 08 Mar 2009 12:48:28 -0700 Subject: [Tutor] UNSUBSCRIPTABLE? Message-ID: <49B4210C.2000003@socal.rr.com> Traceback (most recent call last): File "C:\Python26\TicTacToeD.py", line 165, in main() File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] TypeError: 'function' object is unsubscriptable I am fooling around with Dawson's "...for the Absolute Beginner". The tic-tac-toe program will not run for me. I'm guessing a typi somewhere, but cannot find it. My questions here are; can somebody tell me, in a general way, what the error message means? is there, somewhere, a list of error messages with explanations? is there, somewhere, a dictionary of Python words, such as 'unsubscriptable'? From duakapil at gmail.com Sun Mar 8 21:30:55 2009 From: duakapil at gmail.com (Kapsicum) Date: Mon, 9 Mar 2009 02:00:55 +0530 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B4210C.2000003@socal.rr.com> References: <49B4210C.2000003@socal.rr.com> Message-ID: <4d846e3e0903081330k7be75b0dq1eeee851d1717e8d@mail.gmail.com> On Mon, Mar 9, 2009 at 1:18 AM, WM. wrote: > Traceback (most recent call last): > File "C:\Python26\TicTacToeD.py", line 165, in > main() > File "C:\Python26\TicTacToeD.py", line 150, in main > DisplayBoard(board) > File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard > print "\n\t", board[1], "|", board[2], "|", board[3] > TypeError: 'function' object is unsubscriptable error means the object returned is not of type sequence > > > I am fooling around with Dawson's "...for the Absolute Beginner". The > tic-tac-toe program will not run for me. I'm guessing a typi somewhere, but > cannot find it. > > My questions here are; > can somebody tell me, in a general way, what the error message means? > is there, somewhere, a list of error messages with explanations? > is there, somewhere, a dictionary of Python words, such as > 'unsubscriptable'? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Kapil Dua Mobile: +919711311052 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mustafa.cmpe at gmail.com Sun Mar 8 21:32:10 2009 From: mustafa.cmpe at gmail.com (mustafa akkoc) Date: Sun, 8 Mar 2009 22:32:10 +0200 Subject: [Tutor] probelm pyhton shell doesnt open help please Message-ID: <401fd82b0903081332p4daee0cen334a1c8fdae672c1@mail.gmail.com> it gives this message socket error -- Mustafa Akkoc -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Sun Mar 8 22:27:08 2009 From: john at fouhy.net (John Fouhy) Date: Mon, 9 Mar 2009 10:27:08 +1300 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B4210C.2000003@socal.rr.com> References: <49B4210C.2000003@socal.rr.com> Message-ID: <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> 2009/3/9 WM. : > ?File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard > ? ?print "\n\t", board[1], "|", board[2], "|", board[3] > TypeError: 'function' object is unsubscriptable > > I am fooling around with Dawson's "...for the Absolute Beginner". The > tic-tac-toe program will not run for me. I'm guessing a typi somewhere, but > cannot find it. "subscript" means "a thing in square brackets after a name". You've got three subscripts in that line: board[1], board[2], and board[3]. The error means that you're trying to use square brackets after something that doesn't support them. It's telling you that 'board' is a function (as opposed to a list or a dict, for example) and functions don't support []. Possibly you're meant to call board: print "\n\t", board(1), "|", board(2), "|", board(3) Or, alternatively, you may have assigned to it by mistake somewhere. -- John. From lupin at orcon.net.nz Mon Mar 9 00:13:11 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Mon, 09 Mar 2009 12:13:11 +1300 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> Message-ID: <49B45107.7090604@orcon.net.nz> Given that board is a function then I believe that it is likely you're either (a) doing something wrong beforehand, or (b) if board is a function that generates the Tic Tac Toe board, then the syntax you more likely need is board()[number] , but I can't be completely certain. when I say doing something wrong beforehand, I'm thinking you might be accidentally giving the funtion a new name, instead of assigning it's return value to a variable, like so: newname = functionname //see here, no brackets on the end of the function, this basically tells python that newname is also functionname. variable = functionReturningValue() //and here, the function's return value is obviously being assigned to the variable Disclaimer: My naming scheme sucks, I know this :) Cheers --Brett John Fouhy wrote: > 2009/3/9 WM. : > >> File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard >> print "\n\t", board[1], "|", board[2], "|", board[3] >> TypeError: 'function' object is unsubscriptable >> >> I am fooling around with Dawson's "...for the Absolute Beginner". The >> tic-tac-toe program will not run for me. I'm guessing a typi somewhere, but >> cannot find it. >> > > "subscript" means "a thing in square brackets after a name". You've > got three subscripts in that line: board[1], board[2], and board[3]. > > The error means that you're trying to use square brackets after > something that doesn't support them. It's telling you that 'board' is > a function (as opposed to a list or a dict, for example) and functions > don't support []. > > Possibly you're meant to call board: > > print "\n\t", board(1), "|", board(2), "|", board(3) > > Or, alternatively, you may have assigned to it by mistake somewhere. > > From bgailer at gmail.com Mon Mar 9 00:52:48 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 08 Mar 2009 19:52:48 -0400 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <4d846e3e0903081330k7be75b0dq1eeee851d1717e8d@mail.gmail.com> References: <49B4210C.2000003@socal.rr.com> <4d846e3e0903081330k7be75b0dq1eeee851d1717e8d@mail.gmail.com> Message-ID: <49B45A50.2060504@gmail.com> Kapsicum wrote: > > > On Mon, Mar 9, 2009 at 1:18 AM, WM. > wrote: > > Traceback (most recent call last): > File "C:\Python26\TicTacToeD.py", line 165, in > main() > File "C:\Python26\TicTacToeD.py", line 150, in main > DisplayBoard(board) > File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard > print "\n\t", board[1], "|", board[2], "|", board[3] > TypeError: 'function' object is unsubscriptable > > > error means the object returned is not of type sequence No. It means that the object does not have a way to handle []. Many objects are subscriptable besides sequences. dict, set, objects with certain "special methods" e.g., __getitem__ -- Bob Gailer Chapel Hill NC 919-636-4239 From wferguson1 at socal.rr.com Mon Mar 9 01:30:54 2009 From: wferguson1 at socal.rr.com (WM.) Date: Sun, 08 Mar 2009 17:30:54 -0700 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B45107.7090604@orcon.net.nz> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> Message-ID: <49B4633E.1000400@socal.rr.com> Brett Wilkins wrote: > Given that board is a function then I believe that it is likely you're > either (a) doing something wrong beforehand, or (b) if board is a > function that generates the Tic Tac Toe board, then the syntax you more > likely need is board()[number] , but I can't be completely certain. > > when I say doing something wrong beforehand, I'm thinking you might be > accidentally giving the funtion a new name, instead of assigning it's > return value to a variable, > like so: > > newname = functionname //see here, no brackets on the end of the > function, this basically tells python that newname is also functionname. > variable = functionReturningValue() //and here, the function's return > value is obviously being assigned to the variable > > Disclaimer: My naming scheme sucks, I know this :) > > Cheers > --Brett > > John Fouhy wrote: >> 2009/3/9 WM. : >> >>> File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard >>> print "\n\t", board[1], "|", board[2], "|", board[3] >>> TypeError: 'function' object is unsubscriptable >>> >>> I am fooling around with Dawson's "...for the Absolute Beginner". The >>> tic-tac-toe program will not run for me. I'm guessing a typi >>> somewhere, but >>> cannot find it. >>> >> >> "subscript" means "a thing in square brackets after a name". You've >> got three subscripts in that line: board[1], board[2], and board[3]. >> >> The error means that you're trying to use square brackets after >> something that doesn't support them. It's telling you that 'board' is >> a function (as opposed to a list or a dict, for example) and functions >> don't support []. >> >> Possibly you're meant to call board: >> >> print "\n\t", board(1), "|", board(2), "|", board(3) >> >> Or, alternatively, you may have assigned to it by mistake somewhere. >> >> > > Thank you for your remarks. Too bad they fell into my acres of ignorance. One thing is certain, Dawson used brackets [] not parens (). When I spoke of typi (plural of typo) I meant ; for : or \ for /, not line after line of error. My only alternative now seems to be 'get out the old curry comb' and go letter by letter, between the monitor and the page. Headache time. From john at fouhy.net Mon Mar 9 01:34:51 2009 From: john at fouhy.net (John Fouhy) Date: Mon, 9 Mar 2009 13:34:51 +1300 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B4633E.1000400@socal.rr.com> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> <49B4633E.1000400@socal.rr.com> Message-ID: <5e58f2e40903081734m64696bb1vca738bd00d1d95a8@mail.gmail.com> 2009/3/9 WM. : > Thank you for your remarks. Too bad they fell into my acres of ignorance. > One thing is certain, Dawson used brackets [] not parens (). When I spoke of > typi (plural of typo) I meant ; for : or \ for /, not line after line of > error. > My only alternative now seems to be 'get out the old curry comb' and go > letter by letter, between the monitor and the page. Headache time. I think Brett's suggestion is the most likely one. Look for a line that starts with: board = That's probably where your error is. -- John. From lupin at orcon.net.nz Mon Mar 9 01:45:19 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Mon, 09 Mar 2009 13:45:19 +1300 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <5e58f2e40903081734m64696bb1vca738bd00d1d95a8@mail.gmail.com> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> <49B4633E.1000400@socal.rr.com> <5e58f2e40903081734m64696bb1vca738bd00d1d95a8@mail.gmail.com> Message-ID: <49B4669F.6040107@orcon.net.nz> Found this book at the local library... If you're doing the TicTacToe game in chapter 6, then have a look at the main function (def main: ) and find the line that says board = new_board() This is likely where your troubles lie... Cheers --Brett John Fouhy wrote: > 2009/3/9 WM. : > >> Thank you for your remarks. Too bad they fell into my acres of ignorance. >> One thing is certain, Dawson used brackets [] not parens (). When I spoke of >> typi (plural of typo) I meant ; for : or \ for /, not line after line of >> error. >> My only alternative now seems to be 'get out the old curry comb' and go >> letter by letter, between the monitor and the page. Headache time. >> > > I think Brett's suggestion is the most likely one. Look for a line > that starts with: > > board = > > That's probably where your error is. > > From david at abbottdavid.com Mon Mar 9 02:19:20 2009 From: david at abbottdavid.com (David) Date: Sun, 08 Mar 2009 21:19:20 -0400 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B45A50.2060504@gmail.com> References: <49B4210C.2000003@socal.rr.com> <4d846e3e0903081330k7be75b0dq1eeee851d1717e8d@mail.gmail.com> <49B45A50.2060504@gmail.com> Message-ID: <49B46E98.6030804@abbottdavid.com> bob gailer wrote: > Kapsicum wrote: >> >> >> On Mon, Mar 9, 2009 at 1:18 AM, WM. > > wrote: >> >> Traceback (most recent call last): >> File "C:\Python26\TicTacToeD.py", line 165, in >> main() >> File "C:\Python26\TicTacToeD.py", line 150, in main >> DisplayBoard(board) >> File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard >> print "\n\t", board[1], "|", board[2], "|", board[3] >> TypeError: 'function' object is unsubscriptable >> >> >> error means the object returned is not of type sequence > > No. It means that the object does not have a way to handle []. Many > objects are subscriptable besides sequences. > > dict, set, objects with certain "special methods" e.g., __getitem__ > how about; print "\n\t", board[0], "|", board[1], "|", board[2] -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From wferguson1 at socal.rr.com Mon Mar 9 02:20:41 2009 From: wferguson1 at socal.rr.com (WM.) Date: Sun, 08 Mar 2009 18:20:41 -0700 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B45107.7090604@orcon.net.nz> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> Message-ID: <49B46EE9.5050402@socal.rr.com> I am using Python 26 on a Windows XP OK, here are the three lines mentioned following the error message. Traceback (most recent call last): File "C:\Python26\TicTacToeD.py", line 165, in main() File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] TypeError: 'function' object is unsubscriptable line 165 = main() def main(): DisplayInstruct() puter, human = Pieces() turn = X board = NewBoard DisplayBoard(board) line 150 = DisplayBoard(board) line 69 def DisplayBoard(board): """Display board on screen.""" print "\n\t", board[1], "|", board[2], "|", board[3] print "\t", "______" print "\t", board[4], "|", board[5], "|", board[6] print "\t", "______" print "\t", board[7], "|", board[8], "|", board[9], "\n" From lupin at orcon.net.nz Mon Mar 9 02:25:36 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Mon, 09 Mar 2009 14:25:36 +1300 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B46EE9.5050402@socal.rr.com> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> <49B46EE9.5050402@socal.rr.com> Message-ID: <49B47010.6090400@orcon.net.nz> Your problem: def main(): DisplayInstruct() puter, human = Pieces() turn = X board = NewBoard <<<------This line DisplayBoard(board) if you read my email before, I described this to you :) put brackets on the end of NewBoard (so NewBoard() ) and this should work. Cheers WM. wrote: > I am using Python 26 on a Windows XP > > OK, here are the three lines mentioned following the error message. > > Traceback (most recent call last): > File "C:\Python26\TicTacToeD.py", line 165, in > main() > File "C:\Python26\TicTacToeD.py", line 150, in main > DisplayBoard(board) > File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard > print "\n\t", board[1], "|", board[2], "|", board[3] > TypeError: 'function' object is unsubscriptable > > > line 165 = main() > > def main(): > DisplayInstruct() > puter, human = Pieces() > turn = X > board = NewBoard > DisplayBoard(board) > > line 150 = DisplayBoard(board) > > line 69 > def DisplayBoard(board): > """Display board on screen.""" > print "\n\t", board[1], "|", board[2], "|", board[3] > print "\t", "______" > print "\t", board[4], "|", board[5], "|", board[6] > print "\t", "______" > print "\t", board[7], "|", board[8], "|", board[9], "\n" > > From david at abbottdavid.com Mon Mar 9 02:31:02 2009 From: david at abbottdavid.com (David) Date: Sun, 08 Mar 2009 21:31:02 -0400 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B46EE9.5050402@socal.rr.com> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> <49B46EE9.5050402@socal.rr.com> Message-ID: <49B47156.5020103@abbottdavid.com> WM. wrote: > I am using Python 26 on a Windows XP > > OK, here are the three lines mentioned following the error message. > > Traceback (most recent call last): > File "C:\Python26\TicTacToeD.py", line 165, in > main() > File "C:\Python26\TicTacToeD.py", line 150, in main > DisplayBoard(board) > File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard > print "\n\t", board[1], "|", board[2], "|", board[3] > TypeError: 'function' object is unsubscriptable > > > line 165 = main() > > def main(): > DisplayInstruct() > puter, human = Pieces() > turn = X > board = NewBoard > DisplayBoard(board) > > line 150 = DisplayBoard(board) > > line 69 > def DisplayBoard(board): > """Display board on screen.""" > print "\n\t", board[1], "|", board[2], "|", board[3] > print "\t", "______" > print "\t", board[4], "|", board[5], "|", board[6] > print "\t", "______" > print "\t", board[7], "|", board[8], "|", board[9], "\n" > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > so you have this def NewBoard(): """Create new game board.""" board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board for your DisplayBoard I have this; def new_board(): """Create new game board.""" board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board def display_board(board): """Display game board on screen.""" print "\n\t", board[0], "|", board[1], "|", board[2] print "\t", "---------" print "\t", board[3], "|", board[4], "|", board[5] print "\t", "---------" print "\t", board[6], "|", board[7], "|", board[8], "\n" -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From wstephens10 at suddenlink.net Mon Mar 9 01:27:42 2009 From: wstephens10 at suddenlink.net (William Stephens) Date: Sun, 08 Mar 2009 19:27:42 -0500 Subject: [Tutor] Long list error Message-ID: <49B4627E.9010201@suddenlink.net> Hello, I was working on a sieve of eratosthenes and ran into an error I don't understand. >>> size = 10000000000 >>> l = [0,1]*(size/2) Traceback (most recent call last): File "", line 1, in OverflowError: cannot fit 'long' into an index-sized integer Is there a type or something that I can do to prevent this error? Or am I on the wrong track for such large primes? Thanks, William Stephens From wferguson1 at socal.rr.com Mon Mar 9 02:50:56 2009 From: wferguson1 at socal.rr.com (WM.) Date: Sun, 08 Mar 2009 18:50:56 -0700 Subject: [Tutor] UNSUBSCRIPTABLE? In-Reply-To: <49B47010.6090400@orcon.net.nz> References: <49B4210C.2000003@socal.rr.com> <5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com> <49B45107.7090604@orcon.net.nz> <49B46EE9.5050402@socal.rr.com> <49B47010.6090400@orcon.net.nz> Message-ID: <49B47600.5020602@socal.rr.com> Well, Mr. Wilkins takes the biscuit. He found where I did not enter a pair of parens.() From kent37 at tds.net Mon Mar 9 03:06:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Mar 2009 22:06:37 -0400 Subject: [Tutor] Long list error In-Reply-To: <49B4627E.9010201@suddenlink.net> References: <49B4627E.9010201@suddenlink.net> Message-ID: <1c2a2c590903081906iaf675cfm16176fb37e5137f8@mail.gmail.com> On Sun, Mar 8, 2009 at 8:27 PM, William Stephens wrote: > Hello, > > I was working on a sieve of eratosthenes and ran into an error I don't > understand. > >>>> size = 10 000 000 000 >>>> l = [0,1]*(size/2) > Traceback (most recent call last): > ?File "", line 1, in > OverflowError: cannot fit 'long' into an index-sized integer > > > Is there a type or something that I can do to prevent this error? Or am I on > the wrong track for such large primes? The maximum size of a list is given by Py_ssize_t in pyport.h in the Python source and discussed in PEP 353: http://www.python.org/dev/peps/pep-0353/ My understanding is that list size is limited to the maximum signed integer supported by the underlying C compiler. On a 32-bit processor this is 2**31 = 2,147,483,647 which is a bit smaller than your requested 10,000,000,000. But...think about what you are asking for. Each array element is 8 bytes (a pointer) so you are trying to create a 80,000,000,000 byte array. That's about 74 gigabytes before you even try to put any values in it. So, yes, I think you are on the wrong track... Kent From srilyk at gmail.com Mon Mar 9 03:49:30 2009 From: srilyk at gmail.com (W W) Date: Sun, 8 Mar 2009 21:49:30 -0500 Subject: [Tutor] probelm pyhton shell doesnt open help please In-Reply-To: <401fd82b0903081332p4daee0cen334a1c8fdae672c1@mail.gmail.com> References: <401fd82b0903081332p4daee0cen334a1c8fdae672c1@mail.gmail.com> Message-ID: <333efb450903081949o7086d7abgbb557107c45215d3@mail.gmail.com> On Sun, Mar 8, 2009 at 3:32 PM, mustafa akkoc wrote: > > it gives this message socket error That's not terribly descriptive... what type of python shell? IDLE? Interactive prompt? Ipython? Certainly you don't mean this? user at system:~$ python socket error user at system:~$ -Wayne From mwalsh at mwalsh.org Mon Mar 9 05:18:10 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sun, 08 Mar 2009 23:18:10 -0500 Subject: [Tutor] probelm pyhton shell doesnt open help please In-Reply-To: <401fd82b0903081332p4daee0cen334a1c8fdae672c1@mail.gmail.com> References: <401fd82b0903081332p4daee0cen334a1c8fdae672c1@mail.gmail.com> Message-ID: <49B49882.2070901@mwalsh.org> mustafa akkoc wrote: > > it gives this message socket error > IDLE's subprocess didn't make a connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection. IIRC, this was once a known issue with IDLE when combined with the windows firewall service, or when running multiple instances of IDLE (perhaps inadvertently). But, I'm having difficulty tracking down the pertinent bug report(s) -- maybe these have been fixed? or I'm just tired, probably the latter. A couple of suggestions from memory ... 1. Check the process/task list for errant pythonw.exe processes, and end them. 2. Launch IDLE with the -n flag from a terminal (command prompt). 3. Report back to the list with your results, and include the python and windows version info if you continue to have trouble. HTH, Marty PS. Keep in mind, some of us won't see images you post to the list so you should generally include a text version of error messages whenever possible. Or at least, note when you've included an image so that those with sufficient interest can make the extra effort to view it, if necessary. From lie.1296 at gmail.com Mon Mar 9 06:51:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 09 Mar 2009 16:51:28 +1100 Subject: [Tutor] while loop problem In-Reply-To: <401fd82b0903081056h77328be4l12980f995dc80bbb@mail.gmail.com> References: <401fd82b0903081056h77328be4l12980f995dc80bbb@mail.gmail.com> Message-ID: mustafa akkoc wrote: > hello i have syntax problem in this program > > After correcting the indentations, and putting a missing parentheses in line 24 (the last line), I don't see any Syntax Error. #!/usr/bin/python # Filename: while.py number = 23 running = True while running : guess= int(input('Enter an integer : ')) # it give a syntax error this line can you me ? if guess == number: print('Congratulations, you guessed it.') running = False # this causes the while loop to stop elif guess < number: print('No, it is a little higher than that.') else: print('No, it is a little lower than that.') else: print('The while loop is over.') # Do anything else you want to do here print('Done') # you missed a paren, probably CopyPasteError From jessica06cruz at yahoo.com Mon Mar 9 09:28:38 2009 From: jessica06cruz at yahoo.com (jessica cruz) Date: Mon, 9 Mar 2009 01:28:38 -0700 (PDT) Subject: [Tutor] problem with an anagram program Message-ID: <823438.88941.qm@web43139.mail.sp1.yahoo.com> I just started learning python an I'm currently working on this program. The purpose of this program is to read a string of letters from user input and print out all the words which are anagrams of the input string. This is what I have and when I try to run the program it says that there is an error "invalid syntax" but I can't figure out where. #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words word_list = infile.readlines() wordList = [] # code that will be compared will be a histogram type code with frequency # characters def code(w): ??? hist = [] ??? chars = list(w) ??? chars.sort() ??? for letter in chars: ??????? if not letter in hist:? # when the letter is not already in hist, ??????????? hist.extend([letter, str(w.count(letter))])? # its added to hist along with its freq. ??????? else: ??????????? continue ??? coding = "".join(hist) # then they are joined as one string ??? return coding # new list is made with words in word_list followed by its code for word in? word_list: ??? wordList.append(word) ??? wordList.append(code(word[:(len(word)-2)])) while True: ??? word1 = raw_input('Enter word:') ??? word = word1.lower() ??? sig = code(word) ??? i = 1 ??? if sig in wordList: ??????? print "Anagrams:" ??????? while i <= len(wordList):? # when the sig of the inputed word is in the word list, ??????????? if sig == wordList[i] ??????????? print wordList[i-1]? # the corresponding words are printed ??????????? i += 2 # then adds two because codes are every other entry ??? else: ??????? print "No anagrams" ??? choice = raw_input("Continue? (yes/no)") ??? if choice == 'y' or choice == 'yes': ??????? continue ??? else: ??????? break ??????????? ??????? ??????? ??? ??????? ??? ????????????? ??? ??? ??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 9 09:39:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Mar 2009 08:39:44 -0000 Subject: [Tutor] UNSUBSCRIPTABLE? References: <49B4210C.2000003@socal.rr.com><5e58f2e40903081427u2ff2c8f0kd60ac629c445504c@mail.gmail.com><49B45107.7090604@orcon.net.nz> <49B46EE9.5050402@socal.rr.com><49B47010.6090400@orcon.net.nz> <49B47600.5020602@socal.rr.com> Message-ID: "WM." wrote > Well, Mr. Wilkins takes the biscuit. He found where I did not enter > a pair of parens.() But do you understand *why* you got the error and what it was telling you? Pyton's error message told you exactly what you had done wrong although you may not have quite understood it. But do you now see what the error message was telling you when it said: ------------------ File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] TypeError: 'function' object is unsubscriptable ------------------ Can you understand it clearly enough that when a similar error comes up in future you will know what to look for and where? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l From andreengels at gmail.com Mon Mar 9 09:40:36 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 9 Mar 2009 09:40:36 +0100 Subject: [Tutor] problem with an anagram program In-Reply-To: <823438.88941.qm@web43139.mail.sp1.yahoo.com> References: <823438.88941.qm@web43139.mail.sp1.yahoo.com> Message-ID: <6faf39c90903090140v6c88ae93pe9e5e773c337a524@mail.gmail.com> Please next time, if possible, add the complete error message you get. In this case, it tells us that the error is in this line: if sig == wordList[i] You forgot the : at the end of this line (also, the next lines are not indented extra, as they should). On Mon, Mar 9, 2009 at 9:28 AM, jessica cruz wrote: > I just started learning python an I'm currently working on this program. The > purpose of this program is to read a string of letters from user input and > print out all the words which are anagrams of the input string. This is what > I have and when I try to run the program it says that there is an error > "invalid syntax" but I can't figure out where. > > > > > #this reads all of the words in the file into a list > infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') > wdcount = int(infile.readline()) #first item is count of all the words > word_list = infile.readlines() > wordList = [] > > # code that will be compared will be a histogram type code with frequency > # characters > def code(w): > ??? hist = [] > ??? chars = list(w) > ??? chars.sort() > ??? for letter in chars: > ??????? if not letter in hist:? # when the letter is not already in hist, > ??????????? hist.extend([letter, str(w.count(letter))])? # its added to hist > along with its freq. > ??????? else: > ??????????? continue > ??? coding = "".join(hist) # then they are joined as one string > ??? return coding > > > > > # new list is made with words in word_list followed by its code > for word in? word_list: > ??? wordList.append(word) > ??? wordList.append(code(word[:(len(word)-2)])) > > > while True: > ??? word1 = raw_input('Enter word:') > ??? word = word1.lower() > ??? sig = code(word) > ??? i = 1 > ??? if sig in wordList: > ??????? print "Anagrams:" > ??????? while i <= len(wordList):? # when the sig of the inputed word is in > the word list, > ??????????? if sig == wordList[i] > ??????????? print wordList[i-1]? # the corresponding words are printed > ??????????? i += 2 # then adds two because codes are every other entry > ??? else: > ??????? print "No anagrams" > ??? choice = raw_input("Continue? (yes/no)") > ??? if choice == 'y' or choice == 'yes': > ??????? continue > ??? else: > ??????? break -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Mon Mar 9 09:45:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Mar 2009 08:45:10 -0000 Subject: [Tutor] probelm pyhton shell doesnt open help please References: <401fd82b0903081332p4daee0cen334a1c8fdae672c1@mail.gmail.com> Message-ID: "mustafa akkoc" wrote > it gives this message socket error This used to happen in older versions of IDLE. What version of Python are you using? If possible upgrade to v2.5 or later. If not you probably need to tweak your firewall settings to open a particular port - but I can't recall which one! Or to allow IDLE to send/receive without hindrance. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 9 09:53:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Mar 2009 08:53:32 -0000 Subject: [Tutor] Long list error References: <49B4627E.9010201@suddenlink.net> Message-ID: "William Stephens" wrote > I was working on a sieve of eratosthenes and ran into an error I > don't understand. > > >>> size = 10000000000 > >>> l = [0,1]*(size/2) > OverflowError: cannot fit 'long' into an index-sized integer > > Is there a type or something that I can do to prevent this error? The problem is not really to do with the type, despite the error. You are multiplying the list contents by 5 billion. This will create a list with 10 billion entries. Python cannot handle lists of that length. BUT, I doubt if your PC can even if Python could. Does your PC really have around 40G of Memory? > I on the wrong track for such large primes? I think so. Your PC does not have infinitely large memory. You need to find an algorithm that keeps the data within the limits of your hardware. (Just be glad you don't have a ZX81 with only 1K of RAM...) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ > > Thanks, > William Stephens > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Mar 9 10:23:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Mar 2009 09:23:06 -0000 Subject: [Tutor] problem with an anagram program References: <823438.88941.qm@web43139.mail.sp1.yahoo.com> Message-ID: "jessica cruz" wrote > I just started learning python an I'm currently working on this > program. > The purpose of this program is to read a string of letters from user > input and print out all the words which are anagrams of the input > string. Where you define an anagram to be a word that is in wordlist I assume? > it says that there is an error "invalid syntax" but I can't figure > out where. Always send us the full error message, it usually tells us where to look, which is easier than reading the full program! > #this reads all of the words in the file into a list > infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') > wdcount = int(infile.readline()) #first item is count of all the > words You do not use this, why bother? > word_list = infile.readlines() > wordList = [] > # code that will be compared will be a histogram type code with > frequency > # characters > def code(w): > hist = [] > chars = list(w) > chars.sort() > for letter in chars: > if not letter in hist: # when the letter is not already in > hist, > hist.extend([letter, str(w.count(letter))]) # its added > to hist along with its freq. > else: > continue > coding = "".join(hist) # then they are joined as one string > return coding > # new list is made with words in word_list followed by its code > for word in word_list: > wordList.append(word) > wordList.append(code(word[:(len(word)-2)])) word[:len(word)-2] could be written much more clearly as word[:-2] > while True: > word1 = raw_input('Enter word:') > word = word1.lower() > sig = code(word) > i = 1 > if sig in wordList: > print "Anagrams:" > while i <= len(wordList): # when the sig of the inputed word is in > the word list, > if sig == wordList[i] This looks like the syntax error - no colon. I stopped here. I think there are easier ways to do this! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From dextrous85 at gmail.com Mon Mar 9 13:07:54 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 9 Mar 2009 17:37:54 +0530 Subject: [Tutor] Excel addin in Python Message-ID: <5487b3060903090507n4ece59d4oe6c77005fbd2e4fa@mail.gmail.com> Dear All, I have created an excel addin in python; everything is working pretty fine when I execute the python file, addin is getting added and I am able to use it fine. But I want to distribute this addin to users so I used py2exe to convert it in to an exe so far so good I am able to create exe but when I run this exe it works fine and say registering excel addin but I am not able to see the addin in excel but the entry in registry is present. Any pointers on what may be going wrong?? -- Cheers, Vishwajeet http://www.singhvishwajeet.com From mustafa.cmpe at gmail.com Mon Mar 9 13:22:07 2009 From: mustafa.cmpe at gmail.com (mustafa akkoc) Date: Mon, 9 Mar 2009 14:22:07 +0200 Subject: [Tutor] if inside if help python Message-ID: <401fd82b0903090522j7c4faa01x5eb56531cec52199@mail.gmail.com> I have question if we make if statement inside if like cprogramming below how to do in python int x-1 , y=2; if (x==1) { printf(" inside first if "); if (y==2) { printf ("inside second if "); } } -- Mustafa Akkoc -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Mon Mar 9 13:26:36 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Mon, 9 Mar 2009 17:56:36 +0530 Subject: [Tutor] if inside if help python In-Reply-To: <401fd82b0903090522j7c4faa01x5eb56531cec52199@mail.gmail.com> References: <401fd82b0903090522j7c4faa01x5eb56531cec52199@mail.gmail.com> Message-ID: <7c42eba10903090526k1d1c0117q43089154f3488731@mail.gmail.com> > I have question ?if we make if statement inside if ?like cprogramming below how to do ?in python Indentation is the key here. It is very simple. x=1 y=2 if x == 1: print "inside first if" if x == 2: print "inside second if" -- Senthil From mustafa.cmpe at gmail.com Mon Mar 9 14:18:09 2009 From: mustafa.cmpe at gmail.com (mustafa akkoc) Date: Mon, 9 Mar 2009 15:18:09 +0200 Subject: [Tutor] i can only write one line of code on python shell help please ? Message-ID: <401fd82b0903090618g27d930c9r5689d1b81b84b5ed@mail.gmail.com> Hello , - In python shell , i can only write one line of code when I go to next line this sign appears >>> how can write the code like in script mode and run thanks -- Mustafa Akkoc -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Mar 9 14:30:32 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Mar 2009 06:30:32 -0700 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net><49B3D8DA.8060306@sbcglobal.net> Message-ID: <49B519F8.4090401@sbcglobal.net> An HTML attachment was scrubbed... URL: From norman at khine.net Mon Mar 9 16:28:41 2009 From: norman at khine.net (ski) Date: Mon, 09 Mar 2009 16:28:41 +0100 Subject: [Tutor] creating new dictionary based on membership testing Message-ID: <49B535A9.7050508@khine.net> hello, i have this list which contains a number of dictionaries. >>>d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] what would be the correct way to create a new list with the dictionaries but only for dictionaries with key 'is_selected': False here is what I have tried, so far, perhaps there is a better and less error prone method: >>> d2 = [] >>> for x in d1: ... if False in x.values(): ... d2.append(x) ... >>> d2 [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] Thank you Norman From david at abbottdavid.com Mon Mar 9 16:23:41 2009 From: david at abbottdavid.com (David) Date: Mon, 09 Mar 2009 11:23:41 -0400 Subject: [Tutor] i can only write one line of code on python shell help please ? In-Reply-To: <401fd82b0903090618g27d930c9r5689d1b81b84b5ed@mail.gmail.com> References: <401fd82b0903090618g27d930c9r5689d1b81b84b5ed@mail.gmail.com> Message-ID: <49B5347D.5020908@abbottdavid.com> mustafa akkoc wrote: > Hello , > > - In python shell , i can only write one line of code when I go to > next line this sign appears >>> how can write the code like in > script mode and run > > thanks > -- > Mustafa Akkoc > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > This should help; http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ -- powered by Gentoo/GNU Linux http://linuxcrazy.com From a.t.hofkamp at tue.nl Mon Mar 9 16:47:49 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 09 Mar 2009 16:47:49 +0100 Subject: [Tutor] creating new dictionary based on membership testing In-Reply-To: <49B535A9.7050508@khine.net> References: <49B535A9.7050508@khine.net> Message-ID: <49B53A25.406@tue.nl> ski wrote: > hello, > > i have this list which contains a number of dictionaries. > > >>>d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of > Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. > Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', > 'title': 'Association of British Prof. Conf. Organisation'}, > {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British > Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': > 'Association of Bonded Travel Organisation Trust'}, {'is_selected': > False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] > > what would be the correct way to create a new list with the dictionaries > but only for dictionaries with key > > 'is_selected': False > > here is what I have tried, so far, perhaps there is a better and less > error prone method: > > >>> d2 = [] > >>> for x in d1: > ... if False in x.values(): > ... d2.append(x) This code is wrong, x.values() gives a list of values in the dictionary x, and if 'False' is in it, you append the dict. You never check for the key. Thus d1 = [ {'id':False} ] would also be copied. Also, if you have a dict, and you know which key to use, use that key!! Key-lookup in a dict is very much faster than a linear search in a list like x.values(). You can do something like [d for d in d1 if d['is_selected'] == False] to get your dicts. If 'is_selected' is not always present, it gets a bit more complicated, I'll leave that as an exercise for the interested reader :) Sincerely, Albert From sander.sweers at gmail.com Mon Mar 9 16:52:42 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 9 Mar 2009 16:52:42 +0100 Subject: [Tutor] creating new dictionary based on membership testing In-Reply-To: <49B53A25.406@tue.nl> References: <49B535A9.7050508@khine.net> <49B53A25.406@tue.nl> Message-ID: 2009/3/9 A.T.Hofkamp : > You can do something like > [d for d in d1 if d['is_selected'] == False] > to get your dicts. > > If 'is_selected' is not always present, it gets a bit more complicated, I'll > leave that as an exercise for the interested reader :) You would use d.get('is_selected', False) == False. If nothing is found then .get() will return False instead of None. Greets Sander From kent37 at tds.net Mon Mar 9 16:58:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Mar 2009 10:58:46 -0500 Subject: [Tutor] creating new dictionary based on membership testing In-Reply-To: <49B535A9.7050508@khine.net> References: <49B535A9.7050508@khine.net> Message-ID: <1c2a2c590903090858v5378b035s4f364993880cec6d@mail.gmail.com> On Mon, Mar 9, 2009 at 10:28 AM, ski wrote: > hello, > > i have this list which contains a number of dictionaries. > >>>>d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of >>>> Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. >>>> Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': >>>> 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, >>>> 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, >>>> {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel >>>> Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': >>>> 'Association of Europe Rail Agents'}] > > what would be the correct way to create a new list with the dictionaries but > only for dictionaries with key > > 'is_selected': False > > here is what I have tried, so far, perhaps there is a better and less error > prone method: > >>>> d2 = [] >>>> for x in d1: > ... ? ? if False in x.values(): > ... ? ? ? ? ? ? d2.append(x) This doesn't take advantage of dict lookup and it doesn't do exactly what you asked; it will exclude dicts having any False value, not just for is_selected. Better would be d2 = [] for x in d1: if x['is_selected'] != False: d2.append(x) This can be further simplified; you probably can just test x['is_selected'] without comparing to False, and you can use a list comprehension to simplify the structure: d2 = [ x for x in d1 if x['is_selected'] ] Kent From norman at khine.net Mon Mar 9 17:05:29 2009 From: norman at khine.net (ski) Date: Mon, 09 Mar 2009 17:05:29 +0100 Subject: [Tutor] creating new dictionary based on membership testing In-Reply-To: References: <49B535A9.7050508@khine.net> <49B53A25.406@tue.nl> Message-ID: <49B53E49.9000201@khine.net> thank you all, great feedback. Sander Sweers wrote: > 2009/3/9 A.T.Hofkamp : >> You can do something like >> [d for d in d1 if d['is_selected'] == False] >> to get your dicts. >> >> If 'is_selected' is not always present, it gets a bit more complicated, I'll >> leave that as an exercise for the interested reader :) > > You would use d.get('is_selected', False) == False. > > If nothing is found then .get() will return False instead of None. > > Greets > Sander > From norman at khine.net Mon Mar 9 18:31:33 2009 From: norman at khine.net (ski) Date: Mon, 09 Mar 2009 18:31:33 +0100 Subject: [Tutor] compare csv file values against a python dictionary and create a new list from this. Message-ID: <49B55275.1080405@khine.net> hello, i have created this function that compares the values of a csv file against a dictionary, you can see the code, here http://paste.lisp.org/display/76705 the affiliations list has 130 items. is there a better way to build the 'items' list? thanks norman From timmichelsen at gmx-topmail.de Mon Mar 9 18:40:57 2009 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 09 Mar 2009 18:40:57 +0100 Subject: [Tutor] creating a list of all imported modules Message-ID: Hello, how do I create a list of all modules imported by my module/script? I am looking for something like %who in Ipython. Thanks for your help in advance. Regards, Timmie From sierra_mtnview at sbcglobal.net Mon Mar 9 19:18:12 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Mar 2009 11:18:12 -0700 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: <1c2a2c590903090716u79722c84t6e9ec737c95bdf4d@mail.gmail.com> References: <49B09E13.7080402@sbcglobal.net> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> <49B3D8DA.8060306@sbcglobal.net> <49B519F8.4090401@sbcglobal.net> <1c2a2c590903090716u79722c84t6e9ec737c95bdf4d@mail.gmail.com> Message-ID: <49B55D64.1010206@sbcglobal.net> An HTML attachment was scrubbed... URL: From jessica06cruz at yahoo.com Mon Mar 9 19:38:19 2009 From: jessica06cruz at yahoo.com (jessica cruz) Date: Mon, 9 Mar 2009 11:38:19 -0700 (PDT) Subject: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM Message-ID: <709392.48770.qm@web43141.mail.sp1.yahoo.com> I made this program but it says that there is an error and I have a hard time trying to solve the problem with program. Here is the program: #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words word_list = infile.readlines() #print them out from the internal list i = 0 while i < wdcount: ??? print word_list[i], ??? i = i + 1 #map of alphabet to prime numbers with respect to frecuency #more frequent the letter the smaller the assigment prime letter_to_prime = { ??? 'a':7, ??? 'b':59, ??? 'c':29, ??? 'd':31, ??? 'e':2, ??? 'f':67, ??? 'g':41, ??? 'h':53, ??? 'i':3, ??? 'j':97, ??? 'k':73, ??? 'l':23, ??? 'm':47, ??? 'n':13, ??? 'o':19, ??? 'p':43, ??? 'q':101, ??? 'r':11, ??? 's':5, ??? 't':17, ??? 'u':37, ??? 'v':71, ??? 'w':79, ??? 'x':89, ??? 'y':61, ??? 'z':83}, j = 0 while j < wdcount: ??? print word_list [j], ??? prod = 1 ??? i = 0 ??? while i < len(word_list[j])-2: ??????? prod = prod * letter_to_prime[word_list[j] [i]: ??????? i = i + 1 ??? print prod (right here is where it says that there's an error I try to fix it ) ??? j = j =1 ????????????????????????????????????? # code that will be compared will be a histogram type code with frequency # characters def code(w): ??? hist = [] ??? chars = list(w) ??? chars.sort() ??? for letter in chars: ??????? if not letter in hist:? # when the letter is not already in hist, ??????????? hist.extend([letter, str(w.count(letter))])? # its added to hist along with its freq. ??????? else: ??????????? continue ??? coding = "".join(hist) # then they are joined as one string ??? return coding # new list is made with words in word_list followed by its code for word in? word_list: ??? wordList.append(word) ??? wordList.append(code(word[:(len(word)-2)])) while True: ??? word1 = raw_input('Enter word:') ??? word = word1.lower() ??? sig = code(word) ??? i = 1 ??? if sig in wordList: ??????? print "Anagrams:" ??????? while i <= len(wordList):? # when the sig of the inputed word is in the word list, ??????????? if sig == wordList[i]: ??????????????? print wordList[i-1]? # the corresponding words are printed ??????????? i += 2 # then adds two because codes are every other entry ??? else: ??????? print "No anagrams" ??? choice = raw_input("Continue? (yes/no)") ??? if choice == 'y' or choice == 'yes': ??????? continue ??? else: ??????? break I don't know how to figure out the error since the only message that I get is that "there's an error: invalid syntax" -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Mar 9 20:34:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Mar 2009 14:34:06 -0500 Subject: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM In-Reply-To: <709392.48770.qm@web43141.mail.sp1.yahoo.com> References: <709392.48770.qm@web43141.mail.sp1.yahoo.com> Message-ID: <1c2a2c590903091234qf0b4b4bu7a2e671d2bfd12b9@mail.gmail.com> On Mon, Mar 9, 2009 at 1:38 PM, jessica cruz wrote: > I don't know how to figure out the error since the only message that I get > is that "there's an error: invalid syntax" Please copy & paste the whole error message including the traceback so we know where the error is. Kent From wescpy at gmail.com Mon Mar 9 20:53:37 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 9 Mar 2009 11:53:37 -0800 Subject: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM In-Reply-To: <78b3a9580903091150m4cf2f331nd18be6b7f72de01@mail.gmail.com> References: <709392.48770.qm@web43141.mail.sp1.yahoo.com> <78b3a9580903091150m4cf2f331nd18be6b7f72de01@mail.gmail.com> Message-ID: <78b3a9580903091253s59b969b0p402a00dbc839f71b@mail.gmail.com> On Mon, Mar 9, 2009 at 10:38 AM, jessica cruz wrote: > I made this program but it says that there is an error and I have a hard > time trying to solve the problem with program. > ? ? ? ?: > I don't know how to figure out the error since the only message that I get > is that "there's an error: invalid syntax" hi jessica, in order for us to help you more effectively, you'll need to cut-n-paste the entire error traceback as well as tell us what version of Python you're using including what platform (i.e., mac, PC, etc.) also, keep in mind that we aren't able to do your homework for you but would be able to help out with small difficulties you face on the way to your own solution(s)! thanks, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ?http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at abbottdavid.com Mon Mar 9 21:25:54 2009 From: david at abbottdavid.com (David) Date: Mon, 09 Mar 2009 16:25:54 -0400 Subject: [Tutor] Newby Linux Program review + help with regular expressions Message-ID: <49B57B52.40303@abbottdavid.com> This program generates a report of a Linux System and some important .conf files. The goal is for users to be able to post their information and compare with others, ask for help etc. Am I using the subrocess module too much because I am comfortable with the commands? Should I just write this type of program in bash. I am trying to get rid of all the comments generated in the report. I got rid of blank lines and lines starting with #. But can not figure out how the get rid of a line like; #This is a comment with 5 spaces I never programed before so everything is new to me. Here is my code; http://asterisklinks.com/wiki/doku.php?id=wiki:gentoo_report The report it generates is at the bottom. I didn't want to post it all here. Thanks, -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From christopher.henk at allisontransmission.com Mon Mar 9 21:01:37 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Mon, 9 Mar 2009 16:01:37 -0400 Subject: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM In-Reply-To: <709392.48770.qm@web43141.mail.sp1.yahoo.com> Message-ID: Just glancing at your program, I would guess that you have a ":" where you want a "]" on the line below. prod = prod * letter_to_prime[word_list[j] [i]: HTH, Chris jessica cruz Sent by: tutor-bounces+christopher.henk=allisontransmission.com at python.org 03/09/2009 02:38 PM To Tutor at python.org cc Subject [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM I made this program but it says that there is an error and I have a hard time trying to solve the problem with program. Here is the program: #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words word_list = infile.readlines() #print them out from the internal list i = 0 while i < wdcount: print word_list[i], i = i + 1 #map of alphabet to prime numbers with respect to frecuency #more frequent the letter the smaller the assigment prime letter_to_prime = { 'a':7, 'b':59, 'c':29, 'd':31, 'e':2, 'f':67, 'g':41, 'h':53, 'i':3, 'j':97, 'k':73, 'l':23, 'm':47, 'n':13, 'o':19, 'p':43, 'q':101, 'r':11, 's':5, 't':17, 'u':37, 'v':71, 'w':79, 'x':89, 'y':61, 'z':83}, j = 0 while j < wdcount: print word_list [j], prod = 1 i = 0 while i < len(word_list[j])-2: prod = prod * letter_to_prime[word_list[j] [i]: i = i + 1 print prod (right here is where it says that there's an error I try to fix it ) j = j =1 # code that will be compared will be a histogram type code with frequency # characters def code(w): hist = [] chars = list(w) chars.sort() for letter in chars: if not letter in hist: # when the letter is not already in hist, hist.extend([letter, str(w.count(letter))]) # its added to hist along with its freq. else: continue coding = "".join(hist) # then they are joined as one string return coding # new list is made with words in word_list followed by its code for word in word_list: wordList.append(word) wordList.append(code(word[:(len(word)-2)])) while True: word1 = raw_input('Enter word:') word = word1.lower() sig = code(word) i = 1 if sig in wordList: print "Anagrams:" while i <= len(wordList): # when the sig of the inputed word is in the word list, if sig == wordList[i]: print wordList[i-1] # the corresponding words are printed i += 2 # then adds two because codes are every other entry else: print "No anagrams" choice = raw_input("Continue? (yes/no)") if choice == 'y' or choice == 'yes': continue else: break I don't know how to figure out the error since the only message that I get is that "there's an error: invalid syntax" _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Mon Mar 9 22:20:02 2009 From: norman at khine.net (ski) Date: Mon, 09 Mar 2009 22:20:02 +0100 Subject: [Tutor] comparing lists of dictionaries Message-ID: <49B58802.1020606@khine.net> hello again, i am trying to get my head around this but without success, here is what i have so far: >>> list1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] >>> list2 = [{'affiliation': 'ABTA', 'affiliation_no': u'G3903'}, {'affiliation': 'AAC', 'affiliation_no': u'none'}] >>> for dic1 in list1: ... for dic2 in list2: ... diff = [k for k, v in dic1.iteritems() if v != dic2['affiliation']] ... print k, v ... is_selected False is_selected False is_selected False is_selected True is_selected False is_selected False >>> what am i missing here, i would like to get a list of the diff between list1 and list2 again thanks in advance. norman From kent37 at tds.net Mon Mar 9 22:37:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Mar 2009 16:37:57 -0500 Subject: [Tutor] comparing lists of dictionaries In-Reply-To: <49B58802.1020606@khine.net> References: <49B58802.1020606@khine.net> Message-ID: <1c2a2c590903091437ve5d2ce8wd21298eb4dd08b9@mail.gmail.com> On Mon, Mar 9, 2009 at 4:20 PM, ski wrote: > what am i missing here, i would like to get a list of the diff between list1 > and list2 What do you mean by diff in this case? Items in one list and not in the other? Items that are in both lists but with different elements? What elements do you want to use for the comparison? Kent From norman at khine.net Mon Mar 9 22:56:49 2009 From: norman at khine.net (ski) Date: Mon, 09 Mar 2009 22:56:49 +0100 Subject: [Tutor] comparing lists of dictionaries In-Reply-To: <1c2a2c590903091437ve5d2ce8wd21298eb4dd08b9@mail.gmail.com> References: <49B58802.1020606@khine.net> <1c2a2c590903091437ve5d2ce8wd21298eb4dd08b9@mail.gmail.com> Message-ID: <49B590A1.6060606@khine.net> i was looking to list all the items in list1 that are not in list2 based on the key['id] and key['affiliation'] respectively. thanks Kent Johnson wrote: > On Mon, Mar 9, 2009 at 4:20 PM, ski wrote: > >> what am i missing here, i would like to get a list of the diff between list1 >> and list2 > > What do you mean by diff in this case? Items in one list and not in > the other? Items that are in both lists but with different elements? > What elements do you want to use for the comparison? > > Kent > From alan.gauld at btinternet.com Mon Mar 9 23:17:19 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Mar 2009 22:17:19 -0000 Subject: [Tutor] i can only write one line of code on python shell helpplease ? References: <401fd82b0903090618g27d930c9r5689d1b81b84b5ed@mail.gmail.com> Message-ID: "mustafa akkoc" wrote > - In python shell , i can only write one line of code when I go to > next > line this sign appears >>> how can write the code like in script > mode and > run You can't. Shell mode means you are entering code directly into the interpreter so it executes the code line by line (or as a block if it is a block, like a for loop say) If you are using IDLE (or Pyhonwin) you can open a new window which will alow you to create a new Python script and run that from within IDLE. And you can keep entering lines in the shell window, the results from previous lines are stored as they would be in a normal program. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 9 23:28:19 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Mar 2009 22:28:19 -0000 Subject: [Tutor] Newby Linux Program review + help with regular expressions References: <49B57B52.40303@abbottdavid.com> Message-ID: "David" wrote > and compare with others, ask for help etc. Am I using the subrocess > module too much because I am comfortable with the commands? Should I > just write this type of program in bash. Personally I'd use bash for this kind of thing. If you wanted to post process the report then I'd use Python. You could do a faitr bit with Python commands, especially the functions in the os module, but since the scripts already exist you might as well use them. One thing though, you could use triple quoted strings and string formatting more: fobj.write(nick) fobj.write(" \n") fobj.write(make) fobj.write(" \n") fobj.write(model) fobj.write(" \n") fobj.close()Could be: fobj.write("%s\n%s\n%s\n" % (nick,make,model) ) > #This is a comment with 5 spaces you can use the lstrip() methjod of a string: if line.lstrip().startswith('#'): isComment = True HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wferguson1 at socal.rr.com Mon Mar 9 23:39:10 2009 From: wferguson1 at socal.rr.com (WM.) Date: Mon, 09 Mar 2009 15:39:10 -0700 Subject: [Tutor] Tutor Digest, Vol 61, Issue 32 In-Reply-To: References: Message-ID: <49B59A8E.8040000@socal.rr.com> tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: probelm pyhton shell doesnt open help please (Martin Walsh) > 2. Re: while loop problem (Lie Ryan) > 3. problem with an anagram program (jessica cruz) > 4. Re: UNSUBSCRIPTABLE? (Alan Gauld) > 5. Re: problem with an anagram program (Andre Engels) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 08 Mar 2009 23:18:10 -0500 > From: Martin Walsh > Subject: Re: [Tutor] probelm pyhton shell doesnt open help please > To: tutor at python.org > Message-ID: <49B49882.2070901 at mwalsh.org> > Content-Type: text/plain; charset=ISO-8859-1 > > mustafa akkoc wrote: >> it gives this message socket error >> > > IDLE's subprocess didn't make a connection. Either IDLE can't start a > subprocess or personal firewall software is blocking the connection. > > > IIRC, this was once a known issue with IDLE when combined with the > windows firewall service, or when running multiple instances of IDLE > (perhaps inadvertently). But, I'm having difficulty tracking down the > pertinent bug report(s) -- maybe these have been fixed? or I'm just > tired, probably the latter. > > A couple of suggestions from memory ... > 1. Check the process/task list for errant pythonw.exe processes, and end > them. > 2. Launch IDLE with the -n flag from a terminal (command prompt). > 3. Report back to the list with your results, and include the python and > windows version info if you continue to have trouble. > > HTH, > Marty > > PS. Keep in mind, some of us won't see images you post to the list so > you should generally include a text version of error messages whenever > possible. Or at least, note when you've included an image so that those > with sufficient interest can make the extra effort to view it, if > necessary. > > > > > ------------------------------ > > Message: 2 > Date: Mon, 09 Mar 2009 16:51:28 +1100 > From: Lie Ryan > Subject: Re: [Tutor] while loop problem > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > mustafa akkoc wrote: >> hello i have syntax problem in this program >> > > > After correcting the indentations, and putting a missing parentheses in > line 24 (the last line), I don't see any Syntax Error. > > #!/usr/bin/python > # Filename: while.py > number = 23 > running = True > > while running : > guess= int(input('Enter an integer : ')) # it give a syntax error > this line can you me ? > > if guess == number: > print('Congratulations, you guessed it.') > running = False # this causes the while loop to stop > > elif guess < number: > print('No, it is a little higher than that.') > > else: > print('No, it is a little lower than that.') > > else: > print('The while loop is over.') > > # Do anything else you want to do here > print('Done') # you missed a paren, probably CopyPasteError > > > > ------------------------------ > > Message: 3 > Date: Mon, 9 Mar 2009 01:28:38 -0700 (PDT) > From: jessica cruz > Subject: [Tutor] problem with an anagram program > To: Tutor at python.org > Message-ID: <823438.88941.qm at web43139.mail.sp1.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > I just started learning python an I'm currently working on this program. The purpose of this program is to read a string of letters from user input and print out all the words which are anagrams of the input string. This is what I have and when I try to run the program it says that there is an error "invalid syntax" but I can't figure out where. > > > > > #this reads all of the words in the file into a list > infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') > wdcount = int(infile.readline()) #first item is count of all the words > word_list = infile.readlines() > wordList = [] > > # code that will be compared will be a histogram type code with frequency > # characters > def code(w): > ??? hist = [] > ??? chars = list(w) > ??? chars.sort() > ??? for letter in chars: > ??????? if not letter in hist:? # when the letter is not already in hist, > ??????????? hist.extend([letter, str(w.count(letter))])? # its added to hist along with its freq. > ??????? else: > ??????????? continue > ??? coding = "".join(hist) # then they are joined as one string > ??? return coding > > > > > # new list is made with words in word_list followed by its code > for word in? word_list: > ??? wordList.append(word) > ??? wordList.append(code(word[:(len(word)-2)])) > > > while True: > ??? word1 = raw_input('Enter word:') > ??? word = word1.lower() > ??? sig = code(word) > ??? i = 1 > ??? if sig in wordList: > ??????? print "Anagrams:" > ??????? while i <= len(wordList):? # when the sig of the inputed word is in the word list, > ??????????? if sig == wordList[i] > ??????????? print wordList[i-1]? # the corresponding words are printed > ??????????? i += 2 # then adds two because codes are every other entry > ??? else: > ??????? print "No anagrams" > ??? choice = raw_input("Continue? (yes/no)") > ??? if choice == 'y' or choice == 'yes': > ??????? continue > ??? else: > ??????? break > ??????????? > ??????? > ??????? > ??? > ??????? > ??? > > > > ????????????? > ??? > ??? > ??? > > > > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 4 > Date: Mon, 9 Mar 2009 08:39:44 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] UNSUBSCRIPTABLE? > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > "WM." wrote > >> Well, Mr. Wilkins takes the biscuit. He found where I did not enter >> a pair of parens.() > > But do you understand *why* you got the error and what it was telling > you? > Pyton's error message told you exactly what you had done wrong > although you may not have quite understood it. But do you now see > what the error message was telling you when it said: > > ------------------ > File "C:\Python26\TicTacToeD.py", line 150, in main > DisplayBoard(board) > File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard > print "\n\t", board[1], "|", board[2], "|", board[3] > TypeError: 'function' object is unsubscriptable > ------------------ > > Can you understand it clearly enough that when a similar error > comes up in future you will know what to look for and where? > No, Mr. G., I cannot. My approach has been to key in most of Dawson's programs, to get accustomed to the jargon and to get used to some keys that I didn't know were on the keyboard. My long term memory seems to be pretty shot and the stuff is not soaking in. I have found your tutorial, and some others in the Python B/G file of interest, but not retainable. Two O'Reilly books are worthless to me. Dawson's book is very clear; being half way through it, I should know a great deal more than I do. Oh, well, one should not bring a cap-pistol to a knife fight, nor a leaky brain to an academic task. From kent37 at tds.net Tue Mar 10 01:23:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Mar 2009 20:23:15 -0400 Subject: [Tutor] comparing lists of dictionaries In-Reply-To: <49B590A1.6060606@khine.net> References: <49B58802.1020606@khine.net> <1c2a2c590903091437ve5d2ce8wd21298eb4dd08b9@mail.gmail.com> <49B590A1.6060606@khine.net> Message-ID: <1c2a2c590903091723y67ca5895xfa6eafe067f530db@mail.gmail.com> On Mon, Mar 9, 2009 at 5:56 PM, ski wrote: > i was looking to list all the items in list1 that are not in list2 based on > the key['id] and key['affiliation'] respectively. OK. Generally, when you want to test for membership, a set or dict is a good choice. In this case, I would first make a set of the keys from list2: In [6]: list2 = [{'affiliation': 'ABTA', 'affiliation_no': u'G3903'}, {'affiliation': 'AAC', 'affiliation_no': u'none'}] In [8]: list2keys = set(item['affiliation'] for item in list2) In [9]: list2keys Out[9]: set(['AAC', 'ABTA']) Now you can filter list1 items by whether their id is in list2keys: In [10]: list1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] In [11]: for item in list1: ....: if item['id'] not in list2keys: ....: print item {'title': 'Adv. Activity Licence. Auth.', 'id': 'AALA', 'is_selected': False} {'title': 'Association of British Prof. Conf. Organisation', 'id': 'ABPCO', 'is_selected': False} {'title': 'Association of Bonded Travel Organisation Trust', 'id': 'ABTOT', 'is_selected': False} {'title': 'Association of Europe Rail Agents', 'id': 'AERA', 'is_selected': False} Kent From ctcast at gmail.com Tue Mar 10 01:25:55 2009 From: ctcast at gmail.com (Chris Castillo) Date: Mon, 9 Mar 2009 19:25:55 -0500 Subject: [Tutor] Binary to Decimal conversion Message-ID: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> I am having some difficulties in producing the correct code for a simple binary to decimal conversion program. The arithmetic I want to use is the doubling method - so if I wanted to get the decimal equivalent of 1001, I would start with multiplying 0 * 2 and adding the left most digit. I would then take the sum of 1 and multiply it by 2 and add the next digit to that product and so on and so forth until I come to an end sum of 9. I seem to come up with something like this: binnum = raw_input("Please enter a binary number: ") for i in range(0, len(binum), 1): item = "0" if i < len(binum) - 1: item = binum[i + 1] binsum = binsum * int(item) * 2 + binsum + int(binum[i]) print "\nThe binary number ", binum, " you entered converts to", binsum, " in decimal." I can't really figure out what is going wrong here. Please help me - this has been driving me insane. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Mar 10 01:42:04 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 09 Mar 2009 20:42:04 -0400 Subject: [Tutor] Binary to Decimal conversion In-Reply-To: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> References: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> Message-ID: <49B5B75C.7030308@gmail.com> Chris Castillo wrote: > I am having some difficulties in producing the correct code for a > simple binary to decimal conversion program. The arithmetic I want to > use is the doubling method - so if I wanted to get the decimal > equivalent of 1001, I would start with multiplying 0 * 2 and adding > the left most digit. I would then take the sum of 1 and multiply it by > 2 and add the next digit to that product and so on and so forth until > I come to an end sum of 9. > > I seem to come up with something like this: > > binnum = raw_input("Please enter a binary number: ") > > > for i in range(0, len(binum), 1): > item = "0" > if i < len(binum) - 1: > item = binum[i + 1] > > binsum = binsum * int(item) * 2 + binsum + int(binum[i]) > > > print "\nThe binary number ", binum, " you entered converts to", > binsum, " in decimal." > > > I can't really figure out what is going wrong here. I don't see anything going wrong. All I see is some Python code. Would you be kind enough to tell us why you think something is going wrong. If there is an error post the traceback If you get a result you did not expect tell us what the input was, the desired result and the actual result. -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Tue Mar 10 01:50:47 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 09 Mar 2009 20:50:47 -0400 Subject: [Tutor] Binary to Decimal conversion In-Reply-To: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> References: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> Message-ID: <49B5B967.6070500@gmail.com> Chris Castillo wrote: > I am having some difficulties in producing the correct code for a > simple binary to decimal conversion program. The arithmetic I want to > use is the doubling method - so if I wanted to get the decimal > equivalent of 1001, I would start with multiplying 0 * 2 and adding > the left most digit. I would then take the sum of 1 and multiply it by > 2 and add the next digit to that product and so on and so forth until > I come to an end sum of 9. > > I seem to come up with something like this: > > binnum = raw_input("Please enter a binary number: ") > > > for i in range(0, len(binum), 1): > item = "0" > if i < len(binum) - 1: > item = binum[i + 1] > > binsum = binsum * int(item) * 2 + binsum + int(binum[i]) > > > print "\nThe binary number ", binum, " you entered converts to", > binsum, " in decimal." Having said that I will point out 1 - to access elements of a sequence you may write: for item in binnum: 2 - the first element of binnum is binnum[0]. Your code starts by accessing the 2nd element. 3- you use binsum before assigning anything to it. That is bound to raise a Name error. 4 - I don't understand binsum = binsum * int(item) * 2 + binsum + int(binum[i]) That does not agree with your verbal algorithm. -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Tue Mar 10 02:04:26 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 09 Mar 2009 21:04:26 -0400 Subject: [Tutor] compare csv file values against a python dictionary and create a new list from this. In-Reply-To: <49B55275.1080405@khine.net> References: <49B55275.1080405@khine.net> Message-ID: <49B5BC9A.5060102@gmail.com> ski wrote: > hello, > i have created this function that compares the values of a csv file > against a dictionary, you can see the code, here > > http://paste.lisp.org/display/76705 > > the affiliations list has 130 items. > > is there a better way to build the 'items' list? Please define "better". If you mean less code, create a list of just the variable values: values = [['AAC', 'Association of Airline Cons.'], ['AALA', 'Adv. Activity Licence. Auth.'], ...] then provide some code to read the list and construct the dicts. In the above I assume all is_selected are False so there is no need to include that. But why a list of dictionaries? Would not the values list be sufficient? Or possibly even better define a class (Cls) and make each list entry an instance of the class. Then values = [Cls('AAC', 'Association of Airline Cons.'), Cls('AALA', 'Adv. Activity Licence. Auth.'), ...] That I think would be far more useful in the long run. -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Tue Mar 10 03:28:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Mar 2009 02:28:42 -0000 Subject: [Tutor] Tutor Digest, Vol 61, Issue 32 References: <49B59A8E.8040000@socal.rr.com> Message-ID: "WM." wrote >> From: "Alan Gauld" >> Pyton's error message told you exactly what you had done wrong >> although you may not have quite understood it. But do you now see >> what the error message was telling you when it said: ... >> Can you understand it clearly enough that when a similar error >> comes up in future you will know what to look for and where? >> > No, Mr. G., I cannot. OK, Let's revisit it to try and unravel what it is saying. >> File "C:\Python26\TicTacToeD.py", line 150, in main >> DisplayBoard(board) >> File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard >> print "\n\t", board[1], "|", board[2], "|", board[3] >> TypeError: 'function' object is unsubscriptable Start at the bottom and work upwards. >> TypeError: 'function' object is unsubscriptable unsubscriptable means you can't use the [] indexing syntax, it is not supported by the object to which you have applied it And the object to which you applied it is a function. >> File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard >> print "\n\t", board[1], "|", board[2], "|", board[3] The thing you subscripted was board. Therefore board must be a function, not something that you can subscript. >> File "C:\Python26\TicTacToeD.py", line 150, in main >> DisplayBoard(board) This is where you call DisplayBoard and pass in board as an argument to DisplayBoard. So you need to look at the code in TicTacToeD.py to see how board comes to be a function. There are really only two possibilities: a) Is it a function to begin with? ie do you have code that looks like def board(...): or b) Did you assign board to a function? ie is there a line like board = In your case it was 'b', an assignment. Now at this stage we have reached the end of what the Python error message is telling us. We need to do some actual debugging to find out what we assigned to board. Was it a function? Should it have been? And here experience comes into play, and we might either guess that we intended to call the function rather than assign it - ie we need the parens at the end. OR we check the source code we are copying to see whether we made a mistake in typing it in. (Which was the case here) If that had not yielded any joy we would need to get into deeper debugging and trace back the source of whatever we assigned to board. Maybe using print type(....) to check at what stage our errant value became a function. But in this case it was not necessary. The faulty line was board = NewBoard <<<------This line And NewBoard we could tell (because it was defined as such in our code) was a function, so we almost certainly should have added parens. board = NewBoard() 80% of this was deductable from the Python error message once you get used to reading them carefully and with some experience. That is why it's important not just to fix the problems but to understand what Python was telling you for future reference. If you look back the thread John Fouhy actually told you that you probably missed some parens within 2 hours of your original post: He just got the location wrong... --------------- ....something that doesn't support them. It's telling you that 'board' is a function (as opposed to a list or a dict, for example) and functions don't support []. Possibly you're meant to call board: print "\n\t", board(1), "|", board(2), "|", board(3) Or, alternatively, you may have assigned to it by mistake somewhere. --------------- But it took Brett to point out where you needed to apply the parens! Which he did by locating the original source code you had copied. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From iwasroot at gmail.com Tue Mar 10 03:53:14 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Mon, 9 Mar 2009 19:53:14 -0700 Subject: [Tutor] Binary to Decimal conversion In-Reply-To: <49B5B967.6070500@gmail.com> References: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> <49B5B967.6070500@gmail.com> Message-ID: <7b13ba330903091953t73089dd5mb195ffb41e4c169d@mail.gmail.com> You're making it more complicated than it needs to. Also, you first used binnum then binum, and you didn't define binsum. It could easily be done like this: binnum = raw_input("Please enter a binary number: ") decnum = 0 rank = 1 for i in reversed(binnum): decnum += rank * int(i) rank *= 2 Moos From iwasroot at gmail.com Tue Mar 10 05:02:22 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Mon, 9 Mar 2009 21:02:22 -0700 Subject: [Tutor] memory error In-Reply-To: References: Message-ID: <7b13ba330903092102h67fdebbfm4ffeb4b7e4f4beea@mail.gmail.com> On Fri, Mar 6, 2009 at 5:03 PM, Harris, Sarah L wrote: > fname=filter(isfile, glob.glob('*.zip')) > for fname in fname: > zipnames=filter(isfile, glob.glob('*.zip')) > for zipname in zipnames: > ... It looks you're using an unnecessary extra loop. Aren't the contents of fname similar to zipnames? I tried it with one loop (for zipname in zipnames:) and it worked. P.S. You're at jpl? That's awesome! I was looking at internships they have few days ago. From sierra_mtnview at sbcglobal.net Tue Mar 10 05:48:32 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Mar 2009 21:48:32 -0700 Subject: [Tutor] Misunderstanding the Entry Widget In-Reply-To: References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> Message-ID: <49B5F120.7080109@sbcglobal.net> An HTML attachment was scrubbed... URL: From samuelavinash at in.com Tue Mar 10 12:11:28 2009 From: samuelavinash at in.com (Samuel Avinash) Date: Tue, 10 Mar 2009 16:41:28 +0530 Subject: [Tutor] =?utf-8?q?How_to_send_an_email_using_Python?= Message-ID: <1236683488.f96f40bdb8cb393c6e35be1f7464e339@mail.in.com> Hi, Can anybody tell me how to send an email to a recipient using PythonI am trying to send an email using GmailI create an instance of ?smtplib and use :x=smtplib.SMTP(sever,port)?and then?x.login(user,pwd)I try to send the email usingx..sendmail(SENDER, RECIPIENTS, msg)But I get the following errorTraceback (most recent call last):File "C:UsersAvisDesktopMail.py", line 13, in session = smtplib.SMTP(smtpserver,port)File "C:Python26libsmtplib.py", line 239, in init(code, msg) = self.connect(host, port)File "C:Python26libsmtplib.py", line 295, in connectself.sock = self.getsocket(host, port, self.timeout)File "C:Python26libsmtplib.py", line 273, in getsocketreturn socket.createconnection((port, host), timeout)File "C:Python26libsocket.py", line 498, in createconnectionfor res in getaddrinfo(host, port, 0, SOCKSTREAM):socket.gaierror: [Errno 11001] getaddrinfo failedThis is in Windows Vista and I am trying to connect to "smtp.gmail.com" with port 465 -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Mar 10 12:30:54 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 10 Mar 2009 22:30:54 +1100 Subject: [Tutor] Newby Linux Program review + help with regular expressions In-Reply-To: <49B57B52.40303@abbottdavid.com> References: <49B57B52.40303@abbottdavid.com> Message-ID: David wrote: > This program generates a report of a Linux System and some important > ..conf files. The goal is for users to be able to post their information > and compare with others, ask for help etc. Am I using the subrocess > module too much because I am comfortable with the commands? Should I > just write this type of program in bash. I am trying to get rid of all > the comments generated in the report. I got rid of blank lines and lines > starting with #. But can not figure out how the get rid of a line like; > #This is a comment with 5 spaces > I never programed before so everything is new to me. > Here is my code; > http://asterisklinks.com/wiki/doku.php?id=wiki:gentoo_report > The report it generates is at the bottom. I didn't want to post it all > here. > Thanks, > -david > Why are you piping the shell while you ordered the shell to redirect output to a file, then dumping the pipe? def uname_report(): p = subprocess.Popen("uname -a >> /root/gentoo_report.txt", shell=True, stdout=subprocess.PIPE) return p.stdout.readlines() You should choose either one, use the pipe and write to the report file yourself (more flexibility) or use the shell >> redirection. Also, I'd rather not use search and replace if I decided to put the report file somewhere else. PS: for unix-style program, the report should be outputted to the stdout From alan.gauld at btinternet.com Tue Mar 10 12:46:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Mar 2009 11:46:43 -0000 Subject: [Tutor] memory error References: Message-ID: "Harris, Sarah L" wrote fname=filter(isfile, glob.glob('*.zip')) for fname in fname: This will confuse things. fname starts off as a list of files and then becomes a single filename inside the loop. It's never a good idea to duplicate variable names like that. It also means that after the loop completes fname referes only to the last filename, the list has gone. zipnames=filter(isfile, glob.glob('*.zip')) for zipname in zipnames: This is much better. HTH, Alan G. From neven.gorsic at gmail.com Tue Mar 10 13:55:13 2009 From: neven.gorsic at gmail.com (=?ISO-8859-2?B?TmV2ZW4gR29yuWnm?=) Date: Tue, 10 Mar 2009 13:55:13 +0100 Subject: [Tutor] wxPython vs PyQt In-Reply-To: <200903041810.24685.jfabiani@yolo.com> References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> <200903041810.24685.jfabiani@yolo.com> Message-ID: <8acd28da0903100555j68053abbj24928204f7dad937@mail.gmail.com> Thank you all. It was not easy to decide what to learn/use, so I "Google" some more. I have found that PyQT is more stable, faster, more consistent and more expensive :). 400 ? is too much for playing around with some GUI, but GPL licence resolves that issue. The cons are C++ oriented documentation, editor and some structures ... Neven --------------- On Thu, Mar 5, 2009 at 3:10 AM, johnf wrote: > On Wednesday 04 March 2009 04:56:37 pm Alan Gauld wrote: > > "Kent Johnson" wrote > > > > > I've heard good things about Dabo, never tried it myself though. > > > http://dabodev.com/ > > > > I looked at Dabo but decided not to try it since it was yet another > > framework. Although it's based on wxPython they have layered their > > own widgets on top which is what the GUI Builder uses. (PythonCard > > fell into the same hole) > > Yes, it's true that Dabo has wrapped (subclassed) most of the controls. The > purpose of course was to provide developer ease of use. If you are > building > a real business app then I doubt there is anything better in the python > world. I personally have used both VB and Delphi and see Dabo on the same > level. With one exception - we have a beta GUI builder. Everything that > has > been done in Dabo is the very same things that all developers would be > required to do if they access a database and associate fields to controls. > BTW there is nothing stopping a Dabo developer from directly using wx > controls. Dabo prevents nothing. > > So Alan, I don't see my work as falling into any hole. > > > > But the web pages and writeup looked good and the forum seemed > > to be active and not all negative. > > > > Alan G > > > > > -- > John Fabiani > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sarah.l.harris at jpl.nasa.gov Tue Mar 10 16:45:01 2009 From: sarah.l.harris at jpl.nasa.gov (Harris, Sarah L) Date: Tue, 10 Mar 2009 08:45:01 -0700 Subject: [Tutor] memory error files over 100MB Message-ID: That looks better, thank you. However I still have a memory error when I try to run it on three or more files that are over 100 MB? import zipfile, glob, os from os.path import isfile zipnames=filter(isfile, glob.glob('*.zip')) for zipname in zipnames: zf=zipfile.ZipFile(zipname, 'r') for zfilename in zf.namelist(): newFile=open(zfilename, 'wb') newFile.write(zf.read(zfilename)) newFile.close() zf.close() ________________________________________ From: Moos Heintzen [iwasroot at gmail.com] Sent: Monday, March 09, 2009 9:02 PM To: Harris, Sarah L Cc: tutor at python.org Subject: Re: [Tutor] memory error On Fri, Mar 6, 2009 at 5:03 PM, Harris, Sarah L wrote: > fname=filter(isfile, glob.glob('*.zip')) > for fname in fname: > zipnames=filter(isfile, glob.glob('*.zip')) > for zipname in zipnames: > ... It looks you're using an unnecessary extra loop. Aren't the contents of fname similar to zipnames? I tried it with one loop (for zipname in zipnames:) and it worked. P.S. You're at jpl? That's awesome! I was looking at internships they have few days ago. From ctcast at gmail.com Tue Mar 10 16:51:49 2009 From: ctcast at gmail.com (Chris Castillo) Date: Tue, 10 Mar 2009 11:51:49 -0400 Subject: [Tutor] Binary to Decimal conversion In-Reply-To: <7b13ba330903091953t73089dd5mb195ffb41e4c169d@mail.gmail.com> References: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> <49B5B967.6070500@gmail.com> <7b13ba330903091953t73089dd5mb195ffb41e4c169d@mail.gmail.com> Message-ID: <50e459210903100851lec8a8bfkeab0a929052f1965@mail.gmail.com> Thanks for clearing that up. I knew it was much simpler than I was trying to make it I just couldn't quite see the logic that I needed for the problem clearly. Thanks for the elegant code. On Mon, Mar 9, 2009 at 10:53 PM, Moos Heintzen wrote: > You're making it more complicated than it needs to. > Also, you first used binnum then binum, and you didn't define binsum. > > It could easily be done like this: > > binnum = raw_input("Please enter a binary number: ") > decnum = 0 > rank = 1 > > for i in reversed(binnum): > decnum += rank * int(i) > rank *= 2 > > Moos > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Tue Mar 10 17:01:53 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 10 Mar 2009 17:01:53 +0100 Subject: [Tutor] Binary to Decimal conversion In-Reply-To: <50e459210903100851lec8a8bfkeab0a929052f1965@mail.gmail.com> References: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> <49B5B967.6070500@gmail.com> <7b13ba330903091953t73089dd5mb195ffb41e4c169d@mail.gmail.com> <50e459210903100851lec8a8bfkeab0a929052f1965@mail.gmail.com> Message-ID: <49B68EF1.9050204@tue.nl> Hello, Chris Castillo wrote: > Thanks for clearing that up. I knew it was much simpler than I was trying to > make it I just couldn't quite see the logic that I needed for the problem > clearly. Thanks for the elegant code. > > On Mon, Mar 9, 2009 at 10:53 PM, Moos Heintzen wrote: >> >> binnum = raw_input("Please enter a binary number: ") >> decnum = 0 >> rank = 1 >> >> for i in reversed(binnum): >> decnum += rank * int(i) >> rank *= 2 If you reverse the computation, it gets even simpler: binstr = raw_input("Please enter a binary number: ") decnum = 0 for i in binstr: decnum = decnum * 2 + int(i) print decnum If you want to preserve the binary spirit of the conversion, you should of course do for i in binstr: decnum = (decnum << 1) | int(i) instead. Sincerely, Albert From iwasroot at gmail.com Tue Mar 10 20:33:16 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Tue, 10 Mar 2009 12:33:16 -0700 Subject: [Tutor] memory error files over 100MB In-Reply-To: References: Message-ID: <7b13ba330903101233u2d9eb958o331d0c38d6458945@mail.gmail.com> On Tue, Mar 10, 2009 at 8:45 AM, Harris, Sarah L wrote: > That looks better, thank you. > However I still have a memory error when I try to run it on three or more files that are over 100 MB? How big are files in the zip file? It seems that in this line newFile.write(zf.read(zfilename)) the compressed file is unzipped to memory first, then written to the new file. You can read and write in smaller chunks using file objects returned by zf.open(), which take a size parameter. (Maybe it wouldn't work since the file is going to get extracted to memory anyway.) However, the open() method is in Python 2.6, and in Python 2.6 there is also the extractall() method http://docs.python.org/library/zipfile.html#zipfile.ZipFile.extractall which does what you're doing. I'm not sure if it will still cause a memory error. Also, are files in your zip files not in directories, since you're not creating directories? Since this is a learning experience, it might also help creating functions to minimize clutter, or you could familiarize yourself with the language. Moos From sierra_mtnview at sbcglobal.net Tue Mar 10 20:48:02 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 10 Mar 2009 12:48:02 -0700 Subject: [Tutor] Misunderstanding the Entry Widget (Closed) In-Reply-To: <49B5F120.7080109@sbcglobal.net> References: <49B09E13.7080402@sbcglobal.net> <49B113D0.60005@sbcglobal.net><1c2a2c590903060500j693195efm84bdecb636f7b29b@mail.gmail.com> <49B14EB7.4050504@sbcglobal.net> <49B3477E.50900@sbcglobal.net> <49B34F86.70003@sbcglobal.net> <49B5F120.7080109@sbcglobal.net> Message-ID: <49B6C3F2.60204@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 10 22:32:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Mar 2009 21:32:13 -0000 Subject: [Tutor] Binary to Decimal conversion References: <50e459210903091725n7e9d1574w9bda770634c4c91c@mail.gmail.com> <49B5B967.6070500@gmail.com> <7b13ba330903091953t73089dd5mb195ffb41e4c169d@mail.gmail.com><50e459210903100851lec8a8bfkeab0a929052f1965@mail.gmail.com> <49B68EF1.9050204@tue.nl> Message-ID: "A.T.Hofkamp" wrote > If you reverse the computation, it gets even simpler: > > binstr = raw_input("Please enter a binary number: ") > decnum = 0 > > for i in binstr: > decnum = decnum * 2 + int(i) > But if we are allowed to use int() it is easier still: decnum = int(raw_input("Please enter a binary number"), 2) Since int() now converts binary strings to decimal... :-) Alan G. From alan.gauld at btinternet.com Tue Mar 10 22:41:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Mar 2009 21:41:13 -0000 Subject: [Tutor] memory error files over 100MB References: Message-ID: "Harris, Sarah L" wrote > However I still have a memory error when I try to run it on three > or more files that are over 100 MB? And this surprises you? :-) How much memory do you have free on your computer when you run this? > newFile.write(zf.read(zfilename)) Remember you are reading the file into memory and then writing it out again in a single operation, that will use twice the space of the uncompressed files - plus some extra for overhead. Also is the 100M the zipped size? That means the uncompressed data could well be over 500M for text or spreadsheets, or bitmaps etc So you would need potentially over 1GB RAM minimum. If you are running anything else at the same time probably several GB would be safer. Have you tried watching this with Taskmanager or top? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sander.sweers at gmail.com Wed Mar 11 00:10:53 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 11 Mar 2009 00:10:53 +0100 Subject: [Tutor] memory error files over 100MB In-Reply-To: References: Message-ID: 2009/3/10 Alan Gauld : >> ? ? ? ? ? newFile.write(zf.read(zfilename)) > > Remember you are reading the file into memory and then writing it > out again in a single operation, that will use twice the space of the > uncompressed files - plus some extra for overhead. Question, Do you mean the file in the zipfile (zfilename) or the whole zipfile (zf)? I would expect zf.read(zfilename) to only read the requested file in the zipfile. Thanks Sander From alan.gauld at btinternet.com Wed Mar 11 02:20:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Mar 2009 01:20:58 -0000 Subject: [Tutor] memory error files over 100MB References: Message-ID: "Sander Sweers" wrote >> out again in a single operation, that will use twice the space of >> the >> uncompressed files - plus some extra for overhead. > > Question, Do you mean the file in the zipfile (zfilename) or the > whole > zipfile (zf)? I would expect zf.read(zfilename) to only read the > requested file in the zipfile. That's a dangerous assumption. You might be right but I'd want to do some tests first to see. But if even one zipped file was big the same would apply. Alan G. From lie.1296 at gmail.com Wed Mar 11 02:26:16 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 11 Mar 2009 12:26:16 +1100 Subject: [Tutor] memory error files over 100MB In-Reply-To: References: Message-ID: Sander Sweers wrote: > 2009/3/10 Alan Gauld : >>> newFile.write(zf.read(zfilename)) >> Remember you are reading the file into memory and then writing it >> out again in a single operation, that will use twice the space of the >> uncompressed files - plus some extra for overhead. > > Question, Do you mean the file in the zipfile (zfilename) or the whole > zipfile (zf)? I would expect zf.read(zfilename) to only read the > requested file in the zipfile. I've never used zipfile extensively, but I think it depends on the archive and the compression algorithm. Solid archive (multiple files compressed as a single big file) may need to be fully extracted, except if the algorithm can somehow figure out a way of extracting a single file from a solid archive without extracting everything first. From emadnawfal at gmail.com Wed Mar 11 02:44:30 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 10 Mar 2009 21:44:30 -0400 Subject: [Tutor] How can I extract a specific sublist from a nested list? Message-ID: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> Hi Tutors, How can I extract a specific sublist (??) from a nested list, for example, if I want to extract the sublist ["ADJ", "good"], or the bigger sublist ["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]] from the following nested list? nested_list = ["S",["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]], ["VP", ["V", "came"]]] -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc at marcd.org Wed Mar 11 00:02:21 2009 From: marc at marcd.org (marc at marcd.org) Date: Tue, 10 Mar 2009 19:02:21 -0400 (EDT) Subject: [Tutor] Issues Parsing XML In-Reply-To: References: Message-ID: <49277.64.252.205.230.1236726141.squirrel@webmail1.hrnoc.net> Hello, I am new to Python and as a first project decided to try to parse an XML report using Python. I have the following, which works to extract one element. I am stuck, however, at one element. I want to extract several differenct elements per line, creating a comma separated variable (CSV) line that can be imported to a spreadsheet. Not all elements are in each line or part of the XML document - so if an element is not in a line, I would leave a blank (2 commas). I can probably figure that out - it's the extracting multiple elements and putting them in one line that has me stumped. Help would be greatly appreciated. Thank you. What I have so far (and I would like to stick to the DOM model): import xml.dom.minidom import sys datasource=open(sys.argv[1]) domDatasource=xml.dom.minidom.parse(datasource) def getText(nodelist): rc="" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc=rc+node.data return rc def HandleStatus(Finding): for Status in Finding: print getText(Status.childNodes) HandleStatus (domDatasource.getElementsByTagName("FINDING_STATUS")) domDatasource.unlink() An excerpt of the xml file: GD2.0.8.8TRUEDTBI134-Allow paste operations via scripts-Restric2V0006310NFGD2.0.8.8TRUEDTBI135-Scripting of Java applets - Restricted2V0006311OThe value: Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\1A00 does not exist. The value: Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\1A00 does not exist. GD2.0.8.8TRUEDTBI136-User Authentication - Logon - Restricted2V0006312NFGD2.0.8.8TRUEDTBI150-Microsoft Java VM is installed2V0006313NFGD2.0.8.8TRUEDTBI151-Cipher setting for DES 56/56 not set2V0006314NFGD2.0.8.8TRUEDTBI152-Cipher setting for Null is not set2V0006315NFGD2.0.8.8TRUEDTBI153-Cipher setting for Triple DES is not set2V0006316OThe value: SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes\SHA\Enabled does not exist. The value: SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes\SHA\Enabled does not exist. GD2.0.8.8TRUEDTBI160-Hash setting for SHA is not set properly2V0006317NFGD2.0.8.8TRUEDTBG007-IE is not capable to use 128-bit encryptio2V0006318OThe key: SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\10F193F340AC91D6DE5F1EDC006247C4F25D9671 does not exist. The key: SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\10F193F340AC91D6DE5F1EDC006247C4F25D9671 does not exist. GD2.0.8.8TRUEDTBG010-DoD Root Certificate is not installed2V0006319NAGD2.0.8.8TRUEDTBI140-Error Reporting tool is installed or enabl2V0007006OThe value: Software\Microsoft\Internet Explorer\Main\AutoSearch does not exist. The value: Software\Microsoft\Internet Explorer\Main\AutoSearch does not exist. From orsenthil at gmail.com Wed Mar 11 05:28:53 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Wed, 11 Mar 2009 09:58:53 +0530 Subject: [Tutor] How to send an email using Python In-Reply-To: <1236683488.f96f40bdb8cb393c6e35be1f7464e339@mail.in.com> References: <1236683488.f96f40bdb8cb393c6e35be1f7464e339@mail.in.com> Message-ID: <7c42eba10903102128t17d6a054obca73acb12b43699@mail.gmail.com> Hello Samuel, When sending through smtp.gmail.com you might need to starttls() and do a login() before sending. >>> import smtplib >>> headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" %(from,to,subject) >>> message = headers + "Hello, How are you?" >>> mailserver = smtplib.SMTP('smtp.gmail.com') >>> mailserver.ehlo() >>> mailserver.starttls() >>> mailserver.login('username','password') >>> mailserver.sendmail(from,to,message) As I try it now, startls() was giving me a message " reply: '454 TLS not available due to temporary reason\r\n'" - As the error message says, it could be temporary. Try it at your end and report if you succeed. Thanks, Senthil On Tue, Mar 10, 2009 at 4:41 PM, Samuel Avinash wrote: > Hi, > Can anybody tell me how to send an email to a recipient using Python > I am trying to send an email using Gmail > I create an instance of ?smtplib and use : > x=smtplib.SMTP(sever,port) > and then > x.login(user,pwd) > I try to send the email using > x..sendmail(SENDER, RECIPIENTS, msg) > But I get the following error > Traceback (most recent call last): > File "C:UsersAvisDesktopMail.py", line 13, in > session = smtplib.SMTP(smtpserver,port) > File "C:Python26libsmtplib.py", line 239, in __init__ > (code, msg) = self.connect(host, port) > File "C:Python26libsmtplib.py", line 295, in connect > self.sock = self._get_socket(host, port, self.timeout) > File "C:Python26libsmtplib.py", line 273, in _get_socket > return socket.create_connection((port, host), timeout) > File "C:Python26libsocket.py", line 498, in create_connection > for res in getaddrinfo(host, port, 0, SOCK_STREAM): > socket.gaierror: [Errno 11001] getaddrinfo failed > > This is in Windows Vista and I am trying to connect to "smtp.gmail.com" with > port 465 > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- Senthil From stefan at lsd.co.za Wed Mar 11 07:42:45 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Wed, 11 Mar 2009 08:42:45 +0200 Subject: [Tutor] How to send an email using Python In-Reply-To: <7c42eba10903102128t17d6a054obca73acb12b43699@mail.gmail.com> References: <1236683488.f96f40bdb8cb393c6e35be1f7464e339@mail.in.com> <7c42eba10903102128t17d6a054obca73acb12b43699@mail.gmail.com> Message-ID: <5cb309e70903102342l7fcd1b58n3013ee13ce54c661@mail.gmail.com> Hi. I use the following to send through gmail. message = headers + text mailserver = smtplib.SMTP('smtp.gmail.com') if debug == 1: mailserver.set_debuglevel(1) mailserver.ehlo() mailserver.starttls() mailserver.ehlo() #Define username / password if using SMTP Auth username = 'email at gmail.com' password = getpass.getpass("%s's password: " % username) mailserver.login(username,password) mailserver.sendmail(sender, to, message) mailserver.close() I believe for gmail smtp you need the ehlo() and then the starttls() and then another ehlo(). My first post, been lurking a while. :) On Wed, Mar 11, 2009 at 6:28 AM, Senthil Kumaran wrote: > Hello Samuel, > > When sending through smtp.gmail.com you might need to starttls() and > do a login() before sending. > >>>> import smtplib >>>> headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" %(from,to,subject) >>>> message = headers + "Hello, How are you?" >>>> mailserver = smtplib.SMTP('smtp.gmail.com') >>>> mailserver.ehlo() >>>> mailserver.starttls() >>>> mailserver.login('username','password') >>>> mailserver.sendmail(from,to,message) > > As I try it now, startls() was giving me a message " reply: '454 TLS > not available due to temporary reason\r\n'" > - As the error message says, it could be temporary. > > Try it at your end and report if you succeed. > > Thanks, > Senthil > > On Tue, Mar 10, 2009 at 4:41 PM, Samuel Avinash wrote: >> Hi, >> Can anybody tell me how to send an email to a recipient using Python >> I am trying to send an email using Gmail >> I create an instance of ?smtplib and use : >> x=smtplib.SMTP(sever,port) >> and then >> x.login(user,pwd) >> I try to send the email using >> x..sendmail(SENDER, RECIPIENTS, msg) >> But I get the following error >> Traceback (most recent call last): >> File "C:UsersAvisDesktopMail.py", line 13, in >> session = smtplib.SMTP(smtpserver,port) >> File "C:Python26libsmtplib.py", line 239, in __init__ >> (code, msg) = self.connect(host, port) >> File "C:Python26libsmtplib.py", line 295, in connect >> self.sock = self._get_socket(host, port, self.timeout) >> File "C:Python26libsmtplib.py", line 273, in _get_socket >> return socket.create_connection((port, host), timeout) >> File "C:Python26libsocket.py", line 498, in create_connection >> for res in getaddrinfo(host, port, 0, SOCK_STREAM): >> socket.gaierror: [Errno 11001] getaddrinfo failed >> >> This is in Windows Vista and I am trying to connect to "smtp.gmail.com" with >> port 465 >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > -- > -- > Senthil > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lie.1296 at gmail.com Wed Mar 11 08:41:48 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 11 Mar 2009 18:41:48 +1100 Subject: [Tutor] How can I extract a specific sublist from a nested list? In-Reply-To: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> References: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> Message-ID: Emad Nawfal (???? ????) wrote: > Hi Tutors, > How can I extract a specific sublist (??) from a nested list, for > example, The same as the way you extract other objects from non-nested list > if I want to extract the sublist ["ADJ", "good"], nested_list[1][2] > or the bigger > sublist ["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]] nested_list[1] From srivatsav.prasanna at gmail.com Wed Mar 11 08:51:50 2009 From: srivatsav.prasanna at gmail.com (prasanna) Date: Wed, 11 Mar 2009 13:21:50 +0530 Subject: [Tutor] How can I extract a specific sublist from a nested list? In-Reply-To: References: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> Message-ID: Just a suggestion: It would be better if you turn this list into a dictionary. I presume you want to know the "adjective" or "noun" of the sentence. To do that, it would be easier if you had a dictionary. You can do this as: >> dict(nested_sublist[1]) {'ADJ': 'good', 'DET': 'The', 'NOUN': 'man'} 2009/3/11 Lie Ryan : > Emad Nawfal (???? ????) wrote: >> >> Hi Tutors, >> How can I extract a specific sublist (??) from a nested list, for example, > > The same as the way you extract other objects from non-nested list > >> if I want to extract the sublist ["ADJ", "good"], > > nested_list[1][2] > >> or the bigger sublist ?["NP",["DET", "The"],["ADJ", "good"],["NOUN", >> "man"]] > > nested_list[1] > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Prasanna., From alan.gauld at btinternet.com Wed Mar 11 10:44:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Mar 2009 09:44:34 -0000 Subject: [Tutor] How can I extract a specific sublist from a nested list? References: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> Message-ID: "Emad Nawfal (???? ????)" wrote > How can I extract a specific sublist (??) from a nested list, Just extract eaach item using indexing. So first extract the sublist, then from the sublist extract the item. > if I want to extract the sublist ["ADJ", "good"], or the bigger > sublist > ["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]] from the > following > nested list? Look at the structure of your list: nested_list = [ "S", <--- 0 [ "NP", <--------- 1,0 [ "DET", "The" ], <-------1,1,0 / 1,1,1 [ "ADJ", "good" ], <-------1,2,0 / 1,2,1 [ "NOUN", "man" ] <-------1,3,0 / 1,3,1 ], [ "VP", <-------2,0 [ "V", "came" ] <-------2,1,0 / 2,1,1 ] ] So to extract ['ADJ','good'] we use nested_llist[1][2] and to extract the lionger list nested_list[1] and to extract the word 'good' nested_list[1][2][1] HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emadnawfal at gmail.com Wed Mar 11 11:44:02 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Wed, 11 Mar 2009 06:44:02 -0400 Subject: [Tutor] How can I extract a specific sublist from a nested list? In-Reply-To: References: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> Message-ID: <652641e90903110344s3ebcd026re56587ca93742360@mail.gmail.com> 2009/3/11 Alan Gauld > "Emad Nawfal (???? ????)" wrote > >> How can I extract a specific sublist (??) from a nested list, >> > > Just extract eaach item using indexing. So first extract the sublist, > then from the sublist extract the item. > > if I want to extract the sublist ["ADJ", "good"], or the bigger sublist >> ["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]] from the following >> nested list? >> > > Look at the structure of your list: > > nested_list = [ "S", <--- 0 > [ "NP", <--------- 1,0 > [ "DET", "The" ], <-------1,1,0 / 1,1,1 > [ "ADJ", "good" ], <-------1,2,0 / 1,2,1 > [ "NOUN", "man" ] <-------1,3,0 / 1,3,1 > ], > [ "VP", <-------2,0 > [ "V", "came" ] <-------2,1,0 / 2,1,1 > ] > ] > So to extract ['ADJ','good'] we use nested_llist[1][2] > and to extract the lionger list nested_list[1] > and to extract the word 'good' nested_list[1][2][1] > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Now I know that I did not ask the right question. What I meant was: how to extract a sublist from a list whose length is unknown. Let's say I have a hundred of these lists and each of these has an NP somewhere, it could be nested in nested list, which is turn nested in another one and so on. The bottom line is that I do not know the index. To make things more concrete, this is a representative list. How can I extract all the sublists beginning with "NP" from it? nested_list2 = [['SBAR-TMP', ['WHADVP-4', ['SUB_CONJ', 'EndmA']], ['S', ['VP', ['PV+PVSUFF_SUBJ:3FS', 'Evrt'], ['PP-CLR', ['PREP', 'Ely'], ['NP', ['PRON_3MS', 'h']]], ['NP-SBJ', ['NOUN+NSUFF_FEM_SG+CASE_DEF_NOM', '$qyqt'], ['POSS_PRON_3MS', 'h']], ['PP-TMP', ['PREP', 'bEd'], ['NP', ['NOUN+CASE_INDEF_GEN', "EnA'"], ['ADJ+CASE_INDEF_GEN', 'Twyl']]], ['SBAR-PRP', ['SUB_CONJ', 'l'], ['S', ['VP', ['IV3FS+IV+IVSUFF_MOOD:S', 'tblg'], ['NP-SBJ', ['-NONE-', '*']], ['NP-OBJ', ['IVSUFF_DO:3MS', 'h']], ['SBAR', ['SBAR', ['PREP', 'b'], ['SUB_CONJ', '>n'], ['S', ['NP-TPC-2', ['PRON_3MS', 'h']], ['VP', ['PV+PVSUFF_SUBJ:3MS', 'wrv'], ['NP-SBJ-2', ['-NONE-', '*T*']], ['NP-OBJ', ['QP', ['NUM', '300'], ['NUM+CASE_DEF_ACC', 'Alf']], ['NOUN+CASE_INDEF_GEN', 'dwlAr']]]]], ['CONJ', 'w'], ['SBAR', ['PREP', 'b'], ['SUB_CONJ', '>n'], ['S', ['NP-TPC-3', ['PRON_3MS', 'h']], ['VP', ['PV+PVSUFF_SUBJ:3MS', 'bAt'], ['NP-SBJ-3', ['-NONE-', '*T*']], ['ADJP-PRD', ['ADJ+CASE_INDEF_ACC', 'qAdrA'], ['PP', ['PREP', 'ElY'], ['NP', ['NOUN+CASE_DEF_GEN', 'wDE'], ['NP', ['NP', ['NOUN+CASE_INDEF_GEN', 'Hd']], ['PP', ['PREP', 'l'], ['NP', ['NP', ['NUM+NSUFF_MASC_PL_GEN', 'E$ryn'], ['NOUN+NSUFF_FEM_SG+CASE_INDEF_ACC', 'snp']], ['PP', ['PREP', 'mn'], ['NP', ['NOUN+NSUFF_FEM_SG+CASE_DEF_GEN', 'HyAp'], ['NP', ['NP', ['DET+NOUN+CASE_DEF_GEN', 'Alt$rd']], ['PP-LOC', ['PREP', 'fy'], ['NP', ['NOUN+CASE_DEF_GEN', '$wArE'], ['NP', ['NP', ['NOUN+NSUFF_FEM_SG+CASE_DEF_GEN', 'mdynp'], ['NP', ['NOUN_PROP', 'lwng'], ['NOUN_PROP', 'byt$']]], ['PP-LOC', ['PREP', 'fy'], ['NP', ['NOUN+NSUFF_FEM_SG+CASE_DEF_GEN', 'wlAyp'], ['NP', ['NOUN_PROP', 'kAlyfwrnyA']]]]]]]]]]]]]]]]]]]]]]], ['ADVP-TMP-4', ['-NONE-', '*T*']]]]]] -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Wed Mar 11 12:47:52 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 11 Mar 2009 12:47:52 +0100 Subject: [Tutor] How can I extract a specific sublist from a nested list? In-Reply-To: <652641e90903110344s3ebcd026re56587ca93742360@mail.gmail.com> References: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> <652641e90903110344s3ebcd026re56587ca93742360@mail.gmail.com> Message-ID: <6faf39c90903110447q26da7c72hc2ec532ad633efe8@mail.gmail.com> 2009/3/11 Emad Nawfal (???? ????) : > Now I know that I did not ask the right question. What I meant was: how to > extract a sublist from a list whose length is unknown. Let's say I have a > hundred of these lists and each of these has an NP somewhere, it could be > nested in nested list, which is turn nested in another one and so on. The > bottom line is that I do not know the index.? To make things more concrete, > this is a representative list. How can I extract all the sublists beginning > with "NP" from it? You'll have to do recursion - that is: NPstart(alist) = if alist starts with "NP": alist + NPstart for all sublists of alist else: NPstart for all sublists of alist Turning that into Python we get: def NPstart(alist): if isinstance(alist, basestring): # It's ugly to do an isinstance in Python, but any better method would be fully changing your data structure, so I use it for now return [] else: if alist[0] == 'NP': return [alist] + [NPstart(sublist) for sublist in alist] else: return [NPstart(sublist) for sublist in alist] -- Andr? Engels, andreengels at gmail.com From samuelavinash at in.com Wed Mar 11 13:22:06 2009 From: samuelavinash at in.com (Samuel Avinash) Date: Wed, 11 Mar 2009 17:52:06 +0530 Subject: [Tutor] =?utf-8?q?Tutor_Digest=2C_Vol_61=2C_Issue_42?= Message-ID: <1236774126.575425a3f433138553be468c9d1ecba7@mail.in.com> Reply to Message 3 :?How can I extract a specific sublist from a nested?list?Comments Inline Original message From:tutorrequest at python.org< tutorrequest at python.org >Date: 11 Mar 09 12:12:51Subject:Tutor Digest, Vol 61, Issue 42To: tutor at python.orgSend Tutor mailing list submissions to tutor at python.orgTo subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutorrequest at python.orgYou can reach the person managing the list at tutorowner at python.orgWhen replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: memory error files over 100MB (Alan Gauld)2. Re: memory error files over 100MB (Lie Ryan)3. How can I extract a specific sublist from a nested list? (Emad Nawfal (???? ????))4. Issues Parsing XML (marc at marcd.org)5. Re: How to send an email using Python (Senthil Kumaran)6. Re: How to send an email us ing Python (Stefan Lesicnik) Message: 1 Date: Wed, 11 Mar 2009 01:20:58 0000 From: "Alan Gauld"Subject: Re: [Tutor] memory error files over 100MB To: tutor at python.org MessageID:ContentType: text/plain; format=flowed; charset="utf8"; replytype=original "Sander Sweers"wrote>> out again in a single operation, that will use twice the space of>> the >> uncompressed files plus some extra for overhead. > > Question, Do you mean the file in the zipfile (zfilename) or the> whole > zipfile (zf)? I would expect zf.read(zfilename) to only read the > requested file in the zipfile.That's a dangerous assumption. You might be right but I'd want to do some tests first to see. But if even one zipped file was big the same would apply.Alan G.Message: 2 Date: Wed, 11 Mar 2009 12:26:16 +1100 From: Lie RyanSubject: Re: [Tutor] memory error files over 100MB To: tutor at python.org MessageID:ContentType: text/plain; charset=UTF8; format=flowedSander Sweers wrote: > 2009/3/10 Alan Gauld : >>> newFile.w rite(zf.read(zfilename)) >> Remember you are reading the file into memory and then writing it >> out again in a single operation, that will use twice the space of the >> uncompressed files plus some extra for overhead. >> Question, Do you mean the file in the zipfile (zfilename) or the whole > zipfile (zf)? I would expect zf.read(zfilename) to only read the > requested file in the zipfile.I've never used zipfile extensively, but I think it depends on thearchive and the compression algorithm. Solid archive (multiple filescompressed as a single big file) may need to be fully extracted, exceptif the algorithm can somehow figure out a way of extracting a singlefile from a solid archive without extracting everything first.Message: 3 Date: Tue, 10 Mar 2009 21:44:30 0400 From: Emad Nawfal (???? ????)Subject: [Tutor] How can I extract a specific sublist from a nested list? To: tutorMessageID:ContentType: text/plain; charset="windows1256"Hi Tutors, How can I extract a specific subli st (??) from a nested list, for example, if I want to extract the sublist ["ADJ", "good"], or the bigger sublist ["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]] from the following nested list?nestedlist = ["S",["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]], ["VP", ["V", "came"]]]?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ???????>>> x=nestedlist[1]>>> x['NP', ['DET', 'The'], ['ADJ', 'good'], ['NOUN', 'man']]>>> x[2]['ADJ', 'good']>>>? "No victim has ever been more repressed and alienated than the truth"Emad Soliman Nawfal Indiana University, Bloomington next part An HTML attachment was scrubbed... URL: Message: 4 Date: Tue, 10 Mar 2009 19:02:21 0400 (EDT) From: marc at marcd.org Subject: [Tutor] Issues Parsing XML To: tutor at python.org MessageID:ContentType: text/plain;charset=iso88591Hello,I am new to Python and as a first project decided to try to parse an XML report using Python.I have the following, which works to extract one ele ment.I am stuck, however, at one element.I want to extract several differenct elements per line, creating a comma separated variable (CSV) line that can be imported to a spreadsheet.Not all elements are in each line or part of the XML document so if an element is not in a line, I would leave a blank (2 commas).I can probably figure that out it's the extracting multiple elements and putting them in one line that has me stumped.Help would be greatly appreciated.Thank you.What I have so far (and I would like to stick to the DOM model):import xml.dom.minidom import sys datasource=open(sys.argv[1]) domDatasource=xml.dom.minidom.parse(datasource)def getText(nodelist): rc="" for node in nodelist: if node.nodeType == node.TEXTNODE: rc=rc+node.data return rcdef HandleStatus(Finding): for Status in Finding: print getText(Status.childNodes)HandleStatus (domDatasource.getElementsByTagName("FINDINGSTATUS"))domDatasource.unlink()An excerpt of the xml file:GD2.0.8.8TRUEDTBI134Allow paste operations via scriptsRestric2 TYPE="VK">V0006310NFGD2.0.8.8TRUEDTBI135Scripting of Java applets Restricted2 TYPE="VK">V0006311O OVERRIDE="O">The value: Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\1A00 does not exist.The value: Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\1A00 does not exist.GD2.0.8.8TRUEDTBI136User Authentication Logon Restricted2 TYPE="VK">V0006312NFGD2.0.8.8TRUEDTBI150Microsoft Java VM is installed2 TYPE="VK">V0006313NFGD2.0.8.8TRUEDTBI151Cipher setting for DES 56/56 not set2 TYPE="VK">V0006314NFGD2.0.8.8TRUEDTBI152Cipher setting for Null is not set2 TYPE="VK">V0006315NFGD2.0.8.8TRUEDTBI153Cipher setting for Triple DES is not set2 TYPE="VK">V0006316O OVERRIDE="O">The value: SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes\SHA\Enabled does not exist.The value: SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes\SHA\Enabled does not exist.GD2.0.8.8TRUEDTBI1 60Hash setting for SHA is not set properly2 TYPE="VK">V0006317NFGD2.0.8.8TRUEDTBG007IE is not capable to use 128bit encryptio2 TYPE="VK">V0006318O OVERRIDE="O">The key: SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\10F193F340AC91D6DE5F1EDC006247C4F25D9671 does not exist.The key: SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\10F193F340AC91D6DE5F1EDC006247C4F25D9671 does not exist.GD2.0.8.8TRUEDTBG010DoD Root Certificate is not installed2 TYPE="VK">V0006319NAGD2.0.8.8TRUEDTBI140Error Reporting tool is installed or enabl2 TYPE="VK">V0007006O OVERRIDE="O">The value: Software\Microsoft\Internet Explorer\Main\AutoSearch does not exist.The value: Software\Microsoft\Internet Explorer\Main\AutoSearch does not exist.Message: 5 Date: Wed, 11 Mar 2009 09:58:53 +0530 From: Senthil KumaranSubject: Re: [Tutor] How to send an email using Python To: Samuel AvinashCc: tutorMessageID:ContentType: text/plain; charset=UTF8Hello Samuel,When sending through smtp.gmail.com you m ight need to starttls() and do a login() before sending.>>> import smtplib >>> headers = "From: %s\r To: %s\r Subject: %s\r \r " %(from,to,subject) >>> message = headers + "Hello, How are you?" >>> mailserver = smtplib.SMTP('smtp.gmail.com') >>> mailserver.ehlo() >>> mailserver.starttls() >>> mailserver.login('username','password') >>> mailserver.sendmail(from,to,message)As I try it now, startls() was giving me a message " reply: '454 TLS not available due to temporary reason\r '" As the error message says, it could be temporary.Try it at your end and report if you succeed.Thanks, SenthilOn Tue, Mar 10, 2009 at 4:41 PM, Samuel Avinashwrote: > Hi, > Can anybody tell me how to send an email to a recipient using Python > I am trying to send an email using Gmail > I create an instance of ?smtplib and use : > x=smtplib.SMTP(sever,port) > and then > x.login(user,pwd) > I try to send the email using > x..sendmail(SENDER, RECIPIENTS, msg) > But I get the following error > Traceback (most recent call last): > File "C:UsersAvisDesktopMail.py", line 13, in> session = smtplib.SMTP(smtpserver,port) > File "C:Python26libsmtplib.py", line 239, in init > (code, msg) = self.connect(host, port) > File "C:Python26libsmtplib.py", line 295, in connect > self.sock = self.getsocket(host, port, self.timeout) > File "C:Python26libsmtplib.py", line 273, in getsocket > return socket.createconnection((port, host), timeout) > File "C:Python26libsocket.py", line 498, in createc onnection > for res in getaddrinfo(host, port, 0, SOCKSTREAM): > socket.gaierror: [Errno 11001] getaddrinfo failed > > This is in Windows Vista and I am trying to connect to "smtp.gmail.com" with > port 465 > > Tutor maillist ? ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > >Senthil Message: 6 Date: Wed, 11 Mar 2009 08:42:45 +0200 From: Stefan LesicnikSubject: Re: [Tutor] How to send an email using Python To: Senthil KumaranCc: Samuel Avinash , tutorMessageID:ContentType: text/plain; charset=ISO88591Hi.I use the following to send through gmail. message = headers + text mailserver = smtplib.SMTP('smtp.gmail.com') if debug == 1: mailserver.setdebuglevel(1) mailserver.ehlo() mailserver.starttls() mailserver.ehlo()#Define username / password if using SMTP Auth username = 'email at gmail.com' password = getpass.getpass("%s's password: " % username)mailserver.login(username,password) mailserver.sendmail(sender, to, message) mailserver.close() I believe for gmail smtp you need the ehlo() and then the starttls() and then another ehlo(). My first post, been lurking a while.:) On Wed, Mar 11, 2009 at 6:28 AM, Senthil Kumaranwrote: > Hello Samuel, > > When sending through smtp.gmail.com you might need to starttls() and > do a login() before sending. > >>>> import smtplib >>>> headers = "From: %s\r To: %s\r Subject: %s\r \r " %(from,to,subject) >>>> message = headers + "Hello, How are you?" >>>> mailserver = smtplib.SMTP('smtp.gmail.com') >>>> mailserver.ehlo() >>>> mailserver.starttls() >>>> mailserver.login('username','password') >>>> mailserver.sendmail(from,to,message) > > As I try it now, startls() was giving me a message " reply: '454 TLS > not available due to temporary reason\r '" > As the error message says, it could be temporary. > > Try it at your end and report if you succeed. > > Thanks, > Senthil > > On Tue, Mar 10, 2009 at 4:41 PM, Samuel Avinashwrote: >> Hi, >> Can anybody tell me how to send an email to a recipient using Python >> I am trying to send an email using Gmail >> I create an instance of ?smtplib and use : >> x=smtplib.SMTP(sever,port) >> and then >> x.login(user,pwd) >> I try to send the email using >> x..sendmail(SENDER, RECIPIENTS, msg) >> But I get the following error >> Traceback (most recent call last): >> File "C:UsersAvisDesktopMail.py", line 13, in>> session = smtplib.SMTP(smtpserver,port) >> File "C:Python26libsmtplib.py", line 239, in init >> (code, msg) = self.connect(host, port) >> File "C:Python26libsmtplib.py", line 295, in connect >> self.sock = self.getsocket(host, port, self.timeout) >> File "C:Python26libsmtplib.py", line 273, in getsocket >> return socket.createconnection((port, host), timeout) >> File "C:Pyth on26libsocket.py", line 498, in createconnection >> for res in getaddrinfo(host, port, 0, SOCKSTREAM): >> socket.gaierror: [Errno 11001] getaddrinfo failed >> >> This is in Windows Vista and I am trying to connect to "smtp.gmail.com" with >> port 465 >> >> Tutor maillist ? ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > > > Senthil > > Tutor maillist ? ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Tutor maillistTutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 61, Issue 42 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Mar 11 17:19:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Mar 2009 12:19:25 -0400 Subject: [Tutor] Replying to digest messages Message-ID: <1c2a2c590903110919m683f7d8dlc8a18ce092f2e2da@mail.gmail.com> When replying to digest messages, please - change the subject to the subject of the message you are replying to - trim the message body to contain only the (portion of the) message you are replying to Thanks, Kent From samuelavinash at in.com Wed Mar 11 17:36:06 2009 From: samuelavinash at in.com (Samuel Avinash) Date: Wed, 11 Mar 2009 22:06:06 +0530 Subject: [Tutor] =?utf-8?q?How_to_send_an_email_using_Python?= In-Reply-To: <7c42eba10903102128t17d6a054obca73acb12b43699@mail.gmail.com> Message-ID: <1236789366.675be3930765f553975c0b140bbf0863@mail.in.com> Hey Senthil,Thanks for your response. My script is similar to yours, but as you've pointed that it could be temporary. I've been retrying to connect and send email but in vain.Here's the snippet of my code. Can you debug and help me what could really have gone wrong.import smtplibimport base64smtpserver = 'smtp.gmail.com'AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1smtpuser = 'user at gmail.com'# for SMTP AUTH, set SMTP username heresmtppass = '*****'# for SMTP AUTH, set SMTP password hereRECIPIENTS = ['someuser at gmail.com']SENDER = 'someuser at gmail.com'mssg = open('mssg.txt', 'r').read() # I am reading from this file on the same directorysession = smtplib.SMTP(smtpserver,'465')session.ehlo()#session.esmtpfeatures["auth"] = "LOGIN PLAIN"session.connect(smtpserver,'465')session.ehlo()session.starttls()session.setdebuglevel(1)session.helo()if AUTHREQUIRED:try:session.login(smtpuser, smtppass)except SMTPAuthenticationError, e:# if login fails, try again using a manual pla in login methodsmtp.docmd("AUTH LOGIN", base64.b64encode( smtpuser ))smtp.docmd(base64.b64encode( smtppass ), "")smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)if smtpresult:errstr = ""for recip in smtpresult.keys():errstr = """Could not delivery mail to: %sServer said: %s%s%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)raise smtplib.SMTPException, errstr This is the Stack Trace I got when I ran the above script after a very long time(>15min)Traceback (most recent call last): File "C:\Python26\Mail.py", line 13, insession = smtplib.SMTP(smtpserver,'465') File "C:\Python26\lib\smtplib.py", line 239, in init (code, msg) = self.connect(host, port) File "C:\Python26\lib\smtplib.py", line 296, in connect (code, msg) = self.getreply() File "C:\Python26\lib\smtplib.py", line 340, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closedTool completed with exit code 1ThanksAvi nash Original message From:Senthil Kumaran< orsenthil at gmail.com >Date: 11 Mar 09 09:58:53Subject:Re: [Tutor] How to send an email using PythonTo: Samuel Avinash Hello Samuel,When sending through smtp.gmail.com you might need to starttls() and do a login() before sending.>>> import smtplib >>> headers = "From: %s\r To: %s\r Subject: %s\r \r " %(from,to,subject) >>> message = headers + "Hello, How are you?" >>> mailserver = smtplib.SMTP('smtp.gmail.com') >>> mailserver.ehlo() >>> mailserver.starttls() >>> mailserver.login('username','password') >>> mailserver.sendmail(from,to,message)As I try it now, startls() was giving me a message " reply: '454 TLS not available due to temporary reason\r '" As the error message says, it could be temporary.Try it at your end and report if you succeed.Thanks, SenthilOn Tue, Mar 10, 2009 at 4:41 PM, Samuel Avinashwrote: > Hi, > Can anybody tell me how to send an email to a recipient using Python > I am trying to send an email using Gmail > I create an instance ofsmtplib and use : > x=smtplib.SMTP(sever,port) > and then > x.login(user,pwd) > I try to send the email using > x..sendmail(SENDER, RECIPIENTS, msg) > But I get the following error > Traceback (most recent call last): > File "C:UsersAvisDesktopMail.py", line 13, in> session = smtplib.SMTP(smtpserver,port) > File "C:Python26libsmtplib.py", line 239, in init > (code, msg) = self.connect(host, port) > File "C:Python26libsmtplib.py", line 295, in connect > self.sock = self.getsocket(host, port, self.timeout) > File "C:Python26libsmtplib.py", line 273, in getsocket > return socket.createconnection((port, host), timeout) > File "C:Python26libsocket.py", line 498, in createcon nection > for res in getaddrinfo(host, port, 0, SOCKSTREAM): > socket.gaierror: [Errno 11001] getaddrinfo failed > > This is in Windows Vista and I am trying to connect to "smtp.gmail.com" with > port 465 > > Tutor maillistTutor at python.org > http://mail.python.org/mailman/listinfo/tutor > >Senthil -------------- next part -------------- An HTML attachment was scrubbed... URL: From samuelavinash at in.com Wed Mar 11 17:36:18 2009 From: samuelavinash at in.com (Samuel Avinash) Date: Wed, 11 Mar 2009 22:06:18 +0530 Subject: [Tutor] =?utf-8?q?How_to_send_an_email_using_Python?= In-Reply-To: <5cb309e70903102342l7fcd1b58n3013ee13ce54c661@mail.gmail.com> Message-ID: <1236789378.51e6d6e679953c6311757004d8cbbba9@mail.in.com> Hey Stefan,Thanks for your response.My script is similar to yours, but as you've pointed that it could be temporary. I've been retrying to connect and send email but in vain. Here's the snippet of my code. Can you debug and help me what could really have gone wrong. import smtplib import base64smtpserver = 'smtp.gmail.com' AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1 smtpuser = 'user at gmail.com'# for SMTP AUTH, set SMTP username here smtppass = '*****'# for SMTP AUTH, set SMTP password hereRECIPIENTS = ['someuser at gmail.com'] SENDER = 'someuser at gmail.com' mssg = open('mssg.txt', 'r').read() # I am reading from this file on the same directorysession = smtplib.SMTP(smtpserver,'465') session.ehlo() #session.esmtpfeatures["auth"] = "LOGIN PLAIN" session.connect(smtpserver,'465') session.ehlo() session.starttls() session.setdebuglevel(1) session.helo()if AUTHREQUIRED: try: session.login(smtpuser, smtppass)except SMTPAuthenticationError, e: # if login fails, try again u sing a manual plain login method smtp.docmd("AUTH LOGIN", base64.b64encode( smtpuser )) smtp.docmd(base64.b64encode( smtppass ), "") smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %sServer said: %s %s%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr This is the Stack Trace I got when I ran the above script after a very long time(>15min)Traceback (most recent call last):File "C:\Python26\Mail.py", line 13, in session = smtplib.SMTP(smtpserver,'465')File "C:\Python26\lib\smtplib.py", line 239, in init(code, msg) = self.connect(host, port)File "C:\Python26\lib\smtplib.py", line 296, in connect(code, msg) = self.getreply()File "C:\Python26\lib\smtplib.py", line 340, in getreplyraise SMTPServerDisconnected("Connection unexpectedly closed")smtplib.SMTPServerDisconnected: Connection unexpectedly closedTool completed with e xit code 1 Thanks Avinash Original message From:Stefan Lesicnik< stefan at lsd.co.za >Date: 11 Mar 09 12:12:45Subject:Re: [Tutor] How to send an email using PythonTo: Senthil Kumaran -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Wed Mar 11 18:16:12 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 12 Mar 2009 04:16:12 +1100 Subject: [Tutor] Replying to digest messages In-Reply-To: <1c2a2c590903110919m683f7d8dlc8a18ce092f2e2da@mail.gmail.com> References: <1c2a2c590903110919m683f7d8dlc8a18ce092f2e2da@mail.gmail.com> Message-ID: Kent Johnson wrote: > When replying to digest messages, please > - change the subject to the subject of the message you are replying to > - trim the message body to contain only the (portion of the) message > you are replying to > > Thanks, > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Can I add some other guideline/rule/law/dictation, especially for frequent poster: - Send in text instead of HTML or configure your newsreader/mail client to send both text and HTML. From emadnawfal at gmail.com Wed Mar 11 22:21:07 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Wed, 11 Mar 2009 17:21:07 -0400 Subject: [Tutor] How can I extract a specific sublist from a nested list? In-Reply-To: <6faf39c90903110447q26da7c72hc2ec532ad633efe8@mail.gmail.com> References: <652641e90903101844u27ef2d1dx6a401f1f5fcf3880@mail.gmail.com> <652641e90903110344s3ebcd026re56587ca93742360@mail.gmail.com> <6faf39c90903110447q26da7c72hc2ec532ad633efe8@mail.gmail.com> Message-ID: <652641e90903111421q1baca124ib4eb551ed1bd1fed@mail.gmail.com> On Wed, Mar 11, 2009 at 7:47 AM, Andre Engels wrote: > 2009/3/11 Emad Nawfal (???? ????) : > > > Now I know that I did not ask the right question. What I meant was: how > to > > extract a sublist from a list whose length is unknown. Let's say I have a > > hundred of these lists and each of these has an NP somewhere, it could be > > nested in nested list, which is turn nested in another one and so on. The > > bottom line is that I do not know the index. To make things more > concrete, > > this is a representative list. How can I extract all the sublists > beginning > > with "NP" from it? > > You'll have to do recursion - that is: > NPstart(alist) = > if alist starts with "NP": > alist + NPstart for all sublists of alist > else: > NPstart for all sublists of alist > > > Turning that into Python we get: > > def NPstart(alist): > if isinstance(alist, basestring): # It's ugly to do an isinstance > in Python, but any better method would be fully changing your data > structure, so I use it for now > return [] > else: > if alist[0] == 'NP': > return [alist] + [NPstart(sublist) for sublist in alist] > else: > return [NPstart(sublist) for sublist in alist] > > -- > Andr? Engels, andreengels at gmail.com > Thanks Andre This works. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From org.python.pythonlist at pooryorick.com Thu Mar 12 13:13:52 2009 From: org.python.pythonlist at pooryorick.com (Poor Yorick) Date: Thu, 12 Mar 2009 08:13:52 -0400 Subject: [Tutor] loop performance in global namespace (python-2.6.1) Message-ID: <49B8FC80.8030809@pooryorick.com> In the following snippet, the loop in the global namespace takes twice as long as the loop in the function namespace. Why? limit = 50000000 def f1(): counter = 0 while counter < limit: counter += 1 time1 = time.time() f1() print(time.time() - time1) print('number of locals: ', len(locals())) time1 = time.time() counter = 0 while counter < limit: counter += 1 print(time.time() - time1) print('number of locals: ', len(locals())) -- Yorick From dineshbvadhia at hotmail.com Thu Mar 12 14:43:49 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 12 Mar 2009 06:43:49 -0700 Subject: [Tutor] Sorting large numbers of co-ordinate pairs Message-ID: Have a large number (> 1bn) of integer co-ordinates (i, j). The i are ordered and the j unordered. I want to create (j, i) with j ordered and i unordered ie. from: ... 6940, 22886 6940, 38277 6940, 43788 ... to: ... 38277, 567 38277, 90023 38277, 6940 ... I've tried the dictionary route and it works perfectly for small set of co-ordinate pairs but not for large sets as it hits memory capacity. Any ideas how I could do this? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Mar 12 15:22:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Mar 2009 10:22:19 -0400 Subject: [Tutor] Sorting large numbers of co-ordinate pairs In-Reply-To: References: Message-ID: <1c2a2c590903120722k321bbe87vc2dff5fb47660b1@mail.gmail.com> On Thu, Mar 12, 2009 at 9:43 AM, Dinesh B Vadhia wrote: > Have a large number (> 1bn) of integer co-ordinates (i, j).? The i are > ordered and the j unordered. > > I want to create (j, i) with j ordered and i unordered ie. > > from: > > ... > 6940, 22886 > 6940, 38277 > 6940, 43788 > ... > > to: > ... > 38277, 567 > 38277, 90023 > 38277, 6940 > ... > > I've tried the dictionary route and it works perfectly for small set of > co-ordinate pairs but not for large sets as it hits memory capacity. I'm not sure what the dictionary route is. Holding the data in lists might be more memory efficient but you still need enough memory to hold one or more copies of the list. Otherwise a file-based merge sort. I would do something like this: - read or otherwise acquire as many coordinates as you can comfortably reorder and sort - reorder and sort them - write the sorted list to a file, one coordinate pair per line - repeat until all coordinates have been written, using a new file for each group of coordinates - Make an iterator (use a generator function) that will open one of your files and yield individual coordinates. - use this recipe: http://code.activestate.com/recipes/491285/ to sort the coordinates, processing the result however you like (writing to a file?) Kent From kent37 at tds.net Thu Mar 12 16:13:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Mar 2009 11:13:33 -0400 Subject: [Tutor] loop performance in global namespace (python-2.6.1) In-Reply-To: <49B8FC80.8030809@pooryorick.com> References: <49B8FC80.8030809@pooryorick.com> Message-ID: <1c2a2c590903120813j5bf050c4q426491b6d3b7a67@mail.gmail.com> On Thu, Mar 12, 2009 at 8:13 AM, Poor Yorick wrote: > In the following snippet, the loop in the global namespace takes twice as > long > as the loop in the function namespace. ?Why? Because local name lookup is faster than global name lookup. Local variables are stored in an array in the stack frame and accessed by index. Global names are stored in a dict and accessed with dict access (dict.__getitem__()). One trick for optimizing a function is to make local variable copies of any globals that are referenced more than once per function call, so they can use the faster lookup. Kent From denis.spir at free.fr Thu Mar 12 16:41:49 2009 From: denis.spir at free.fr (spir) Date: Thu, 12 Mar 2009 16:41:49 +0100 Subject: [Tutor] loop performance in global namespace (python-2.6.1) In-Reply-To: <1c2a2c590903120813j5bf050c4q426491b6d3b7a67@mail.gmail.com> References: <49B8FC80.8030809@pooryorick.com> <1c2a2c590903120813j5bf050c4q426491b6d3b7a67@mail.gmail.com> Message-ID: <20090312164149.3fca3037@o> Le Thu, 12 Mar 2009 11:13:33 -0400, Kent Johnson s'exprima ainsi: > Because local name lookup is faster than global name lookup. Local > variables are stored in an array in the stack frame and accessed by > index. Global names are stored in a dict and accessed with dict access > (dict.__getitem__()). ? I thought this was mainly because a name has first to be searched (unsuccessfully) locally before a global lookup is launched. Also, are locals really stored in an array? How does lookup then proceed? Is it a kind of (name,ref) sequence? Denis ------ la vita e estrany From emadnawfal at gmail.com Thu Mar 12 17:10:22 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Thu, 12 Mar 2009 12:10:22 -0400 Subject: [Tutor] reading lists from a text file Message-ID: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> Hi Tutors, I've never had a situation in which this was useful for me, but I'm just curious. If there is a text file that has a list or number of lists in it, is there is a way to read the lists in the file as lists, and not as a string. Sample file attached. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- ["this", "is", "a", "list"] ["this", "is", "another", "list"] ["this", "is","list", "#", "2"] From kent37 at tds.net Thu Mar 12 17:37:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Mar 2009 12:37:15 -0400 Subject: [Tutor] loop performance in global namespace (python-2.6.1) In-Reply-To: <20090312164149.3fca3037@o> References: <49B8FC80.8030809@pooryorick.com> <1c2a2c590903120813j5bf050c4q426491b6d3b7a67@mail.gmail.com> <20090312164149.3fca3037@o> Message-ID: <1c2a2c590903120937w52f19ba3yb3753beb43a119fa@mail.gmail.com> On Thu, Mar 12, 2009 at 11:41 AM, spir wrote: > Le Thu, 12 Mar 2009 11:13:33 -0400, > Kent Johnson s'exprima ainsi: > >> Because local name lookup is faster than global name lookup. Local >> variables are stored in an array in the stack frame and accessed by >> index. Global names are stored in a dict and accessed with dict access >> (dict.__getitem__()). > > ? I thought this was mainly because a name has first to be searched (unsuccessfully) locally before a global lookup is launched. I'm pretty sure, local names are hard-coded to the stack frame. Non-local names must follow the lookup sequence (containing scope), (global scope), (builtins). > Also, are locals really stored in an array? How does lookup then proceed? Is it a kind of (name,ref) sequence? Yes, they are really stored in an array. A reference from GvR himself: "The Python "compiler" optimizes most function bodies so that for local variables, no dictionary lookup is necessary, but a simple array indexing operation is sufficient." http://www.python.org/doc/essays/list2str.html Local variables are accessed using the LOAD_FAST and STORE_FAST opcodes. From http://docs.python.org/library/dis.html: LOAD_FAST(var_num)? Pushes a reference to the local co_varnames[var_num] onto the stack. STORE_FAST(var_num)? Stores Top Of Stack into the local co_varnames[var_num]. Looking at the OP's code: In [1]: def f1(): ...: counter = 0 ...: while counter < limit: ...: counter += 1 In [2]: In [3]: import dis In [4]: dis.dis(f1) 3 0 LOAD_CONST 1 (0) 3 STORE_FAST 0 (counter) 4 6 SETUP_LOOP 28 (to 37) >> 9 LOAD_FAST 0 (counter) 12 LOAD_GLOBAL 0 (limit) 15 COMPARE_OP 0 (<) 18 JUMP_IF_FALSE 14 (to 35) 21 POP_TOP 5 22 LOAD_FAST 0 (counter) 25 LOAD_CONST 2 (1) 28 INPLACE_ADD 29 STORE_FAST 0 (counter) 32 JUMP_ABSOLUTE 9 >> 35 POP_TOP 36 POP_BLOCK >> 37 LOAD_CONST 0 (None) 40 RETURN_VALUE Kent From alan.gauld at btinternet.com Thu Mar 12 18:46:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Mar 2009 17:46:34 -0000 Subject: [Tutor] reading lists from a text file References: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> Message-ID: "Emad Nawfal (???? ????)" wrote > If there is a text file that has a list or number of lists in it, is > there > is a way to read the lists in the file as lists, and not as a > string. Sample > file attached. Not that I know of. If you made the file include assignments to variables or one big list with embedded lists inside you could eval() the file but that is a huge security risk. Alan G. From noufal at nibrahim.net.in Thu Mar 12 18:52:10 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Thu, 12 Mar 2009 23:22:10 +0530 Subject: [Tutor] reading lists from a text file In-Reply-To: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> References: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> Message-ID: <49B94BCA.4020505@nibrahim.net.in> Emad Nawfal (???? ????) wrote: > Hi Tutors, > I've never had a situation in which this was useful for me, but I'm just > curious. > If there is a text file that has a list or number of lists in it, is > there is a way to read the lists in the file as lists, and not as a > string. Sample file attached. > I suppose you could read it as a string and then 'eval' it. That'd be risky though. -- ~noufal http://nibrahim.net.in/ From alan.gauld at btinternet.com Thu Mar 12 18:50:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Mar 2009 17:50:21 -0000 Subject: [Tutor] Sorting large numbers of co-ordinate pairs References: Message-ID: "Dinesh B Vadhia" wrote > Have a large number (> 1bn) of integer co-ordinates (i, j). > I want to create (j, i) with j ordered and i unordered ie. > I've tried the dictionary route and it works perfectly for small set > of > co-ordinate pairs but not for large sets as it hits memory capacity. One option is to load them into a database and use its sort facilities. Another is to use the old mainframe approach of batching the data and sorting each batch. Its then a relatively easy job to merge the sorted batches back into a single file without ever holding the whole thing in memory at once. But its not fast... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Thu Mar 12 20:10:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Mar 2009 15:10:28 -0400 Subject: [Tutor] reading lists from a text file In-Reply-To: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> References: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> Message-ID: <1c2a2c590903121210t7159db84n7de028aa79b463f5@mail.gmail.com> 2009/3/12 Emad Nawfal (???? ????) : > Hi Tutors, > I've never had a situation in which this was useful for me, but I'm just > curious. > If there is a text file that has a list or number of lists in it, is there > is a way to read the lists in the file as lists, and not as a string. Sample > file attached. For the individual lines, there are various solutions. eval() is easy but not recommended because of the security risk. There are several recipes in the Python cookbook - search for "safe eval". Python 2.6 includes ast.literal_eval() which does the job safely: In [1]: from ast import literal_eval In [4]: data = '''["this", "is", "a", "list"] ...: ["this", "is", "another", "list"] ...: ["this", "is","list", "#", "2"]''' In [5]: for line in data.splitlines(): ...: print literal_eval(line) ['this', 'is', 'a', 'list'] ['this', 'is', 'another', 'list'] ['this', 'is', 'list', '#', '2'] Extending from parsing a single line to parsing all the lines in a file is trivial. Kent From stefan_ml at behnel.de Thu Mar 12 20:47:24 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 12 Mar 2009 20:47:24 +0100 Subject: [Tutor] Issues Parsing XML In-Reply-To: <49277.64.252.205.230.1236726141.squirrel@webmail1.hrnoc.net> References: <49277.64.252.205.230.1236726141.squirrel@webmail1.hrnoc.net> Message-ID: marc at marcd.org wrote: > I am new to Python and as a first project decided to try to parse an XML > report using Python. I have the following, which works to extract one > element. I am stuck, however, at one element. I want to extract several > differenct elements per line, creating a comma separated variable (CSV) > line that can be imported to a spreadsheet. Not all elements are in each > line or part of the XML document - so if an element is not in a line, I > would leave a blank (2 commas). I can probably figure that out - it's the > extracting multiple elements and putting them in one line that has me > stumped. Help would be greatly appreciated. Thank you. What I have so > far (and I would like to stick to the DOM model): There is another "DOM Model" in the stdlib. It's called ElementTree and is generally a lot easier to use. For example, to find the text content of an element called "element_that_has_text_content" in a subtree below "some_element", you can do print some_element.findtext(".//element_that_has_text_content") Stefan From norman at khine.net Thu Mar 12 21:24:37 2009 From: norman at khine.net (ski) Date: Thu, 12 Mar 2009 21:24:37 +0100 Subject: [Tutor] merging dictionary values based on key Message-ID: <49B96F85.8070803@khine.net> Hello, I have this issue, which I am unsure on how to solve. >>> mylist1 = {'a': 'x123', 'b':'12'} >>> mylist2 = {'a': 'x234', 'c': 'a23'} >>> for k in mylist2: ... if k in mylist1: ... mylist1[k] = [mylist1[k], mylist2[k]] ... else: ... mylist1[k] = mylist2[k] ... >>> mylist1 {'a': ['x123', 'x234'], 'c': 'a23', 'b': '12'} >>> this merges the two dictionaries, but what should be the method if: >>> mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] where mylist has nth number of dictionaries and i want to merge the values of the keys that are the same? Thanks Norman From greg at thewhittiers.com Thu Mar 12 21:32:51 2009 From: greg at thewhittiers.com (greg whittier) Date: Thu, 12 Mar 2009 16:32:51 -0400 Subject: [Tutor] merging dictionary values based on key In-Reply-To: <49B96F85.8070803@khine.net> References: <49B96F85.8070803@khine.net> Message-ID: On Thu, Mar 12, 2009 at 4:24 PM, ski wrote: > Hello, > I have this issue, which I am unsure on how to solve. > >>>> mylist1 = {'a': 'x123', 'b':'12'} >>>> mylist2 = {'a': 'x234', 'c': 'a23'} >>>> for k in mylist2: > ... ? ? if k in mylist1: > ... ? ? ? ? ? ? mylist1[k] = [mylist1[k], mylist2[k]] > ... ? ? else: > ... ? ? ? ? ? ? mylist1[k] = mylist2[k] > ... >>>> mylist1 > {'a': ['x123', 'x234'], 'c': 'a23', 'b': '12'} >>>> > > this merges the two dictionaries, but what should be the method if: > >>>> mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': >>>> 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] > > where mylist has nth number of dictionaries and i want to merge the values > of the keys that are the same? > > Thanks > > Norman If I understand what you mean by merging, I think you want mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] merged_dict = {} for dictionary in mylist: for key, value in dictionary.items(): merged_dict.setdefault(key,[]).append(value) From dkuhlman at rexx.com Thu Mar 12 21:14:30 2009 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 12 Mar 2009 13:14:30 -0700 Subject: [Tutor] Issues Parsing XML In-Reply-To: References: <49277.64.252.205.230.1236726141.squirrel@webmail1.hrnoc.net> Message-ID: <20090312201430.GA17491@cutter.rexx.com> On Thu, Mar 12, 2009 at 08:47:24PM +0100, Stefan Behnel wrote: > marc at marcd.org wrote: [snip] > > There is another "DOM Model" in the stdlib. It's called ElementTree and is > generally a lot easier to use. For example, to find the text content of an > element called "element_that_has_text_content" in a subtree below > "some_element", you can do > > print some_element.findtext(".//element_that_has_text_content") And, if you install lxml, then you will be able to use XPath, which is more powerful that the findtext() in ElementTree. Stefan did not tell you about that because he is a developer who has helped give us lxml, and perhaps he is a bit modest. There is a bit to learn in order to use the XPath capability in lxml. But, if you are doing any amount of XML processing in Python, it's likely to be worth it. You can learn about lxml here: http://codespeak.net/lxml/ - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From norman at khine.net Fri Mar 13 00:05:06 2009 From: norman at khine.net (ski) Date: Fri, 13 Mar 2009 00:05:06 +0100 Subject: [Tutor] merging dictionary values based on key In-Reply-To: References: <49B96F85.8070803@khine.net> Message-ID: <49B99522.2080504@khine.net> how would you do this for a specific key instead of all the keys? greg whittier wrote: > On Thu, Mar 12, 2009 at 4:24 PM, ski wrote: >> Hello, >> I have this issue, which I am unsure on how to solve. >> >>>>> mylist1 = {'a': 'x123', 'b':'12'} >>>>> mylist2 = {'a': 'x234', 'c': 'a23'} >>>>> for k in mylist2: >> ... if k in mylist1: >> ... mylist1[k] = [mylist1[k], mylist2[k]] >> ... else: >> ... mylist1[k] = mylist2[k] >> ... >>>>> mylist1 >> {'a': ['x123', 'x234'], 'c': 'a23', 'b': '12'} >> this merges the two dictionaries, but what should be the method if: >> >>>>> mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': >>>>> 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] >> where mylist has nth number of dictionaries and i want to merge the values >> of the keys that are the same? >> >> Thanks >> >> Norman > > If I understand what you mean by merging, I think you want > > mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': > 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] > merged_dict = {} > for dictionary in mylist: > for key, value in dictionary.items(): > merged_dict.setdefault(key,[]).append(value) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From iwasroot at gmail.com Fri Mar 13 01:54:28 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Thu, 12 Mar 2009 17:54:28 -0700 Subject: [Tutor] Issues Parsing XML In-Reply-To: <20090312201430.GA17491@cutter.rexx.com> References: <49277.64.252.205.230.1236726141.squirrel@webmail1.hrnoc.net> <20090312201430.GA17491@cutter.rexx.com> Message-ID: <7b13ba330903121754kd3a5dear3282875961990fbf@mail.gmail.com> So you want one line for each element? Easy: # Get elements findings = domDatasource.getElementsByTagName('FINDING') # Get the text of all direct child nodes in each element # That's assuming every child has a TEXT_NODE node. lines = [] for finding in findings: lines.append([f.firstChild.data for f in finding.childNodes]) # print for line in lines: print ", ".join(line) Not sure how you want to deal with newlines. You can escape them to \n in the output, or you might find something in the CSV module. (I haven't looked at it.) Now this doesn't deal with missing elements. I found some have 7, and others have 9. You might be able to insert two empty elements in lines with length 7. Or, if you want to have more control, you can make a dictionary with keys of all available tag names, and for each element found in , insert it in the dictionary (If it's a valid tag name). Then you have a list of dictionaries, and you can print the elements in any order you want. Missing elements will have null strings as values. Moos From iwasroot at gmail.com Fri Mar 13 02:40:36 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Thu, 12 Mar 2009 18:40:36 -0700 Subject: [Tutor] Issues Parsing XML In-Reply-To: <7b13ba330903121754kd3a5dear3282875961990fbf@mail.gmail.com> References: <49277.64.252.205.230.1236726141.squirrel@webmail1.hrnoc.net> <20090312201430.GA17491@cutter.rexx.com> <7b13ba330903121754kd3a5dear3282875961990fbf@mail.gmail.com> Message-ID: <7b13ba330903121840h4c7275e7pf6ae473d04c0e796@mail.gmail.com> I'm a little bored, so I wrote a function that gets elements and puts them in a dictionary. Missing elements are just an empty string. http://gist.github.com/78385 Usage: >>> d = process_finding(findings[0]) >>> ", ".join(map(lambda e: d[e], elements)) u'V0006310, NF, , , GD, 2.0.8.8, TRUE, DTBI135-Scripting\nof Java applets -\nRestricted, 2' Now for a of 9 elements: >>> d = process_finding(findings[1]) >>> ", ".join(map(lambda e: d[e], elements)) u'V0006311, O, The value:\nSoftware\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet\nSettings\\Zones\\4\\1A00 does not exist.\n\n, The value:\nSoftware\\Policies\\Microsoft\\Windows\\CurrentVersion\\Internet\nSettings\\Zones\\4\\1A00 does not exist.\n\n, GD, 2.0.8.8, TRUE, DTBI136-User\nAuthentication - Logon -\nRestricted, 2' The map() function just applies the dictionary to each element in the elements list. You can reorder them anyway you want. You're welcome :) Moos From mwalsh at mwalsh.org Fri Mar 13 03:08:54 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 12 Mar 2009 21:08:54 -0500 Subject: [Tutor] merging dictionary values based on key In-Reply-To: <49B99522.2080504@khine.net> References: <49B96F85.8070803@khine.net> <49B99522.2080504@khine.net> Message-ID: <49B9C036.5000605@mwalsh.org> > greg whittier wrote: >> On Thu, Mar 12, 2009 at 4:24 PM, ski wrote: >>>>>> mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': >>>>>> 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] >>> where mylist has nth number of dictionaries and i want to merge the >>> values >>> of the keys that are the same? >>> >> >> If I understand what you mean by merging, I think you want >> >> mylist = [{'a': 'x123', 'b':'12'}, {'a': 'x234', 'b': 'd33', 'c': >> 'a23'}, {'a': 'x234', 'c': 'XX123'} .... ] >> merged_dict = {} >> for dictionary in mylist: >> for key, value in dictionary.items(): >> merged_dict.setdefault(key,[]).append(value) Or similarly with defaultdict: from collections import defaultdict merged_dict = defaultdict(list) for d in mylist: for k, v in d.items(): merged_dict[k].append(v) ski wrote: > how would you do this for a specific key instead of all the keys? alist = [d['a'] for d in mylist if d.has_key('a')] HTH, Marty From lie.1296 at gmail.com Fri Mar 13 07:57:03 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 13 Mar 2009 17:57:03 +1100 Subject: [Tutor] Sorting large numbers of co-ordinate pairs In-Reply-To: References: Message-ID: Dinesh B Vadhia wrote: > Have a large number (> 1bn) of integer co-ordinates (i, j). The i are > ordered and the j unordered. > > I want to create (j, i) with j ordered and i unordered ie. > > from: > > ... > 6940, 22886 > 6940, 38277 > 6940, 43788 > ... > > to: > ... > 38277, 567 > 38277, 90023 > 38277, 6940 > ... > > I've tried the dictionary route and it works perfectly for small set of > co-ordinate pairs but not for large sets as it hits memory capacity. > > Any ideas how I could do this? Can you actually load the original (unsorted) data to memory? If you can, the easiest way is to use list.sort (which is in-place sort) with key: data = [...taken from somewhere...] data.sort(key=lambda x: x[1]) if you can't load the whole thing into memory, the easiest way (without relying on external modules) might be to load it in fixed size chunks that can be loaded to memory, sort it, then write it to a temporary file. Next, load all of the files, then interleave them. From norman at khine.net Fri Mar 13 16:09:58 2009 From: norman at khine.net (ski) Date: Fri, 13 Mar 2009 16:09:58 +0100 Subject: [Tutor] update list of dictionaries based on key Message-ID: <49BA7746.6090103@khine.net> Hello, Here is what I have so far: >>> mylist = [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', 'affiliation_no': u'G3903'}, {'index': 1, 'title': 'Appointed Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': 'Association of Airline Cons.', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}, {'index': 1, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no': u'zser'}] >>> key = 'affiliation_no' >>> my_dup_keys = [] >>> merged_list = [] >>> mykeys = [item['affiliation'] for item in mylist] >>> for x in mykeys: if mykeys.count(x) >= 2: my_dup_keys.append(x) >>> for item in mylist: if item['affiliation'] in set(my_dup_keys): merged_list.append(item) >>> values = [d[key] for d in merged_list if d.has_key(key)] >>> for dict in merged_list: dict[key] = values mylist.append(dict) >>> print mylist [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Appointed Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': 'Association of Airline Cons.', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}, {'index': 1, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index': 0, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', u'zser']}] This sort of works but I want to return a list that updates 'mylist' not append to it, so I will get: [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Appointed Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': 'Association of Airline Cons.', 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}] Thanks Norman From greg at thewhittiers.com Fri Mar 13 16:43:19 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 13 Mar 2009 11:43:19 -0400 Subject: [Tutor] update list of dictionaries based on key In-Reply-To: <49BA7746.6090103@khine.net> References: <49BA7746.6090103@khine.net> Message-ID: On Fri, Mar 13, 2009 at 11:09 AM, ski wrote: > Hello, > Here is what I have so far: > >>>> mylist = [{'index': 0, 'title': 'Association of British Travel Agents', >>>> 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', >>>> 'affiliation_no': u'G3903'}, {'index': 1, 'title': 'Appointed Agents of >>>> IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': >>>> 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': 'Association of >>>> Airline Cons.', 'selected': False, 'edit_row': '?edit_affiliation=0', >>>> 'affiliation': 'AAC', 'affiliation_no': u'sss'}, {'index': 1, 'title': >>>> 'Association of British Travel Agents', 'selected': False, 'edit_row': >>>> '?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no': u'zser'}] > >>>> key = 'affiliation_no' > >>>> my_dup_keys = [] >>>> merged_list = [] > >>>> mykeys = [item['affiliation'] for item in mylist] > >>>> for x in mykeys: > ? ? ? ?if mykeys.count(x) >= 2: > ? ? ? ? ? ? ? ?my_dup_keys.append(x) > >>>> for item in mylist: > ? ? ? ?if item['affiliation'] in set(my_dup_keys): > ? ? ? ? ? ? ? ?merged_list.append(item) > > >>>> values = [d[key] for d in merged_list if d.has_key(key)] >>>> for dict in merged_list: > ? ? ? ?dict[key] = values > ? ? ? ?mylist.append(dict) > >>>> print mylist > [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': > False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Appointed > Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', > 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': > 'Association of Airline Cons.', 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}, > {'index': 1, 'title': 'Association of British Travel Agents', 'selected': > False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', u'zser']}, {'index': 0, 'title': 'Association > of British Travel Agents', 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', > u'zser']}, {'index': 1, 'title': 'Association of British Travel Agents', > 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', u'zser']}] > > > This sort of works but I want to return a list that updates 'mylist' not > append to it, so I will get: > > [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': > False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Appointed > Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', > 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': > 'Association of Airline Cons.', 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}] > It's a little hard to figure what you're getting at. This looks like a table represented by a list of dictionaries that you'd like to group by "affiliation." affiliation_nos = {} for row in mylist: affiliation_nos.set_default(row['affiliation'],[]).append(row['affliation_no']) will give you a list of affiliation_no's for each affiliation and if you want a list of dicts, you could do mynewlist = [dict(affiliation=affiliation, affiliation_nos = affiliation_nos[affiliation]) for affiliation in affiliation_nos.keys()] I don't know what to do about all the other fields though. In your example input list you have two dictionaries with affiliation = 'ABTA'. In your output you kept the one with index=0 and threw away index=1. (same for 'edit_row') How do you determine which to keep? From norman at khine.net Fri Mar 13 17:23:32 2009 From: norman at khine.net (ski) Date: Fri, 13 Mar 2009 17:23:32 +0100 Subject: [Tutor] update list of dictionaries based on key In-Reply-To: References: <49BA7746.6090103@khine.net> Message-ID: <49BA8884.3040708@khine.net> greg whittier wrote: > On Fri, Mar 13, 2009 at 11:09 AM, ski wrote: >> Hello, >> Here is what I have so far: >> >>>>> mylist = [{'index': 0, 'title': 'Association of British Travel Agents', >>>>> 'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', >>>>> 'affiliation_no': u'G3903'}, {'index': 1, 'title': 'Appointed Agents of >>>>> IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': >>>>> 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': 'Association of >>>>> Airline Cons.', 'selected': False, 'edit_row': '?edit_affiliation=0', >>>>> 'affiliation': 'AAC', 'affiliation_no': u'sss'}, {'index': 1, 'title': >>>>> 'Association of British Travel Agents', 'selected': False, 'edit_row': >>>>> '?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no': u'zser'}] >>>>> key = 'affiliation_no' >>>>> my_dup_keys = [] >>>>> merged_list = [] >>>>> mykeys = [item['affiliation'] for item in mylist] >>>>> for x in mykeys: >> if mykeys.count(x) >= 2: >> my_dup_keys.append(x) >> >>>>> for item in mylist: >> if item['affiliation'] in set(my_dup_keys): >> merged_list.append(item) >> >> >>>>> values = [d[key] for d in merged_list if d.has_key(key)] >>>>> for dict in merged_list: >> dict[key] = values >> mylist.append(dict) >> >>>>> print mylist >> [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': >> False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', >> 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Appointed >> Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', >> 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': >> 'Association of Airline Cons.', 'selected': False, 'edit_row': >> '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}, >> {'index': 1, 'title': 'Association of British Travel Agents', 'selected': >> False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', >> 'affiliation_no': [u'G3903', u'zser']}, {'index': 0, 'title': 'Association >> of British Travel Agents', 'selected': False, 'edit_row': >> '?edit_affiliation=0', 'affiliation': 'ABTA', 'affiliation_no': [u'G3903', >> u'zser']}, {'index': 1, 'title': 'Association of British Travel Agents', >> 'selected': False, 'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA', >> 'affiliation_no': [u'G3903', u'zser']}] >> >> >> This sort of works but I want to return a list that updates 'mylist' not >> append to it, so I will get: >> >> [{'index': 0, 'title': 'Association of British Travel Agents', 'selected': >> False, 'edit_row': '?edit_affiliation=0', 'affiliation': 'ABTA', >> 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title': 'Appointed >> Agents of IATA', 'selected': False, 'edit_row': '?edit_affiliation=1', >> 'affiliation': 'IATA', 'affiliation_no': u'none'}, {'index': 0, 'title': >> 'Association of Airline Cons.', 'selected': False, 'edit_row': >> '?edit_affiliation=0', 'affiliation': 'AAC', 'affiliation_no': u'sss'}] >> > > It's a little hard to figure what you're getting at. This looks like > a table represented by a list of dictionaries that you'd like to group > by "affiliation." i have objects in my database, called addresses, each address has a metadata called affiliation. also each address is a member of a company. in my company class, i wanted to get all the addresses affiliations and only list the unique values. > > affiliation_nos = {} > for row in mylist: > affiliation_nos.set_default(row['affiliation'],[]).append(row['affliation_no']) > > will give you a list of affiliation_no's for each affiliation and if > you want a list of dicts, you could do > > mynewlist = [dict(affiliation=affiliation, affiliation_nos = > affiliation_nos[affiliation]) for affiliation in > affiliation_nos.keys()] > > I don't know what to do about all the other fields though. In your > example input list you have two dictionaries with affiliation = > 'ABTA'. In your output you kept the one with index=0 and threw away > index=1. (same for 'edit_row') How do you determine which to keep? I want to keep it based on the 'affiliation' key. In essence, from my original 'mylist' I want to keep all the list items as they are, but just update the list items that have more than one 'affiliation' by updating only the 'affiliation_no' to contain both entries. Perhaps there is a simpler way to do this ;) I will change my code so that mylist does not contain the 'index' and 'edit_row' keys. Perhaps then it will be easier to update the dictionary? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Fri Mar 13 18:29:16 2009 From: srilyk at gmail.com (W W) Date: Fri, 13 Mar 2009 12:29:16 -0500 Subject: [Tutor] best gui for the job? Message-ID: <333efb450903131029r62a29c30n60d24c5003fa7142@mail.gmail.com> Hi, What is the best gui to implement a simple paint-esque program in? I already built a really simple one in Tkinter - but Tkinter lacks a save functionality. I considered using the PIL to draw in the background, but it didn't seem to have a good enough resolution. I thought about pyGTK because I have some familiarity with that, but I can't find any examples of saving a drawingarea. Also, to clarify what I mean by "best" - I want it to be fairly simple to implement (my non-saving sketch in a single color/size is about 100 lines), yet extensible - I'd like the ability to further enhance my program down the road. Changing the opacity, and the possibility to work with layers is a plus. If anyone has tips or knows of any tutorials (I haven't really been able to find anything suitable), please let me know. Thanks for any suggestions, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi From lie.1296 at gmail.com Fri Mar 13 19:18:00 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 14 Mar 2009 05:18:00 +1100 Subject: [Tutor] best gui for the job? In-Reply-To: <333efb450903131029r62a29c30n60d24c5003fa7142@mail.gmail.com> References: <333efb450903131029r62a29c30n60d24c5003fa7142@mail.gmail.com> Message-ID: W W wrote: > Hi, > > What is the best gui to implement a simple paint-esque program in? > > I already built a really simple one in Tkinter - but Tkinter lacks a > save functionality. I considered using the PIL to draw in the > background, but it didn't seem to have a good enough resolution. I > thought about pyGTK because I have some familiarity with that, but I > can't find any examples of saving a drawingarea. What do you mean "good enough resolution"? From srilyk at gmail.com Fri Mar 13 20:02:34 2009 From: srilyk at gmail.com (W W) Date: Fri, 13 Mar 2009 14:02:34 -0500 Subject: [Tutor] best gui for the job? In-Reply-To: References: <333efb450903131029r62a29c30n60d24c5003fa7142@mail.gmail.com> Message-ID: <333efb450903131202y7622ee71s95f68f6b808f2f43@mail.gmail.com> On Fri, Mar 13, 2009 at 1:18 PM, Lie Ryan wrote: > W W wrote: > > What do you mean "good enough resolution"? I suppose I really meant quality - the shapes I drew with PIL were severely aliased, but maybe I didn't do it right. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi From sanhitam at yahoo.com Sat Mar 14 00:40:54 2009 From: sanhitam at yahoo.com (Sanhita Mallick) Date: Fri, 13 Mar 2009 16:40:54 -0700 (PDT) Subject: [Tutor] help In-Reply-To: Message-ID: <29406.97163.qm@web55004.mail.re4.yahoo.com> help --- On Sat, 3/14/09, tutor-request at python.org wrote: > From: tutor-request at python.org > Subject: Tutor Digest, Vol 61, Issue 50 > To: tutor at python.org > Date: Saturday, March 14, 2009, 5:18 AM > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body > 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more > specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. update list of dictionaries based on key (ski) > 2. Re: update list of dictionaries based on key (greg > whittier) > 3. Re: update list of dictionaries based on key (ski) > 4. best gui for the job? (W W) > 5. Re: best gui for the job? (Lie Ryan) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 13 Mar 2009 16:09:58 +0100 > From: ski > Subject: [Tutor] update list of dictionaries based on key > To: python tutor > Message-ID: <49BA7746.6090103 at khine.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hello, > Here is what I have so far: > > >>> mylist = [{'index': 0, > 'title': 'Association of British Travel > Agents', 'selected': False, 'edit_row': > '?edit_affiliation=0', > 'affiliation': 'ABTA', > 'affiliation_no': u'G3903'}, > {'index': 1, > 'title': 'Appointed Agents of IATA', > 'selected': False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'IATA', 'affiliation_no': > u'none'}, {'index': 0, 'title': > 'Association of Airline Cons.', > 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'AAC', 'affiliation_no': u'sss'}, > {'index': 1, 'title': 'Association of > British Travel Agents', 'selected': False, > 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'ABTA', 'affiliation_no': u'zser'}] > > >>> key = 'affiliation_no' > > >>> my_dup_keys = [] > >>> merged_list = [] > > >>> mykeys = [item['affiliation'] for > item in mylist] > > >>> for x in mykeys: > if mykeys.count(x) >= 2: > my_dup_keys.append(x) > > >>> for item in mylist: > if item['affiliation'] in set(my_dup_keys): > merged_list.append(item) > > > >>> values = [d[key] for d in merged_list if > d.has_key(key)] > >>> for dict in merged_list: > dict[key] = values > mylist.append(dict) > > >>> print mylist > [{'index': 0, 'title': 'Association of > British Travel Agents', > 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'ABTA', 'affiliation_no': > [u'G3903', u'zser']}, {'index': 1, > 'title': > 'Appointed Agents of IATA', 'selected': > False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'IATA', 'affiliation_no': > u'none'}, {'index': 0, 'title': > 'Association of Airline Cons.', > 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'AAC', 'affiliation_no': u'sss'}, > {'index': 1, 'title': 'Association of > British Travel Agents', 'selected': False, > 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'ABTA', 'affiliation_no': > [u'G3903', u'zser']}, {'index': 0, > 'title': 'Association of British > Travel Agents', 'selected': False, > 'edit_row': '?edit_affiliation=0', > 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', > u'zser']}, {'index': > 1, 'title': 'Association of British Travel > Agents', 'selected': False, > 'edit_row': '?edit_affiliation=1', > 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', > u'zser']}] > > > This sort of works but I want to return a list that updates > 'mylist' not > append to it, so I will get: > > [{'index': 0, 'title': 'Association of > British Travel Agents', > 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'ABTA', 'affiliation_no': > [u'G3903', u'zser']}, {'index': 1, > 'title': > 'Appointed Agents of IATA', 'selected': > False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'IATA', 'affiliation_no': > u'none'}, {'index': 0, 'title': > 'Association of Airline Cons.', > 'selected': False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'AAC', 'affiliation_no': u'sss'}] > > > Thanks > > Norman > > > > ------------------------------ > > Message: 2 > Date: Fri, 13 Mar 2009 11:43:19 -0400 > From: greg whittier > Subject: Re: [Tutor] update list of dictionaries based on > key > To: python tutor > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > On Fri, Mar 13, 2009 at 11:09 AM, ski > wrote: > > Hello, > > Here is what I have so far: > > > >>>> mylist = [{'index': 0, > 'title': 'Association of British Travel > Agents', > >>>> 'selected': False, > 'edit_row': '?edit_affiliation=0', > 'affiliation': 'ABTA', > >>>> 'affiliation_no': > u'G3903'}, {'index': 1, 'title': > 'Appointed Agents of > >>>> IATA', 'selected': False, > 'edit_row': '?edit_affiliation=1', > 'affiliation': > >>>> 'IATA', 'affiliation_no': > u'none'}, {'index': 0, 'title': > 'Association of > >>>> Airline Cons.', 'selected': > False, 'edit_row': '?edit_affiliation=0', > >>>> 'affiliation': 'AAC', > 'affiliation_no': u'sss'}, {'index': > 1, 'title': > >>>> 'Association of British Travel > Agents', 'selected': False, 'edit_row': > >>>> '?edit_affiliation=1', > 'affiliation': 'ABTA', > 'affiliation_no': u'zser'}] > > > >>>> key = 'affiliation_no' > > > >>>> my_dup_keys = [] > >>>> merged_list = [] > > > >>>> mykeys = [item['affiliation'] for > item in mylist] > > > >>>> for x in mykeys: > > ? ? ? ?if mykeys.count(x) >= 2: > > ? ? ? ? ? ? ? ?my_dup_keys.append(x) > > > >>>> for item in mylist: > > ? ? ? ?if item['affiliation'] in > set(my_dup_keys): > > ? ? ? ? ? ? ? ?merged_list.append(item) > > > > > >>>> values = [d[key] for d in merged_list if > d.has_key(key)] > >>>> for dict in merged_list: > > ? ? ? ?dict[key] = values > > ? ? ? ?mylist.append(dict) > > > >>>> print mylist > > [{'index': 0, 'title': > 'Association of British Travel Agents', > 'selected': > > False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'ABTA', > > 'affiliation_no': [u'G3903', > u'zser']}, {'index': 1, 'title': > 'Appointed > > Agents of IATA', 'selected': False, > 'edit_row': '?edit_affiliation=1', > > 'affiliation': 'IATA', > 'affiliation_no': u'none'}, > {'index': 0, 'title': > > 'Association of Airline Cons.', > 'selected': False, 'edit_row': > > '?edit_affiliation=0', 'affiliation': > 'AAC', 'affiliation_no': u'sss'}, > > {'index': 1, 'title': 'Association > of British Travel Agents', 'selected': > > False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'ABTA', > > 'affiliation_no': [u'G3903', > u'zser']}, {'index': 0, 'title': > 'Association > > of British Travel Agents', 'selected': > False, 'edit_row': > > '?edit_affiliation=0', 'affiliation': > 'ABTA', 'affiliation_no': [u'G3903', > > u'zser']}, {'index': 1, > 'title': 'Association of British Travel > Agents', > > 'selected': False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'ABTA', > > 'affiliation_no': [u'G3903', > u'zser']}] > > > > > > This sort of works but I want to return a list that > updates 'mylist' not > > append to it, so I will get: > > > > [{'index': 0, 'title': > 'Association of British Travel Agents', > 'selected': > > False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'ABTA', > > 'affiliation_no': [u'G3903', > u'zser']}, {'index': 1, 'title': > 'Appointed > > Agents of IATA', 'selected': False, > 'edit_row': '?edit_affiliation=1', > > 'affiliation': 'IATA', > 'affiliation_no': u'none'}, > {'index': 0, 'title': > > 'Association of Airline Cons.', > 'selected': False, 'edit_row': > > '?edit_affiliation=0', 'affiliation': > 'AAC', 'affiliation_no': u'sss'}] > > > > It's a little hard to figure what you're getting > at. This looks like > a table represented by a list of dictionaries that > you'd like to group > by "affiliation." > > affiliation_nos = {} > for row in mylist: > > affiliation_nos.set_default(row['affiliation'],[]).append(row['affliation_no']) > > will give you a list of affiliation_no's for each > affiliation and if > you want a list of dicts, you could do > > mynewlist = [dict(affiliation=affiliation, affiliation_nos > = > affiliation_nos[affiliation]) for affiliation in > affiliation_nos.keys()] > > I don't know what to do about all the other fields > though. In your > example input list you have two dictionaries with > affiliation = > 'ABTA'. In your output you kept the one with > index=0 and threw away > index=1. (same for 'edit_row') How do you > determine which to keep? > > > ------------------------------ > > Message: 3 > Date: Fri, 13 Mar 2009 17:23:32 +0100 > From: ski > Subject: Re: [Tutor] update list of dictionaries based on > key > To: greg whittier > Cc: python tutor > Message-ID: <49BA8884.3040708 at khine.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > > > greg whittier wrote: > > On Fri, Mar 13, 2009 at 11:09 AM, ski > wrote: > >> Hello, > >> Here is what I have so far: > >> > >>>>> mylist = [{'index': 0, > 'title': 'Association of British Travel > Agents', > >>>>> 'selected': False, > 'edit_row': '?edit_affiliation=0', > 'affiliation': 'ABTA', > >>>>> 'affiliation_no': > u'G3903'}, {'index': 1, 'title': > 'Appointed Agents of > >>>>> IATA', 'selected': False, > 'edit_row': '?edit_affiliation=1', > 'affiliation': > >>>>> 'IATA', > 'affiliation_no': u'none'}, > {'index': 0, 'title': 'Association of > >>>>> Airline Cons.', > 'selected': False, 'edit_row': > '?edit_affiliation=0', > >>>>> 'affiliation': 'AAC', > 'affiliation_no': u'sss'}, {'index': > 1, 'title': > >>>>> 'Association of British Travel > Agents', 'selected': False, 'edit_row': > >>>>> '?edit_affiliation=1', > 'affiliation': 'ABTA', > 'affiliation_no': u'zser'}] > >>>>> key = 'affiliation_no' > >>>>> my_dup_keys = [] > >>>>> merged_list = [] > >>>>> mykeys = [item['affiliation'] > for item in mylist] > >>>>> for x in mykeys: > >> if mykeys.count(x) >= 2: > >> my_dup_keys.append(x) > >> > >>>>> for item in mylist: > >> if item['affiliation'] in > set(my_dup_keys): > >> merged_list.append(item) > >> > >> > >>>>> values = [d[key] for d in merged_list > if d.has_key(key)] > >>>>> for dict in merged_list: > >> dict[key] = values > >> mylist.append(dict) > >> > >>>>> print mylist > >> [{'index': 0, 'title': > 'Association of British Travel Agents', > 'selected': > >> False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'ABTA', > >> 'affiliation_no': [u'G3903', > u'zser']}, {'index': 1, 'title': > 'Appointed > >> Agents of IATA', 'selected': False, > 'edit_row': '?edit_affiliation=1', > >> 'affiliation': 'IATA', > 'affiliation_no': u'none'}, > {'index': 0, 'title': > >> 'Association of Airline Cons.', > 'selected': False, 'edit_row': > >> '?edit_affiliation=0', > 'affiliation': 'AAC', > 'affiliation_no': u'sss'}, > >> {'index': 1, 'title': > 'Association of British Travel Agents', > 'selected': > >> False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'ABTA', > >> 'affiliation_no': [u'G3903', > u'zser']}, {'index': 0, 'title': > 'Association > >> of British Travel Agents', 'selected': > False, 'edit_row': > >> '?edit_affiliation=0', > 'affiliation': 'ABTA', > 'affiliation_no': [u'G3903', > >> u'zser']}, {'index': 1, > 'title': 'Association of British Travel > Agents', > >> 'selected': False, 'edit_row': > '?edit_affiliation=1', 'affiliation': > 'ABTA', > >> 'affiliation_no': [u'G3903', > u'zser']}] > >> > >> > >> This sort of works but I want to return a list > that updates 'mylist' not > >> append to it, so I will get: > >> > >> [{'index': 0, 'title': > 'Association of British Travel Agents', > 'selected': > >> False, 'edit_row': > '?edit_affiliation=0', 'affiliation': > 'ABTA', > >> 'affiliation_no': [u'G3903', > u'zser']}, {'index': 1, 'title': > 'Appointed > >> Agents of IATA', 'selected': False, > 'edit_row': '?edit_affiliation=1', > >> 'affiliation': 'IATA', > 'affiliation_no': u'none'}, > {'index': 0, 'title': > >> 'Association of Airline Cons.', > 'selected': False, 'edit_row': > >> '?edit_affiliation=0', > 'affiliation': 'AAC', > 'affiliation_no': u'sss'}] > >> > > > > It's a little hard to figure what you're > getting at. This looks like > > a table represented by a list of dictionaries that > you'd like to group > > by "affiliation." > > i have objects in my database, called addresses, each > address has a > metadata called affiliation. > > also each address is a member of a company. > > in my company class, i wanted to get all the addresses > affiliations and > only list the unique values. > > > > > > affiliation_nos = {} > > for row in mylist: > > > affiliation_nos.set_default(row['affiliation'],[]).append(row['affliation_no']) > > > > will give you a list of affiliation_no's for each > affiliation and if > > you want a list of dicts, you could do > > > > mynewlist = [dict(affiliation=affiliation, > affiliation_nos = > > affiliation_nos[affiliation]) for affiliation in > > affiliation_nos.keys()] > > > > I don't know what to do about all the other fields > though. In your > > example input list you have two dictionaries with > affiliation = > > 'ABTA'. In your output you kept the one with > index=0 and threw away > > index=1. (same for 'edit_row') How do you > determine which to keep? > > I want to keep it based on the 'affiliation' key. > > > In essence, from my original 'mylist' I want to > keep all the list items > as they are, but just update the list items that have more > than one > 'affiliation' by updating only the > 'affiliation_no' to contain both entries. > > Perhaps there is a simpler way to do this ;) > > I will change my code so that mylist does not contain the > 'index' and > 'edit_row' keys. Perhaps then it will be easier to > update the dictionary? > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ------------------------------ > > Message: 4 > Date: Fri, 13 Mar 2009 12:29:16 -0500 > From: W W > Subject: [Tutor] best gui for the job? > To: "tutor at python.org" > Message-ID: > <333efb450903131029r62a29c30n60d24c5003fa7142 at mail.gmail.com> > Content-Type: text/plain; charset=windows-1252 > > Hi, > > What is the best gui to implement a simple paint-esque > program in? > > I already built a really simple one in Tkinter - but > Tkinter lacks a > save functionality. I considered using the PIL to draw in > the > background, but it didn't seem to have a good enough > resolution. I > thought about pyGTK because I have some familiarity with > that, but I > can't find any examples of saving a drawingarea. > > Also, to clarify what I mean by "best" - I want > it to be fairly simple > to implement (my non-saving sketch in a single color/size > is about 100 > lines), yet extensible - I'd like the ability to > further enhance my > program down the road. Changing the opacity, and the > possibility to > work with layers is a plus. > > If anyone has tips or knows of any tutorials (I haven't > really been > able to find anything suitable), please let me know. > > Thanks for any suggestions, > Wayne > > -- > To be considered stupid and to be told so is more painful > than being > called gluttonous, mendacious, violent, lascivious, lazy, > cowardly: > every weakness, every vice, has found its defenders, its > rhetoric, its > ennoblement and exaltation, but stupidity hasn?t. - Primo > Levi > > > ------------------------------ > > Message: 5 > Date: Sat, 14 Mar 2009 05:18:00 +1100 > From: Lie Ryan > Subject: Re: [Tutor] best gui for the job? > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > W W wrote: > > Hi, > > > > What is the best gui to implement a simple paint-esque > program in? > > > > I already built a really simple one in Tkinter - but > Tkinter lacks a > > save functionality. I considered using the PIL to draw > in the > > background, but it didn't seem to have a good > enough resolution. I > > thought about pyGTK because I have some familiarity > with that, but I > > can't find any examples of saving a drawingarea. > > What do you mean "good enough resolution"? > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 61, Issue 50 > ************************************* From emile at fenx.com Sat Mar 14 01:15:56 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 13 Mar 2009 17:15:56 -0700 Subject: [Tutor] help In-Reply-To: <29406.97163.qm@web55004.mail.re4.yahoo.com> References: <29406.97163.qm@web55004.mail.re4.yahoo.com> Message-ID: Sanhita Mallick wrote: > help YOU ARE STANDING AT THE END OF A ROAD BEFORE A SMALL BRICK BUILDING . AROUND YOU IS A FOREST. A SMALL STREAM FLOWS OUT OF THE BUILDING AND DOWN A GULLY. Emile From bgailer at gmail.com Sat Mar 14 02:18:52 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 13 Mar 2009 21:18:52 -0400 Subject: [Tutor] help In-Reply-To: References: <29406.97163.qm@web55004.mail.re4.yahoo.com> Message-ID: <49BB05FC.3040008@gmail.com> A hollow voice says PLUGH. Be sure your lantern is lit! -- Bob Gailer Chapel Hill NC 919-636-4239 From dukelx2005 at gmail.com Sat Mar 14 01:43:42 2009 From: dukelx2005 at gmail.com (Jared White) Date: Fri, 13 Mar 2009 20:43:42 -0400 Subject: [Tutor] Having an Issue Message-ID: <9239372b0903131743o2c037367m90e9221e82fd4fe3@mail.gmail.com> I dunno how this works but hopefully someone can help me I am trying to build a program in Python but for someone i can not get what i am trying to build WORK by email you guys is there a way i can get some help some pointer on the program i am trying to solve Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Mar 14 05:44:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 14 Mar 2009 00:44:18 -0400 Subject: [Tutor] Having an Issue In-Reply-To: <9239372b0903131743o2c037367m90e9221e82fd4fe3@mail.gmail.com> References: <9239372b0903131743o2c037367m90e9221e82fd4fe3@mail.gmail.com> Message-ID: <1c2a2c590903132144u3f50877fo6697af348331e27b@mail.gmail.com> On Fri, Mar 13, 2009 at 8:43 PM, Jared White wrote: > I dunno how this works but hopefully someone can help me > > I am trying to build a program in Python but for someone i can not get what > i am trying to build WORK > > by email you guys is there a way i can get some help some pointer on the > program i am trying to solve Yes, just send your questions to the list and we will try to help. It works best if you can - clearly describe what you are trying to do - show what you have tried so far - tell us what happens, including full error messages if any Kent From qsqgeekyogdty at tiscali.co.uk Sat Mar 14 14:16:22 2009 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Sat, 14 Mar 2009 14:16:22 +0100 (GMT+01:00) Subject: [Tutor] TypeError: dict objects are unhashable Message-ID: <16014207.1237036582618.JavaMail.root@ps26> hi, i have a list which contains duplicate dictionaries. how do i extract the unique items out? l1 = [{'a': 'ddd'}, {'a': 'ddd'}, {'b': 'eee'}, {'c': 'ggg'}] set(l1) TypeError: dict objects are unhashable but, >>> {'a': 'ddd'} == {'a': 'ddd'} True >>> david Fancy a job? - http://www.tiscali.co.uk/jobs/ __________________________________________ From metolone+gmane at gmail.com Sat Mar 14 15:57:06 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 14 Mar 2009 07:57:06 -0700 Subject: [Tutor] TypeError: dict objects are unhashable References: <16014207.1237036582618.JavaMail.root@ps26> Message-ID: wrote in message news:16014207.1237036582618.JavaMail.root at ps26... > hi, > i have a list which contains duplicate dictionaries. > > how do i extract the unique items out? > > l1 = [{'a': 'ddd'}, {'a': 'ddd'}, {'b': 'eee'}, {'c': 'ggg'}] > set(l1) > TypeError: dict objects are unhashable > > but, >>>> {'a': 'ddd'} == {'a': 'ddd'} > True How about: >>> l1 = [{'a': 'ddd'}, {'a': 'ddd'}, {'b': 'eee'}, {'c': 'ggg'}] >>> [dict(n) for n in set(tuple(n.items()) for n in l1)] [{'c': 'ggg'}, {'b': 'eee'}, {'a': 'ddd'}] -Mark From emile at fenx.com Sat Mar 14 22:27:32 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 14 Mar 2009 14:27:32 -0700 Subject: [Tutor] TypeError: dict objects are unhashable In-Reply-To: References: <16014207.1237036582618.JavaMail.root@ps26> Message-ID: Mark Tolonen wrote: >>>> [dict(n) for n in set(tuple(n.items()) for n in l1)] Anyone know if the ordered items for two different dicts where dicta == dictb is guaranteed the same? I know the ordering is unspecified but you can depend on the sequence of keys matching data and I think it'll also match items. but for all DA's and DB's below, is that true? >>> a = range(52) >>> import string >>> DA = dict(zip(a,string.letters)) >>> DB = dict(zip(a,string.letters)) >>> DA == DB True >>> DA.items() == DB.items() True >>> Emile From echolynx at gmail.com Sat Mar 14 22:49:52 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 14 Mar 2009 17:49:52 -0400 Subject: [Tutor] Simple User Entry Verification Message-ID: Newbie here who can't figure out why this doesn't work: start = input("Please enter the starting number.\n>") print(type(start)) while type(start)!=float: start = input("Sorry, that number was invalid.\nPlease enter the starting number.\n>") print(type(start)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Sat Mar 14 22:52:32 2009 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 14 Mar 2009 17:52:32 -0400 Subject: [Tutor] Simple User Entry Verification In-Reply-To: References: Message-ID: <58935358143.20090314175232@columbus.rr.com> > while type(start)!=float: Did you try quotes around the word "float"? Alan From amonroe at columbus.rr.com Sat Mar 14 23:07:33 2009 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 14 Mar 2009 18:07:33 -0400 Subject: [Tutor] Simple User Entry Verification In-Reply-To: References: Message-ID: <110936259890.20090314180733@columbus.rr.com> > Newbie here who can't figure out why this doesn't work: > start = input("Please enter the starting number.\n>") > print(type(start)) > while type(start)!=float: > start = input("Sorry, that number was invalid.\nPlease enter the starting number.\n>>") > print(type(start)) Google to the rescue. Try this: while not isinstance(start, float) Alan From lagrapidis at yahoo.com Sat Mar 14 23:30:35 2009 From: lagrapidis at yahoo.com (Lukas Agrapidis) Date: Sat, 14 Mar 2009 15:30:35 -0700 (PDT) Subject: [Tutor] Parse XML file Message-ID: <876506.96777.qm@web36108.mail.mud.yahoo.com> I am trying to parse an XML file using Python and found this resource http://diveintopython.org/xml_processing/parsing_xml.html But I didn't even get past the second line... it does not see the xml file? But it is there. >>> from xml.dom import minidom >>> xmldoc = minidom.parse('~/Desktop/test/test.xml') Traceback (most recent call last): File "", line 1, in xmldoc = minidom.parse('~/Desktop/test/test.xml') File "C:\Program Files\python26\lib\xml\dom\minidom.py", line 1918, in parse return expatbuilder.parse(file) File "C:\Program Files\python26\lib\xml\dom\expatbuilder.py", line 922, in parse fp = open(file, 'rb') IOError: [Errno 2] No such file or directory: '~/Desktop/test/test.xml' >>> Lukas ________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lagrapidis at yahoo.com Sat Mar 14 23:47:22 2009 From: lagrapidis at yahoo.com (Lukas Agrapidis) Date: Sat, 14 Mar 2009 15:47:22 -0700 (PDT) Subject: [Tutor] Parse XML file In-Reply-To: <876506.96777.qm@web36108.mail.mud.yahoo.com> References: <876506.96777.qm@web36108.mail.mud.yahoo.com> Message-ID: <913481.11854.qm@web36105.mail.mud.yahoo.com> Sorry please ignore... I changed the path to c:\temp\test.xml and it worked just fine. I'm sure I'll have some questions when I actually start playing with it though. Lukas ________________________________ ________________________________ From: Lukas Agrapidis To: tutor at python.org Sent: Saturday, March 14, 2009 6:30:35 PM Subject: [Tutor] Parse XML file I am trying to parse an XML file using Python and found this resource http://diveintopython.org/xml_processing/parsing_xml.html But I didn't even get past the second line... it does not see the xml file? But it is there. >>> from xml.dom import minidom >>> xmldoc = minidom.parse('~/Desktop/test/test.xml') Traceback (most recent call last): File "", line 1, in xmldoc = minidom.parse('~/Desktop/test/test.xml') File "C:\Program Files\python26\lib\xml\dom\minidom.py", line 1918, in parse return expatbuilder.parse(file) File "C:\Program Files\python26\lib\xml\dom\expatbuilder.py", line 922, in parse fp = open(file, 'rb') IOError: [Errno 2] No such file or directory: '~/Desktop/test/test.xml' >>> Lukas ________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 15 01:35:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Mar 2009 00:35:20 -0000 Subject: [Tutor] Simple User Entry Verification References: Message-ID: "Ian Egland" wrote > Newbie here who can't figure out why this doesn't work: It worked perfectly for me. But then, maybe I expected it to do something different to what you expected? When posting please tell us what you expected to happen, what actually happened plus any error messages (in full) (It also helps if you tell us what OS and what version of Python. I'd guess from your print statements that you are using v3 here?) That way we can align our answers to your expectation... > start = input("Please enter the starting number.\n>") > print(type(start)) > while type(start)!=float: > start = input("Sorry, that number was invalid.\nPlease enter the > starting number.\n>") > print(type(start)) The key thing to note here is that input() in Python v3 always returns a string, you need to convert it to a different type. In your case you probably want to try converting to a float: start = float(input("Please enter the starting number.\n>")) print(type(start)) > while type(start)!=float: Now instead of using a while loop to test the type you can expect an exception if the type is not a float. But that's a topic for another time! HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From echolynx at gmail.com Sun Mar 15 02:21:09 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 14 Mar 2009 21:21:09 -0400 Subject: [Tutor] Simple User Entry Verification In-Reply-To: <24947434528.20090314211348@columbus.rr.com> References: <110936259890.20090314180733@columbus.rr.com> <45936528817.20090314181202@columbus.rr.com> <24947434528.20090314211348@columbus.rr.com> Message-ID: I'm sorry I wasn't more specifc. I will try to next time. Thanks Alan for you help. (Both of you.) -Ian On Sat, Mar 14, 2009 at 9:13 PM, R. Alan Monroe wrote: > > Success (as in number is entered) = Success > > Failure (as in a letter is entered) = failure > > Working as designed :) Python is _supposed_ to throw an exception when > trying to convert text to float. Have you learnt about try/except > statements yet? If not, that's your next stop. > > Alan > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimcarnell at yahoo.com Sun Mar 15 09:22:00 2009 From: jimcarnell at yahoo.com (james carnell) Date: Sun, 15 Mar 2009 01:22:00 -0700 (PDT) Subject: [Tutor] How to only give the user so much time to enter response? Message-ID: <733752.66937.qm@web54307.mail.re2.yahoo.com> Trying to use Timer in console based game that gives the user so much time to act. If they do not act then it just passes the turn back to the program to do the next thing. I have Python 2.5 and Windows XP. http://www.python.org/doc/2.5.2/lib/timer-objects.html def hello(): print "hello, world" t = Timer(30.0, hello) TypeError:__init__() takes exactly 2 arguments (3 given) =============================== http://mail.python.org/pipermail/tutor/2004-November/033333.html Also tried this, but I think it might be outdated. When I type it in it never triggers the function. ================================ so... this kind is where I am: t=Timer(10.0) def waitFunction(timerObj): newMove = 5 #5 = player will stay in same position on 2d array newMove = int(raw_input("Move 1-9 / 0 to quit:")) timerObj.start() while timerObj.isAlive(): pass print newMove It works, but I am guessing it isn't a very good way to do it. I am curious why I can't get anything to work from the docs. Any help appreciated (and hopefully yahoo won't butcher my indentation). -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 15 09:57:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Mar 2009 08:57:30 -0000 Subject: [Tutor] How to only give the user so much time to enter response? References: <733752.66937.qm@web54307.mail.re2.yahoo.com> Message-ID: "james carnell" wrote > Trying to use Timer in console based game that gives the user > so much time to act. Thats quite tricky in standard console mode. If you were on Linux (or MacOS?) you could use curses and I think it would be easier there. But on XP I think you may have to get into the world of threads and launch the input prompt in a separate thread which can be terminated after the timeout. Its one of those things that is easier in a GUI than in a console. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Sun Mar 15 10:56:22 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 15 Mar 2009 10:56:22 +0100 Subject: [Tutor] Parse XML file In-Reply-To: <876506.96777.qm@web36108.mail.mud.yahoo.com> References: <876506.96777.qm@web36108.mail.mud.yahoo.com> Message-ID: Lukas Agrapidis wrote: > I am trying to parse an XML file using Python and found this resource > http://diveintopython.org/xml_processing/parsing_xml.html You might be interested in ElementTree: http://effbot.org/zone/element.htm It's a lot easier to use than minidom, especially for new users. It's available in the standard library as "xml.etree.ElementTree" module since Python 2.5. Stefan From lie.1296 at gmail.com Sun Mar 15 12:40:10 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 15 Mar 2009 22:40:10 +1100 Subject: [Tutor] TypeError: dict objects are unhashable In-Reply-To: References: <16014207.1237036582618.JavaMail.root@ps26> Message-ID: Emile van Sebille wrote: > Mark Tolonen wrote: >>>>> [dict(n) for n in set(tuple(n.items()) for n in l1)] > > Anyone know if the ordered items for two different dicts where dicta == > dictb is guaranteed the same? I know the ordering is unspecified but > you can depend on the sequence of keys matching data and I think it'll > also match items. > > but for all DA's and DB's below, is that true? > Considering how dictionary is implemented, I don't think so. The dictionary is internally implemented as a hash table, and two dictionary with identical items may have different sized hash table, the algorithm guarantees efficient usage of memory (it resizes when it's too small or too big). On a resize, the hashes are recalculated and the ordering rescrambled. From roberto03 at gmail.com Sun Mar 15 12:45:12 2009 From: roberto03 at gmail.com (roberto) Date: Sun, 15 Mar 2009 12:45:12 +0100 Subject: [Tutor] calling user defined function In-Reply-To: <49A1CD47.9020401@gmail.com> References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> <49A1CD47.9020401@gmail.com> Message-ID: <4bcde3e10903150445ueaaf5dfx2614f26d7199905e@mail.gmail.com> On Sun, Feb 22, 2009 at 11:10 PM, bob gailer wrote: > roberto wrote: >> >> hello >> i have a question which i didn't solved yet: >> i can define a function using the text editor provided by IDLE 3.0; >> then i'd like to call this function from the python prompt >> >> but when i try to do it, python warns me that function doesn't exist >> of course if i define the function directly using the >>> prompt, >> after that everything is fine >> >> may you tell me where i have to save the file that defines the >> function is order to use it later ? >> is it a problem of path ? >> > > Let's say you saved the file as foo.py. Then: >>>> import foo >>>> foo.afunction() > thank you very much, the help you provided me works fine nonetheless, yesterday i met a little problem: the procedure you indicated me >>>> import foo >>>> foo.afunction() works fine but when i modify the function "afunction" in the file foo.py then no change occurs when i call it again, i mean the function behavior is exactely the same as before i made any modification; i tried to import foo again, but nothing happens, the output of "foo.afunction" is as if i never made any change to it ... if you have any suggestion, it is very appreciated -- roberto OS: GNU/Linux Debian Kubuntu, Edubuntu From qsqgeekyogdty at tiscali.co.uk Sun Mar 15 13:27:59 2009 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Sun, 15 Mar 2009 13:27:59 +0100 (GMT+01:00) Subject: [Tutor] TypeError: list objects are unhashable Message-ID: <16876607.1237120079665.JavaMail.root@ps30> >>> l1 = [{'url': 'ws.geonames.org', 'type': 'findNearby', 'parameters': [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org', 'type': 'findNearby', 'parameters': [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org', 'type': 'countryInfo', 'parameters': [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org', 'type': 'countryInfo', 'parameters': [50.100000000000001, 10.02]}] >>> [dict(n) for n in set(tuple(n.items()) for n in l1)] Traceback (most recent call last): File "", line 1, in TypeError: list objects are unhashable How do I make this return two records instead of four? Fancy a job? - http://www.tiscali.co.uk/jobs/ __________________________________________ From kent37 at tds.net Sun Mar 15 14:20:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Mar 2009 09:20:04 -0400 Subject: [Tutor] Simple User Entry Verification In-Reply-To: <58935358143.20090314175232@columbus.rr.com> References: <58935358143.20090314175232@columbus.rr.com> Message-ID: <1c2a2c590903150620h4a001d1aq676f781bd869ddef@mail.gmail.com> On Sat, Mar 14, 2009 at 5:52 PM, R. Alan Monroe wrote: > >> while type(start)!=float: > > Did you try quotes around the word "float"? That won't help, type(start) is a type object, not a string. It's also possible that Ian is entering an integer, he didn't show the input value: In [1]: print type(input('Enter a number: ')) Enter a number: 123 Alan G's solution - explicit conversion using float() with an exception handler - is the best way to do this. Kent From kent37 at tds.net Sun Mar 15 14:28:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Mar 2009 09:28:39 -0400 Subject: [Tutor] How to only give the user so much time to enter response? In-Reply-To: <733752.66937.qm@web54307.mail.re2.yahoo.com> References: <733752.66937.qm@web54307.mail.re2.yahoo.com> Message-ID: <1c2a2c590903150628h162356c4y47f35a61fcdc04d8@mail.gmail.com> On Sun, Mar 15, 2009 at 4:22 AM, james carnell wrote: > Trying to use Timer in console based game that gives the user so much time > to act. If they do not act then it just passes the turn back to the program > to do the next thing. I have Python 2.5 and Windows XP. > so... this kind is where I am: > > t=Timer(10.0) > > def waitFunction(timerObj): > newMove = 5 #5 = player will stay in same position on 2d array > newMove = int(raw_input("Move 1-9 / 0 to > quit:")) > timerObj.start() > while timerObj.isAlive(): > pass > print newMove > > It works, but I am guessing it isn't a very good way to do it. I am surprised that this works. The raw_input() call should block until the user enters a move. One way to do this would be to poll for user input using kbhit(). If a key is not hit in your required interval, exit the loop and continue processing. You don't need a threaded timer for this, just use time.time() to measure duration. On Windows use msvcrt.kbhit() and msvcrt.getch(). On Linux (or Mac?) use this recipe: http://code.activestate.com/recipes/572182/ Kent From bgailer at gmail.com Sun Mar 15 14:56:13 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 15 Mar 2009 09:56:13 -0400 Subject: [Tutor] How to only give the user so much time to enter response? In-Reply-To: <733752.66937.qm@web54307.mail.re2.yahoo.com> References: <733752.66937.qm@web54307.mail.re2.yahoo.com> Message-ID: <49BD08FD.9030209@gmail.com> james carnell wrote: > Trying to use Timer in console based game that gives the user so much > time to act. If they do not act then it just passes the turn back to > the program to do the next thing. I have Python 2.5 and Windows XP. > > http://www.python.org/doc/2.5.2/lib/timer-objects.html > def hello(): > print "hello, world" > > t = Timer(30.0, hello) > TypeError:__init__() takes exactly 2 arguments (3 given) > > Where is Timer defined? If you used from threading import Timer you should not get that error. > =============================== > http://mail.python.org/pipermail/tutor/2004-November/033333.html > > Also tried this, but I think it might be outdated. When I type it > in it never triggers the function. > ================================ > so... this kind is where I am: > > t=Timer(10.0) > > def waitFunction(timerObj): > newMove = 5 #5 = player will stay in same position on 2d array > newMove = int(raw_input("Move 1-9 / 0 to > quit:")) > timerObj.start() > while timerObj.isAlive(): > pass > print newMove > > It works, but I am guessing it isn't a very good way to do it. > I am curious why I can't get anything to work from the docs. > Any help appreciated (and hopefully yahoo won't butcher my indentation). > > > > > > > > > > > -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Sun Mar 15 15:00:02 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 15 Mar 2009 10:00:02 -0400 Subject: [Tutor] calling user defined function In-Reply-To: <4bcde3e10903150445ueaaf5dfx2614f26d7199905e@mail.gmail.com> References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> <49A1CD47.9020401@gmail.com> <4bcde3e10903150445ueaaf5dfx2614f26d7199905e@mail.gmail.com> Message-ID: <49BD09E2.9020601@gmail.com> roberto wrote: > On Sun, Feb 22, 2009 at 11:10 PM, bob gailer wrote: > >> roberto wrote: >> >>> hello >>> i have a question which i didn't solved yet: >>> i can define a function using the text editor provided by IDLE 3.0; >>> then i'd like to call this function from the python prompt >>> >>> but when i try to do it, python warns me that function doesn't exist >>> of course if i define the function directly using the >>> prompt, >>> after that everything is fine >>> >>> may you tell me where i have to save the file that defines the >>> function is order to use it later ? >>> is it a problem of path ? >>> >>> >> Let's say you saved the file as foo.py. Then: >> >>>>> import foo >>>>> foo.afunction() >>>>> > > thank you very much, the help you provided me works fine > > nonetheless, yesterday i met a little problem: > the procedure you indicated me > > >>>>> import foo >>>>> foo.afunction() >>>>> > > works fine but when i modify the function "afunction" in the file > foo.py then no change occurs when i call it again, i mean the function > behavior is exactely the same as before i made any modification; i > tried to import foo again, but nothing happens, the output of > "foo.afunction" is as if i never made any change to it ... > > if you have any suggestion, it is very appreciated > After initially importing foo you must reload(foo) for changes to take effect. -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Sun Mar 15 15:00:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Mar 2009 10:00:48 -0400 Subject: [Tutor] TypeError: list objects are unhashable In-Reply-To: <16876607.1237120079665.JavaMail.root@ps30> References: <16876607.1237120079665.JavaMail.root@ps30> Message-ID: <1c2a2c590903150700p494a22d2kab9269d8e76e83f9@mail.gmail.com> On Sun, Mar 15, 2009 at 8:27 AM, qsqgeekyogdty at tiscali.co.uk wrote: >>>> l1 = [{'url': 'ws.geonames.org', 'type': 'findNearby', > 'parameters': [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org', > 'type': 'findNearby', 'parameters': [50.100000000000001, 10.02]}, > {'url': 'ws.geonames.org', 'type': 'countryInfo', 'parameters': > [50.100000000000001, 10.02]}, {'url': 'ws.geonames.org', 'type': > 'countryInfo', 'parameters': [50.100000000000001, 10.02]}] > >>>> [dict(n) for n in set(tuple(n.items()) for n in l1)] > Traceback (most recent call last): > ?File "", line 1, in > TypeError: list objects are unhashable > > How do I make this return two records instead of four? If performance is not an issue you could use brute force: In [9]: l2 = [] In [10]: for d in l1: ....: if d not in l2: ....: l2.append(d) In [11]: l2 Out[11]: [{'parameters': [50.100000000000001, 10.02], 'type': 'findNearby', 'url': 'ws.geonames.org'}, {'parameters': [50.100000000000001, 10.02], 'type': 'countryInfo', 'url': 'ws.geonames.org'}] if you have many dicts in l1 this is likely to be slow. Where do the dicts come from? If they are from a database you could ask the database for unique records. Kent Kent From dukelx2005 at gmail.com Sun Mar 15 15:13:56 2009 From: dukelx2005 at gmail.com (Jared White) Date: Sun, 15 Mar 2009 10:13:56 -0400 Subject: [Tutor] Need Assistants with Python Please Message-ID: <9239372b0903150713w72559d27k9782d6ac39d66d64@mail.gmail.com> Good Morning Everyone, I am having a little issue with Python, Hopefully Someone Can Help Me.... I am trying to Develop a Python program that converts a single fuel rating from mpg to lp100km. So far ive come up with this code. But it seems not to be working, Can someone please help me figure out what ive done wrong def main (): print "The program converts Miles Per Gallon (US) to Liters Per 100 Kilometer." kilometers = input ("What is the Miles Per Gallon?") MilesperUSGallon * (1.60934/3.78541) = kilometersperliter. 1/(kilometers per liter) = liters per kilometer. Liters/kilometer * 100 = liters per 100 km. print "The Distance in Miles per Gallon", miles\ main () But is has giving me an error like ive done something wrong with the spacing.. Can someone please check my work to see what ive done wrong here. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 15 16:42:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Mar 2009 15:42:38 -0000 Subject: [Tutor] Need Assistants with Python Please References: <9239372b0903150713w72559d27k9782d6ac39d66d64@mail.gmail.com> Message-ID: "Jared White" wrote > So far ive come up with this code. But it seems not to be working, > Can > someone please help me figure out what ive done wrong > > def main (): > print "The program converts Miles Per Gallon (US) to Liters Per > 100 > Kilometer." > kilometers = input ("What is the Miles Per Gallon?") This might be better named mpg? > MilesperUSGallon * (1.60934/3.78541) = kilometersperliter. > 1/(kilometers > per liter) = liters per kilometer. Liters/kilometer * 100 = liters > per 100 > km. I have no idea what you think this line does but it isn't valid Python so you will get an error! MilesperUSGallon * (1.60934/3.78541) = kilometersperliter This bit is almost valid except you dont define kilometersperliter anywhere. . 1/(kilometers per liter) = liters per kilometer. Liters/kilometer * 100 = liters per 100 km. But this makes no sense whatsoever to me or Python... Do you think the dot at the front makes it a comment maybe? If so you need to use a # sign. But I'm still notclear what the comment refers to in your program? > print "The Distance in Miles per Gallon", miles\ And I'm not sure why there is a \ at the end of this line? > But is has giving me an error like ive done something wrong with the > spacing.. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Sun Mar 15 16:53:25 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 15 Mar 2009 08:53:25 -0700 Subject: [Tutor] Need Assistants with Python Please In-Reply-To: <9239372b0903150713w72559d27k9782d6ac39d66d64@mail.gmail.com> References: <9239372b0903150713w72559d27k9782d6ac39d66d64@mail.gmail.com> Message-ID: Jared White wrote: > Good Morning Everyone, > > I am having a little issue with Python, Actually, two... > > Hopefully Someone Can Help Me.... > > I am trying to Develop a Python program that converts a single fuel > rating from mpg to lp100km. > > So far ive come up with this code. But it seems not to be working, Can > someone please help me figure out what ive done wrong > > def main (): > print "The program converts Miles Per Gallon (US) to Liters Per 100 > Kilometer." > kilometers = input ("What is the Miles Per Gallon?") Review the use of input at http://docs.python.org/library/functions.html?highlight=input#input > MilesperUSGallon * (1.60934/3.78541) = kilometersperliter. > 1/(kilometers per liter) = liters per kilometer. Liters/kilometer * 100 > = liters per 100 km. Read up a little on variable usage. Start at http://docs.python.org/tutorial/introduction.html HTH, Emile From marc at Marcd.org Sun Mar 15 16:25:27 2009 From: marc at Marcd.org (marc at Marcd.org) Date: Sun, 15 Mar 2009 11:25:27 -0400 (EDT) Subject: [Tutor] Parse XML file In-Reply-To: References: Message-ID: <49480.64.252.205.230.1237130727.squirrel@webmail1.hrnoc.net> > Message: 5 > Date: Sun, 15 Mar 2009 10:56:22 +0100 > From: Stefan Behnel > Subject: Re: [Tutor] Parse XML file > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1 > > Lukas Agrapidis wrote: >> I am trying to parse an XML file using Python and found this resource http://diveintopython.org/xml_processing/parsing_xml.html > > You might be interested in ElementTree: > > http://effbot.org/zone/element.htm > > It's a lot easier to use than minidom, especially for new users. It's available in the standard library as "xml.etree.ElementTree" module since > Python 2.5. > I would agree - I was struggling with minidom, Stefan recommended ElementTree and another person (deleted the email and can't recall his name) recommended lxml. I was able to get a working understanding of these libraries in less than an hour and solve the problems I had encountered with minidom in a very short time. (BTW, parsing xml was probably a poor choice for my first project while learning Python, but then again, nobody has ever accused me of making my life easy) Marc From s.brendy at gmail.com Mon Mar 16 02:29:01 2009 From: s.brendy at gmail.com (Brendy Siguenza) Date: Sun, 15 Mar 2009 18:29:01 -0700 Subject: [Tutor] Help With Rock, Paper Scissor Game Message-ID: This is the template that we are suppose to use while doing the program, I am a beginner to this programming language and really have no clue what I am doing import random #table of winning plays win_play_for = {?r?:?p?, ?p?:?s?, ?s?:?r?} #scoring results player_score = 0 mach_score = 0 #keep track of users?last plays #assume initially an even distribution hist = [?r?, ?p?, ?s?, ?r?, ?p?, ?s?, ?r?, ?p?, ?s?] next = 0 #index of where to put next user play while True: #guess what user play will be based on past #behavior. Pick a machine play to win based #on guess #get user?s play user_play = raw_input("what?s your play (r|p|s)? ") #if the user does not respond with one of those break #otherwise #update history of user plays #determine winner for current play or draw #print results of current play and scores so far NOW THIS IS WHAT I HAVE SO FAR, AND THESE ARE ALL JUMBLE AROUND BECAUSE I HAVE NO CLUE WHERE THEY ARE SUPPOSE TO GO PLZ HELP import random #table of winning plays win_play_for = {'r':'p', 'p':'s', 's':'r'} #scoring results player_score = 0 mach_score = 0 #kepp track of users' last plays #assume initially an even distribution hist = ['r', 'p', 's', 'r', 'p', 's', 'r', 'p', 's'] next = 0 #index of where to put next user play while True: hist = ['r', 'p', 's', 'r', 'p', 's', 'r', 'p', 's'] next = 0 guess = random_choice(hist) len (hist) #gets user's play user_play = raw_input("What's your play (r|p|s)?") hist[next] = user_play next = next + 1 if next == len(hist): next = 0 user_play == win_play_for(mach_play) mach_play == win_play_for(user_play) -------------- next part -------------- An HTML attachment was scrubbed... URL: From optomatic at rogers.com Mon Mar 16 03:47:49 2009 From: optomatic at rogers.com (Patrick) Date: Sun, 15 Mar 2009 22:47:49 -0400 Subject: [Tutor] way of dictating leading zeros Message-ID: <49BDBDD5.5040406@rogers.com> Hi Everyone I am trying to write a program that creates a bunch of svg files and then edits their values. I am then encoding them into a video. It's not encoding right because my filenames are wrong. They have to have a sequence. Right now they are 1.svg, 2.svg, 3.svg etc but they should be 001.svg, 002.svg, 003.svg. At the moment I think 12.svg is ending up before 2.svg because it starts with 1. Is there an easy way to dictate how many digits a number will occupy that also allows for leading zeros? Below is a sample of my code if it helps: Thanks in advance-Patrick def thingcreate(): thingfile = raw_input("Enter full pathname of your template: ") thingseconds = raw_input("Enter how many seconds your film will be: ") thingseconds =int(thingseconds) thingframes = raw_input("Enter how many frames per second your film will be: ") thingframes =int(thingframes) thingnumber = thingframes * thingseconds f = open(thingfile, 'r') thingread = f.read() for i in range(thingnumber): i = str(i) file =open(i+".svg", 'w') file.write(thingread) file.close() From andreengels at gmail.com Mon Mar 16 07:42:02 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 16 Mar 2009 07:42:02 +0100 Subject: [Tutor] way of dictating leading zeros In-Reply-To: <49BDBDD5.5040406@rogers.com> References: <49BDBDD5.5040406@rogers.com> Message-ID: <6faf39c90903152342t24d42f13y974174eaa1d799da@mail.gmail.com> On Mon, Mar 16, 2009 at 3:47 AM, Patrick wrote: > Hi Everyone > > I am trying to write a program that creates a bunch of svg files and > then edits their values. I am then encoding them into a video. It's not > encoding right because my filenames are wrong. They have to have a > sequence. Right now they are 1.svg, 2.svg, 3.svg etc but they should be > 001.svg, 002.svg, 003.svg. At the moment I think 12.svg is ending up > before 2.svg because it starts with 1. > > Is there an easy way to dictate how many digits a number will occupy > that also allows for leading zeros? "%03i"%i for example: "%03i"%2 equals "002" and "%03i"%12 equals "012". Of course in your case you can combine the adding of .svg at once: "%03i.svg"%2 equals "002.svg". Explanation of what this means: "blabla %s bla"%something means that the '%s' is to replaced by the string representation of something. Changing %s to %i means that the something is read as an integer for that, and %03i means that the integer has to be shown padded with zeroes with a length of (minimal) 3. -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Mon Mar 16 10:34:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Mar 2009 09:34:38 -0000 Subject: [Tutor] Help With Rock, Paper Scissor Game References: Message-ID: "Brendy Siguenza" wrote > This is the template that we are suppose to use while doing the > program, I > am a beginner to this programming language and really have no clue > what I am > doing We don;t do homework problems for you but we can try to point you in the right direction. First off, it looks like you don;t understand dictionaries? Try reading about dictionaries in a tutorial somwhere (eg mine - the Raw Materials topic has some info) > NOW THIS IS WHAT I HAVE SO FAR, AND THESE ARE ALL > JUMBLE AROUND BECAUSE I HAVE NO CLUE WHERE > THEY ARE SUPPOSE TO GO PLZ HELP Randomly coding is never a good idea. Try to work out how you would solve it in your head before charging into writing code. > import random > #table of winning plays > win_play_for = {'r':'p', 'p':'s', 's':'r'} This is a dictionary but you call it like a function. See my comments above #scoring results > player_score = 0 > mach_score = 0 You don't use these? What are they for and when should you set them? > #kepp track of users' last plays > #assume initially an even distribution > hist = ['r', 'p', 's', 'r', 'p', 's', 'r', 'p', 's'] > next = 0 #index of where to put next user play You set these here so dpnt need to set them again inside the while loop > while True: > hist = ['r', 'p', 's', 'r', 'p', 's', 'r', 'p', 's'] > next = 0 don't need those two lines > guess = random_choice(hist) > len (hist) The len() does nothing because you throw itr away. Plus its always the same so no point in calculating it every time round the loop. > #gets user's play > user_play = raw_input("What's your play (r|p|s)?") > hist[next] = user_play > next = next + 1 > if next == len(hist): > next = 0 This bit is fine. But where is the computers play? > user_play == win_play_for(mach_play) > mach_play == win_play_for(user_play) These are dictionaries not function. See comment above Also, where is the output? You never print anything? Go think some more and come back to use with specific questions about what you don't understand. Until you undersand the basic structure of what you are trying to do there is not much point in trying to fix the individual code issues. Try to describe how it should work in English before describing it in Python. You probably think better in English than you do in Python... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Mon Mar 16 10:38:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Mar 2009 09:38:01 -0000 Subject: [Tutor] way of dictating leading zeros References: <49BDBDD5.5040406@rogers.com> Message-ID: "Patrick" wrote > Is there an easy way to dictate how many digits a number will occupy > that also allows for leading zeros? Andre showed you the way to do this using "String Formatting". Search for that phrase in the docs for al lot more info. If you are considering using Python v3 then that style is deprecated and you may want to use the new String Formatter object. See the Python 3 string docs for more on that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk From a.t.hofkamp at tue.nl Mon Mar 16 10:50:14 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 16 Mar 2009 10:50:14 +0100 Subject: [Tutor] TypeError: dict objects are unhashable In-Reply-To: References: <16014207.1237036582618.JavaMail.root@ps26> Message-ID: <49BE20D6.9010404@tue.nl> Lie Ryan wrote: > Emile van Sebille wrote: >> Mark Tolonen wrote: >>>>>> [dict(n) for n in set(tuple(n.items()) for n in l1)] >> >> Anyone know if the ordered items for two different dicts where dicta >> == dictb is guaranteed the same? I know the ordering is unspecified >> but you can depend on the sequence of keys matching data and I think >> it'll also match items. >> >> but for all DA's and DB's below, is that true? >> > > Considering how dictionary is implemented, I don't think so. The > dictionary is internally implemented as a hash table, and two dictionary > with identical items may have different sized hash table, the algorithm > guarantees efficient usage of memory (it resizes when it's too small or > too big). On a resize, the hashes are recalculated and the ordering > rescrambled. And a short demo to confirm: Python 2.3.4 (#1, Jul 25 2008, 14:24:21) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = range(10) >>> y = x[:] >>> y.reverse() >>> d1 = dict([(i*1000, i) for i in x]) >>> d2 = dict([(i*1000, i) for i in y]) >>> d1.items() [(0, 0), (4000, 4), (1000, 1), (8000, 8), (6000, 6), (9000, 9), (2000, 2), (5000, 5), (7000, 7), (3000, 3)] >>> d2.items() [(8000, 8), (4000, 4), (2000, 2), (0, 0), (9000, 9), (6000, 6), (5000, 5), (3000, 3), (1000, 1), (7000, 7)] Sincerely, Albert From neven.gorsic at gmail.com Mon Mar 16 12:20:44 2009 From: neven.gorsic at gmail.com (=?ISO-8859-2?B?TmV2ZW4gR29yuWnm?=) Date: Mon, 16 Mar 2009 12:20:44 +0100 Subject: [Tutor] wxPython vs PyQt In-Reply-To: <49B66ACC.1020905@gmail.com> References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> <200903041810.24685.jfabiani@yolo.com> <8acd28da0903100555j68053abbj24928204f7dad937@mail.gmail.com> <49B66ACC.1020905@gmail.com> Message-ID: <8acd28da0903160420s7f5460ecxde43e8f3231aeb22@mail.gmail.com> I just would like to correct my incomplete PyQT pricing list from above and mislead none. If you intent to write commercial programs you have to pay: 400 EURO for PyQT AND 3000 EURO for QT !!! --------------------------------------------------------------------------------- On Tue, Mar 10, 2009 at 2:27 PM, andr? palma wrote: > Neven Gor?i? wrote: >> >> Thank you all. It was not easy to decide what to learn/use, so I "Google" >> some more. >> >> I have found that PyQT is more stable, faster, more consistent and more >> expensive :). >> 400 EURO is too much for playing around with some GUI, but GPL licence >> resolves that issue. >> The cons are C++ oriented documentation, editor and some structures ... >> >> Neven >> >> --------------- >> >> On Thu, Mar 5, 2009 at 3:10 AM, johnf > > wrote: >> >> On Wednesday 04 March 2009 04:56:37 pm Alan Gauld wrote: >> > "Kent Johnson" > wrote >> > >> > > I've heard good things about Dabo, never tried it myself though. >> > > http://dabodev.com/ >> > >> > I looked at Dabo but decided not to try it since it was yet another >> > framework. Although it's based on wxPython they have layered their >> > own widgets on top which is what the GUI Builder uses. (PythonCard >> > fell into the same hole) >> >> Yes, it's true that Dabo has wrapped (subclassed) most of the >> controls. The >> purpose of course was to provide developer ease of use. If you >> are building >> a real business app then I doubt there is anything better in the >> python >> world. I personally have used both VB and Delphi and see Dabo on >> the same >> level. With one exception - we have a beta GUI builder. >> Everything that has >> been done in Dabo is the very same things that all developers would be >> required to do if they access a database and associate fields to >> controls. >> BTW there is nothing stopping a Dabo developer from directly using wx >> controls. Dabo prevents nothing. >> >> So Alan, I don't see my work as falling into any hole. >> > >> > But the web pages and writeup looked good and the forum seemed >> > to be active and not all negative. >> > >> > Alan G >> > >> Hey, i've found your discussion interesting. >> > I'm developing my final course project and i'm using a toll called "Glade" > to create my application. It has a IDE that let you to create your windows, > with text boxes, combo boxes ... everything! And the really good thing: it > is totally open source =) > It's quit simple to do applications with glade. You just have to create your > GUI with it IDE and then you just need to link the "signals" to de functions > that actually preform actions. > > GLADE: > http://glade.gnome.org/ > http://www.pygtk.org/articles/pygtk-glade-gui/Creating_a_GUI_using_PyGTK_and_Glade.htm > (examples how to use glade and pyGTK) > > and if you look for it in youtube there is a lot of a good video tutorials > >> >> -- >> John Fabiani >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > From elena.valhalla at gmail.com Mon Mar 16 13:06:53 2009 From: elena.valhalla at gmail.com (Elena of Valhalla) Date: Mon, 16 Mar 2009 13:06:53 +0100 Subject: [Tutor] wxPython vs PyQt In-Reply-To: <8acd28da0903160420s7f5460ecxde43e8f3231aeb22@mail.gmail.com> References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> <200903041810.24685.jfabiani@yolo.com> <8acd28da0903100555j68053abbj24928204f7dad937@mail.gmail.com> <49B66ACC.1020905@gmail.com> <8acd28da0903160420s7f5460ecxde43e8f3231aeb22@mail.gmail.com> Message-ID: <5c5e5c350903160506o5abbbbc6he6c2e9d48a5a43d2@mail.gmail.com> 2009/3/16 Neven Gor?i? : > I just would like to correct my incomplete PyQT pricing list from > above and mislead none. > > If you intent to write commercial programs you have to pay: > > 400 EURO ? for PyQT ? ? AND ? ?3000 EURO ?for QT !!! actually, QT is moving to LGPL, so in the near future you may be able not to pay anything even for writing some proprietary programs anyway, you're still free to use the GPL version to play around with it and to develop free software apps -- Elena ``of Valhalla'' email: elena.valhalla at gmail.com From kent37 at tds.net Mon Mar 16 15:43:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Mar 2009 10:43:10 -0400 Subject: [Tutor] wxPython vs PyQt In-Reply-To: <5c5e5c350903160506o5abbbbc6he6c2e9d48a5a43d2@mail.gmail.com> References: <8acd28da0903040606j5610bcb2idef2474895e0afd0@mail.gmail.com> <1c2a2c590903041417j42b27e84nbffb17a07d1a608@mail.gmail.com> <200903041810.24685.jfabiani@yolo.com> <8acd28da0903100555j68053abbj24928204f7dad937@mail.gmail.com> <49B66ACC.1020905@gmail.com> <8acd28da0903160420s7f5460ecxde43e8f3231aeb22@mail.gmail.com> <5c5e5c350903160506o5abbbbc6he6c2e9d48a5a43d2@mail.gmail.com> Message-ID: <1c2a2c590903160743t2c5b1992v47f3bdc0e406d05a@mail.gmail.com> 2009/3/16 Elena of Valhalla : > 2009/3/16 Neven Gor?i? : >> I just would like to correct my incomplete PyQT pricing list from >> above and mislead none. >> >> If you intent to write commercial programs you have to pay: >> >> 400 EURO ? for PyQT ? ? AND ? ?3000 EURO ?for QT !!! > > actually, QT is moving to LGPL, so in the near future you may be able > not to pay anything even for writing some proprietary programs Qt is available now under LGPL. PyQt is still GPL / Commercial AFAICT. > anyway, you're still free to use the GPL version to play around with > it and to develop free software apps Yes, but be careful with the playing around - "Both the Qt and PyQt Commercial Licenses prevent you from developing code using the GPL versions and subsequently selling that code under the commercial license. You must purchase a commercial license at the start of your development. " http://www.riverbankcomputing.co.uk/software/pyqt/license Kent From dineshbvadhia at hotmail.com Mon Mar 16 16:02:54 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 16 Mar 2009 08:02:54 -0700 Subject: [Tutor] 32-bit libaries on 64-bit Windows Message-ID: Does anyone know if 32-bit Python libraries will work with 64-bit Python under 64-bit Windows? For example, will 32-bit Numpy or Scipy work under 64-bit Python? Cheers ... Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From aalokie at hotmail.com Mon Mar 16 15:53:22 2009 From: aalokie at hotmail.com (Cheetah1000) Date: Mon, 16 Mar 2009 07:53:22 -0700 (PDT) Subject: [Tutor] memory error files over 100MB In-Reply-To: References: Message-ID: <22539945.post@talk.nabble.com> Alan Gauld wrote: > > > "Sander Sweers" wrote > >> ... I would expect zf.read(zfilename) to only read the >> requested file in the zipfile. > > That's a dangerous assumption. You might be right but I'd want to > do some tests first to see. But if even one zipped file was big the > same would apply. > > Alan G. > > I can't speak for Python 2.6, but using Jython 2.1 (Python 2.1 for Java), the code only looks at the file you are trying to extract()/read(). Near the end of the zip archive is a directory of all the files in the archive, with the start position and length of each file. Jython's zipfile (written in python, naturally) only reads from the start position to the end of the file. More information on this can be found by searching for 'Central Directory' of a zip archive. Still doesn't explain the 100M problem though. I've having the same issue extracting 20MB from a 22MB zip. It could be Python; or it could be, in my case, a java issue. -- View this message in context: http://www.nabble.com/memory-error-files-over-100MB-tp22437060p22539945.html Sent from the Python - tutor mailing list archive at Nabble.com. From a.t.hofkamp at tue.nl Mon Mar 16 17:30:51 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 16 Mar 2009 17:30:51 +0100 Subject: [Tutor] memory error files over 100MB In-Reply-To: <22539945.post@talk.nabble.com> References: <22539945.post@talk.nabble.com> Message-ID: <49BE7EBB.3020201@tue.nl> Cheetah1000 wrote: > I can't speak for Python 2.6, but using Jython 2.1 (Python 2.1 for Java), > the code only looks at the file you are trying to extract()/read(). Near > the end of the zip archive is a directory of all the files in the archive, > with the start position and length of each file. Jython's zipfile (written > in python, naturally) only reads from the start position to the end of the > file. More information on this can be found by searching for 'Central > Directory' of a zip archive. Still doesn't explain the 100M problem though. > I've having the same issue extracting 20MB from a 22MB zip. It could be > Python; or it could be, in my case, a java issue. Zipped sizes are not really interesting. Since you read the unzipped version into memory, how big is the data unzipped? That is the amount of storage that you need for just the file data. To have a working program, you have to add the size of a running Python or Java program to that number. I don't know what code is executed in an assignment exactly, but **possibly**, first the 'read()' is executed (thus loading a very big string into memory), before assigning the value to the variable (which releases the previous value of the variable). That means that just after reading but before assigning, you **may** have two very big strings in memory that cannot be garbage collected. All that data needs to be available in the memory of a single process at your machine. As already discussed, the only proper way of dealing with such files is to split your read call into smaller blocks, so you can handle zip files up to disk capacity. Sincerely, Albert From kent37 at tds.net Mon Mar 16 17:57:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Mar 2009 12:57:18 -0400 Subject: [Tutor] memory error files over 100MB In-Reply-To: <49BE7EBB.3020201@tue.nl> References: <22539945.post@talk.nabble.com> <49BE7EBB.3020201@tue.nl> Message-ID: <1c2a2c590903160957o49823afah35b18b0111481a2c@mail.gmail.com> On Mon, Mar 16, 2009 at 12:30 PM, A.T.Hofkamp wrote: > I don't know what code is executed in an assignment exactly, but > **possibly**, first the 'read()' is executed (thus loading a very big string > into memory), before assigning the value to the variable (which releases the > previous value of the variable). > That means that just after reading but before assigning, you **may** have > two very big strings in memory that cannot be garbage collected. No. Python variables are references to values, not containers for values. Python assignment is *always* reference assignment, not copying of a value. More here; http://personalpages.tds.net/~kent37/kk/00012.html Kent From sierra_mtnview at sbcglobal.net Mon Mar 16 20:14:20 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Mar 2009 12:14:20 -0700 Subject: [Tutor] Modifying Grayson's Example 5_14 Message-ID: <49BEA50C.2010606@sbcglobal.net> An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Mon Mar 16 20:29:32 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Mon, 16 Mar 2009 14:29:32 -0500 Subject: [Tutor] Modifying Grayson's Example 5_14 In-Reply-To: <49BEA50C.2010606@sbcglobal.net> References: <49BEA50C.2010606@sbcglobal.net> Message-ID: <49BEA89C.1080105@mwalsh.org> Wayne Watson wrote: ... > it. It works pretty well, but puts up a a few probably top level > windows that are blank. How do I get around them, and is there anything ... > > root = Tk() Try adding this, root.withdraw() > dialog = GetPassword(root) HTH, Marty From eduardo.susan at gmail.com Mon Mar 16 20:34:53 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 16 Mar 2009 13:34:53 -0600 Subject: [Tutor] How to connect to an email server? Message-ID: <9356b9f30903161234s875b6b7o9a644f82ce2a27ac@mail.gmail.com> Hello, I'm fairly new to programming and Python and am trying to explore Python's email libraries. But I am having trouble making a connection with an email server, I guess. I'm running Windows XP, in a server environment. I have administrator privileges to my machine (not the server machine) to install, delete programs, for example. My email program (Outlook 2007) says that Exchange Server is albertapdc.express.local I would like to send emails using smtp in a script, but when I do these lines, I get an error: import smtplib server = smtplib.SMTP('localhost') # if I replace 'localhost' with 'albertapdc.express.local' I get the same. Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "C:\Python25\lib\smtplib.py", line 310, in connect raise socket.error, msg error: (10061, 'Connection refused') The same error 'Connection refused' I get trying IMAP: import imaplib se = imaplib.IMAP4('albertapdc.express.local') Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\imaplib.py", line 163, in __init__ self.open(host, port) File "C:\Python25\lib\imaplib.py", line 230, in open self.sock.connect((host, port)) File "", line 1, in connect error: (10061, 'Connection refused') What should I do? And how can I know I can use smtp or IMAP? From emadnawfal at gmail.com Mon Mar 16 20:59:13 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Mon, 16 Mar 2009 15:59:13 -0400 Subject: [Tutor] reading lists from a text file In-Reply-To: <1c2a2c590903121210t7159db84n7de028aa79b463f5@mail.gmail.com> References: <652641e90903120910w3438ecd2h6a426cc0aefb89f8@mail.gmail.com> <1c2a2c590903121210t7159db84n7de028aa79b463f5@mail.gmail.com> Message-ID: <652641e90903161259p71573118h464e870d075d34b2@mail.gmail.com> 2009/3/12 Kent Johnson > 2009/3/12 Emad Nawfal (???? ????) : > > Hi Tutors, > > I've never had a situation in which this was useful for me, but I'm just > > curious. > > If there is a text file that has a list or number of lists in it, is > there > > is a way to read the lists in the file as lists, and not as a string. > Sample > > file attached. > > For the individual lines, there are various solutions. eval() is easy > but not recommended because of the security risk. There are several > recipes in the Python cookbook - search for "safe eval". Python 2.6 > includes ast.literal_eval() which does the job safely: > > In [1]: from ast import literal_eval > > In [4]: data = '''["this", "is", "a", "list"] > ...: ["this", "is", "another", "list"] > ...: ["this", "is","list", "#", "2"]''' > > In [5]: for line in data.splitlines(): > ...: print literal_eval(line) > > ['this', 'is', 'a', 'list'] > ['this', 'is', 'another', 'list'] > ['this', 'is', 'list', '#', '2'] > > Extending from parsing a single line to parsing all the lines in a > file is trivial. > > Kent > Thank you all for the answers. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Mon Mar 16 21:09:41 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 16 Mar 2009 20:09:41 +0000 Subject: [Tutor] How to connect to an email server? In-Reply-To: <9356b9f30903161234s875b6b7o9a644f82ce2a27ac@mail.gmail.com> References: <9356b9f30903161234s875b6b7o9a644f82ce2a27ac@mail.gmail.com> Message-ID: <49BEB205.7090208@timgolden.me.uk> Eduardo Vieira wrote: > Hello, I'm fairly new to programming and Python and am trying to > explore Python's email libraries. But I am having trouble making a > connection with an email server, I guess. > I'm running Windows XP, in a server environment. I have administrator > privileges to my machine (not the server machine) to install, delete > programs, for example. My email program (Outlook 2007) says that > Exchange Server is albertapdc.express.local > I would like to send emails using smtp in a script, but when I do > these lines, I get an error: > > import smtplib > server = smtplib.SMTP('localhost') # if I replace 'localhost' with > 'albertapdc.express.local' I get the same. > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') > > The same error 'Connection refused' I get trying IMAP: > import imaplib > se = imaplib.IMAP4('albertapdc.express.local') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\imaplib.py", line 163, in __init__ > self.open(host, port) > File "C:\Python25\lib\imaplib.py", line 230, in open > self.sock.connect((host, port)) > File "", line 1, in connect > error: (10061, 'Connection refused') > > What should I do? And how can I know I can use smtp or IMAP? SMTP has to be enabled specifically on the Exchange Server: it usually uses its own built-in protocols. It looks as though your Exchange isn't running it. Either switch it on (or ask your admins to do so) or look at using MAPI or CDO instead. TJG From emile at fenx.com Mon Mar 16 21:55:50 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 16 Mar 2009 13:55:50 -0700 Subject: [Tutor] How to connect to an email server? In-Reply-To: <9356b9f30903161234s875b6b7o9a644f82ce2a27ac@mail.gmail.com> References: <9356b9f30903161234s875b6b7o9a644f82ce2a27ac@mail.gmail.com> Message-ID: Eduardo Vieira wrote: > Hello, I'm fairly new to programming and Python and am trying to > explore Python's email libraries. But I am having trouble making a > connection with an email server, I guess. > I'm running Windows XP, in a server environment. I have administrator > privileges to my machine (not the server machine) to install, delete > programs, for example. My email program (Outlook 2007) says that > Exchange Server is albertapdc.express.local > I would like to send emails using smtp in a script, but when I do > these lines, I get an error: > > import smtplib > server = smtplib.SMTP('localhost') # if I replace 'localhost' with > 'albertapdc.express.local' I get the same. > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') The server refuses your connection attempt... > > The same error 'Connection refused' I get trying IMAP: > import imaplib > se = imaplib.IMAP4('albertapdc.express.local') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\imaplib.py", line 163, in __init__ > self.open(host, port) > File "C:\Python25\lib\imaplib.py", line 230, in open > self.sock.connect((host, port)) > File "", line 1, in connect > error: (10061, 'Connection refused') The server again refuses your connection attempt... > > What should I do? I'd start by pinging the server and running nmap on it. Forget imap if your goal is sending mail. If you don't see port 25 or 465 opened you won't make it much further without getting the mail system administrator's help. HTH, Emile > And how can I know I can use smtp or IMAP? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From eduardo.susan at gmail.com Mon Mar 16 23:09:42 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 16 Mar 2009 16:09:42 -0600 Subject: [Tutor] How to connect to an email server? In-Reply-To: <49BEB205.7090208@timgolden.me.uk> References: <9356b9f30903161234s875b6b7o9a644f82ce2a27ac@mail.gmail.com> <49BEB205.7090208@timgolden.me.uk> Message-ID: <9356b9f30903161509x18996503i27fd9fc905d41a9b@mail.gmail.com> Tim wrote: > > > SMTP has to be enabled specifically on the Exchange Server: > it usually uses its own built-in protocols. It looks > as though your Exchange isn't running it. Either switch it > on (or ask your admins to do so) or look at using MAPI > or CDO instead. > > TJG > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I guess I'll use MAPI, CDO, as these have worked before. From rb2.net at gmail.com Mon Mar 16 23:27:28 2009 From: rb2.net at gmail.com (Rene Bourgoin) Date: Mon, 16 Mar 2009 18:27:28 -0400 Subject: [Tutor] help with ftplib and file modification date Message-ID: <1e6b7e620903161527g45cdb98bg5b0fba49cbc5c751@mail.gmail.com> i'm doing a simple upload to an FTP server using the ftplib module and wanted to know how i can preserve the file modification date all the way through the process. I lose the file mod date because i read the original file then ftp writes a new file to the server which changes the mod dateto the time and date of the file transfer. Here is the basic code i used; for file in os.listdir("C:\\dir"): i=file # i catpures file z="STOR " + i #STOR is upload command to FTP server filename=open(i,'r') f.storlines(z,filename) #FTP upload command filename.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Mar 17 01:11:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 16 Mar 2009 20:11:31 -0400 Subject: [Tutor] help with ftplib and file modification date In-Reply-To: <1e6b7e620903161527g45cdb98bg5b0fba49cbc5c751@mail.gmail.com> References: <1e6b7e620903161527g45cdb98bg5b0fba49cbc5c751@mail.gmail.com> Message-ID: <1c2a2c590903161711qc8d7cechbd10e29a763f2efc@mail.gmail.com> On Mon, Mar 16, 2009 at 6:27 PM, Rene Bourgoin wrote: > i'm doing a simple upload to an FTP server using the ftplib module and > wanted to know how i can preserve the file modification date all the way > through the process. I lose the file mod date because i read the original > file?then ftp writes a new file to the server which changes the mod date > to the time and date of the file transfer. Apparently there is no standard way to do this but some servers support using the MDTM command to set time stamps: http://forum.filezilla-project.org/viewtopic.php?f=1&t=4122 Kent From sierra_mtnview at sbcglobal.net Tue Mar 17 04:52:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Mar 2009 20:52:29 -0700 Subject: [Tutor] Modifying Grayson's Example 5_14 In-Reply-To: <49BEA89C.1080105@mwalsh.org> References: <49BEA50C.2010606@sbcglobal.net> <49BEA89C.1080105@mwalsh.org> Message-ID: <49BF1E7D.1050507@sbcglobal.net> An HTML attachment was scrubbed... URL: From hussainali.hussainali at gmail.com Tue Mar 17 07:37:52 2009 From: hussainali.hussainali at gmail.com (Hussain Ali) Date: Tue, 17 Mar 2009 11:37:52 +0500 Subject: [Tutor] Paython as a career Message-ID: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Dear all I want to start learning python but before going further I need answer to my questions so that my path can be clear to me. I shall be grateful for your answers: 1) Where does python stand as compared to other programming languages? 2) What is the future for python? 3) Will it survive for long in this rapidly changing trends and new languages? 4) Should I start it to earn my bread and butter? I mean is that beneficial for income. Sincerely Hussain -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Mar 17 09:45:36 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Mar 2009 03:45:36 -0500 Subject: [Tutor] Paython as a career In-Reply-To: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Message-ID: You should not choose a specific programming language and start a career in it. If you want a career in programming you need to learn a great deal about computer science (the theory). One of the things you will learn in your studies is that programming languages are just the tools, and you leverage them to create great software. Therefore you shouldn't need to "know" how used a programming language is - if you understand how programming works, you can choose a language to specialize in (for example, I use Python for all my personal projects because I feel like the language design is better than most others), but I am grounded enough in the theory that I am not tied to Python. For example, I worked a 6-month internship where the main programming language was C#, and they used all Microsoft tools. I'd never used C# or the tools, but within a week or two, I was able to familiarize myself with their codebase and start working on it at a fairly competent level. Now it would take a while for me to become as productive in C# as I am in Python, just based on my ability to recall so much information about Python without having to look at reference material. If you're really asking us which language has the largest job market, Python is definitely not the answer to that question? Can you find jobs in Python? Sure, if you are determined and you look hard enough. But as far as widespread use, I'd say C/C++, Java, and C# are still the reigning programming languages. That's just my personal opinion and I didn't consult any statistical sources for that. What it all boils down to is this: Programming is difficult. If you like to spend your free time solving mathematical equations and doing logic problems, it might be for you. If you like to spend your free time fixing up your car, or something, you'd probably do better to choose a different career. I think you will not be very successful if you try to pick up a programming career on a whim, as a side income. If you are not committed enough to either study it in school or learn it really well at a job, you will not be successful. Especially if your boss is a programmer, it is very clear after only a short while at a job whether you are a competent programmer, and unless you find yourself in a very poorly run company, you won't be able to skirt by. You'll have to know what you're doing. That having been said, for people of a certain mindset, programming is extremely enjoyable and a rewarding field to be in. If you are interested in Python because you are interested in the things you can do with it, rather than being interested in it because it is a potential source of revenue, start playing around with it and learning it. Do some projects. Ask us lots of questions. And if you still like it after completing something substantial, then start thinking about it in terms of a career path. That's my 2 cents, of course you have no obligation to take my advice. I hope it helps you one way or the other. Good luck. -Luke On Tue, Mar 17, 2009 at 1:37 AM, Hussain Ali < hussainali.hussainali at gmail.com> wrote: > Dear all > > I want to start learning python but before going further I need answer to > my > questions so that my path can be clear to me. I shall be grateful for your > answers: > > 1) Where does python stand as compared to other programming languages? > 2) What is the future for python? > 3) Will it survive for long in this rapidly changing trends and new > languages? > 4) Should I start it to earn my bread and butter? I mean is that beneficial > for income. > > > Sincerely > > Hussain > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 17 09:51:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 08:51:29 -0000 Subject: [Tutor] Paython as a career References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Message-ID: "Hussain Ali" wrote > 1) Where does python stand as compared to other programming > languages? That depends on how you measure it. On functionality? On popularity? On number of active projects on Sourceforge? How do you measure "standing"? > 2) What is the future for python? I don't have psychic powers but the short term future is version 3 growing and version 2 slowly diminishing. Beyond that I couldn't say. > 3) Will it survive for long in this rapidly changing trends and new > languages? Provided there is an active community of users it will survive. Very few languages die out completely. There are still plenty users of COBOL, Fortran, Lisp, Smalltalk, ADA, Pascal, etc. Python has been around for almost 20 years, if it survived that long I don't see it disappearing any time soon. > 4) Should I start it to earn my bread and butter? > I mean is that beneficial for income. There are plenty people earning a living using Python. There are probably even more who use Python as a second language for building tools, prototyping, etc. Any professional programmer should know several languages, not all of which are likely to be his main source of income but all will be useful tools. In my experience its very unusual to find any significant project that only uses one language (especially if we include shell scripting, SQL, etc) More to the point is the matter of what do YOU want to do? What kind of projects do you want to work on? What kind of company do you want to work for? The programming language should not be your primary concern. But if I was starting out as a programer today I'd want to know at least the basics of: 1) Java 2) C (plus a little bit of C++) 3) SQL 4) bash 5) VB.NET/VBA 6) Javascript 7) One of the scripting languages (Perl, Python, PHP, Ruby, Tcl) And more than the basics of at least two of them. And for a rounded out education I'd consider reading up on: 1) Lisp/Scheme 2) Prolog 3) Haskell 4) Smalltalk With that under my belt I'd feel reasonably competent. Other languages you can pick up as you need them. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From zebra05 at gmail.com Tue Mar 17 10:17:44 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Tue, 17 Mar 2009 11:17:44 +0200 Subject: [Tutor] Paython as a career In-Reply-To: References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Message-ID: Luke, i think you gave a more balanced answer :) On Tue, Mar 17, 2009 at 10:45 AM, Luke Paireepinart wrote: > You should not choose a specific programming language and start a career in > it. If you want a career in programming you need to learn a great deal > about computer science (the theory). One of the things you will learn in > your studies is that programming languages are just the tools, and you > leverage them to create great software. Therefore you shouldn't need to > "know" how used a programming language is - if you understand how > programming works, you can choose a language to specialize in (for example, > I use Python for all my personal projects because I feel like the language > design is better than most others), but I am grounded enough in the theory > that I am not tied to Python. For example, I worked a 6-month internship > where the main programming language was C#, and they used all Microsoft > tools. I'd never used C# or the tools, but within a week or two, I was able > to familiarize myself with their codebase and start working on it at a > fairly competent level. Now it would take a while for me to become as > productive in C# as I am in Python, just based on my ability to recall so > much information about Python without having to look at reference material. > If you're really asking us which language has the largest job market, Python > is definitely not the answer to that question? Can you find jobs in > Python? Sure, if you are determined and you look hard enough. But as far > as widespread use, I'd say C/C++, Java, and C# are still the reigning > programming languages. That's just my personal opinion and I didn't consult > any statistical sources for that. > > What it all boils down to is this: Programming is difficult. If you like > to spend your free time solving mathematical equations and doing logic > problems, it might be for you. If you like to spend your free time fixing > up your car, or something, you'd probably do better to choose a different > career. I think you will not be very successful if you try to pick up a > programming career on a whim, as a side income. If you are not committed > enough to either study it in school or learn it really well at a job, you > will not be successful. Especially if your boss is a programmer, it is very > clear after only a short while at a job whether you are a competent > programmer, and unless you find yourself in a very poorly run company, you > won't be able to skirt by. You'll have to know what you're doing. > > That having been said, for people of a certain mindset, programming is > extremely enjoyable and a rewarding field to be in. If you are interested > in Python because you are interested in the things you can do with it, > rather than being interested in it because it is a potential source of > revenue, start playing around with it and learning it. Do some projects. > Ask us lots of questions. And if you still like it after completing > something substantial, then start thinking about it in terms of a career > path. > > That's my 2 cents, of course you have no obligation to take my advice. I > hope it helps you one way or the other. > Good luck. > -Luke > > On Tue, Mar 17, 2009 at 1:37 AM, Hussain Ali < > hussainali.hussainali at gmail.com> wrote: > >> Dear all >> >> I want to start learning python but before going further I need answer to >> my >> questions so that my path can be clear to me. I shall be grateful for your >> answers: >> >> 1) Where does python stand as compared to other programming languages? >> 2) What is the future for python? >> 3) Will it survive for long in this rapidly changing trends and new >> languages? >> 4) Should I start it to earn my bread and butter? I mean is that >> beneficial for income. >> >> >> Sincerely >> >> Hussain >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Mar 17 10:46:59 2009 From: denis.spir at free.fr (spir) Date: Tue, 17 Mar 2009 10:46:59 +0100 Subject: [Tutor] Paython as a career In-Reply-To: References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Message-ID: <20090317104659.5197eba1@o> Le Tue, 17 Mar 2009 03:45:36 -0500, Luke Paireepinart s'exprima ainsi: > If you're really asking us which language has the largest job market, Python > is definitely not the answer to that question? Can you find jobs in > Python? Sure, if you are determined and you look hard enough. But as far > as widespread use, I'd say C/C++, Java, and C# are still the reigning > programming languages. That's just my personal opinion and I didn't consult > any statistical sources for that. Python is much more prominent in the free software/open-source world -- than for commercial software. You may think the reason is that free developpers can choose ;-) Free software rarely pays back in terms of money. Denis ------ la vita e estrany From neven.gorsic at gmail.com Tue Mar 17 10:50:25 2009 From: neven.gorsic at gmail.com (=?ISO-8859-2?B?TmV2ZW4gR29yuWnm?=) Date: Tue, 17 Mar 2009 10:50:25 +0100 Subject: [Tutor] Making exe Python file - standalone executable file Message-ID: <8acd28da0903170250o34e09ddbo444a3684d411f631@mail.gmail.com> Hi! Py2exe i standard way (up to my knowledge) of making standalone executable Python file in order to distribute your program to others who don't have Python installed (too bad that it is not part of standard Python distribution). I have no experience with wxPython and PyQT. Do they have their own compilers or we must do it again with Py2exe? Thanks, Neven From a.t.hofkamp at tue.nl Tue Mar 17 11:34:50 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 17 Mar 2009 11:34:50 +0100 Subject: [Tutor] memory error files over 100MB In-Reply-To: <1c2a2c590903160957o49823afah35b18b0111481a2c@mail.gmail.com> References: <22539945.post@talk.nabble.com> <49BE7EBB.3020201@tue.nl> <1c2a2c590903160957o49823afah35b18b0111481a2c@mail.gmail.com> Message-ID: <49BF7CCA.5020407@tue.nl> Kent Johnson wrote: > On Mon, Mar 16, 2009 at 12:30 PM, A.T.Hofkamp wrote: > >> I don't know what code is executed in an assignment exactly, but >> **possibly**, first the 'read()' is executed (thus loading a very big string >> into memory), before assigning the value to the variable (which releases the >> previous value of the variable). >> That means that just after reading but before assigning, you **may** have >> two very big strings in memory that cannot be garbage collected. > > No. Python variables are references to values, not containers for > values. Python assignment is *always* reference assignment, not > copying of a value. More here; > http://personalpages.tds.net/~kent37/kk/00012.html Nice web-page! I am aware of how variables are treated in Python. Let me explain my reasoning in more detail. Consider the statement s = s + "def" under the assumption that s is now "abc" (or rather, s references the data value "abc"). For the assignment, I believe the following happens inside the python interpreter (but I am not 100% sure that it is exactly the sequence): 1. get a reference to the current value of s. 2. get a reference to the constant value "def". 3. compute the new value "abcdef", store it in memory, and make a reference to it. 4. drop the old reference of s (thus free-ing "abc") 5. give s a reference to the newly computed value. The point I was trying to make is that after step 3 and before step 4, the old value of s is still referenced by s, and the new value is referenced internally (so step 5 can be performed). In other words, both the old and the new value are in memory at the same time after step 3 and before step 4, and both are referenced (that is, they cannot be garbage-collected). Assuming that the above mechanism is used with all assignments, this will also be the case in the sequence of assignments s = read() # write s s = read() # write s where in the second assignment statement, the read() is done (creating the new value in memory) before dropping the value of s from the first assignment. You can do the above statements also iteratively of course for i in ... s = read() # write s but since the loop does nothing with either s or read(), this will not change how the assignment works. In the case that you are manipulating large values (as in taking a lot of computer memory for each value), the execution of the read() during step 3 may fail due to memory being used for the previously assigned value of s. Sincerely, Albert From raj at adventnet.com Tue Mar 17 10:26:58 2009 From: raj at adventnet.com (Rajkumar. B) Date: Tue, 17 Mar 2009 14:56:58 +0530 Subject: [Tutor] Paython as a career In-Reply-To: References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Message-ID: <12013c1546c.8125360338676952162.6876958100810610736@adventnet.com> Luke, You have explained it beautifully ! Thanks & Regards Rajkumar. B ---- On Tue, 17 Mar 2009 02:17:44 -0700 OkaMthembo wrote ---- > Luke, i think you gave a more balanced answer :) > > On Tue, Mar 17, 2009 at 10:45 AM, Luke Paireepinart wrote: > You should not choose a specific programming language and start a career in it. If you want a career in programming you need to learn a great deal about computer science (the theory). One of the things you will learn in your studies is that programming languages are just the tools, and you leverage them to create great software. Therefore you shouldn't need to "know" how used a programming language is - if you understand how programming works, you can choose a language to specialize in (for example, I use Python for all my personal projects because I feel like the language design is better than most others), but I am grounded enough in the theory that I am not tied to Python. For example, I worked a 6-month internship where the main programming language was C#, and they used all Microsoft tools. I'd never used C# or the tools, but within a week or two, I was able to familiarize myself with their codebase and start working on it at a fairly competent level. Now it would take a while for me to become as productive in C# as I am in Python, just based on my ability to recall so much information about Python without having to look at reference material. If you're really asking us which language has the largest job market, Python is definitely not the answer to that question? Can you find jobs in Python? Sure, if you are determined and you look hard enough. But as far as widespread use, I'd say C/C++, Java, and C# are still the reigning programming languages. That's just my personal opinion and I didn't consult any statistical sources for that. > > What it all boils down to is this: Programming is difficult. If you like to spend your free time solving mathematical equations and doing logic problems, it might be for you. If you like to spend your free time fixing up your car, or something, you'd probably do better to choose a different career. I think you will not be very successful if you try to pick up a programming career on a whim, as a side income. If you are not committed enough to either study it in school or learn it really well at a job, you will not be successful. Especially if your boss is a programmer, it is very clear after only a short while at a job whether you are a competent programmer, and unless you find yourself in a very poorly run company, you won't be able to skirt by. You'll have to know what you're doing. > > That having been said, for people of a certain mindset, programming is extremely enjoyable and a rewarding field to be in. If you are interested in Python because you are interested in the things you can do with it, rather than being interested in it because it is a potential source of revenue, start playing around with it and learning it. Do some projects. Ask us lots of questions. And if you still like it after completing something substantial, then start thinking about it in terms of a career path. > > That's my 2 cents, of course you have no obligation to take my advice. I hope it helps you one way or the other. > Good luck. > -Luke > > > On Tue, Mar 17, 2009 at 1:37 AM, Hussain Ali wrote: > > > > Dear all > > I want to start learning python but before going further I need answer to my > questions so that my path can be clear to me. I shall be grateful for your answers: > > 1) Where does python stand as compared to other programming languages? > 2) What is the future for python? > 3) Will it survive for long in this rapidly changing trends and new languages? > 4) Should I start it to earn my bread and butter? I mean is that beneficial for income. > > > Sincerely > > Hussain > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Lloyd Dube > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dukelx2005 at gmail.com Tue Mar 17 11:56:00 2009 From: dukelx2005 at gmail.com (Jared White) Date: Tue, 17 Mar 2009 06:56:00 -0400 Subject: [Tutor] (no subject) Message-ID: <9239372b0903170356v5b8a92a6ldbe0d3b35b050393@mail.gmail.com> Would anyone know how to Write an application that displays the following patterns separately, one below the other. Use for or while loops to generate the patterns. All asterisks (*) should be printed by a single statement of print( '*' ); which causes the asterisks to print side by side. A statement of println(\n); can be used to move to the next line. * ** *** **** ***** ****** ******* ******** ********* ********** ********** ********* ******** ******* ****** ***** **** *** ** * dukelx2005 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Mar 17 12:01:54 2009 From: denis.spir at free.fr (spir) Date: Tue, 17 Mar 2009 12:01:54 +0100 Subject: [Tutor] list.replace -- string.swap Message-ID: <20090317120154.215f99d3@o> Is there a list.replace builtin I cannot find? Or a workaround? Also: How would perform string.swap(s1, s2) in the following cases: * There is no secure 'temp' char, meaning that s.replace(s1,temp).replace(s2,s1).replace(temp,s2) will fail because any char can be part of s. * Either s1 or s2 can be more than a single char. Denis ------ la vita e estrany From connorsml at gmail.com Tue Mar 17 12:05:03 2009 From: connorsml at gmail.com (Michael Connors) Date: Tue, 17 Mar 2009 12:05:03 +0100 Subject: [Tutor] (no subject) In-Reply-To: <9239372b0903170356v5b8a92a6ldbe0d3b35b050393@mail.gmail.com> References: <9239372b0903170356v5b8a92a6ldbe0d3b35b050393@mail.gmail.com> Message-ID: So the extent of your effort is "Would anyone know how to Ctrl+c". That deserves an award. 2009/3/17 Jared White > Would anyone know how to Write an application that displays the following > patterns separately, one below the other. Use for or while loops to generate > the patterns. All asterisks (*) should be printed by a single statement of > print( '*' ); which causes the asterisks to print side by side. A statement > of println(\n); can be used to move to the next line. > * > ** > *** > **** > ***** > ****** > ******* > ******** > ********* > ********** > > ********** > ********* > ******** > ******* > ****** > ***** > **** > *** > ** > * > dukelx2005 at gmail.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: From dukelx2005 at gmail.com Tue Mar 17 12:00:57 2009 From: dukelx2005 at gmail.com (dukelx2005 at gmail.com) Date: Tue, 17 Mar 2009 11:00:57 +0000 Subject: [Tutor] (no subject) Message-ID: <558999250-1237287707-cardhu_decombobulator_blackberry.rim.net-41636070-@bxe1285.bisx.prod.on.blackberry> Would anyone know how to Write an application that displays the following patterns separately, one below the other. Use for or while loops to generate the patterns. All asterisks (*) should be printed by a single statement of print( '*' ); which causes the asterisks to print side by side. A statement of println(\n); can be used to move to the next line.???? ?*?? ?**?? ?***?? ?****?? ?*****?? ?******?? ?*******?? ?********?? ?*********?? ?**********?? ??? ? **********?? ?*********?? ?********?? ?*******?? ?******?? ?*****?? ?**** ?***?? ?**?? ?* dukelx2005 at gmail.com Sent from my Verizon Wireless BlackBerry Please consider the environment before printing this email or attachments From mail at timgolden.me.uk Tue Mar 17 12:09:39 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 17 Mar 2009 11:09:39 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: <9239372b0903170356v5b8a92a6ldbe0d3b35b050393@mail.gmail.com> Message-ID: <49BF84F3.2010906@timgolden.me.uk> Michael Connors wrote: > So the extent of your effort is "Would anyone know how to Ctrl+c". > That deserves an award. I think you meant ctrl-v, but good point, nonetheless :) (Took me a moment, because I thought you were referring to a KeyboardInterrupt-type ctrl-c!) TJG From andreengels at gmail.com Tue Mar 17 12:33:56 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 17 Mar 2009 12:33:56 +0100 Subject: [Tutor] combining Python 2.x and Python 3 Message-ID: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> I have an open source project I have done some work on, which is programmed in Python 2.3-2.6. I would like to change it so that it can be run under both Python 3 and Python 2.x. Two questions for that: * is there a place where I can find an overview of what to do to make such a change? * is there a way to check, on one computer, the code under both versions (I am using Windows Vista, in case it matters)? -- Andr? Engels, andreengels at gmail.com From a.t.hofkamp at tue.nl Tue Mar 17 12:45:23 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 17 Mar 2009 12:45:23 +0100 Subject: [Tutor] list.replace -- string.swap In-Reply-To: <20090317120154.215f99d3@o> References: <20090317120154.215f99d3@o> Message-ID: <49BF8D53.3020606@tue.nl> Hello Denis, spir wrote: > Is there a list.replace builtin I cannot find? Or a workaround? You didn't find it because it does not exist. You should do something like [f(x) for x in old_lst] where f(x) implements the replacement. > Also: How would perform string.swap(s1, s2) in the following cases: > > * There is no secure 'temp' char, meaning that > s.replace(s1,temp).replace(s2,s1).replace(temp,s2) > will fail because any char can be part of s. split on s1, replace all pieces s2 -> s1, join with s2 ? pieces = txt.split(s1) pieces = [p.replace(s2, s1) for p in pieces] text = s2.join(pieces) which may not work if s1 and s2 overlap, but that case was not described above. Sincerely, Albert From kent37 at tds.net Tue Mar 17 13:54:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 08:54:25 -0400 Subject: [Tutor] list.replace -- string.swap In-Reply-To: <20090317120154.215f99d3@o> References: <20090317120154.215f99d3@o> Message-ID: <1c2a2c590903170554u2f1f2ae5hadfdaea2be2e3cf5@mail.gmail.com> On Tue, Mar 17, 2009 at 7:01 AM, spir wrote: > Is there a list.replace builtin I cannot find? Or a workaround? Just assign directly to list elements. To replace s1 with s2 in l: for i, x in enumerate(l): if x == s1: l[i] = s2 > Also: How would perform string.swap(s1, s2) in the following cases: > > * There is no secure 'temp' char, meaning that > ? ? ? ?s.replace(s1,temp).replace(s2,s1).replace(temp,s2) > ?will fail because any char can be part of s. You could use re.sub() with a function for the replacement string. It takes a little setup but it's not really difficult: import re def string_swap(s, s1, s2): ''' Swap s1 and s2 in s''' # Given a match, return s2 for s1 and vice-versa def replace(m): return s2 if m.group()==s1 else s1 # re to match s1 or s2 matcher = re.compile('%s|%s' % (re.escape(s1), re.escape(s2))) return matcher.sub(replace, s) print string_swap('go to the park', 'o', 'a') Kent From kent37 at tds.net Tue Mar 17 13:56:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 08:56:58 -0400 Subject: [Tutor] (no subject) In-Reply-To: <9239372b0903170356v5b8a92a6ldbe0d3b35b050393@mail.gmail.com> References: <9239372b0903170356v5b8a92a6ldbe0d3b35b050393@mail.gmail.com> Message-ID: <1c2a2c590903170556m5d8f9dc8u5f3c0d0117fcfc5e@mail.gmail.com> On Tue, Mar 17, 2009 at 6:56 AM, Jared White wrote: > Would anyone know how to Write an application that displays the following > patterns separately, one below the other. Yes. How about if you try? Presumably this is homework. What have you learned that might be helpful here? Kent From kent37 at tds.net Tue Mar 17 13:59:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 08:59:20 -0400 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> Message-ID: <1c2a2c590903170559x5a7b3aag1466e05008e90edf@mail.gmail.com> On Tue, Mar 17, 2009 at 7:33 AM, Andre Engels wrote: > I have an open source project I have done some work on, which is > programmed in Python 2.3-2.6. I would like to change it so that it can > be run under both Python 3 and Python 2.x. Two questions for that: > * is there a place where I can find an overview of what to do to make > such a change? A very brief overwiew here: http://docs.python.org/3.0/whatsnew/3.0.html#porting-to-python-3-0 There are quite a few porting anecdotes in blogs, etc. Some googling should turn them up. > * is there a way to check, on one computer, the code under both > versions (I am using Windows Vista, in case it matters)? You can install Python 2.x and 3.0 on the same computer, no problem. Kent From kent37 at tds.net Tue Mar 17 14:02:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 09:02:44 -0400 Subject: [Tutor] memory error files over 100MB In-Reply-To: <49BF7CCA.5020407@tue.nl> References: <22539945.post@talk.nabble.com> <49BE7EBB.3020201@tue.nl> <1c2a2c590903160957o49823afah35b18b0111481a2c@mail.gmail.com> <49BF7CCA.5020407@tue.nl> Message-ID: <1c2a2c590903170602m4a5f1ffo684fc76b650be642@mail.gmail.com> On Tue, Mar 17, 2009 at 6:34 AM, A.T.Hofkamp wrote: >> http://personalpages.tds.net/~kent37/kk/00012.html > > Nice web-page! Thanks! > You can do the above statements also iteratively of course > > for i in ... > ?s = read() > ?# write s > > but since the loop does nothing with either s or read(), this will not > change how the assignment works. > > > In the case that you are manipulating large values (as in taking a lot of > computer memory for each value), the execution of the read() during step 3 > may fail due to memory being used for the previously assigned value of s. Ah, thanks, I misunderstood the point you were making. You can allow the previous value of s to be garbage-collected by assigning s=None, for example: for i in ... s = read() # process s s = None Kent From dukelx2005 at gmail.com Tue Mar 17 14:03:52 2009 From: dukelx2005 at gmail.com (dukelx2005 at gmail.com) Date: Tue, 17 Mar 2009 13:03:52 +0000 Subject: [Tutor] (no subject) Message-ID: <2033431806-1237295077-cardhu_decombobulator_blackberry.rim.net-1006782193-@bxe1285.bisx.prod.on.blackberry> Honestly I'm doing tutorials, I'm not in school. I am trying to learn it for my own sake. I got the *'s to come up but they are not forming the way I would like it to. So that why I was asking for help. This isn't a homework assignment. I'm just going thu tutorials which are not helping me Sent from my Verizon Wireless BlackBerry Please consider the environment before printing this email or attachments From kent37 at tds.net Tue Mar 17 14:26:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 09:26:05 -0400 Subject: [Tutor] (no subject) In-Reply-To: <2033431806-1237295077-cardhu_decombobulator_blackberry.rim.net-1006782193-@bxe1285.bisx.prod.on.blackberry> References: <2033431806-1237295077-cardhu_decombobulator_blackberry.rim.net-1006782193-@bxe1285.bisx.prod.on.blackberry> Message-ID: <1c2a2c590903170626k242e19f0mb2a21c709376add4@mail.gmail.com> On Tue, Mar 17, 2009 at 9:03 AM, wrote: > Honestly I'm doing tutorials, I'm not in school. ?I am trying to learn it for my own sake. > > I got the *'s to come up but they are not forming the way I would like it to. ?So that why I was asking for help. OK, then show us the code you have and we'll help you fix it. Tell us what happens and what you want to happen. Don't just ask us to write a program for you. Kent From kent37 at tds.net Tue Mar 17 14:26:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 09:26:47 -0400 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <1c2a2c590903170559x5a7b3aag1466e05008e90edf@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> <1c2a2c590903170559x5a7b3aag1466e05008e90edf@mail.gmail.com> Message-ID: <1c2a2c590903170626y6f37fcfel5aaa55d2697676a3@mail.gmail.com> On Tue, Mar 17, 2009 at 8:59 AM, Kent Johnson wrote: > There are quite a few porting anecdotes in blogs, etc. Some googling > should turn them up. Google "python 3 porting" for lots of resources. Kent From rabidpoobear at gmail.com Tue Mar 17 14:53:43 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 17 Mar 2009 08:53:43 -0500 Subject: [Tutor] (no subject) In-Reply-To: <558999250-1237287707-cardhu_decombobulator_blackberry.rim.net-41636070-@bxe1285.bisx.prod.on.blackberry> References: <558999250-1237287707-cardhu_decombobulator_blackberry.rim.net-41636070-@bxe1285.bisx.prod.on.blackberry> Message-ID: As a policy we don't give answers to homework questions. However, if you have tried this and you are stuck, we'd be happy to help with any specific questions you have about your implementation. On Tue, Mar 17, 2009 at 6:00 AM, wrote: > Would anyone know how to Write an application that displays the following > patterns separately, one below the other. Use for or while loops to generate > the patterns. All asterisks (*) should be printed by a single statement of > print( '*' ); which causes the asterisks to print side by side. A statement > of println(\n); can be used to move to the next line. > * > ** > *** > **** > ***** > ****** > ******* > ******** > ********* > ********** > > ********** > ********* > ******** > ******* > ****** > ***** > **** > *** > ** > * > > dukelx2005 at gmail.com > Sent from my Verizon Wireless BlackBerry > > Please consider the environment before printing this email or attachments > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Tue Mar 17 15:25:10 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 17 Mar 2009 10:25:10 -0400 Subject: [Tutor] Gtk time control and Glade Message-ID: <49BFB2C6.3040500@cfl.rr.com> I am writing a Blood-Glucose Analysis application for Diabetics. I am using Python 2.5 under Ubuntu 8.10 and Glade 3.4.5. Manually recorded test results require a calendar control for the date of the test (no problem) and a timer control for the time of the test(big problem). While Glade certainly supports a calender control with a great deal of documentation, there is not an available time control for Glade. Nor was I able to find a general time control for Gtk. I did find one for wxwidgets but I am not using wxwidgets nor am I using PyQt. I am reasonably sure such a control exists. I know I'm not the only individual who needs date and time controls. But, using Google has provided all kinds of information, there has not been a specific statement about any specific controls. At this time I do not feel I have the level of expertise to build my own control and it is something I would rather not have to do. Have any of you heard of such an available time control specifically for Gtk and available or capable of being used by Glade. Thank you for any insights and suggestions. Robert Berman From mwalsh at mwalsh.org Tue Mar 17 15:33:04 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 17 Mar 2009 09:33:04 -0500 Subject: [Tutor] Modifying Grayson's Example 5_14 In-Reply-To: <49BF1E7D.1050507@sbcglobal.net> References: <49BEA50C.2010606@sbcglobal.net> <49BEA89C.1080105@mwalsh.org> <49BF1E7D.1050507@sbcglobal.net> Message-ID: <49BFB4A0.1000909@mwalsh.org> > Martin Walsh wrote: >> Wayne Watson wrote: >> .... >> >> >>> it. It works pretty well, but puts up a a few probably top level >>> windows that are blank. How do I get around them, and is there anything >>> >> >> .... >> >> >>> root = Tk() >>> >> >> Try adding this, >> >> root.withdraw() >> >> >>> dialog = GetPassword(root) >>> >> >> HTH, >> Marty Wayne Watson wrote: > That worked. Why the "extra" blank window though? I'm no Tkinter expert -- far from it. But I would assume that GetPassword, as a subclass of Dialog, creates a new window, and thus you have no need for the root window. root.withdraw() hides the root window from view, and allows the application to continue running. I imagine there are other ways to accomplish the same thing. HTH, Marty From d.conca at gmail.com Tue Mar 17 15:33:27 2009 From: d.conca at gmail.com (Daniele) Date: Tue, 17 Mar 2009 15:33:27 +0100 Subject: [Tutor] (no subject) Message-ID: <537341c70903170733n1d39c1cfhdbdb254101e08c31@mail.gmail.com> > From:?dukelx2005 at gmail.com > To:?tutor at python.org > Honestly I'm doing tutorials, I'm not in school. ?I am trying to learn it for my own sake. > I got the *'s to come up but they are not forming the way I would like it to. ?So that why I was asking for help. I suppose the trick here is to add a comma at the end of the print statement, to let the next one continue printing on the same line. From zebra05 at gmail.com Tue Mar 17 16:05:46 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Tue, 17 Mar 2009 17:05:46 +0200 Subject: [Tutor] (no subject) In-Reply-To: <537341c70903170733n1d39c1cfhdbdb254101e08c31@mail.gmail.com> References: <537341c70903170733n1d39c1cfhdbdb254101e08c31@mail.gmail.com> Message-ID: Doesn't backslash also escape the newline? Thought i saw something to that effect in the tutorial. Lloyd On Tue, Mar 17, 2009 at 4:33 PM, Daniele wrote: > > From: dukelx2005 at gmail.com > > To: tutor at python.org > > Honestly I'm doing tutorials, I'm not in school. I am trying to learn it > for my own sake. > > I got the *'s to come up but they are not forming the way I would like it > to. So that why I was asking for help. > > I suppose the trick here is to add a comma at the end of the print > statement, to let the next one continue printing on the same line. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Mar 17 16:08:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 08:08:29 -0700 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? Message-ID: <49BFBCED.20204@sbcglobal.net> An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Tue Mar 17 16:14:05 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Tue, 17 Mar 2009 17:14:05 +0200 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> Message-ID: Apparently there's a tool to convert older Python code to Python 3 compatibility - is this what you want? Must be somewhere in the cheese shop - sorry i cannot recall the name, or where exactly i saw the discussion. Lloyd On Tue, Mar 17, 2009 at 1:33 PM, Andre Engels wrote: > I have an open source project I have done some work on, which is > programmed in Python 2.3-2.6. I would like to change it so that it can > be run under both Python 3 and Python 2.x. Two questions for that: > * is there a place where I can find an overview of what to do to make > such a change? > * is there a way to check, on one computer, the code under both > versions (I am using Windows Vista, in case it matters)? > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Tue Mar 17 16:53:51 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 17 Mar 2009 16:53:51 +0100 Subject: [Tutor] escaping newline (was: (no subject)) In-Reply-To: References: <537341c70903170733n1d39c1cfhdbdb254101e08c31@mail.gmail.com> Message-ID: <49BFC78F.3090206@tue.nl> OkaMthembo wrote: > Doesn't backslash also escape the newline? Thought i saw something to that > effect in the tutorial. It does, but only inside the .py file. It has no effect when you run the program. Its purpose is to allow you to break long lines, for example if long_function_name(a) == long_function_name(b) \ and long_function_name(c) == long_function_name(d) \ and long_function_name(e) == long_function_name(f): # do something if all three equalities hold note that you can place the \ break anywhere. Some people like the following layout if long_function_name(a) == long_function_name(b) and \ long_function_name(c) == long_function_name(d) and \ long_function_name(e) == long_function_name(f): # do something if all three equalities hold The conditions now nicely line up, making it easier to read. The down side (in my opinion) is that the difference in indent is really small. Sincerely, Albert From sierra_mtnview at sbcglobal.net Tue Mar 17 17:35:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 09:35:43 -0700 Subject: [Tutor] Checking Entry Values in Tkinter Widgets Message-ID: <49BFD15F.5030901@sbcglobal.net> An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Mar 17 15:58:39 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 17 Mar 2009 09:58:39 -0500 Subject: [Tutor] Gtk time control and Glade In-Reply-To: <49BFB2C6.3040500@cfl.rr.com> References: <49BFB2C6.3040500@cfl.rr.com> Message-ID: <200903170958.39806.cfuller084@thinkingplanet.net> Make your own. You can have empty containers in glade that you fill in at runtime, or you could create the interface in glade, perhaps a couple of ComboBoxes. I would leave an empty container and create a reusable widget descended from gtk.HBox that implements validation or anything else that it would need to do. Maybe it could default to the current time, for instance. I know its possible to configure glade to use custom widgets, but I've never bothered to learn about since it's so easy (and free of caveats that I might become subject to) to leave empty space for runtime use. Here's a quick and dirty (and untested!) example: class TimeEntry(gtk.HBox): def __init__(self): gtk.HBox.__init__(self) self.hr = \ w = gtk.ComboBox() for i in range(24): w.append_text('%02d'%(i,)) self.pack_start(w, False, False, 0) w.show() w = gtk.Label(':') self.pack_start(w, False, False, 0) w.show() self.min = \ w = gtk.ComboBox() for i in range(60): w.append_text('%02d'%(i,)) self.pack_start(w, False, False, 0) w.show() def get(self): return '%02d:%02d' % (self.hr.get_active(),self.min.get_active()) Cheers On Tuesday 17 March 2009 09:25, Robert Berman wrote: > I am writing a Blood-Glucose Analysis application for Diabetics. I am > using Python 2.5 under Ubuntu 8.10 and Glade 3.4.5. > > Manually recorded test results require a calendar control for the date > of the test (no problem) and a timer control for the time of the > test(big problem). While Glade certainly supports a calender control > with a great deal of documentation, there is not an available time > control for Glade. Nor was I able to find a general time control for > Gtk. I did find one for wxwidgets but I am not using wxwidgets nor am I > using PyQt. > > I am reasonably sure such a control exists. I know I'm not the only > individual who needs date and time controls. But, using Google has > provided all kinds of information, there has not been a specific > statement about any specific controls. At this time I do not feel I have > the level of expertise to build my own control and it is something I > would rather not have to do. > > Have any of you heard of such an available time control specifically for > Gtk and available or capable of being used by Glade. > > Thank you for any insights and suggestions. > > > Robert Berman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Tue Mar 17 18:01:31 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 17 Mar 2009 13:01:31 -0400 Subject: [Tutor] Gtk time control and Glade In-Reply-To: <200903170958.39806.cfuller084@thinkingplanet.net> References: <49BFB2C6.3040500@cfl.rr.com> <200903170958.39806.cfuller084@thinkingplanet.net> Message-ID: <49BFD76B.3020201@cfl.rr.com> Thank you Chris, that will certainly get me started. Robert Chris Fuller wrote: > Make your own. You can have empty containers in glade that you fill in at > runtime, or you could create the interface in glade, perhaps a couple of > ComboBoxes. I would leave an empty container and create a reusable widget > descended from gtk.HBox that implements validation or anything else that it > would need to do. Maybe it could default to the current time, for instance. > > I know its possible to configure glade to use custom widgets, but I've never > bothered to learn about since it's so easy (and free of caveats that I might > become subject to) to leave empty space for runtime use. > > Here's a quick and dirty (and untested!) example: > > class TimeEntry(gtk.HBox): > def __init__(self): > gtk.HBox.__init__(self) > > self.hr = \ > w = gtk.ComboBox() > > for i in range(24): > w.append_text('%02d'%(i,)) > > self.pack_start(w, False, False, 0) > w.show() > > w = gtk.Label(':') > self.pack_start(w, False, False, 0) > w.show() > > self.min = \ > w = gtk.ComboBox() > > for i in range(60): > w.append_text('%02d'%(i,)) > > self.pack_start(w, False, False, 0) > w.show() > > def get(self): > return '%02d:%02d' % (self.hr.get_active(),self.min.get_active()) > > Cheers > > On Tuesday 17 March 2009 09:25, Robert Berman wrote: > >> I am writing a Blood-Glucose Analysis application for Diabetics. I am >> using Python 2.5 under Ubuntu 8.10 and Glade 3.4.5. >> >> Manually recorded test results require a calendar control for the date >> of the test (no problem) and a timer control for the time of the >> test(big problem). While Glade certainly supports a calender control >> with a great deal of documentation, there is not an available time >> control for Glade. Nor was I able to find a general time control for >> Gtk. I did find one for wxwidgets but I am not using wxwidgets nor am I >> using PyQt. >> >> I am reasonably sure such a control exists. I know I'm not the only >> individual who needs date and time controls. But, using Google has >> provided all kinds of information, there has not been a specific >> statement about any specific controls. At this time I do not feel I have >> the level of expertise to build my own control and it is something I >> would rather not have to do. >> >> Have any of you heard of such an available time control specifically for >> Gtk and available or capable of being used by Glade. >> >> Thank you for any insights and suggestions. >> >> >> Robert Berman >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dkuhlman at rexx.com Tue Mar 17 19:16:53 2009 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 17 Mar 2009 11:16:53 -0700 Subject: [Tutor] Paython as a career In-Reply-To: <20090317104659.5197eba1@o> References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> <20090317104659.5197eba1@o> Message-ID: <20090317181653.GA75636@cutter.rexx.com> On Tue, Mar 17, 2009 at 10:46:59AM +0100, spir wrote: [snip] > Python is much more prominent in the free software/open-source > world -- than for commercial software. You may think the reason > is that free developpers can choose ;-) Free software rarely pays > back in terms of money. I'd like to disagree to some extend. While you may be right that it's less than common to be able to get a job as a Python programmer. It's also true that programming skills in general and Python skills in particular can add value to your resume. I've been hired a number of times to teach classes in corporations that had a need for Python skills. So, there are definitely companies out there that would view Python programming skills as valuable. I suspect that there are others on this list who also teach Python in a corporate setting. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From jeff at dcsoftware.com Tue Mar 17 19:51:36 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Tue, 17 Mar 2009 11:51:36 -0700 Subject: [Tutor] Paython as a career In-Reply-To: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> References: <116686ABAFDD46368D6B21B98F5CA9CA@HussainPC> Message-ID: <49BFF138.2030301@dcsoftware.com> Lukes answer is an excellent one! I would add that you can find language popularity here: http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html I am moving to Python from Visual FoxPro. I have been programming all of my adult career. I have used Cobol, RPG, Basic, FoxPro and Python all in production to make my living. I have been using FoxPro for 16 years and really love it, but find Python the most complete language. You don't need active X or third party libraries because they are all there and written Python. My success as a programmer has little to do with the language or even how well I program. It has more to do with my ability to understand the problem and communicate with customers or my employer. Good luck Hussain Ali wrote: > Dear all > > I want to start learning python but before going further I need answer > to my > questions so that my path can be clear to me. I shall be grateful for > your answers: > > 1) Where does python stand as compared to other programming languages? > 2) What is the future for python? > 3) Will it survive for long in this rapidly changing trends and new > languages? > 4) Should I start it to earn my bread and butter? I mean is that > beneficial for income. > > > Sincerely > > Hussain > -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From dukelx2005 at gmail.com Tue Mar 17 20:16:37 2009 From: dukelx2005 at gmail.com (Jared White) Date: Tue, 17 Mar 2009 15:16:37 -0400 Subject: [Tutor] (no subject) Message-ID: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> This is what i have so far an this is not what i want it to do "NO this isnt homework" i am trying to learn this myself #!/usr/bin/env python # # Author: J White # Python 2.5.2 # howmany = int(raw_input('How many lines ')) rhowmany = howmany strout = '*' while howmany > 0: print strout strout += '*' howmany -= 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Mar 17 20:24:00 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 12:24:00 -0700 Subject: [Tutor] Fun with Label and Entry--Why NoneType? Message-ID: <49BFF8D0.7020504@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Mar 17 20:52:48 2009 From: srilyk at gmail.com (W W) Date: Tue, 17 Mar 2009 14:52:48 -0500 Subject: [Tutor] (no subject) In-Reply-To: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> References: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> Message-ID: <333efb450903171252w55dd3411oeaaa615c4c7342b2@mail.gmail.com> On Tue, Mar 17, 2009 at 2:16 PM, Jared White wrote: > This is what i have so far an this is not what i want it to do > "NO this isnt homework" i am trying to learn this myself > > #!/usr/bin/env python > # > # Author: J White > # Python 2.5.2 > # > howmany = int(raw_input('How many lines ')) > rhowmany = howmany > strout = '*' > while howmany > 0: > print strout > strout += '*' > howmany -= 1 > try this: mystr = "h" print mystr*10 that should help. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Tue Mar 17 20:53:20 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 17 Mar 2009 14:53:20 -0500 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: <49BFF8D0.7020504@sbcglobal.net> References: <49BFF8D0.7020504@sbcglobal.net> Message-ID: <49BFFFB0.1080308@mwalsh.org> Wayne Watson wrote: > The program below is derived from an example in Grayson for showing how > one might a dialog for entering passwords. The structure seems just like > the original, down to the use of self, Label and Entry plus . Yet the > print "here" statement produces: > here None > I'm missing something. The NoneType causes the print of the self.lat to > fail with get(). > > The original returns something from the corresponding body function, but > taking it out does nothing in either program. The original program is > posted above under "Modifying Grayson's Example 5_14". > > # Derived from Grayson 5_14.py > from Tkinter import * > from tkSimpleDialog import Dialog > import tkSimpleDialog > import tkMessageBox > #import Pmw > > class DialogPrototype(Dialog): > > def body(self, master): > self.title("Enter Site Data") > Label(master, text='Latitude:').grid(row=0, sticky=W) > self.lat=Entry(master, width=12).grid(row=0, column=1) This is where you diverge from the Grayson example. What you're saying is that self.lat should be set to the result of Entry(...).grid(...) which is always None, presumably. What I think you want is self.lat to be a reference to the Entry widget itself. Try this, self.lat = Entry(master, width=12) self.lat.grid(row=0, column=1) > > Label(master, text='Longitude:').grid(row=0, column=2) > self.long=Entry(master, width=12).grid(row=0, column=3) ... and, self.long = Entry(master, width=12) self.long.grid(row=0, column=3) > print "here", self.long,type(self.long) > return > > def apply(self): > print "apply" > print self.lat.get() > print self.long.get() > > print "setting" > lat=1.0 > long=0.0 Is that the way you indented the above, really? I suppose it could be intentional, but probably not. > > root = Tk() > root.withdraw() > dialog = DialogPrototype(root) HTH, Marty From wescpy at gmail.com Tue Mar 17 20:54:27 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 17 Mar 2009 12:54:27 -0700 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> Message-ID: <78b3a9580903171254i7c72fc6asf0e5b98275cda53c@mail.gmail.com> > I would like to change it so that it can be run under both Python 3 and Python 2.x. everyone who has responded so far are telling about converting your piece of code from Python 2 to Python 3, for example, using the "2to3" tool that comes with Python 2.6+: http://docs.python.org/library/2to3.html however, that means that you have to maintain 2 different files, one for Python 3 and one for Python 2. no one has addressed your original request directly, so i'll do it here: it is nearly impossible to have a sufficiently complex single .py source file that will run under both Python 3 and Python 2 -- one single print statement would ruin it, if you know what i mean. however, Python 2.6 (and the rest of the 2.x series) have some of 3.0's features backported to it so that you can start writing against 3.x interpreters, and i would recommend that you start there. finally, 2.6 has a -3 switch that you can turn on to warn you about Python 3 incompatibilities. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue Mar 17 21:14:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 16:14:32 -0400 Subject: [Tutor] (no subject) In-Reply-To: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> References: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> Message-ID: <1c2a2c590903171314l466d2c70gc64f0e5adb7ba0b1@mail.gmail.com> On Tue, Mar 17, 2009 at 3:16 PM, Jared White wrote: > howmany = int(raw_input('How many lines ')) > rhowmany = howmany > strout = '*' > while howmany > 0: > ??? print strout > ??? strout += '*' > ??? howmany -= 1 Another hint: learn how to use the range() function and for loops: In [1]: for i in range(4) ...: print i 0 1 2 3 Kent From alan.gauld at btinternet.com Tue Mar 17 21:34:48 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 20:34:48 -0000 Subject: [Tutor] Making exe Python file - standalone executable file References: <8acd28da0903170250o34e09ddbo444a3684d411f631@mail.gmail.com> Message-ID: "Neven Gorsic" wrote > Py2exe i standard way (up to my knowledge) of making standalone > executable Python file in order to distribute your program to others > who don't have Python installed It is one of several ways to do that for those who believe that it is more advantageousd that simply packaging python with the application. But it is not "the standard way", it is a way. > (too bad that it is not part of standard Python distribution). I actually like that since it helps people get out of thinking that way. > I have no experience with wxPython and PyQT. Do they have > their own compilers or we must do it again with Py2exe? Neither is a compiled environment (and py2exe is not a compiler either). But if you want to package Qt or wxPython apps as a single file then yes you need to use a bundling tool like py2exe. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 17 21:40:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 20:40:42 -0000 Subject: [Tutor] escaping newline (was: (no subject)) References: <537341c70903170733n1d39c1cfhdbdb254101e08c31@mail.gmail.com> <49BFC78F.3090206@tue.nl> Message-ID: "A.T.Hofkamp" wrote > Some people like the following layout > > if long_function_name(a) == long_function_name(b) and \ > long_function_name(c) == long_function_name(d) and \ > long_function_name(e) == long_function_name(f): > # do something if all three equalities hold > I prefer to use parens for that: if ( long_function_name(a) == long_function_name(b) and long_function_name(c) == long_function_name(d) and long_function_name(e) == long_function_name(f) ): # do something if all three equalities hold That increases the indent and avoids the pesky \ chars. But it adds a hard-to-spot closing paren at the end :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From sierra_mtnview at sbcglobal.net Tue Mar 17 21:41:22 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 13:41:22 -0700 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: <49BFFFB0.1080308@mwalsh.org> References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org> Message-ID: <49C00AF2.8030503@sbcglobal.net> An HTML attachment was scrubbed... URL: From jeff at dcsoftware.com Tue Mar 17 21:44:42 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Tue, 17 Mar 2009 13:44:42 -0700 Subject: [Tutor] Personal: Fwd: Re: Paython as a career In-Reply-To: <1237320822.11376.1305924899@webmail.messagingengine.com> References: <1237320822.11376.1305924899@webmail.messagingengine.com> Message-ID: <49C00BBA.90501@dcsoftware.com> Malcolm: I have four sticky XML / flat files downloaded from a web site that is converted into four text files and then synchronized into one file. Due to the web interface I moved it from VFP to Python. It was easier, cleaner and very fast. I run it from the VFP RUN command. I have been using VFP / Foxpro since 1992. I have an app that is running fine for a long time and then something seems to go wrong. Maybe it's an upgrade of the OS or a Microsoft update or who knows what. I have to deal with it and rehash old code that was working fine. I have noticed that Python "just works". I have seen it already with this first project. Oh, I download all of my bank accounts and credit cards as .csv files. I then use Python to convert them to Quickbooks IIF files and import them into Quickbooks. No data entry because of Python! I am now developing a dabo app that has a UI. I should have it done soon and will let you know more about it on the dabo list. For me, Python is a lot like VFP only you don't need to bring in active X or third party libraries. I also have two Ubuntu machines that I can run it all on. As far as Dabo goes, check it out. The video of the report designer will get you hooked. I just wish I had more time. Malcolm Greene wrote: > Hi Jeff, > >> My success as a programmer has little to do with the language or even > how well I program. It has more to do with my ability to understand the > problem and communicate with customers or my employer. > > Great response! > > I'm really enjoying my move to Python. Not only the language, but the > optimism that surrounds the language (vs. the gray cloud of depression > that has haunted FoxPro for so many years). I've focused all my Python > efforts on back room data processing (ETL) vs. GUI type applications. In > fact, I haven't moved any of our GUI based products to Python (or Dabo). > > What are you doing with Python? Have you built any GUI apps yet and if > so, using wxPython (and Dabo?), pyQt, Tkinter, etc? > > Do you have any Dabo based apps in production yet? > > Curious to hear about your FoxPro migration journey when you have a > moment. > > Regards, > > Malcolm (from the Profox list) > > -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From alan.gauld at btinternet.com Tue Mar 17 21:44:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 20:44:28 -0000 Subject: [Tutor] (no subject) References: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> Message-ID: "Jared White" wrote > howmany = int(raw_input('How many lines ')) > rhowmany = howmany what does rhowmany do? > strout = '*' > while howmany > 0: > print strout > strout += '*' > howmany -= 1 > Combine the two hints so far to improve it, then look even more closely at range() to see how to do the decreasing lengths. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 17 21:46:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 20:46:06 -0000 Subject: [Tutor] list.replace -- string.swap References: <20090317120154.215f99d3@o> Message-ID: "spir" wrote > Is there a list.replace builtin I cannot find? Or a workaround? myList[x] = newValue Or is that too obvious? > Also: How would perform string.swap(s1, s2) in the following cases: > > * There is no secure 'temp' char, meaning that > s.replace(s1,temp).replace(s2,s1).replace(temp,s2) > will fail because any char can be part of s. > > * Either s1 or s2 can be more than a single char. Sorry you lost me there. No idea what you mean. Alan G. From kent37 at tds.net Tue Mar 17 21:44:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Mar 2009 16:44:57 -0400 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <78b3a9580903171254i7c72fc6asf0e5b98275cda53c@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> <78b3a9580903171254i7c72fc6asf0e5b98275cda53c@mail.gmail.com> Message-ID: <1c2a2c590903171344r4b56f0cfs465a1f7d69e2aa4b@mail.gmail.com> On Tue, Mar 17, 2009 at 3:54 PM, wesley chun wrote: >> I would like to change it so that it can be run under both Python 3 and Python 2.x. > > everyone who has responded so far are telling about converting your > piece of code from Python 2 to Python 3, for example, using the "2to3" > tool that comes with Python 2.6+: > http://docs.python.org/library/2to3.html > > however, that means that you have to maintain 2 different files, one > for Python 3 and one for Python 2. Not necessarily. I think the intent of 2to3 is that you maintain the Python 2.6 version and automatically create the Python 3 version from it. So there is only one source file. At least one person found this practical, for a large codebase (well, he says it "mostly works"): http://wiki.python.org/moin/PortingDjangoTo3k > no one has addressed your original > request directly, so i'll do it here: it is nearly impossible to have > a sufficiently complex single .py source file that will run under both > Python 3 and Python 2 -- one single print statement would ruin it, if > you know what i mean. Here are three success stories of creating a single version of a sizable project that runs in both 2.x and 3.0: http://pythonology.blogspot.com/2009/02/making-code-run-on-python-20-through-30.html http://mail.mems-exchange.org/durusmail/qp/441/ and followup The postings have a fair amount of detail. Durus, QP, QPy and evoque are all open source so you can see how they did it. http://www.mems-exchange.org/software/ - the latest releases include the Py 3.0 code though the README files don't mention it. http://evoque.gizmojo.org/ Kent From alan.gauld at btinternet.com Tue Mar 17 21:51:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 20:51:43 -0000 Subject: [Tutor] combining Python 2.x and Python 3 References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> Message-ID: "Andre Engels" wrote >I have an open source project I have done some work on, which is > programmed in Python 2.3-2.6. I would like to change it so that it > can > be run under both Python 3 and Python 2.x. That will be tricky. I think you can pretty much make Python 3 code that can run under v2.6. But I doubt you can make it run under anything older. There are too many new syntax features - just think about the difference in input() and print()... That's all your user I/O operations affected for starters! Maybe a Tkinter GUI could be made to work though? Alan G. From alan.gauld at btinternet.com Tue Mar 17 22:08:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 21:08:06 -0000 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? References: <49BFBCED.20204@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I've poked around at the pieces of the book in Subject, which are on > the web > It was published in 2000, first ed. It looks quite good, and > certainly is big, About a third of it is reference material. Not a bad thing, I use it a lot, but other sources have the same stuff. A lot is PMW which although still active I think, is no longer the only add on toolkit. Indeed Tix is now partof the standard library and adds a lot of the same sort of things. (Tabbed notebooks etc) The other oddity is a fair portion of the book is taken up with building photo-realistic UIs. This is not something I've ever found a need for! It is quite impressive but of distinctly limitedvalue for most programmers IMHO. > I'd like to think the author is going to produce another version. I've seen no signs of that. And although some of the newer widgets are not included very little of the book is out of date. OTOH if you just need a reference the "Tcl/Tk in a Nutshell" by O'Reilly might suit just as well and is available very cheaply second hand on Amazon... It is my second most used Tk source. (after Lundh's online reference, Grayson is my third!) It also covers Tix. Alan G. From alan.gauld at btinternet.com Tue Mar 17 22:13:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 21:13:13 -0000 Subject: [Tutor] Checking Entry Values in Tkinter Widgets References: <49BFD15F.5030901@sbcglobal.net> Message-ID: "Wayne Watson" wrote > The program I'm modifying uses something of a primitive way > to check the validity of values entered into widgets on a larger > dialog. You can bind events to the individual entry widgets to check values when you navigate away from the widget. Or even on each keypress... > ...Isn't this supposed to be done in the apply method for the > dialog? I believe so. That is where you would check the data consisterncy/integrity across all the widgets in the dialog. From your question it seems you don't think the apply() is getting called? > A typical data widget inside the set operations dialog class is: > > class OperationalSettingsDialog(tkSimpleDialog.Dialog): > > def __init__(self, parent, sdict): > self.sdict = sdict > tkSimpleDialog.Dialog.__init__(self, parent) > > def body(self,master): > self.title("Operational Settings") > ... > # data widget > Label( master, text="Max Hourly Event Rate: ").grid(row=5, > sticky=W) > self.rateVar = StringVar() > Entry(master, width=10, > textvariable=self.rateVar).grid(row=5, column=1) > self.rateVar.set( "%s" % self.sdict["hourly_rate"] ) > ... > def apply(self): > self.sdict["ok"] = True > #END of class > > Furthermore, doesn't the use of tkSimpleDialog.Dialog provide an OK > and Cancel button, which upon use causes the the invocation of the > apply method to depart? Again I believe so but I'm no expert on SimpleDialog. I usually just write my own dialogs based on Toplevel... Just habit. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cfuller084 at thinkingplanet.net Tue Mar 17 20:04:39 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 17 Mar 2009 14:04:39 -0500 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: <49BFBCED.20204@sbcglobal.net> References: <49BFBCED.20204@sbcglobal.net> Message-ID: <200903171404.40228.cfuller084@thinkingplanet.net> This is a super book for beginners who are new to GUI programming. Tkinter is easy to use, and comes included with Python. Serious programmers will probably want something faster, better looking, and with nicer features, but they can be tricky to figure out and install. I still prefer Tkinter for quick and dirty work or programs with simple interfaces. Pmw is a very nice system. I wish it was easily adapted to other GUI toolkits. Development on it has mostly ended, although not entirely, there was a new release within the last year. You will find it very useful if you write anything moderately interesting with Tkinter. This book does not cover the Tix widget set, which was originally created for Tcl/Tk and later included with Tkinter, after this book was published. I find that Pmw covers most of the problem space that Tix is suited for, but a beginner may have a different experience. I was disappointed when I heard that this book was no longer in print. I still have my copy, however, so all I need to do is make sure I clutch onto it tightly, and I'll be aright :) Cheers On Tuesday 17 March 2009 10:08, Wayne Watson wrote: > I've poked around at the pieces of the book in Subject, which are on the > web--two chapters. It was published in 2000, first ed. It looks quite good, > and certainly is big, 680 or so pages. He sells a digital version. It uses > Pmw, which I barely no more than how to spell it. Is that even current any > longer? I'd like to think the author is going to produce another version. > Anyone know? Here's a clipped version of the contents. It got good review > on Amazon. > > bout the cover xxii > author online xxiii > Part 1 Basic concepts 1 > > 1 Python 3 > ??? 1.1 Introduction to Python programming and a feature review 3 > > ??? Why Python? 4, Where can Python be used? 5 > > ??? 1.2 Key data types: lists, tuples and dictionaries 5 > > ??? Lists 5, Tuples 7, Dictionaries 8 > > ??? 1.3 Classes 9 > > ??? How do classes describe objects? 9, Defining classes 9, Neat Python > trick #10 9, Initializing an instance 10, Methods 10, Private and public > variables and methods 11, Inheritance 11, Multiple inheritance 11, Mixin > classes 11 > > 2 Tkinter 12 > ??? 2.1 The Tkinter module 12 > > ??? What is Tkinter? 12, What about performance? 13, How do I use Tkinter? > 13, Tkinter features 14 > > ??? 2.2 Mapping Tcl/Tk to Tkinter 14 > ??? 2.3 Win32 and Unix GUIs 15 > ??? 2.4 Tkinter class hierarchy 16 > ??? 2.5 Tkinter widget appearance 17 > 3 Building an application 18 > ??? 3.1 Calculator example: key features 21 > ??? 3.2 Calculator example: source code 21 > ??? 3.3 Examining the application structure 27 > ??? 3.4 Extending the application 28 > > Part 2 Displays 29 > > 4 Tkinter widgets 31 > ??? 4.1 Tkinter widget tour 31 > > ??? Toplevel 32, Frame 33, Label 35, Button 36, Entry 37, Radiobutton 37, > Checkbutton 38, Menu 39, Message 42, Text 43, Canvas 44, Scrollbar 45, > Listbox 45, Scale 46 > > ??? 4.2 Fonts and colors 47 > > ??? Font descriptors 47, X Window System font descriptors 47, Colors 48, > Setting application-wide default fonts and colors 49 > > ??? 4.3 Pmw Megawidget tour 49 > > ??? AboutDialog 50, Balloon 50, ButtonBox 51, ComboBox 52, ComboBoxDialog > 53, Counter 54, CounterDialog 55, Dialog 56, EntryField 56, Group 57, > LabeledWidget 58, MenuBar 59, MessageBar 59, MessageDialog 61, NoteBookR > 61, NoteBookS 62, NoteBook 63, OptionMenu 64, PanedWidget 65, PromptDialog > 66, RadioSelect 66, ScrolledCanvas 67, ScrolledField 68, ScrolledFrame 69, > ScrolledListbox 70, ScrolledText 70, SelectionDialog 71, TextDialog 72, > TimeCounter 73 ... snip > 8 Dialogs and forms 140 > ??? 8.1 Dialogs 141 > > ??? Standard dialogs 141, Data entry dialogs 142, Single-shot forms 146, > Tkinter variables 152 > > ??? 8.2 A standard application framework 155 > ??? 8.3 Data dictionaries 165 > ??? 8.4 Notebooks 172 > ??? 8.5 Browsers 175 > ??? 8.6 Wizards 184 > ??? 8.7 Image maps 191 > ??? 8.8 Summary 198 > 9 Panels and machines 199 > ??? 9.1 Building a front panel 199 > ??? 9.2 Modularity 201 > ??? 9.3 Implementing the front panel 201 > ??? 9.4 GIF, BMP and overlays 215 > ??? 9.5 And now for a more complete example 220 > ??? 9.6 Virtual machines using POV-Ray 232 > > ??? And now for something completely different... #10 The Example 233 > > ??? 9.7 Summary 236 > 10 Drawing blobs and rubber lines 237 > ??? 10.1 Drawing on a canvas 238 > > ??? Moving canvas objects 243 > > ??? 10.2 A more complete drawing program 244 > ??? 10.3 Scrolled canvases 251 > ??? 10.4 Ruler-class tools 254 > ??? 10.5 Stretching canvas objects 258 > ??? 10.6 Some finishing touches 262 > ??? 10.7 Speed drawing 271 > ??? 10.8 Summary 275 > 11 Graphs and charts 276 > ??? 11.1 Simple graphs 276 > ??? 11.2 A graph widget 279 > > ??? Adding bargraphs 286, Pie charts 289 > > ??? 11.3 3-D graphs 292 > ??? 11.4 Strip charts 296 > ??? 11.5 Summary 298 > 12 Navigation 300 > ??? 12.1 Introduction: navigation models 300 > ??? 12.2 Mouse navigation 301 > ... snip > 18 Threads and asynchronous techniques 361 > ??? 18.1 Threading 361 > > ??? Non-GUI threads 362, GUI threads 365 > > ??? 18.2 ?after? processing 369 > ??? 18.3 Summary 373 > 19 Distributing Tkinter applications 374 > ??? 19.1 General issues in distributing applications 374 > ??? 19.2 Distributing Unix applications 375 > ??? 19.3 Distributing Win32 applications 376 > ??? 19.4 Python distribution tools 379 > > Part 4 Appendices 381 > > appendix A Mapping Tk to Tkinter 383 > appendix B Tkinter reference 425 > appendix C Pmw reference: Python megawidgets 542 > appendix D Building and installing Python, Tkinter 610 > appendix E Events and keysyms 617 > appendix F Cursors 621 > appendix G References 625 > index 629 From alan.gauld at btinternet.com Tue Mar 17 22:19:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 21:19:07 -0000 Subject: [Tutor] Fun with Label and Entry--Why NoneType? References: <49BFF8D0.7020504@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Yet the print "here" statement produces: > here None > I'm missing something. The NoneType causes the print of the self.lat > to fail with get(). > self.long=Entry(master, width=12).grid(row=0, column=3) The placement methods(pack, grod etc) all return None. You must run them as a separate line if you want to get a reference to the widget. self.long=Entry(master, width=12) self.long.grid(row=0, column=3) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 17 22:27:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 21:27:56 -0000 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? References: <49BFBCED.20204@sbcglobal.net> <200903171404.40228.cfuller084@thinkingplanet.net> Message-ID: "Chris Fuller" wrote > easy to use, and comes included with Python. Serious programmers > will > probably want something faster, better looking, and with nicer > features, The next versions of Python/Tkinter will apparently be based on the new widget set of Tk which has native look n feel on each platform so the ugly factor should at least dissappear! > This book does not cover the Tix widget set, which was originally > created for > Tcl/Tk and later included with Tkinter, after this book was > published. I > find that Pmw covers most of the problem space that Tix is suited > for, but a > beginner may have a different experience. Between the new Tkinter standard widgets (Paned Window, Spinbox etc) and Tix virtually everything in PMW is available in the standard library. and there are some extras not in PMW like a Grid and Tree for example. One of the things on my ToDo list is to add a couple of new topics to my tutorial giving simple examples for all the Tkinter and Tix widgets... As much for my own benefit as anything! HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From pyprog05 at gmail.com Tue Mar 17 22:34:42 2009 From: pyprog05 at gmail.com (PyProg PyProg) Date: Tue, 17 Mar 2009 22:34:42 +0100 Subject: [Tutor] sets module equivalent with Python 2.6 Message-ID: Hello all, I want to use an equivalent of sets module with Python 2.6 ... but sets module is deprecated on 2.6 version. In fact I want to make that but with Python 2.6: >>> toto_1 = [0, 1, 2, 3, 4] >>> toto_2 = [1, 127, 4, 7, 12] >>> >>> import sets >>> a = sets.Set(toto_1) >>> b = sets.Set(toto_2) >>> c = a.symmetric_difference(b) >>> d = [p for p in c] >>> d.sort() >>> print d [0, 2, 3, 7, 12, 127] Can you help me ?. Thanks in advance. a+ -- http://ekd.tuxfamily.org From alan.gauld at btinternet.com Tue Mar 17 22:32:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Mar 2009 21:32:53 -0000 Subject: [Tutor] Fun with Label and Entry--Why NoneType? References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> Message-ID: "Wayne Watson" wrote > got shelled by: > dialog = DialogPrototype(root) > TclError: window ".60529560" was deleted before its visibility > changed Thats the result of withdraw I think Try reversing the calls: root = Tk() dialog = DialogPrototype(root) root.withdraw() That way the withdraw happens after the dialog is created. root should not then be garbage collected since it is still referred to by the Dialog parent attribute. I think... :-) Alan G. From wescpy at gmail.com Tue Mar 17 22:48:51 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 17 Mar 2009 14:48:51 -0700 Subject: [Tutor] sets module equivalent with Python 2.6 In-Reply-To: References: Message-ID: <78b3a9580903171448m38d30c6fmeb69267ced5177bb@mail.gmail.com> On Tue, Mar 17, 2009 at 2:34 PM, PyProg PyProg wrote: > > I want to use an equivalent of sets module with Python 2.6 ... but > sets module is deprecated on 2.6 version. it is deprecated only because sets have been rolled into Python proper starting in 2.4. replace sets.Set() with set(), and there is frozenset() as well. > In fact I want to make that but with Python 2.6: > >>>> toto_1 = [0, 1, 2, 3, 4] >>>> toto_2 = [1, 127, 4, 7, 12] >>>> >>>> import sets >>>> a = sets.Set(toto_1) >>>> b = sets.Set(toto_2) >>>> c = a.symmetric_difference(b) >>>> d = [p for p in c] >>>> d.sort() >>>> print d > [0, 2, 3, 7, 12, 127] > > Can you help me ?. here is some code that works under Python 2.4, 2.5, and 2.6: $ python2.6 Python 2.6.1 (r261:67515, Feb 26 2009, 01:19:46) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> toto_1 = [0, 1, 2, 3, 4] >>> toto_2 = [1, 127, 4, 7, 12] >>> >>> a = set(toto_1) >>> b = set(toto_2) >>> c = a.symmetric_difference(b) >>> d = [p for p in c] >>> d.sort() >>> print d [0, 2, 3, 7, 12, 127] in 3.x, you also get set literals, meaning no more factory function calls are required! $ python3.0 Python 3.0.1 (r301:69556, Feb 26 2009, 01:01:25) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = {0, 1, 2, 3, 4} >>> b = {1, 127, 4, 7, 12} >>> c = a.symmetric_difference(b) >>> d = [p for p in c] >>> d.sort() >>> print(d) [0, 2, 3, 7, 12, 127] hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at abbottdavid.com Tue Mar 17 23:07:42 2009 From: david at abbottdavid.com (David) Date: Tue, 17 Mar 2009 18:07:42 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <9239372b0903171216q24d92f9al96d78a4d2e2041d6@mail.gmail.com> Message-ID: <49C01F2E.1090400@abbottdavid.com> Alan Gauld wrote: > >> > Combine the two hints so far to improve it, then look even more closely > at range() to see how to do the decreasing lengths. > > Thanks for the tips, I have been trying to figure it out also. I did get it after about 3 hours :) -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From cfuller084 at thinkingplanet.net Tue Mar 17 21:01:55 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 17 Mar 2009 15:01:55 -0500 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: References: <49BFBCED.20204@sbcglobal.net> <200903171404.40228.cfuller084@thinkingplanet.net> Message-ID: <200903171501.55799.cfuller084@thinkingplanet.net> What sets Pmw apart is the framework it provides for the creation of your own megawidgets. It handles labels, forwards options from the constructor to the constructors of the subcomponents, forwards method calls (say your megawidget is descended from a Frame, but the main feature is a Scale widget), includes a set of standard data validators, etc. Cheers On Tuesday 17 March 2009 16:27, Alan Gauld wrote: > "Chris Fuller" wrote > > This book does not cover the Tix widget set, which was originally > > created for > > Tcl/Tk and later included with Tkinter, after this book was > > published. I > > find that Pmw covers most of the problem space that Tix is suited > > for, but a > > beginner may have a different experience. > > Between the new Tkinter standard widgets (Paned Window, Spinbox etc) > and Tix virtually everything in PMW is available in the standard > library. and > there are some extras not in PMW like a Grid and Tree for example. From alan.gauld at btinternet.com Wed Mar 18 01:12:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Mar 2009 00:12:53 -0000 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? References: <49BFBCED.20204@sbcglobal.net><200903171404.40228.cfuller084@thinkingplanet.net> <200903171501.55799.cfuller084@thinkingplanet.net> Message-ID: "Chris Fuller" wrote > What sets Pmw apart is the framework it provides for the creation of > your own > megawidgets. I can't comment on the PMW framework and I haven't tried it in Python Tix but the Tcl documents claim Tix does a similar thing. Certainly insofar as it provides a framework for creating your own widgets. My Tcl/Tk Nutshell book says: "Tix adds an object oriented (AG: ie. to Tcl/Tk) framework for defining new widget types from existing widget types. Instances of these new widget types are called mega-widgets. Tix includes over 40... and several commands for designing new ones..." The main creation commands I see are tixWidgetClass, tixCallMethod, tixChainMethod. There are maybe half a dozen others. A quick look in Python Tix reveals a TixWidget class. But the other commands are not obvuiously available - but they may be hidden as methods of something else... > It handles labels, forwards options from the constructor to the > constructors of the subcomponents, forwards method calls (say your > megawidget > is descended from a Frame, but the main feature is a Scale widget), > includes > a set of standard data validators, etc. It can do the forwarding of methods but I can't see any validators etc. It would be interesting to do a bit of comparison, if only there were some decent documents for Python Tix! :-( Alan G. From sierra_mtnview at sbcglobal.net Wed Mar 18 01:25:39 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 17:25:39 -0700 Subject: [Tutor] Checking Entry Values in Tkinter Widgets In-Reply-To: References: <49BFD15F.5030901@sbcglobal.net> Message-ID: <49C03F83.7010901@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 18 01:33:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 17:33:43 -0700 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> Message-ID: <49C04167.9080609@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Wed Mar 18 02:06:02 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 18 Mar 2009 14:06:02 +1300 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: <49C04167.9080609@sbcglobal.net> References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> Message-ID: <5e58f2e40903171806k26fae381pe3545b63364043f3@mail.gmail.com> 2009/3/18 Wayne Watson : > Unfortunately, that takes me back to the original situation. That is, the > blank window appears along with the dialog window. It also ends badly with > what looks like the same error messages(below). Maybe focus needs to be > established. I'm really using this code to design a dialog for the larger > application program, so I don't need to get too fussy about how it ends. I > just want to see that I've got the elementary widgets place properly. I didn't notice any call to root.mainloop() in your original code. Are you calling mainloop() anywhere? -- John. From alan.gauld at btinternet.com Wed Mar 18 02:20:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Mar 2009 01:20:14 -0000 Subject: [Tutor] Checking Entry Values in Tkinter Widgets References: <49BFD15F.5030901@sbcglobal.net> <49C03F83.7010901@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Yes, apply is invoked when I click OK. apply has one statement, > and returns to the caller, which then checks the validity > (try-except) > of values passed back to it. It seems like apply should do all the > try-except work instead. Yes, I'd agree that is how it should work. > What I really need are checks like is lat (latitude) from -90 to > +90, > and not -700, say. That is bound checking. Yes, that can be done with binding of validation code to the lat field. You could also use the FocusOut event for example to run something like: # in the create widget section.... self.lat.bind('', self.vLat) # validation handler def vLat(self, ev): if 90 < int(self.lat.get()) < -90: # beep, or error dialog self.lat.focus_set() Which would generate an alert and reset focus to the widget before even hitting apply(). HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Mar 18 03:04:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Mar 2009 02:04:26 -0000 Subject: [Tutor] Fun with Label and Entry--Why NoneType? References: <49BFF8D0.7020504@sbcglobal.net><49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Unfortunately, that takes me back to the original situation. > That is, the blank window appears along with the dialog window. OK Try this version: # Derived from Grayson 5_14.py from Tkinter import * from tkSimpleDialog import Dialog class DialogPrototype(Dialog): def body(self, master): self.title("Enter Site Data") Label(master, text='Latitude:').grid(row=0, sticky=W) self.lat=Entry(master, width=12) self.lat.grid(row=0, column=1) Label(master, text='Longitude:').grid(row=0, column=2) self.long=Entry(master, width=12) self.long.grid(row=0, column=3) self.master.withdraw() def apply(self): print "apply" print self.lat.get() print self.long.get() print "setting" lat=1.0 long=0.0 root = Tk() DialogPrototype(root) From alan.gauld at btinternet.com Wed Mar 18 03:07:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Mar 2009 02:07:41 -0000 Subject: [Tutor] Fun with Label and Entry--Why NoneType? References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org><49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <5e58f2e40903171806k26fae381pe3545b63364043f3@mail.gmail.com> Message-ID: "John Fouhy" wrote >> Unfortunately, that takes me back to the original situation. That >> is, the >> blank window appears along with the dialog window. It also ends >> badly with > I didn't notice any call to root.mainloop() in your original code. > Are you calling mainloop() anywhere? I noticed that too but it doesn't seem to need a mainloop call, I assume that is happening somewhere in the inherited Dialog framework, but I've no idea how/where! But an event loop is surely running somewhere! Alan G. From john at fouhy.net Wed Mar 18 03:11:04 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 18 Mar 2009 15:11:04 +1300 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: <49C0575A.6090509@sbcglobal.net> References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <5e58f2e40903171806k26fae381pe3545b63364043f3@mail.gmail.com> <49C0575A.6090509@sbcglobal.net> Message-ID: <5e58f2e40903171911i2389450by486975913343ceb9@mail.gmail.com> 2009/3/18 Wayne Watson : > Not at all. I took Grayson's example as it stood. However, as it might have > been noted above, he was working with Pmw, so the code may be a false > impression of how it works in Tkinter. > > This gave the same results: > root = Tk() > dialog = DialogPrototype(root) > root.mainloop() > > Extra blank window at start up and crashed the same way when pressing OK. > I'm using this code to prototype a larger dialog with more data entry, so it > doesn't really matter that it crashes when I exit. Well, my Tkinter is pretty rusty, but I'm guessing that your dialog may not work if there is no event loop running. Try this: root = Tk() root.after_idle(DialogPrototype, root) root.mainloop() See docs here for the after_idle() method: http://effbot.org/tkinterbook/widget.htm -- John. From sierra_mtnview at sbcglobal.net Wed Mar 18 04:25:18 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 20:25:18 -0700 Subject: [Tutor] Checking Entry Values in Tkinter Widgets In-Reply-To: References: <49BFD15F.5030901@sbcglobal.net> <49C03F83.7010901@sbcglobal.net> Message-ID: <49C0699E.7030108@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 18 04:25:35 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 20:25:35 -0700 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: <5e58f2e40903171806k26fae381pe3545b63364043f3@mail.gmail.com> References: <49BFF8D0.7020504@sbcglobal.net> <49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <5e58f2e40903171806k26fae381pe3545b63364043f3@mail.gmail.com> Message-ID: <49C069AF.7090906@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 18 04:26:00 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Mar 2009 20:26:00 -0700 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: References: <49BFBCED.20204@sbcglobal.net> Message-ID: <49C069C8.8010502@sbcglobal.net> An HTML attachment was scrubbed... URL: From wescpy at gmail.com Wed Mar 18 06:50:41 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 17 Mar 2009 22:50:41 -0700 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <1c2a2c590903171344r4b56f0cfs465a1f7d69e2aa4b@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> <78b3a9580903171254i7c72fc6asf0e5b98275cda53c@mail.gmail.com> <1c2a2c590903171344r4b56f0cfs465a1f7d69e2aa4b@mail.gmail.com> Message-ID: <78b3a9580903172250r15f2c78v593a0458dd465ac5@mail.gmail.com> > I think the intent of 2to3 is that you maintain the > Python 2.6 version and automatically create the Python 3 version from > it. So there is only one source file. At least one person found this > practical, for a large codebase (well, he says it "mostly works"): > http://wiki.python.org/moin/PortingDjangoTo3k > >> no one has addressed your original >> request directly, so i'll do it here: it is nearly impossible to have >> a sufficiently complex single .py source file that will run under both >> Python 3 and Python 2 -- one single print statement would ruin it, if >> you know what i mean. > > Here are three success stories of creating a single version of a > sizable project that runs in both 2.x and 3.0: > http://pythonology.blogspot.com/2009/02/making-code-run-on-python-20-through-30.html > http://mail.mems-exchange.org/durusmail/qp/441/ and followup > > The postings have a fair amount of detail. Durus, QP, QPy and evoque > are all open source so you can see how they did it. > http://www.mems-exchange.org/software/ - the latest releases include > the Py 3.0 code though the README files don't mention it. > http://evoque.gizmojo.org/ wow, great links Kent. i didn't think that people would be as bold as to do this, but i guess it was inevitable. it's interesting to see both the similarities and the differences for those who are trying to maintain a single version source. (in particular, the "if" statements checking versions with attributes of the sys module reminds me of old C code i worked on years ago when maintaining apps that had to run on both Unix and Windows systems.) it may be worthwhile to collate all of this info into a "2to3 FAQ" at some point. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Wed Mar 18 09:45:14 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 18 Mar 2009 08:45:14 +0000 (GMT) Subject: [Tutor] Fw: list.replace -- string.swap Message-ID: <106858.25675.qm@web86708.mail.ird.yahoo.com> Forwarding to list > From: spir > To: Alan Gauld > Sent: Wednesday, 18 March, 2009 8:41:39 AM > Subject: Re: [Tutor] list.replace -- string.swap > > Le Tue, 17 Mar 2009 20:46:06 -0000, > "Alan Gauld" s'exprima ainsi: > > "spir" wrote > Sorry, I was unclear all along my post. > > > > Is there a list.replace builtin I cannot find? Or a workaround? > > > > myList[x] = newValue > > > > Or is that too obvious? > > I mean like string.replace. Something like: > > def replace(seq, v1, v2): > for (index,item) in enumerate(seq): > if item == v1: > seq[index] = v2 > > Now, I know i does not exist. > > > > Also: How would perform string.swap(s1, s2) in the following cases: > > Here I mean exchanging s1 and s2 occurrences all along a string. As an example, > in a text containing numerous formatted numbers, switch from english to european > format: > 1,234,567.89 > 1.234.567,89 > meaning exchange '.' and ','. > > > > * There is no secure 'temp' char, meaning that > > > s.replace(s1,temp).replace(s2,s1).replace(temp,s2) > > > will fail because any char can be part of s. > > The use of a temp char for marking places of one the chars to be swapped is a > common trick. But if the text can contain any char (even chr(0)), then there no > char you can safely use as temp. > The only workaround I know is to pass through lists. Then swap on the list, > using eg None as temp item, and glue back the result to a string. But you need > them a replace method on lists, hence my previous question ;-) > > > > * Either s1 or s2 can be more than a single char. > > More difficult, cause you cannot simple list() the string. It must split on s1 > and s2, but keeping the delimiters! There is no option afaik for that in > string.split -- too bad! So that you must split it manually at start and end of > each instance of s1 and s2. Or there are other algorithms I cannot figure out. > What I was asking for. > > > Sorry you lost me there. No idea what you mean. > > > Sorry, me! > > > Alan G. > > denis > ------ > la vita e estrany From kent37 at tds.net Wed Mar 18 11:39:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Mar 2009 06:39:16 -0400 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: <78b3a9580903172250r15f2c78v593a0458dd465ac5@mail.gmail.com> References: <6faf39c90903170433r5a4813dfh2a9a2a13b7c97792@mail.gmail.com> <78b3a9580903171254i7c72fc6asf0e5b98275cda53c@mail.gmail.com> <1c2a2c590903171344r4b56f0cfs465a1f7d69e2aa4b@mail.gmail.com> <78b3a9580903172250r15f2c78v593a0458dd465ac5@mail.gmail.com> Message-ID: <1c2a2c590903180339i4293e66kcb160c6f0308c0b4@mail.gmail.com> On Wed, Mar 18, 2009 at 1:50 AM, wesley chun wrote: > wow, great links Kent. i didn't think that people would be as bold as > to do this, but i guess it was inevitable. > it may be worthwhile to collate all of > this info into a "2to3 FAQ" at some point. http://wiki.python.org/moin/PortingPythonToPy3k I should also mention the python-porting mailing list: http://mail.python.org/mailman/listinfo/python-porting Kent From alan.gauld at btinternet.com Wed Mar 18 14:14:38 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 18 Mar 2009 13:14:38 +0000 (GMT) Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? References: <49BFBCED.20204@sbcglobal.net> <49C05B74.40102@sbcglobal.net> <396285.73167.qm@web86702.mail.ird.yahoo.com> <49C0E856.7050302@sbcglobal.net> Message-ID: <208198.58884.qm@web86706.mail.ird.yahoo.com> Here is the news about a new Tk in Python: (Posted on the TkDocs web site - the home of Tk) ================ February 03, 2009 Ttk support in Python. Guilherme Polo passed along the great news that his pyttk module has been accepted into Python's standard library. That means we should see pyttk generally available with Python 2.7 and 3.1 (both still in development). You can see the current docs here. And of course, this is something I was waiting for before updating TkDocs with Python info and examples. Thanks for all your hard work Guilherme! ==================== Note this seems to be a recent web site and they are still building a lot of the documentation, but it looks like it should turn into a very useful Tk resource. As for the Tkinter mailing list. You can either watch it via the gmane news feed (which I do) and using your preferred news reader subscribe to: gmane.comp.python.tkinter Or on the web at: http://dir.gmane.org/gmane.comp.python.tkinter or go to http://mail.python.org/mailman/listinfo/tkinter-discuss to sign up for the emails. HTH, Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Wayne Watson To: ALAN GAULD Sent: Wednesday, 18 March, 2009 12:25:58 PM Subject: Re: [Tutor] Python and Tkinter Programming by Grayson--New Version? How do I get to that mail list? I see no evidence of a "new" Tkinter in my internet Googling. Maybe it's going by a new name? ALAN GAULD wrote: Tk is far from dead. Try the Tkinter mailing list, it is at least as busy as the tutor one. And the Tcl/Tk side of things has had a new lease of life over the past two years with a complete re-architecture of Tk resulting in the new native-look widgets. We just need that new found activity to translate to Tkinter... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Wayne Watson To: Alan Gauld Sent: Wednesday, 18 March, 2009 2:24:52 AM Subject: Re: [Tutor] Python and Tkinter Programming by Grayson--New Version? Working with Tkinter is like trying to dig through fossils. So much out there is old or incomplete. It's like the Tk species went extinct. The trail seems to end in 2005. I think I read it's not quite dead, and a newer looking is coming. Alan Gauld wrote: "Wayne Watson" wrote I've poked around at the pieces of the book in Subject, which are on the web It was published in 2000, first ed. It looks quite good, and certainly is big, About a third of it is reference material. Not a bad thing, I use it a lot, but other sources have the same stuff. A lot is PMW which although still active I think, is no longer the only add on toolkit. Indeed Tix is now partof the standard library and adds a lot of the same sort of things. (Tabbed notebooks etc) The other oddity is a fair portion of the book is taken up with building photo-realistic UIs. This is not something I've ever found a need for! It is quite impressive but of distinctly limitedvalue for most programmers IMHO. I'd like to think the author is going to produce another version. I've seen no signs of that. And although some of the newer widgets are not included very little of the book is out of date. OTOH if you just need a reference the "Tcl/Tk in a Nutshell" by O'Reilly might suit just as well and is available very cheaply second hand on Amazon... It is my second most used Tk source. (after Lundh's online reference, Grayson is my third!) It also covers Tix. Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Signature.html Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) ?Life is one damn thing after another." -- Mark Twain -- Signature.html Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) ?Life is one damn thing after another." -- Mark Twain -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Wed Mar 18 14:49:52 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 18 Mar 2009 08:49:52 -0500 Subject: [Tutor] combining Python 2.x and Python 3 In-Reply-To: References: Message-ID: These are very interesting links, and I just downloaded the evoque code to see how they handled the one "impossible" case that has stymied me in supporting pyparsing under Python 2.x (pre-2.6) and Python 3.0 with a single code base: exception handling. For those new to this topic, here is the problem. Python 2.x uses this syntax (code in []'s is optional, syntax-wise): try: ... body of try block ... except exception_type[, exception_var]: ... body of except block ... In Python 3.0, this has become: try: ... body of try block ... except exception_type[as exception_var]: ... body of except block ... Searching through evoque's code, I found that nearly all excepts are of the form: except exception_type: (3 are bare except:'s - eek!) Unfortunately, pyparsing makes *heavy* use of exceptions for managing the navigation through the parsing alternatives defined in the users parser expression. I have already removed all cases of "except exc_type, exc_var:" where the exc_var is not used in the exception handling block, but there are still some cases where I *must* have the actual exception that was raised. I posted to Stephan Deibel's blog a comment asking how he resolved this - here is his reply: >>> Instead of the version-specific except clause forms I use just 'except SomeException:' or 'except:' and then use sys.exc_info() inside the except block to get at the exception information. That returns a three-value tuple, the second element of which is the same thing you would get for 'e' in 'except SomeException, e:' or 'except SomeException as e:'. >>> Well, this is certainly promising, but pyparsing already has performance challenges, and adding another function call in an exception handler to work around this syntax issue is not that attractive. My rough timing shows that calling exc_info to extract the exception variable incurs a ~30% performance penalty over using "except exc_type, exc_var:". Note that adding this code would impact not only the Python 3.0 users, but would also degrade performance for Python 2.x users using this code base. I can certainly use this trick in those parts of pyparsing that are not performance-critical (when building the parser to begin with for instance, as opposed to the actual parsing time). But in the parse-time code, I'm unwilling to add 30% to my users' parsing time. -- Paul From sierra_mtnview at sbcglobal.net Wed Mar 18 15:29:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 07:29:23 -0700 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: References: <49BFF8D0.7020504@sbcglobal.net><49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> Message-ID: <49C10543.3030609@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 18 15:59:03 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 18 Mar 2009 14:59:03 +0000 (GMT) Subject: [Tutor] Fun with Label and Entry--Why NoneType? References: <49BFF8D0.7020504@sbcglobal.net><49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <49C10543.3030609@sbcglobal.net> Message-ID: <780360.82279.qm@web86711.mail.ird.yahoo.com> > That change got the same result. Maybe this will make it all clearer. > When the prompt appears, there is a small window showing on the > screen, 2x2", Yes, that's the root window that Python expects you to put your GUI into. The master that you pas to your GUI wFrames. It didn't show for me with the code I posted. How are you running this? Are you launching it from Windows Explorer or from a command line or from an IDE? I was just double clicking on the file in explorer... > My guess is that dialog needs to be "connected" to that root window. I suspect the problem is that you are trying to run a dialog as an application. Dialogs are normally launched from another window. So normally that Tk window would come up with the main app form, menus etc. Then from there you would perform an action (button, menu etc) that would launch the Dialog. So we are kind of twisting the way Tkinter expects to be uased here. But putting withdraw into the body method worked for me last night. > IDLE forces a hang in the shell window, which requires effort to > recover. As I keep saying, don't use IDLE to run Tkinter apps. Despite the supposed fixes it is not a reliable mechanism. Use ODLE as an editor but run the app from Windows Explorer or a command line BTW I just double checked and when I double click in Explorer on the python file I only get the dialog and Dos box (which of course would go away if I changeed the file extension to .pyw) Alan G OK Try this version: # Derived from Grayson 5_14.py from Tkinter import * from tkSimpleDialog import Dialog class DialogPrototype(Dialog): def body(self, master): self.title("Enter Site Data") Label(master, text='Latitude:').grid(row=0, sticky=W) self.lat=Entry(master, width=12) self.lat.grid(row=0, column=1) Label(master, text='Longitude:').grid(row=0, column=2) self.long=Entry(master, width=12) self.long.grid(row=0, column=3) self.master.withdraw() def apply(self): print "apply" print self.lat.get() print self.long.get() print "setting" lat=1.0 long=0.0 root = Tk() DialogPrototype(root) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 18 16:31:20 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 08:31:20 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win Message-ID: <49C113C8.80002@sbcglobal.net> An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Wed Mar 18 18:03:33 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 18 Mar 2009 13:03:33 -0400 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C113C8.80002@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> Message-ID: <49C12965.1020600@cfl.rr.com> Wayne, I think I do the opposite of what you are doing. I develop in Python on a Linux (Ubuntu 8.10) box. On that box, I also run a virtual copy of Windows XP in its own little happy environment. That way, when my XP customers have a problem, I drop into the desktop environment running XP and we are off and running. From the gist of your comment, you want to run Linux from within your Windows OS? Well, given the miracle of Virtual Memory, you can do that. Download the Xvm Virtual Memory (free) package from Sun and install it on your Windows system. Then, allocate a Linux system under the auspices of VM and you are off and running. Hope this is of some help. Robert Berman Wayne Watson wrote: > The Subject contains the interest here. Can it be done? I think it > this case it requires executing the program command line with > parameters then executing it? How dependent upon the C compiled code > is this? That is, I would think various distributions of Linux might > produce different executable code. The too I would want to do this in > Win. Is there, in fact, some Linux environment in Win that would allow > me to test its executable? > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time)**** > > > ?Life is one damn thing after another." > -- Mark Twain > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Mar 18 19:00:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Mar 2009 18:00:39 -0000 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win References: <49C113C8.80002@sbcglobal.net> Message-ID: "Wayne Watson" wrote > The Subject contains the interest here. Can it be done? A C program is compiled into a binary executable complete with link loader. The executable is not portable across operating systems (nor hardware architectures in most cases) > I think it this case it requires executing the program > command line with parameters then executing it? Yes and that can be done via the Popen class in the subprocess module. So your python program can launch an executable and read/write to stdout/in Alternatively you can launch a GUI program and access it via technologies such as COM in Windows. Other OS/Desktop environments have other hooks - eg Applescript can often be used on MacOS. > How dependent upon the C compiled code is this? That is, > I would think various distributions of Linux might produce > different executable code. No the compiled code runs (or can run) on any distribution of Linux. The distributions vary in where they store system files, which packages are included/installed as standard and the admin tools they provide. But the underlying OS is essentially the same for all of them. > The too I would want to do this in Win. Is there, in fact, some > Linux environment in Win that would allow me to test its executable? You can run Linux on a virtual machine inside Windows. VMWare is one route to this. Or you might be able to use cygwin to produce a windows application running using cygwin (a set of Linux like libraries for Windows). The formner alloows you to run the actual Linux executable file, the latter allows you to recompile the C code to run under Windows. Depends what suits you best. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Wed Mar 18 19:35:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 11:35:23 -0700 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: <208198.58884.qm@web86706.mail.ird.yahoo.com> References: <49BFBCED.20204@sbcglobal.net> <49C05B74.40102@sbcglobal.net> <396285.73167.qm@web86702.mail.ird.yahoo.com> <49C0E856.7050302@sbcglobal.net> <208198.58884.qm@web86706.mail.ird.yahoo.com> Message-ID: <49C13EEB.7010600@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 18 19:54:37 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 11:54:37 -0700 Subject: [Tutor] Playing with CENTER, Grid, Labels and Entry Message-ID: <49C1436D.1010900@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Mar 18 21:06:51 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 13:06:51 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: References: <49C113C8.80002@sbcglobal.net> Message-ID: <49C1545B.9040706@sbcglobal.net> An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Wed Mar 18 21:20:48 2009 From: greg at thewhittiers.com (greg whittier) Date: Wed, 18 Mar 2009 16:20:48 -0400 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C1545B.9040706@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> Message-ID: On Wed, Mar 18, 2009 at 4:06 PM, Wayne Watson wrote: > Thanks to both above posts before this reply. > I'll forgo the VM route. It would really complicate things for the users of > the application having to deal with VM. Most are near neophytes. > Nevertheless, it looks like there may be some hope here for just doing it > from w/i Win OS. > > My other choice is recoding 38K lines of C code into Python. I'll pass on > that. :-) Unless there's a very good translator between languages. > I'm confused about what you want to do. If you have the code and want to call it from python, then maybe you can use something like http://www.swig.org/ is what you're looking for. What is the Red Hat dependency? I.e., what libraries are needed? Many libraries are available for windows. From daychilde at gmail.com Wed Mar 18 22:26:52 2009 From: daychilde at gmail.com (Alexander Daychilde (Gmail)) Date: Wed, 18 Mar 2009 14:26:52 -0700 Subject: [Tutor] Iterating over letters or arbitrary symbols like they were numbers... In-Reply-To: References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> Message-ID: <038901c9a810$41c40bc0$c54c2340$@com> If there's an easy way to do this, I'd like to have a pointer to it (i.e. what functions would deal with this - not wanting my code written for me...) Right now, I have written code to generate a list of strings that happen to be a range of numbers. (The fact that they're strings is actually desirable to me). My code looks at the range given to the function and zero-pads based on the length of the start of the range. Ranges are indicated by number-colon-number, e.g. 1:9 or 01:99 or 1:99. (for reasons outside this snippet of code, I refer to these as "expressions" or "exp" for short...) Here's the code in question: ______________ exp_list = [] exp_range = exp.split(":") min_padding = len(exp_range[0]) for i in range(int(exp_range[0]),(int(exp_range[1])+1)): exp_list.append('%0*d' % (min_padding, i)) ______________ (in fact, I'm *actually* parsing something like n(1:9;13;15;17:25) - so I have multiple ranges and individual numbers to add to exp_list[], so in my actual code, the list exists elsewhere, and this code is executed if I find a colon in an element in the list created from splitting the original line on commas (and removing the n and parentheses) - hope that makes sense) I'm quite proud of that - for the level of programming I feel I'm at, I thought it was somewhat clever. ;-) But I'm open to feedback on that... BUT, here's what I need to do: That creates a list of numbers. I also need to do letters. That is, treat a-z as base 26, and do the same thing. The three examples I gave from before would be: 1:9 --> a:z 1:99 --> a:zz 01:99 -- no "zero" in alpha to worry about, so no padding necessary... So my first question is: Can I somehow treat letters like base 26? If I can, what about alphanumeric, i.e. 0-9+a-z would be like base 36... Am I stuck rolling my own arithmetic-type function? (i.e. z+a=aa and z+b=ab, etc) Thank you very much for any advice (and again, in addition to my actual question, I wouldn't mind hearing if my solution for the numbers is less clever than I thought-- i.e. not looking for praise; rather, looking for improvement if it's glaringly dumb) From sierra_mtnview at sbcglobal.net Wed Mar 18 23:40:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 15:40:36 -0700 Subject: [Tutor] Iterating over letters or arbitrary symbols like they were numbers... In-Reply-To: <038901c9a810$41c40bc0$c54c2340$@com> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <038901c9a810$41c40bc0$c54c2340$@com> Message-ID: <49C17864.1070204@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 19 00:52:30 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 18 Mar 2009 23:52:30 +0000 (GMT) Subject: [Tutor] Fw: list.replace -- string.swap References: <106858.25675.qm@web86708.mail.ird.yahoo.com> <49C13574.9000607@gmail.com> Message-ID: <868738.66271.qm@web86705.mail.ird.yahoo.com> It wasn't my question :-) Forwarding to list... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Original Message ---- > From: Ricardo Ar?oz > Subject: Re: [Tutor] Fw: list.replace -- string.swap > > > >>>> Also: How would perform string.swap(s1, s2) in the following cases: > >>>> > >> Here I mean exchanging s1 and s2 occurrences all along a string. As an > example, > >> in a text containing numerous formatted numbers, switch from english to > european > >> format: > >> 1,234,567.89 > >> 1.234.567,89 > >> meaning exchange '.' and ','. > >> > >> > >>>> * There is no secure 'temp' char, meaning that > >>>> s.replace(s1,temp).replace(s2,s1).replace(temp,s2) > >>>> will fail because any char can be part of s. > >>>> > >> The use of a temp char for marking places of one the chars to be swapped is a > > >> common trick. But if the text can contain any char (even chr(0)), then there > no > >> char you can safely use as temp. > >> The only workaround I know is to pass through lists. Then swap on the list, > >> using eg None as temp item, and glue back the result to a string. But you > need > >> them a replace method on lists, hence my previous question ;-) > >> > >> > >>>> * Either s1 or s2 can be more than a single char. > >>>> > >> More difficult, cause you cannot simple list() the string. It must split on > s1 > >> and s2, but keeping the delimiters! There is no option afaik for that in > >> string.split -- too bad! So that you must split it manually at start and end > of > >> each instance of s1 and s2. Or there are other algorithms I cannot figure > out. > >> What I was asking for. > >> > > So NOW I get your question!!! > It's easy : > > >>> import string > >>> mystr = '1,234,567.89' > >>> mystr.translate(string.maketrans('.,', ',.')) > '1.234.567,89' > > Any length of string to be translated, any length of translation tables > (not only two values, any amount of them). > > HTH > > Ricardo. From alan.gauld at btinternet.com Thu Mar 19 01:04:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Mar 2009 00:04:39 -0000 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? References: <49BFBCED.20204@sbcglobal.net> <49C05B74.40102@sbcglobal.net><396285.73167.qm@web86702.mail.ird.yahoo.com><49C0E856.7050302@sbcglobal.net><208198.58884.qm@web86706.mail.ird.yahoo.com> <49C13EEB.7010600@sbcglobal.net> Message-ID: "Wayne Watson" wrote > As I wander around the internet trying to get info from Lundh, > New Mexico, and other sites, I wonder if, in particular > New Mexico is not using the "new" Tkinter. How would I know? Nobody is using the new version yet, it's targetted for 3.1 and 2.7 - both are the "next" releases of Python oin their respective streams. But most of the existing documentation doesn't even cover the newer widgets added since 2.x - and none that I know of covers Tix at all. > Still waiting for the wizard. There are lots of news readers around. Which OS are you on? There is also the web page which only requiires a browser, but the gmane archive is much easier accessed by a newsreader IMHO. ================ February 03, 2009 Ttk support in Python. Guilherme Polo passed along the great news that his pyttk module has been accepted into Python's standard library. ? That means we should see pyttk generally available with Python 2.7 and 3.1 (both still in development). ? You can see the current docs here. ? And of course, this is something I was waiting for before updating TkDocs with Python info and examples. Thanks for all your hard work Guilherme! ==================== and using your preferred news reader subscribe to: gmane.comp.python.tkinter Or on the web at: http://dir.gmane.org/gmane.comp.python.tkinter From sierra_mtnview at sbcglobal.net Thu Mar 19 01:10:49 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 17:10:49 -0700 Subject: [Tutor] Playing with CENTER, Grid, Labels and Entry In-Reply-To: <49C1436D.1010900@sbcglobal.net> References: <49C1436D.1010900@sbcglobal.net> Message-ID: <49C18D89.9050901@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 01:14:57 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 17:14:57 -0700 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: References: <49BFBCED.20204@sbcglobal.net> <49C05B74.40102@sbcglobal.net><396285.73167.qm@web86702.mail.ird.yahoo.com><49C0E856.7050302@sbcglobal.net><208198.58884.qm@web86706.mail.ird.yahoo.com> <49C13EEB.7010600@sbcglobal.net> Message-ID: <49C18E81.7080508@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 19 01:18:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Mar 2009 00:18:28 -0000 Subject: [Tutor] Playing with CENTER, Grid, Labels and Entry References: <49C1436D.1010900@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I'm using Grid. It's gone pretty well, but I'd like to make it > "prettier". For that Frame is usually your friend. Create your widgets inside frames and then pack or grid the Frames. You can then use a combination of padding, filling and anchoring etc in both way you insert the widgets into the Frame and the way you insert the Frame into the window. Personally I find drawing it out with pencil and paper helps a lot when layouts start to get complicated. > For example, a row with latitude and longitude gets spread > across the dialog, whereas, they should be closer together. If you put them both in a Frame and then put the frame into one of yourgrid cells they will both be together on one side. > However, at the moment, I'm trying to build a title across > row 8. I want some centering of the text, but the methods Use a Frame to hold the label then use pack to put the label centred in the Frame. Then grid the frame into your window spanning cells as needed. Frames are your friend for layout. To be honest I usually use the packer for the layout of my top window then use grid inside a Frame. I can then create smaller frames to insert into the grid. Don't forget that when creating subframes the subframe should be used as the parent of the widgets: fCoords = Frame(self.master) # the subframe as child of the main window eLat = Entry(fCoords,.....) # use subframe as parent eLat.grid(row=0, col=0) # grid it within the subframe so reset counts to 0 eLong = Entry(fCoords,.....) # and here eLong.grid(row = 0, col=1) fCoords.grid(row = current, col = whatever) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Thu Mar 19 01:32:01 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 17:32:01 -0700 Subject: [Tutor] Fun with Label and Entry--Why NoneType? In-Reply-To: <780360.82279.qm@web86711.mail.ird.yahoo.com> References: <49BFF8D0.7020504@sbcglobal.net><49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <49C10543.3030609@sbcglobal.net> <780360.82279.qm@web86711.mail.ird.yahoo.com> Message-ID: <49C19281.9050709@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Thu Mar 19 02:11:25 2009 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Mar 2009 14:11:25 +1300 Subject: [Tutor] Iterating over letters or arbitrary symbols like they were numbers... In-Reply-To: <038901c9a810$41c40bc0$c54c2340$@com> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <038901c9a810$41c40bc0$c54c2340$@com> Message-ID: <5e58f2e40903181811o564e140fp1e92fe7906834021@mail.gmail.com> 2009/3/19 Alexander Daychilde (Gmail) : > That creates a list of numbers. I also need to do letters. That is, treat > a-z as base 26, and do the same thing. The three examples I gave from before > would be: > ? ? ? ?1:9 --> a:z > ? ? ? ?1:99 --> a:zz > ? ? ? ?01:99 -- no "zero" in alpha to worry about, so no padding > necessary... > > So my first question is: Can I somehow treat letters like base 26? > > If I can, what about alphanumeric, i.e. 0-9+a-z would be like base 36... The int() function takes a second parameter, which is the base. This is so that it can deal with hex strings -- for example, int('7a', 16) == 122. But the base can actually be anything up to 36. For converting a base n string to an integer, the digits are the first n elements of '0123456789abcdefghijklmnopqrstuvwxyz'. To go the other way, I had a quick poke around in the python cookbook and found this one-liner: def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"): return ((num == 0) and "0" ) or ( baseN(num // b, b).lstrip("0") + numerals[num % b]) You may be able to find better ones. If you want to convert 'a'..'z' to integers by treating them as base-26 numbers.. it could be tricky because you (I think) have no 0. Multiplication without a 0 is really quite tricky :-) You might be better off writing a function to take one "integer" (e.g. 'ghzz') and produce the next one ('giaa'). Or you could cheat :-) >>> import string >>> letters = string.lowercase >>> pairs = [''.join([a,b]) for a in letters for b in letters] >>> threes = [''.join([a,b,c]) for a in letters for b in letters for c in letters] >>> fours = [''.join([a,b,c,d]) for a in letters for b in letters for c in letters for d in letters] >>> words = list(letters) + pairs + threes + fours >>> def wcmp(x,y): ... if len(x) < len(y): ... return -1 ... elif len(x) > len(y): ... return 1 ... else: ... return cmp(x,y) ... >>> words.sort(cmp=wcmp) >>> words[words.index('a'):words.index('bb')+1] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak', 'al', 'am', 'an', 'ao', 'ap', 'aq', 'ar', 'as', 'at', 'au', 'av', 'aw', 'ax', 'ay', 'az', 'ba', 'bb'] Note that this is not very practical if your words can get out to five characters.. -- John. From sierra_mtnview at sbcglobal.net Thu Mar 19 02:29:09 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 18:29:09 -0700 Subject: [Tutor] Playing with CENTER, Grid, Labels and Entry In-Reply-To: References: <49C1436D.1010900@sbcglobal.net> Message-ID: <49C19FE5.8060100@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Mar 19 02:40:38 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Mar 2009 21:40:38 -0400 Subject: [Tutor] Iterating over letters or arbitrary symbols like they were numbers... In-Reply-To: <038901c9a810$41c40bc0$c54c2340$@com> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <038901c9a810$41c40bc0$c54c2340$@com> Message-ID: <1c2a2c590903181840g1a0fceeaq8f1eae433e0280ef@mail.gmail.com> On Wed, Mar 18, 2009 at 5:26 PM, Alexander Daychilde (Gmail) wrote: > exp_list = [] > > exp_range = exp.split(":") > > min_padding = len(exp_range[0]) > > for i in range(int(exp_range[0]),(int(exp_range[1])+1)): > > ? ?exp_list.append('%0*d' % (min_padding, i)) This could be a little cleaner using tuple assignment to get rid of the subscripting and list comprehension to get rid of the loop: lower, upper = exp.split(':') min_padding = len(lower) exp_list = [ '%0*d' % (min_padding, i) for in in range(int(lower), int(upper)+1) ] Kent From ricaraoz at gmail.com Thu Mar 19 02:46:27 2009 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 18 Mar 2009 22:46:27 -0300 Subject: [Tutor] Fw: list.replace -- string.swap In-Reply-To: <868738.66271.qm@web86705.mail.ird.yahoo.com> References: <106858.25675.qm@web86708.mail.ird.yahoo.com> <49C13574.9000607@gmail.com> <868738.66271.qm@web86705.mail.ird.yahoo.com> Message-ID: <49C1A3F3.4070403@gmail.com> ALAN GAULD wrote: > It wasn't my question :-) > > Forwarding to list... > > > Alan Gauld > Author of the Learn To Program website > http://www.alan-g.me.uk/ > > > > > ----- Original Message ---- > >> From: Ricardo Ar?oz >> Subject: Re: [Tutor] Fw: list.replace -- string.swap >> >> >> >>>>>> Also: How would perform string.swap(s1, s2) in the following cases: >>>>>> >>>>>> >>>> Here I mean exchanging s1 and s2 occurrences all along a string. As an >>>> >> example, >> >>>> in a text containing numerous formatted numbers, switch from english to >>>> >> european >> >>>> format: >>>> 1,234,567.89 >>>> 1.234.567,89 >>>> meaning exchange '.' and ','. >>>> >>>> >>>> >>>>>> * There is no secure 'temp' char, meaning that >>>>>> s.replace(s1,temp).replace(s2,s1).replace(temp,s2) >>>>>> will fail because any char can be part of s. >>>>>> >>>>>> >>>> The use of a temp char for marking places of one the chars to be swapped is a >>>> >>>> common trick. But if the text can contain any char (even chr(0)), then there >>>> >> no >> >>>> char you can safely use as temp. >>>> The only workaround I know is to pass through lists. Then swap on the list, >>>> using eg None as temp item, and glue back the result to a string. But you >>>> >> need >> >>>> them a replace method on lists, hence my previous question ;-) >>>> >>>> >>>> >>>>>> * Either s1 or s2 can be more than a single char. >>>>>> >>>>>> >>>> More difficult, cause you cannot simple list() the string. It must split on >>>> >> s1 >> >>>> and s2, but keeping the delimiters! There is no option afaik for that in >>>> string.split -- too bad! So that you must split it manually at start and end >>>> >> of >> >>>> each instance of s1 and s2. Or there are other algorithms I cannot figure >>>> >> out. >> >>>> What I was asking for. >>>> >>>> >> So NOW I get your question!!! >> It's easy : >> >> >>>>> import string >>>>> mystr = '1,234,567.89' >>>>> mystr.translate(string.maketrans('.,', ',.')) >>>>> >> '1.234.567,89' >> >> Any length of string to be translated, any length of translation tables >> (not only two values, any amount of them). >> >> HTH >> >> Ricardo. >> Sorry Alan, was meant to the list. Just pressed reply and forgot here it does not go to the list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 02:50:42 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 18:50:42 -0700 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: <49C18E81.7080508@sbcglobal.net> References: <49BFBCED.20204@sbcglobal.net> <49C05B74.40102@sbcglobal.net><396285.73167.qm@web86702.mail.ird.yahoo.com><49C0E856.7050302@sbcglobal.net><208198.58884.qm@web86706.mail.ird.yahoo.com> <49C13EEB.7010600@sbcglobal.net> <49C18E81.7080508@sbcglobal.net> Message-ID: <49C1A4F2.2000609@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 02:56:26 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Mar 2009 18:56:26 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> Message-ID: <49C1A64A.1070600@sbcglobal.net> An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Thu Mar 19 05:27:19 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Wed, 18 Mar 2009 23:27:19 -0500 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C1A64A.1070600@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> Message-ID: <49C1C9A7.6080605@mwalsh.org> Wayne Watson wrote: > If you can execute a C program compiled on a Linux with SWIG, then > that's what I'm looking for. There's really no RH dependency according > to the above posts. If it were compiled on Debian or Ubuntu, it appears > it would not make any difference. That is, one could execute a RH > executable from C on Ubuntu. Yeah, probably -- if it's a static build, or if the dependencies (required libraries/versions) are installed, assuming the program has dependencies. But, I suppose we may be drifting a bit OT. > > Is there a simple example of this in action from a Python program and > some small C Linux executable program? http://docs.python.org/library/subprocess.html The subprocess module is commonly recommended for this type of task (as opposed to os.system, etc). In fact, I believe Alan already suggested it in this thread. And speaking of ... Alan's tutorial has several very good examples of using the subprocess module (OS topic under Manipulating Processes). http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm --- I'll hazard a wild guess that you don't really want SWIG based on your original question, and subsequent comments. IIUC, SWIG is intended to ease the creation of a python wrapper (extension module) for existing C/C++ code. And, I'm not sure you've given enough information about the C program to determine if SWIG would be useful. Regardless, I suggest you get a feel for running an external program using python first. HTH, Marty From alan.gauld at btinternet.com Thu Mar 19 10:12:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Mar 2009 09:12:04 -0000 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> Message-ID: "Wayne Watson" wrote > If you can execute a C program compiled on a Linux with SWIG, > then that's what I'm looking for. Nope, you need the suprocess module not SWIG. What SWIG does (fairly easily!) is allow you to build a wrapper around your C program that python can import and call the C functions like normal Python code. I don;t think you want that, you just want to run the program. What you haven't made clear yet is whether you need to get your program to interact with the C program or whether you just want to run the executable with no interaction. (This is much easier obviously!) See my OS topic for various solutions to this. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Thu Mar 19 11:24:30 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Mar 2009 03:24:30 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> Message-ID: <49C21D5E.1020400@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 19 11:55:16 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 19 Mar 2009 10:55:16 +0000 (GMT) Subject: [Tutor] Executing a C Program from RH Linux in Python for Win References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C21D5E.1020400@sbcglobal.net> Message-ID: <601213.94540.qm@web86707.mail.ird.yahoo.com> > likely will allow the user to enter the 12 or so parameters > on the command line, and execute the program as though > I had entered it at a Linux prompt. OK, In that case you only need the call() convenience function from the subprocess module. Capture the arguments in your GUI and build the command options into a list. Pass that to subprocess.call() See: http://docs.python.org/library/subprocess.html#convenience-functions HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 12:33:18 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Mar 2009 04:33:18 -0700 Subject: [Tutor] Fun with Label and Entry--Why N....(Command Prompt) In-Reply-To: <234832.12143.qm@web86710.mail.ird.yahoo.com> References: <49BFF8D0.7020504@sbcglobal.net><49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <49C10543.3030609@sbcglobal.net> <780360.82279.qm@web86711.mail.ird.yahoo.com> <49C19281.9050709@sbcglobal.net> <234832.12143.qm@web86710.mail.ird.yahoo.com> Message-ID: <49C22D7E.6030505@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 14:50:59 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Mar 2009 06:50:59 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C1C9A7.6080605@mwalsh.org> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> Message-ID: <49C24DC3.5070902@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 21:00:00 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Mar 2009 13:00:00 -0700 Subject: [Tutor] Fun with Label and Entry--Why N....(Command Prompt) In-Reply-To: <212582.14192.qm@web86703.mail.ird.yahoo.com> References: <49BFF8D0.7020504@sbcglobal.net><49BFFFB0.1080308@mwalsh.org> <49C00AF2.8030503@sbcglobal.net> <49C04167.9080609@sbcglobal.net> <49C10543.3030609@sbcglobal.net> <780360.82279.qm@web86711.mail.ird.yahoo.com> <49C19281.9050709@sbcglobal.net> <234832.12143.qm@web86710.mail.ird.yahoo.com> <49C22D7E.6030505@sbcglobal.net> <212582.14192.qm@web86703.mail.ird.yahoo.com> Message-ID: <49C2A440.8090607@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Mar 19 22:39:30 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Mar 2009 14:39:30 -0700 Subject: [Tutor] Tkinter Geometry Management and Other Basics Message-ID: <49C2BB92.4090003@sbcglobal.net> An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Thu Mar 19 22:58:46 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 19 Mar 2009 15:58:46 -0600 Subject: [Tutor] Trouble parsing email from Outlook Message-ID: <9356b9f30903191458x37760bfeq8954e7a0cc53331e@mail.gmail.com> Hello, list! I hope it's not too much out of place to ask this question in the Tutor list. I'm trying to process some information from email messages that goes in a folder called: "SysAdmin". I could reproduce the recipe from Python Programming on Win32 sucessfully to read the subject line of the inbox, but not from a different folder: So far my code is this: import win32com.client ses = win32com.client.Dispatch("Mapi.Session") o = win32com.client.Dispatch("Outlook.Application") ses.Logon("Default") print ses.Inbox.Messages.Item(1).Subject How can I check stuff from the folder "SysAdmin", then? I get lost with the references from CDO, MAPI with Visual Basic code (I don't understad VB) I get from Microsoft and other sites. Thanks for any pointer. Eduardo From cfuller at linuxmail.org Thu Mar 19 20:20:54 2009 From: cfuller at linuxmail.org (Chris Fuller) Date: Thu, 19 Mar 2009 14:20:54 -0500 Subject: [Tutor] Tkinter Geometry Management and Other Basics In-Reply-To: <49C2BB92.4090003@sbcglobal.net> References: <49C2BB92.4090003@sbcglobal.net> Message-ID: <200903191420.54573.cfuller@linuxmail.org> With respect to grid and pack, all siblings must use the same manager. Do otherwise and your application will hang. Children/parents may use different managers. I don't believe there are any restrictions on place, as it doesn't do any negotiation. Cheers From alan.gauld at btinternet.com Fri Mar 20 00:57:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Mar 2009 23:57:04 -0000 Subject: [Tutor] Tkinter Geometry Management and Other Basics References: <49C2BB92.4090003@sbcglobal.net> Message-ID: "Wayne Watson" wrote > As I understand it, there are three geometry managers: > Grids, Pack and Place. Only the first two are of interest. Yes and a new Form one coming in the next Tk release... > Is it possible to mix them? I don't think so, Yes but not in a single Frame. But my normal approach is to defie my top window using multiple frames. Each frame is packed into the top window. But within each subframe I may use either the packer or the grid depemnding on the widgets inside. So long as yyou stick to a single style inside a Frame you can mix n match to suit the layout. > However, if one is used for frameA and another for frameB, > can they both be used with in a parent frame, which has its > own geometry (grid or pack)? Absolutely. > Suppose I want a parent frame to have a title and below it > a 2 column grid with say a Label and Entry. I put the latter > in a frame combo in a frame, and attach it to the parent. I'd have two frames packed into the window (packer stacks vertically by default). In the top Frame I'd pack the title - centred is default with pack. In the second frame I'd use grid with a single row, one cell with label the other with the entry. > First, the resulting dialog looks like this: > > ------------------------------------------------------- > Geographic Location > Latitude:BOXLongitude:BOX > Zenith x:Zenithy:BOXZenith Pixel Position > > OK Cancel <- Std buttons > --------------------------------------------------------- > BOX = a rectangle for data entry. There's very little separation > between labels and entries. Title labels are in bold. > > Stuff is kind of jammed together, padx and pady should fix that. Take a look at the Exploring Layout section in my GUI programming topic for more ideas on that. It uses the packer exclusively but should give you some clues. > My guess is that I need to use the weight concept available > with Grid, columnconfigure and rowconfigure to justify and > open up the data entry rows. You are best just experimenting. The way I do that is to write the simplest possible GUI with just a single frame and a button or label in it. Something like: ############## # testTk.py from Tkinter import * top = Tk() w = Button(top, text="Button") w.pack() top.mainloop() ############## Just play with the pack or grid options and observe the effect If you have the file open in an editor and name the file as .pyw you can then easily run the file from explorer and have multiple versions displayed at the same time to compare results. > Perhaps there's a geometry tutor somewhere on the web. Try the Tcl/Tk web sites they tend to be good for that kind of stuff. Its easy to translate the Tk command to Tkinter. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Fri Mar 20 03:53:37 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Mar 2009 19:53:37 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C24DC3.5070902@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> Message-ID: <49C30531.60701@sbcglobal.net> An HTML attachment was scrubbed... URL: From andrefsp at gmail.com Fri Mar 20 06:17:09 2009 From: andrefsp at gmail.com (=?ISO-8859-1?Q?andr=E9_palma?=) Date: Fri, 20 Mar 2009 05:17:09 +0000 Subject: [Tutor] HI, #Include like in python Message-ID: <49C326D5.4090908@gmail.com> Hi \o I'm asking if there is any #include( C) like or any include('File.php') (php) like in python. I have 2 files: "usbconnection.py" and "listen.py", And i want to use some classes avaiable in "listen.py" on my main file "usbconnection.py". I've tryed to do __import__("listen.py") but obviously it gave me an error... "ImportError: No module named /home/andrefsp/projects/sigre/listen.py" So, if anybody knows how to do an include in python please reply me =) Bye the way, i've sent an email in last week asking how to read data from USB port. So, i've finally did it, yesterday i was able to read data from my USB port, if anybody is interested in some information about it just need to ask, i don't mind to help =) "it is impossible to make eggs without omelettes " From john at fouhy.net Fri Mar 20 06:32:34 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 20 Mar 2009 18:32:34 +1300 Subject: [Tutor] HI, #Include like in python In-Reply-To: <49C326D5.4090908@gmail.com> References: <49C326D5.4090908@gmail.com> Message-ID: <5e58f2e40903192232p171c1ae1iedde659d8adf244@mail.gmail.com> 2009/3/20 andr? palma : > Hi \o > I'm asking if there is any #include( C) like or any include('File.php') > (php) like in python. > I have 2 files: "usbconnection.py" and "listen.py", And i want to use some > classes avaiable in "listen.py" on my main file "usbconnection.py". I've > tryed to do __import__("listen.py") but obviously it gave me an error... > "ImportError: No module named /home/andrefsp/projects/sigre/listen.py" > > So, if anybody knows how to do an include in python please reply me =) Drop the .py. Just type: import listen You can use the __import__ function if you want, but generally you want the import statement as above. The equivalent to 'import listen' is: listen = __import__('listen') See the tutorial here: http://docs.python.org/tutorial/modules.html -- John. From wescpy at gmail.com Fri Mar 20 06:54:56 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 19 Mar 2009 22:54:56 -0700 Subject: [Tutor] HI, #Include like in python In-Reply-To: <5e58f2e40903192232p171c1ae1iedde659d8adf244@mail.gmail.com> References: <49C326D5.4090908@gmail.com> <5e58f2e40903192232p171c1ae1iedde659d8adf244@mail.gmail.com> Message-ID: <78b3a9580903192254x4c2208d3v73e4cf128719ae06@mail.gmail.com> > ? ?import listen > > You can use the __import__ function if you want, but generally you > want the import statement as above. ?The equivalent to 'import listen' > is: > > ? ?listen = __import__('listen') > > See the tutorial here: http://docs.python.org/tutorial/modules.html you also have to make sure that your .py file is in one of the folders/directories listed in sys.path (to see it, import sys then do print sys.path). if the file is not in one of those folders, you will also get an import error. you can either add the correct directory to your PYTHONPATH environment variable, or manually add it at run-time using sys.path.append/insert. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From a.t.hofkamp at tue.nl Fri Mar 20 08:37:25 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 20 Mar 2009 08:37:25 +0100 Subject: [Tutor] HI, #Include like in python In-Reply-To: <78b3a9580903192254x4c2208d3v73e4cf128719ae06@mail.gmail.com> References: <49C326D5.4090908@gmail.com> <5e58f2e40903192232p171c1ae1iedde659d8adf244@mail.gmail.com> <78b3a9580903192254x4c2208d3v73e4cf128719ae06@mail.gmail.com> Message-ID: <49C347B5.40805@tue.nl> wesley chun wrote: >> import listen >> >> You can use the __import__ function if you want, but generally you >> want the import statement as above. The equivalent to 'import listen' >> is: >> >> listen = __import__('listen') >> >> See the tutorial here: http://docs.python.org/tutorial/modules.html > > > you also have to make sure that your .py file is in one of the > folders/directories listed in sys.path (to see it, import sys then do > print sys.path). if the file is not in one of those folders, you will > also get an import error. > > you can either add the correct directory to your PYTHONPATH > environment variable, or manually add it at run-time using > sys.path.append/insert. A simpler form is to put "listen.py" and "usbconnection.py" in the same directory. In the latter you can do something like import listen listener = listen.ListenClass(param1, param2) listener.begin() # Call the 'begin' method of the ListenClass object. You can use the ListenClass like normal, just state that Python should look for it in the "listen" file. Albert From alan.gauld at btinternet.com Fri Mar 20 09:26:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Mar 2009 08:26:39 -0000 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org><49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> Message-ID: "Wayne Watson" wrote > What is meant by "The arguments are the same as for the Popen > constructor.", > in Convenience Functions? In fact, what is such a function? It means that there is a function which takes the same arguments as the __init__() method of the Popen class. They are convenience functions in that you don't need to create the class to use them you can just call them directly. THe payoff is that you lose some of the flexibility of using the class, but often you don;t need that. > class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, > stdout=None, stderr=None, preexec_fn=None, close_fds=False .... > Why not just class Popen instead of subprocess.Popen? The notation is saying that there is a class defined in the subprocess module called Popen with a constructor that has the listed parameters. It is just a shorthand way of expressing that. In practice you would create an instance with either: import subprocess p = subprocess.Popen(....) OR from subprocess import Popen p = Popen(....) > Is there a suggestion here that I need only do: from subprocess import Popen > myProg=Popen() > myProg.call("wolf", "-h") Even simpler, you only need: from subprocess import call myProg = call(["wolf", "-h"]) You need to put the command as the first entry of a list and each argument as a separate entry HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Fri Mar 20 09:57:49 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Mar 2009 08:57:49 +0000 Subject: [Tutor] Trouble parsing email from Outlook In-Reply-To: <9356b9f30903191458x37760bfeq8954e7a0cc53331e@mail.gmail.com> References: <9356b9f30903191458x37760bfeq8954e7a0cc53331e@mail.gmail.com> Message-ID: <49C35A8D.9080703@timgolden.me.uk> Eduardo Vieira wrote: > Hello, list! I hope it's not too much out of place to ask this > question in the Tutor list. > I'm trying to process some information from email messages that goes > in a folder called: "SysAdmin". I could reproduce the recipe from > Python Programming on Win32 sucessfully to read the subject line of > the inbox, but not from a different folder: It can be a bit confusing working out even what to search for, and there are a few things which are similar but subtly different. Ignoring more esoteric possibilities, there are three main ways to do automatic things with Outlook / Exchange emails, all of which are feasible from Python + pywin32/ctypes/comtypes. 1) COM -> CDO ("MAPI.Session") -- that's what you're doing. Altho' technically this is using Exchange rather than Outlook, you basically need Outlook installed for this to work. 2) COM -> Outlook ("Outlook.Application") -- this is very similar to CDO but gives you a few things which are tied to Outlook rather than to the Exchange server. 3) COM -> MAPI -- this is a slightly lower-level Win32 API set which is exposed in pywin32 through the slightly confusing set of modules under win32comext/mapi Of course it's all very confusing because the CDO CLSID above uses the word "MAPI" (as it presumably calls MAPI functions under the covers) while there's another thing called CDONT which is/was a cut-down version of CDO and which you still come across from time to time. > So far my code is this: > import win32com.client > ses = win32com.client.Dispatch("Mapi.Session") > o = win32com.client.Dispatch("Outlook.Application") OK, now you've confused yourself. You don't need to use *both* Outlook automation *and* CDO automation. Just pick one. Let's go with CDO since that's effectively what you've done. > ses.Logon("Default") > print ses.Inbox.Messages.Item(1).Subject Right, because the Inbox is a well-known special case, you get an easy reference to it from the CDO session itself. To find other folders, you either have to walk the tree of folders if you know where to look, or to iterate over them if you just know it's there somewhere but can't guarantee where. The topmost things in a CDO Session is one or more InfoStores. You can't iterate over them directly; you have to loop over their count. Note that they are counted from 1 upwards, while the Python loop is 0-based: for i in range (len (ses.InfoStores)): info_store = ses.InfoStores[i+1] print info_store.Name If you already know the name of the one you want, eg "Mailbox - Tim Golden", you can select that one: mailbox = ses.InfoStores["Mailbox - Tim Golden"] The infostore has a RootFolder which is a CDO Folder object and once you've got that, you can just walk the tree of folders. The key collections you'll be interested in are the Folders and Messages. They can both be iterated the same way, and the function below provides a Pythonish wrapper: def cdo_iter (cdo_collection): item = cdo_collection.GetFirst () while item: yield item item = cdo_collection.GetNext () Each Folder may have a Folders attribute and a Messages attribute. To walk a tree or subtree, you can do this, making use of the function above: def cdo_walk (folder): ## can be the RootFolder or a specific folder try: folders = cdo_iter (folder.Folders) except AttributeError: folders = [] try: items = cdo_iter (folder.Messages) except AttributeError: items = [] yield folder, folders, items for subfolder in folders: for r in cdo_walk (subfolder): yield r Note that, because we're using generators, the sublists of folders and items are generated lazily. If, as in the case we're getting to, you don't need to look at messages until you've got to the folder you want, then you just don't iterate over the items iterable. Putting it together, you can find a folder called "SysAdmin" from a CDO session like this: import os, sys import win32com.client def cdo_iter (cdo_collection): item = cdo_collection.GetFirst () while item: yield item item = cdo_collection.GetNext () def cdo_walk (folder): try: folders = cdo_iter (folder.Folders) except AttributeError: folders = [] try: items = cdo_iter (folder.Messages) except AttributeError: items = [] yield folder, folders, items for subfolder in folders: for r in cdo_walk (subfolder): yield r class x_found (Exception): pass if __name__ == '__main__': session = win32com.client.gencache.EnsureDispatch ("MAPI.Session") session.Logon () try: for i in range (session.InfoStores.Count): info_store = session.InfoStores[i+1] # # Ignore Public Folders which is very big # if info_store.Name == "Public Folders": continue print "Searching", info_store.Name for folder, folders, items in cdo_walk (info_store.RootFolder): if folder.Name == "SysAdmin": for item in items: print item.Subject raise x_found except x_found: pass TJG From bala.biophysics at gmail.com Fri Mar 20 11:45:26 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Fri, 20 Mar 2009 11:45:26 +0100 Subject: [Tutor] statistics with python Message-ID: <288df32a0903200345p4346c604t4cb21697a64c112a@mail.gmail.com> Dear python friends, someone kindly suggest me packages, modules and documentation resources (especially) to i) plot graphs using python. ii) statistical analysis using python. Thanks in advance, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 12:35:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 04:35:36 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org><49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> Message-ID: <49C37F88.9070704@sbcglobal.net> An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Fri Mar 20 13:30:09 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 20 Mar 2009 08:30:09 -0400 Subject: [Tutor] statistics with python In-Reply-To: <288df32a0903200345p4346c604t4cb21697a64c112a@mail.gmail.com> References: <288df32a0903200345p4346c604t4cb21697a64c112a@mail.gmail.com> Message-ID: On Fri, Mar 20, 2009 at 6:45 AM, Bala subramanian wrote: > Dear python friends, > > someone kindly suggest me packages, modules and documentation resources > (especially) to > > i) plot graphs using python. > matplotlib is excellent and probably the most popular > > ii) statistical analysis using python. > > Your best bet is probably using the python binding for R ( http://rpy.sourceforge.net/). This also lets you use R's powerful graphing capability. Scipy.org also has some statistics packages, but nothing as complete as you can get with R. > > Thanks in advance, > Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Mar 20 13:47:05 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 20 Mar 2009 13:47:05 +0100 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C37F88.9070704@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org><49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> Message-ID: <49C39049.4010702@tue.nl> Wayne Watson wrote: > Good. Thanks. > > Here's my code. > ========== > # Executing a Linux program under Win XP > from subprocess import call > myProg = call(["C:\Sandia_Meteors\Various\FuzzyLogic\wolf", "-h"]) You must always escape \ characters in a string. do r"C:\Sandia_Meteors\Various\FuzzyLogic\wolf", "C:\\Sandia_Meteors\\Various\\FuzzyLogic\\wolf", or "C:/Sandia_Meteors/Various/FuzzyLogic/wolf" Albert From sierra_mtnview at sbcglobal.net Fri Mar 20 14:46:41 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 06:46:41 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C39049.4010702@tue.nl> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org><49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> Message-ID: <49C39E41.7060105@sbcglobal.net> An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Mar 20 15:32:44 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 20 Mar 2009 15:32:44 +0100 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C39E41.7060105@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org><49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> Message-ID: <49C3A90C.3040903@tue.nl> Wayne Watson wrote: > Yes, good, but I tried > myProg = call([r"C:\Sandia_Meteors\Various\FuzzyLogic\wolf", "-h"]), > and get exactly the same results. So the next step is to find out what is wrong. In other words, experiment with the problem to get an understanding what is not working. Once you get that, you can start looking for a way to solve it. Some suggestions for possible experiments: Are you sure the program is not already finished? (ie it runs the program, and after finishing it gives an error for some reason?) What does Windows think of it when you run it without Python (ie directly from the OS, eg using a 'cmd' window (or whatever it is called nowadays, my last Win* experience was with W95))? (The error looks like an OS error, not a Python error. By trying it without Python, you can decide whether you need to convince your OS to run the program or you whether need to convince Python.) Possibly a stupid suggestion, don't you need to add '.exe' at the end? (I am pretty much clueless with Windows, so maybe this is nonense.) Alternatively, try executing a different program that you know to be working at Windows. (The python.exe would be one such program, but it may be confusing to run several python programs at the same time.) Last but not least, what error do you get when you try running something that does not exist? (Do you get the same error, or do you get a different one? If the latter, you know Python gives the path correctly to Windows.) What happens if you give it a non-executable file? (just giving wild suggestions for experiments you can do to get more understanding of why it is refusing to run the file.) Albert From emadnawfal at gmail.com Fri Mar 20 16:11:28 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 20 Mar 2009 11:11:28 -0400 Subject: [Tutor] adding dictionary values Message-ID: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> Hi Tutors, I have two pickled dictionaries containing word counts from two different corpora. I need to add the values, so that a word count is the sum of both. If the word "man" has a count of 2 in corpus A and a count of 3 in corpus B, then I need a new dictionary that has "man": 5. Please let me know whether the following is correct/incorrect, good/bad, etc. Your help appreciated: def addDicts(a, b): c = {} for k in a: if k not in b: c[k] = a[k] else: c[k] = a[k] + b[k] for k in b: if k not in a: c[k] = b[k] return c # test this dict1 = {"dad": 3, "man": 2} dict2 = {"dad": 5, "woman": 10} newDict = addDicts(dict1, dict2) print(newDict) # This gives {'dad': 8, 'woman': 10, 'man': 2} -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Fri Mar 20 16:39:56 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 20 Mar 2009 11:39:56 -0400 Subject: [Tutor] adding dictionary values In-Reply-To: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> Message-ID: 2009/3/20 Emad Nawfal (???? ????) > Hi Tutors, > I have two pickled dictionaries containing word counts from two different > corpora. I need to add the values, so that a word count is the sum of both. > If the word "man" has a count of 2 in corpus A and a count of 3 in corpus B, > then I need a new dictionary that has "man": 5. Please let me know whether > the following is correct/incorrect, good/bad, etc. > Your help appreciated: > > def addDicts(a, b): > c = {} > for k in a: > if k not in b: > c[k] = a[k] > else: > c[k] = a[k] + b[k] > > for k in b: > if k not in a: > c[k] = b[k] > return c > > # test this > dict1 = {"dad": 3, "man": 2} > dict2 = {"dad": 5, "woman": 10} > newDict = addDicts(dict1, dict2) > print(newDict) > # This gives > > {'dad': 8, 'woman': 10, 'man': 2} > > This looks like it will work, but you can accomplish this more compactly by just looping over the items in both dictionaries and making use of the default argument of the dictionaries get method. newDict = {} for k, v in dict1.items() + dict2.items(): newDict[k] = newDict.get(k,0) + v -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 16:46:12 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 08:46:12 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C3A90C.3040903@tue.nl> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org><49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> Message-ID: <49C3BA44.4030104@sbcglobal.net> An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Fri Mar 20 13:56:27 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 20 Mar 2009 07:56:27 -0500 Subject: [Tutor] adding dictionary values In-Reply-To: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> Message-ID: <200903200756.28272.cfuller084@thinkingplanet.net> You should iterate over the keys of the dictionary: for k in a.keys(): because if you iterate over the full dictionary, your items are the values, not the keys. Otherwise your code looks correct, and I don't think its terribly bad form. You could do something interesting with sets: sa = set(a.keys()) sb = set(b.keys()) The next step could be a for loop, but if you enjoy terseness and taking advantage of language features (also should be faster for big enough dicts): c = dict( \ [(k, a[k]+b[k]) for k in sa&sb ] + \ [(k, a[k]) for k in sa-sb ] + \ [(k, b[k]) for k in sb-sa ] ) which creates a new dict from a list of key, value pairs. The list is a sum of three lists: those keys in both a and b, those only in a, and those only in b. Cheers On Friday 20 March 2009 10:11, Emad Nawfal wrote: > Hi Tutors, > I have two pickled dictionaries containing word counts from two different > corpora. I need to add the values, so that a word count is the sum of both. > If the word "man" has a count of 2 in corpus A and a count of 3 in corpus > B, then I need a new dictionary that has "man": 5. Please let me know > whether the following is correct/incorrect, good/bad, etc. > Your help appreciated: > > def addDicts(a, b): > c = {} > for k in a: > if k not in b: > c[k] = a[k] > else: > c[k] = a[k] + b[k] > > for k in b: > if k not in a: > c[k] = b[k] > return c > > # test this > dict1 = {"dad": 3, "man": 2} > dict2 = {"dad": 5, "woman": 10} > newDict = addDicts(dict1, dict2) > print(newDict) > # This gives > > {'dad': 8, 'woman': 10, 'man': 2} From cfuller084 at thinkingplanet.net Fri Mar 20 14:02:21 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 20 Mar 2009 08:02:21 -0500 Subject: [Tutor] adding dictionary values In-Reply-To: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> Message-ID: <200903200802.21786.cfuller084@thinkingplanet.net> Oops! The dictionary iterates over keys, not values as I stated (and demonstrated by your working code). Consequently, the example I gave could be more succinctly expressed by: sa = set(a) sb = set(b) Sorry for the error. Cheers From kent37 at tds.net Fri Mar 20 17:00:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Mar 2009 12:00:12 -0400 Subject: [Tutor] adding dictionary values In-Reply-To: References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> Message-ID: <1c2a2c590903200900s59e81977qaeb12c1297976cd8@mail.gmail.com> 2009/3/20 greg whittier : > This looks like it will work, but you can accomplish this more compactly by > just looping over the items in both dictionaries and making use of the > default argument of the dictionaries get method. > > newDict = {} > for k, v in dict1.items() + dict2.items(): > ??? newDict[k] = newDict.get(k,0) + v Even simpler, start with a copy of dict1: newDict = dict(dict1) for k, v in dict2.items(): newDict[k] = newDict.get(k,0) + v Kent From roadierich at googlemail.com Fri Mar 20 17:03:56 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Fri, 20 Mar 2009 16:03:56 +0000 Subject: [Tutor] adding dictionary values In-Reply-To: <200903200756.28272.cfuller084@thinkingplanet.net> References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> <200903200756.28272.cfuller084@thinkingplanet.net> Message-ID: 2009/3/20 Chris Fuller : > You should iterate over the keys of the dictionary: > for k in a.keys(): > because if you iterate over the full dictionary, your items are the values, > not the keys. ?Otherwise your code looks correct, and I don't think its > terribly bad form. ?You could do something interesting with sets: > sa = set(a.keys()) > sb = set(b.keys()) > > The next step could be a for loop, but if you enjoy terseness and taking > advantage of language features (also should be faster for big enough dicts): > c = dict( \ > ? [(k, a[k]+b[k]) for k in sa&sb ] + \ > ? [(k, a[k]) for k in sa-sb ] + \ > ? [(k, b[k]) for k in sb-sa ] > ) > > which creates a new dict from a list of key, value pairs. ?The list is a sum > of three lists: ?those keys in both a and b, those only in a, and those only > in b. > > Cheers > > On Friday 20 March 2009 10:11, Emad Nawfal wrote: >> Hi Tutors, >> I have two pickled dictionaries containing word counts from two different >> corpora. I need to add the values, so that a word count is the sum of both. >> If the word "man" has a count of 2 in corpus A and a count of 3 in corpus >> B, then I need a new dictionary that ?has "man": 5. Please let me know >> whether the following is correct/incorrect, good/bad, etc. >> Your help appreciated: >> >> def addDicts(a, b): >> ? ? c = {} >> ? ? for k in a: >> ? ? ? ? if k not in b: >> ? ? ? ? ? ? c[k] = a[k] >> ? ? ? ? else: >> ? ? ? ? ? ? c[k] = a[k] + b[k] >> >> ? ? for k in b: >> ? ? ? ? if k not in a: >> ? ? ? ? ? ? c[k] = b[k] >> ? ? return c >> >> # test this >> dict1 = {"dad": 3, "man": 2} >> dict2 = {"dad": 5, "woman": 10} >> newDict = addDicts(dict1, dict2) >> print(newDict) >> # This gives >> >> {'dad': 8, 'woman': 10, 'man': 2} > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Just to add another tool to your toolbox, defaultdicts, available from version 2.5, are good for word counts, and simplifies your function no end: from collections import defaultdict def addDict(a, b): newdict = defaultdict(int, a) for k,v in b.iteritems(): newdict[k] += v return newdict you can chage the last line to "return dict(newdict)" if the returned value MUST be a dict, but there is very little advantage to doing so in properly written code. Extra credit: To do a word count with a defaultdict is simple: wordcount = defaultdict(int) for word in list_of_words: wordcount[word] += 1 Look it up in the docs if you want details of defaultdict. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From emadnawfal at gmail.com Fri Mar 20 17:10:43 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 20 Mar 2009 12:10:43 -0400 Subject: [Tutor] adding dictionary values In-Reply-To: References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> <200903200756.28272.cfuller084@thinkingplanet.net> Message-ID: <652641e90903200910lf28b6b5n48d9bb66a3575d4c@mail.gmail.com> On Fri, Mar 20, 2009 at 12:03 PM, Richard Lovely wrote: > 2009/3/20 Chris Fuller : > > You should iterate over the keys of the dictionary: > > for k in a.keys(): > > because if you iterate over the full dictionary, your items are the > values, > > not the keys. Otherwise your code looks correct, and I don't think its > > terribly bad form. You could do something interesting with sets: > > sa = set(a.keys()) > > sb = set(b.keys()) > > > > The next step could be a for loop, but if you enjoy terseness and taking > > advantage of language features (also should be faster for big enough > dicts): > > c = dict( \ > > [(k, a[k]+b[k]) for k in sa&sb ] + \ > > [(k, a[k]) for k in sa-sb ] + \ > > [(k, b[k]) for k in sb-sa ] > > ) > > > > which creates a new dict from a list of key, value pairs. The list is a > sum > > of three lists: those keys in both a and b, those only in a, and those > only > > in b. > > > > Cheers > > > > On Friday 20 March 2009 10:11, Emad Nawfal wrote: > >> Hi Tutors, > >> I have two pickled dictionaries containing word counts from two > different > >> corpora. I need to add the values, so that a word count is the sum of > both. > >> If the word "man" has a count of 2 in corpus A and a count of 3 in > corpus > >> B, then I need a new dictionary that has "man": 5. Please let me know > >> whether the following is correct/incorrect, good/bad, etc. > >> Your help appreciated: > >> > >> def addDicts(a, b): > >> c = {} > >> for k in a: > >> if k not in b: > >> c[k] = a[k] > >> else: > >> c[k] = a[k] + b[k] > >> > >> for k in b: > >> if k not in a: > >> c[k] = b[k] > >> return c > >> > >> # test this > >> dict1 = {"dad": 3, "man": 2} > >> dict2 = {"dad": 5, "woman": 10} > >> newDict = addDicts(dict1, dict2) > >> print(newDict) > >> # This gives > >> > >> {'dad': 8, 'woman': 10, 'man': 2} > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > Just to add another tool to your toolbox, defaultdicts, available from > version 2.5, are good for word counts, and simplifies your function no > end: > > from collections import defaultdict > def addDict(a, b): > newdict = defaultdict(int, a) > for k,v in b.iteritems(): > newdict[k] += v > return newdict > > you can chage the last line to "return dict(newdict)" if the returned > value MUST be a dict, but there is very little advantage to doing so > in properly written code. > > Extra credit: > To do a word count with a defaultdict is simple: > wordcount = defaultdict(int) > for word in list_of_words: > wordcount[word] += 1 > > Look it up in the docs if you want details of defaultdict. > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks All for the help, if I want to do this with more than two dictionaries, the obvious solution for me is to use something like the reduce functions with a list of dictionary names like: dictList = [dict1, dict2, dict3] newDict = reduce(addDicts, dictList) Is this a satisfactory solution? -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 17:56:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 09:56:29 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <1237567169.23684.2.camel@mike-desktop> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> Message-ID: <49C3CABD.9050902@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 18:01:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 10:01:34 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C3CABD.9050902@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> <49C3CABD.9050902@sbcglobal.net> Message-ID: <49C3CBEE.9070804@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Mar 20 18:02:55 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 20 Mar 2009 10:02:55 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C3BA44.4030104@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> Message-ID: <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> On Fri, Mar 20, 2009 at 8:46 AM, Wayne Watson wrote: > I guess I haven't made clear above. This is a Red Hat Linux compiled C > program. Indications from others above, suggest it is possible to execute it > under Win Python. If that's true, then my guess is that something prior to > the call must be done in the way of informing the call it is dealing with a > non-Win program. > Neither Python proper nor Popen() are actually executing the program - the Windows shell/command interpreter does that (command.com or cmd.exe, depending on your Windows version); Popen() is just a mechanism for making the request, waiting for a response, and processing the result when it comes. If you want to run a non-Windows executable on Windows, you need to use an alternate shell - someone mentioned Cygwin - although I'm not certain that even that will do it for you. What makes an executable OS-specific is not the language it's written in, but the libraries that it's compiled/linked with. If you have access to the source code, the simplest thing would probably be to recompile it on your own machine... the GCC (Gnu Compiler Collection) is free. You mentioned the 'A' attribute - in Windows, that stands for Archive, and was created as a way for early backup programs to do differential backups (i.e. you do a full backup - the backup program copies every file, clearing the A attribute as it does so; new and updated files have the A attribute set, so the next time you do a backup, the program only copies files that have the A attribute...) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Mar 20 18:05:24 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 20 Mar 2009 10:05:24 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> References: <49C113C8.80002@sbcglobal.net> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> Message-ID: <40af687b0903201005k54a3877bgcc17472567cc57f5@mail.gmail.com> On Fri, Mar 20, 2009 at 10:02 AM, Marc Tompkins wrote: > If you want to run a non-Windows executable on Windows, you need to use an > alternate shell - someone mentioned Cygwin - although I'm not certain that > even that will do it for you. What makes an executable OS-specific is not > the language it's written in, but the libraries that it's compiled/linked > with. If you have access to the source code, the simplest thing would > probably be to recompile it on your own machine... the GCC (Gnu Compiler > Collection) is free. > Nope, just checked the Cygwin page: What Isn't Cygwin? Cygwin is *not* a way to run native linux apps on Windows. You have to rebuild your application *from source* if you want it to run on Windows. Cygwin is *not* a way to magically make native Windows apps aware of UNIX ? functionality, like signals, ptys, etc. Again, you need to build your apps *from source* if you want to take advantage of Cygwin functionality. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From elena.valhalla at gmail.com Fri Mar 20 18:14:13 2009 From: elena.valhalla at gmail.com (Elena of Valhalla) Date: Fri, 20 Mar 2009 18:14:13 +0100 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C3CBEE.9070804@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> <49C3CABD.9050902@sbcglobal.net> <49C3CBEE.9070804@sbcglobal.net> Message-ID: <5c5e5c350903201014qa7cb55ex79355e8b15e624ef@mail.gmail.com> On Fri, Mar 20, 2009 at 6:01 PM, Wayne Watson wrote: > To be clear. The program I'm trying to execute under Win XP was compiled on > a RH Linux machine. It was not compile on a Win OS machine. It may sound far > fetched some facility might be available to do this, but somewhere in my > very, very distant past before the small computers, these sorts of things > were possible, usually through a simulator of some sort. It is not a far-fetched requirement: the reverse, i.e. running windows binary under linux is often possible and regularily used, but it requires a specific tool for the job, in the linux case wine, that translates every system call. It's not an easy task, and I doubt that there is something for windows to do so, but there may be a solution using some virtualizing layer and a minimal linux installation, depending on what is needed from the red hat executable. -- Elena ``of Valhalla'' email: elena.valhalla at gmail.com From sierra_mtnview at sbcglobal.net Fri Mar 20 18:14:51 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 10:14:51 -0700 Subject: [Tutor] Tkinter Geometry Management and Other Basics In-Reply-To: References: <49C2BB92.4090003@sbcglobal.net> Message-ID: <49C3CF0B.6080409@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Mar 20 18:18:14 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 20 Mar 2009 10:18:14 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> References: <49C113C8.80002@sbcglobal.net> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> Message-ID: <40af687b0903201018t7a4d48dcqaff9b0862f5d4310@mail.gmail.com> On Fri, Mar 20, 2009 at 10:02 AM, Marc Tompkins wrote: > Neither Python proper nor Popen() are actually executing the program - the > Windows shell/command interpreter does that (command.com or cmd.exe, > depending on your Windows version); Popen() is just a mechanism for making > the request, waiting for a response, and processing the result when it > comes. > I wasn't very clear here: instead of "the Windows shell/command interpreter does that..." I should have said "the underlying operating system/shell does that..." There are versions of Python for many platforms, and Python code is intended to be as cross-platform as possible, so if you were running some other operating system on your machine, Popen() would be passing your request to... whatever. And if you were running, say, Linux, and trying to execute a Windows program... that wouldn't work either. (Unless you told Popen to pass it through WINE, but I'm not even sure that's possible. There isn't an equivalent to WINE for running Linux executables under Windows, so far as I can Google.) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Fri Mar 20 18:21:09 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 20 Mar 2009 13:21:09 -0400 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C3CBEE.9070804@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> <49C3CABD.9050902@sbcglobal.net> <49C3CBEE.9070804@sbcglobal.net> Message-ID: On Fri, Mar 20, 2009 at 1:01 PM, Wayne Watson wrote: > To be clear. The program I'm trying to execute under Win XP was compiled > on a RH Linux machine. It was not compile on a Win OS machine. It may sound > far fetched some facility might be available to do this, but somewhere in my > very, very distant past before the small computers, these sorts of things > were possible, usually through a simulator of some sort. > Wayne, do you have the source code? From your previous responses, I think you do. If so, what is preventing you from compiling it on windows? Maybe we can help you with that. - Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 18:32:13 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 10:32:13 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <40af687b0903201018t7a4d48dcqaff9b0862f5d4310@mail.gmail.com> References: <49C113C8.80002@sbcglobal.net> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> <40af687b0903201018t7a4d48dcqaff9b0862f5d4310@mail.gmail.com> Message-ID: <49C3D31D.4070902@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 18:41:50 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 10:41:50 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: References: <49C113C8.80002@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> <49C3CABD.9050902@sbcglobal.net> <49C3CBEE.9070804@sbcglobal.net> Message-ID: <49C3D55E.3050001@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Mar 20 18:49:56 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 10:49:56 -0700 Subject: [Tutor] Executing a C Program from RH Linux ... (Cygwin) In-Reply-To: <49C3D31D.4070902@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> <40af687b0903201018t7a4d48dcqaff9b0862f5d4310@mail.gmail.com> <49C3D31D.4070902@sbcglobal.net> Message-ID: <49C3D744.1050208@sbcglobal.net> An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Fri Mar 20 18:51:56 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 20 Mar 2009 13:51:56 -0400 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C3D55E.3050001@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> <49C3CABD.9050902@sbcglobal.net> <49C3CBEE.9070804@sbcglobal.net> <49C3D55E.3050001@sbcglobal.net> Message-ID: On Fri, Mar 20, 2009 at 1:41 PM, Wayne Watson wrote: > Yes, I'm sure I'll need help. I just posted a message minutes before yours > mentioning I'm willing to try Cygwin. The C program, wolf, is the public > domain If trying to compile the program under Win is what you had in mind, > then I can send you all the necessary files in a zip file. If not, then I'll > be back to ask questions about what might be going wrong either here or in > some Cygwin newsgroup. I distantly recall there is one. > I actually found the code http://nightskylive.net/software/ from googling. A quick "make" under msys/mingw didn't complete as I'd hoped, so you'll have to put in some work, but it doesn't look insurmountable. I think this is pretty far afield from the python-tutor group though. Maybe you could try the community that uses WOLF or the cygwin group? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mfarnham at acm.org Fri Mar 20 17:39:29 2009 From: mfarnham at acm.org (Michael Farnham) Date: Fri, 20 Mar 2009 11:39:29 -0500 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: <49C37F88.9070704@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C1545B.9040706@sbcglobal.net> <49C1A64A.1070600@sbcglobal.net> <49C1C9A7.6080605@mwalsh.org> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> Message-ID: <1237567169.23684.2.camel@mike-desktop> On Fri, 2009-03-20 at 04:35 -0700, Wayne Watson wrote: > Good. Thanks. > > Here's my code. > ========== > # Executing a Linux program under Win XP > from subprocess import call > myProg = call(["C:\Sandia_Meteors\Various\FuzzyLogic\wolf", "-h"]) If I understand your question - A C program which runs in Linux cannot run in Microsoft Windows without being recompiled. I know that many of the people who have replied in this thread know this so maybe I misunderstood the question. HTH Mike From kent37 at tds.net Fri Mar 20 19:06:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Mar 2009 14:06:58 -0400 Subject: [Tutor] adding dictionary values In-Reply-To: <652641e90903200910lf28b6b5n48d9bb66a3575d4c@mail.gmail.com> References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> <200903200756.28272.cfuller084@thinkingplanet.net> <652641e90903200910lf28b6b5n48d9bb66a3575d4c@mail.gmail.com> Message-ID: <1c2a2c590903201106s1a1bb9b8rcf8e5462a8c51d3a@mail.gmail.com> 2009/3/20 Emad Nawfal (???? ????) : > if I want to do this with more than two dictionaries, the obvious solution > for me is to use something like the reduce functions with a list of > dictionary names like: > dictList = [dict1, dict2, dict3] > newDict = reduce(addDicts, dictList) > > Is this a satisfactory solution? This will do some extra copying, as addDicts() always copies the first argument. You would do better with something like def addToDict(a, b): for k,v in b.iteritems(): a[k] += v return a newDict = reduce(addDictTo, dictList[1:], defaultdict(int, dictList[0])) or rewrite addDicts() to take a variable number of arguments and loop over the args. Kent From kent37 at tds.net Fri Mar 20 19:09:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Mar 2009 14:09:02 -0400 Subject: [Tutor] Executing a C Program from RH Linux ... (Cygwin) In-Reply-To: <49C3D744.1050208@sbcglobal.net> References: <49C113C8.80002@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> <40af687b0903201018t7a4d48dcqaff9b0862f5d4310@mail.gmail.com> <49C3D31D.4070902@sbcglobal.net> <49C3D744.1050208@sbcglobal.net> Message-ID: <1c2a2c590903201109j5e00bdf9jc745c8b1a8327527@mail.gmail.com> On Fri, Mar 20, 2009 at 1:49 PM, Wayne Watson wrote: > First questions about Cygwin is I see a 1.7 Beta download version for it, > and references to 1.5 downloads. Where's 1.6? Is it past Beta? > > Wayne Watson wrote: > > That's a lot of text to respond to, but let me see if I can broadly do it. > > It appears that the idea of executing Linux code under Win XP is d-e-a-d. > (Let's ignore VM) > I will need to recompile the c-code in some way under Win XP. Probably > Cygwin. This is really far off-topic. Please don't use this list for discussion of Cygwin and porting C code from Linux to Windows. Kent From sierra_mtnview at sbcglobal.net Fri Mar 20 19:48:41 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 11:48:41 -0700 Subject: [Tutor] Executing a C Program from RH Linux in Python for Win In-Reply-To: References: <49C113C8.80002@sbcglobal.net> <49C24DC3.5070902@sbcglobal.net> <49C30531.60701@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <1237567169.23684.2.camel@mike-desktop> <49C3CABD.9050902@sbcglobal.net> <49C3CBEE.9070804@sbcglobal.net> <49C3D55E.3050001@sbcglobal.net> Message-ID: <49C3E509.5080607@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: makefile URL: From eduardo.susan at gmail.com Fri Mar 20 21:40:56 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 20 Mar 2009 14:40:56 -0600 Subject: [Tutor] Trouble parsing email from Outlook In-Reply-To: <9356b9f30903201329v516e46e6i399ccb317ded5c97@mail.gmail.com> References: <9356b9f30903191458x37760bfeq8954e7a0cc53331e@mail.gmail.com> <49C35A8D.9080703@timgolden.me.uk> <9356b9f30903200757t76fc9fcj48dbddeb0cf92c9c@mail.gmail.com> <49C3B076.9080300@timgolden.me.uk> <9356b9f30903201329v516e46e6i399ccb317ded5c97@mail.gmail.com> Message-ID: <9356b9f30903201340q5751cf7brae2ccef1c707e164@mail.gmail.com> On Fri, Mar 20, 2009 at 2:29 PM, Eduardo Vieira wrote: > On Fri, Mar 20, 2009 at 9:04 AM, Tim Golden wrote: >> Eduardo Vieira wrote: >>> >>> Thank you very much, Tim for the thorough explanation. Much more than >>> I could expect. It will be specially useful for me a newbie python >>> amateur programmer. I will try your guidance as soon as possible >>> today, and see my progress. >> >> That's ok; might be worth posting back to the list to say >> whether it worked or not. All the posts go into the archive >> so people looking in the future for the same kind of solution >> might be interested to know if my suggestion worked or >> whether there were any other obstacles. >> >> TJG >> > Thanks again. I tried the code, trying to reformat the spaces and came > up with this code: http://paste.lisp.org/display/77353 > I'm not sure if I indented correctly, and the result it gave me was: > Searching Archive Folders > Searching Mailbox - Eduardo Silva > > I don't understand the part "for folder, folders, items in cdo_walk > (info_store.RootFolder):" > RootFolder is IPM_SUBTREE if I check the Name value > I worked! sorry, I had to just align "raise x_found" with the "for" statement, thank you very much! From alan.gauld at btinternet.com Fri Mar 20 21:42:23 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Mar 2009 20:42:23 -0000 Subject: [Tutor] Tkinter Geometry Management and Other Basics References: <49C2BB92.4090003@sbcglobal.net> <49C3CF0B.6080409@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I really don't want to spend weeks learning Tk/Tcl. You shouldn't need to. The Tk documentation is very easy to transfer to Tkinter: Here is a sample from the official reference docs for Label (found at: http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm): STANDARD OPTIONS -activebackground, activeBackground, Foreground -activeforeground, activeForeground, Background -anchor, anchor, Anchor ... -takefocus, takeFocus, TakeFocus -text, text, Text -textvariable, textVariable, Variable -underline, underline, Underline -wraplength, wrapLength, WrapLength WIDGET-SPECIFIC OPTIONS -height, height, Height -state, state, State -width, width, Width So you can use Label( option = value) for any of the listed options. If you want to see what values are possible, just click onthe option, for example state gives: ------------------------------------------ Command-Line Name: -state Database Name: state Database Class: State Specifies one of three states for the label: normal, active, or disabled. In normal state the button is displayed using the foreground and background options. In active state the label is displayed using the activeForeground and activeBackground options. In the disabled state the disabledForeground andbackground options determine how the button is displayed. ----------------------------------------- No real Tcl knowledge required. Just remember that in Tkinter you should quote the value as a string, so: lbl = Label(text = "My Label", state='disabled') It really is quite easy. Too few Tkinter programmer shy away from the Tcl/Tk sites because they think they need to know Tcl. Its not the case 90+% of the time. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Fri Mar 20 22:18:52 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Mar 2009 21:18:52 +0000 Subject: [Tutor] Trouble parsing email from Outlook In-Reply-To: <9356b9f30903201340q5751cf7brae2ccef1c707e164@mail.gmail.com> References: <9356b9f30903191458x37760bfeq8954e7a0cc53331e@mail.gmail.com> <49C35A8D.9080703@timgolden.me.uk> <9356b9f30903200757t76fc9fcj48dbddeb0cf92c9c@mail.gmail.com> <49C3B076.9080300@timgolden.me.uk> <9356b9f30903201329v516e46e6i399ccb317ded5c97@mail.gmail.com> <9356b9f30903201340q5751cf7brae2ccef1c707e164@mail.gmail.com> Message-ID: <49C4083C.1040807@timgolden.me.uk> Eduardo Vieira wrote: > On Fri, Mar 20, 2009 at 2:29 PM, Eduardo Vieira wrote: >> On Fri, Mar 20, 2009 at 9:04 AM, Tim Golden wrote: >>> Eduardo Vieira wrote: >>>> Thank you very much, Tim for the thorough explanation. Much more than >>>> I could expect. It will be specially useful for me a newbie python >>>> amateur programmer. I will try your guidance as soon as possible >>>> today, and see my progress. >>> That's ok; might be worth posting back to the list to say >>> whether it worked or not. All the posts go into the archive >>> so people looking in the future for the same kind of solution >>> might be interested to know if my suggestion worked or >>> whether there were any other obstacles. >>> >>> TJG >>> >> Thanks again. I tried the code, trying to reformat the spaces and came >> up with this code: http://paste.lisp.org/display/77353 >> I'm not sure if I indented correctly, and the result it gave me was: >> Searching Archive Folders >> Searching Mailbox - Eduardo Silva >> >> I don't understand the part "for folder, folders, items in cdo_walk >> (info_store.RootFolder):" >> RootFolder is IPM_SUBTREE if I check the Name value >> > I worked! sorry, I had to just align "raise x_found" with the "for" > statement, thank you very much! Glad you got it working. The "for folder, folders, items in..." bit is looping over each folder (with its subfolders and subitems) in turn. cdo_walk is a generator -- a function-type mechanism which keeps returning values, rather than just returning once. Because of that, you can keep looping over it as it walks down the tree of folders, recursively in this case altho' other approaches are possible. FWIW, RootFolder is nearly always IPM_SUBTREE; its name doesn't really matter: it's just a place to start looking. Sorry about the formatting. With something more than a few lines long I usually stick it in pastebin or wherever, but I was moving too quickly when I wrote that this morning! TJG From sierra_mtnview at sbcglobal.net Fri Mar 20 23:31:48 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 15:31:48 -0700 Subject: [Tutor] Executing a C Program from RH Linux ... (Cygwin) In-Reply-To: <1c2a2c590903201109j5e00bdf9jc745c8b1a8327527@mail.gmail.com> References: <49C113C8.80002@sbcglobal.net> <49C37F88.9070704@sbcglobal.net> <49C39049.4010702@tue.nl> <49C39E41.7060105@sbcglobal.net> <49C3A90C.3040903@tue.nl> <49C3BA44.4030104@sbcglobal.net> <40af687b0903201002r1ba79b93nce195c632093c74@mail.gmail.com> <40af687b0903201018t7a4d48dcqaff9b0862f5d4310@mail.gmail.com> <49C3D31D.4070902@sbcglobal.net> <49C3D744.1050208@sbcglobal.net> <1c2a2c590903201109j5e00bdf9jc745c8b1a8327527@mail.gmail.com> Message-ID: <49C41954.8020200@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Mar 21 02:19:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Mar 2009 01:19:20 -0000 Subject: [Tutor] Tkinter Geometry Management and Other Basics References: <49C2BB92.4090003@sbcglobal.net> <49C3CF0B.6080409@sbcglobal.net> Message-ID: "Alan Gauld" wrote > It really is quite easy. Too few Tkinter programmer shy away from > the Tcl/Tk sites because they think they need to know Tcl. Ahem, that should have said too *many* of course not too few.... Sorry, Alan G From sierra_mtnview at sbcglobal.net Sat Mar 21 05:23:45 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Mar 2009 21:23:45 -0700 Subject: [Tutor] Tkinter Geometry Management and Other Basics In-Reply-To: References: <49C2BB92.4090003@sbcglobal.net> <49C3CF0B.6080409@sbcglobal.net> Message-ID: <49C46BD1.7020703@sbcglobal.net> An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Mar 21 10:46:43 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 21 Mar 2009 05:46:43 -0400 Subject: [Tutor] adding dictionary values In-Reply-To: <1c2a2c590903201106s1a1bb9b8rcf8e5462a8c51d3a@mail.gmail.com> References: <652641e90903200811y5c9b164amd5bc46294e35f85e@mail.gmail.com> <200903200756.28272.cfuller084@thinkingplanet.net> <652641e90903200910lf28b6b5n48d9bb66a3575d4c@mail.gmail.com> <1c2a2c590903201106s1a1bb9b8rcf8e5462a8c51d3a@mail.gmail.com> Message-ID: <652641e90903210246g641cc099w42246c460dce13f2@mail.gmail.com> 2009/3/20 Kent Johnson > 2009/3/20 Emad Nawfal (???? ????) : > > > if I want to do this with more than two dictionaries, the obvious > solution > > for me is to use something like the reduce functions with a list of > > dictionary names like: > > dictList = [dict1, dict2, dict3] > > newDict = reduce(addDicts, dictList) > > > > Is this a satisfactory solution? > > This will do some extra copying, as addDicts() always copies the first > argument. You would do better with something like > def addToDict(a, b): > for k,v in b.iteritems(): > a[k] += v > return a > > newDict = reduce(addDictTo, dictList[1:], defaultdict(int, dictList[0])) > > or rewrite addDicts() to take a variable number of arguments and loop > over the args. > > Kent > Thanks Kent and All. I appreciate your helpfulness -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From lauren at protopc.com Sat Mar 21 22:42:49 2009 From: lauren at protopc.com (Lauren Snyder) Date: Sat, 21 Mar 2009 14:42:49 -0700 Subject: [Tutor] Distributing MySQL with my application Message-ID: <4DD66F0CBDF24876A804580EE0D01521@laurenpc> Hello! I have written an application in python that uses a MySQL database. I want to distribute this application to many users so I created an executable using GUI2exe. My executable works marvelously. However, when attempting to run the app on a computer that doesn't have the MySQL server running, I obviously get the error: Can't connect MySQL server on localhost. So I have some questions around this problem: 1. Is it possible to bundle the database into my application? 2. Do I have to write a script that installs the database server locally? 3. Do I have to make "Users must have MySQL server running" as a pre-requisite for using my software? 4. Did I miss an option in GUI2exe that allows me to set up my exe to use MySQL? Thank you, Lauren -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 22 00:54:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Mar 2009 23:54:57 -0000 Subject: [Tutor] Distributing MySQL with my application References: <4DD66F0CBDF24876A804580EE0D01521@laurenpc> Message-ID: "Lauren Snyder" wrote > I have written an application in python that uses a MySQL database. > I want > to distribute this application to many users so I created an > executable > > 1. Is it possible to bundle the database into my application? It may be possible but it is unusual. Normally the database woyuld come as a sseparate installer so that those who already have MySql can simply create a new database on their existing server. It is much easier to administer multiple databases on a single server than to have multiple servers ruinning! > 2. Do I have to write a script that installs the database server > locally? If it needs to be local. Do you not use an environment variable or config file to allow the user to select where the database server runs? > 3. Do I have to make "Users must have MySQL server running" as a > pre-requisite for using my software? Usually yes, then provide a loader for MySql for those who need it. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sigridurs07 at ru.is Sat Mar 21 17:07:42 2009 From: sigridurs07 at ru.is (Sigga Sig) Date: Sat, 21 Mar 2009 16:07:42 +0000 Subject: [Tutor] Opening a cmd.exe Message-ID: <000301c9aa3f$2a4694a0$7ed3bde0$@is> Hello I am writing a code that is supoesed to act as routers and i need to open a different cmd window for each one of them with it's name and so on. I do not know how to implement in mi Python cod a sentece that opens such a cmd. I know how to open a cmd.exe bud not with specific attributes that are needed. Thanks. shs -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 22 15:31:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Mar 2009 14:31:04 -0000 Subject: [Tutor] Opening a cmd.exe References: <000301c9aa3f$2a4694a0$7ed3bde0$@is> Message-ID: "Sigga Sig" wrote > I am writing a code that is supoesed to act as routers and i need to > open a > different cmd window for each one of them with it's name and so on. > I do not > know how to implement in mi Python cod a sentece that opens such a > cmd. > > I know how to open a cmd.exe bud not with specific attributes that > are > needed. Neither do I. You can use shortcuts and set the name of the shortcut and that will show up on the window title. There are probably ways to do it using the Win32 API too, but you would need to get the Window Handle using FindWindow(). And I'm still not sure which API call would set the title. I'd probably just create a set of shortfcuts on a folder and execute those. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Sun Mar 22 15:49:02 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 22 Mar 2009 14:49:02 +0000 Subject: [Tutor] Opening a cmd.exe In-Reply-To: References: <000301c9aa3f$2a4694a0$7ed3bde0$@is> Message-ID: <49C64FDE.6090504@timgolden.me.uk> Alan Gauld wrote: > "Sigga Sig" wrote > >> I am writing a code that is supoesed to act as routers and i need to >> open a >> different cmd window for each one of them with it's name and so on. I >> do not >> know how to implement in mi Python cod a sentece that opens such a cmd. >> >> I know how to open a cmd.exe bud not with specific attributes that are >> needed. > > Neither do I. You can use shortcuts and set the name of the shortcut > and that will show up on the window title. > > There are probably ways to do it using the Win32 API too, but you would > need to get the Window Handle using FindWindow(). And I'm still not sure > which API call would set the title. I'd probably just create a set of > shortfcuts on a folder and execute those. You can do it with the win32console functions from pywin32: win32console.SetConsoleTitle (u"blahblah") TJG From mail at timgolden.me.uk Sun Mar 22 15:51:20 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 22 Mar 2009 14:51:20 +0000 Subject: [Tutor] Opening a cmd.exe In-Reply-To: <49C64FDE.6090504@timgolden.me.uk> References: <000301c9aa3f$2a4694a0$7ed3bde0$@is> <49C64FDE.6090504@timgolden.me.uk> Message-ID: <49C65068.2080709@timgolden.me.uk> Tim Golden wrote: > Alan Gauld wrote: >> "Sigga Sig" wrote >> >>> I am writing a code that is supoesed to act as routers and i need to >>> open a >>> different cmd window for each one of them with it's name and so on. I >>> do not >>> know how to implement in mi Python cod a sentece that opens such a cmd. >>> >>> I know how to open a cmd.exe bud not with specific attributes that are >>> needed. >> >> Neither do I. You can use shortcuts and set the name of the shortcut >> and that will show up on the window title. >> >> There are probably ways to do it using the Win32 API too, but you would >> need to get the Window Handle using FindWindow(). And I'm still not sure >> which API call would set the title. I'd probably just create a set of >> shortfcuts on a folder and execute those. > > You can do it with the win32console functions from pywin32: > > win32console.SetConsoleTitle (u"blahblah") Ah, sorry, missed the point that you're not actually running Python code in these windows. Yes, as Alan says, you'd have to use FindWindow to identify your windows by their existing titles and then use SetWindowText (or whatever) to set the title. You probably are better off using shortcuts... TJG From bgailer at gmail.com Sun Mar 22 17:04:02 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 22 Mar 2009 12:04:02 -0400 Subject: [Tutor] Opening a cmd.exe In-Reply-To: <000301c9aa3f$2a4694a0$7ed3bde0$@is> References: <000301c9aa3f$2a4694a0$7ed3bde0$@is> Message-ID: <49C66172.40601@gmail.com> Sigga Sig wrote: > > Hello > > I am writing a code that is supoesed to act as routers and i need to > open a different cmd window for each one of them with it?s name and so > on. > Why are you opening cmd windows? The only reason I can imagine is that a human will be typing commands into them. If that is not the case please tell us more about your goals and objectives. I don't understand "act as routers". -- Bob Gailer Chapel Hill NC 919-636-4239 From metolone+gmane at gmail.com Sun Mar 22 17:22:12 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 22 Mar 2009 09:22:12 -0700 Subject: [Tutor] Opening a cmd.exe References: <000301c9aa3f$2a4694a0$7ed3bde0$@is> <49C64FDE.6090504@timgolden.me.uk> <49C65068.2080709@timgolden.me.uk> Message-ID: "Tim Golden" wrote in message news:49C65068.2080709 at timgolden.me.uk... > Tim Golden wrote: >> Alan Gauld wrote: >>> "Sigga Sig" wrote >>> >>>> I am writing a code that is supoesed to act as routers and i need to >>>> open a >>>> different cmd window for each one of them with it's name and so on. I >>>> do not >>>> know how to implement in mi Python cod a sentece that opens such a cmd. >>>> >>>> I know how to open a cmd.exe bud not with specific attributes that are >>>> needed. >>> Does this do what you want? It creates a new cmd window titled "Dir", then executes some commands. If you want the window to stay open after executing the commands, use /k instead of /c. 'cmd /?' gives other switches you might want. The escaping(^) of the ampersands(&) is required or the commands will run in the current console not the new one. import os os.system('start cmd /c title Dir ^&^& dir ^&^& pause') -Mark From alan.gauld at btinternet.com Sun Mar 22 17:58:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Mar 2009 16:58:52 -0000 Subject: [Tutor] Opening a cmd.exe References: <000301c9aa3f$2a4694a0$7ed3bde0$@is><49C64FDE.6090504@timgolden.me.uk><49C65068.2080709@timgolden.me.uk> Message-ID: "Mark Tolonen" wrote > Does this do what you want? It creates a new cmd window titled > "Dir", then executes some commands. > import os > os.system('start cmd /c title Dir ^&^& dir ^&^& pause') It didn't do quite what I expected, but it made me look at the help for start, which says: =================== Starts a separate window to run a specified program or command. START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/WAIT] [/B] [command/program] [parameters] "title" Title to display in window title bar. path Starting directory ===================== So it looks like simply running start and specifying a title string before the command should do the trick: >>> os.system('start "my window" cmd.exe') Note the title MUST be in double quotes so the string to system must either be rw or use single quotes. You learn somethhing new... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ If you want the window to stay open after executing > the commands, use /k instead of /c. 'cmd /?' gives other switches > you might want. The escaping(^) of the ampersands(&) is required or > the commands will run in the current console not the new one. > > import os > os.system('start cmd /c title Dir ^&^& dir ^&^& pause') > > -Mark > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From zeptii at gmail.com Sun Mar 22 23:02:31 2009 From: zeptii at gmail.com (Mathias Andersson) Date: Sun, 22 Mar 2009 23:02:31 +0100 Subject: [Tutor] Inspiration/examples Message-ID: Hi all! Im currently trying to learn how to use python. But my only problem seems to be at what to make? So anyone have a nifty list or some ideas on things to program, school tasks or algorithms to try and implement. Beginner- to mid-skill level. Thanks in advance. /Mathias -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian505 at gmail.com Sun Mar 22 23:38:28 2009 From: ian505 at gmail.com (Ian Egland) Date: Sun, 22 Mar 2009 18:38:28 -0400 Subject: [Tutor] Inspiration/examples In-Reply-To: References: Message-ID: I am just as interested in this. So far I've found http://openbookproject.net/pybiblio/practice/ from the openbookproject. -Ian On Sun, Mar 22, 2009 at 6:02 PM, Mathias Andersson wrote: > Hi all! > > Im currently trying to learn how to use python. But my only problem seems > to be at what to make? So anyone have a nifty list or some ideas on things > to program, school tasks or algorithms to try and implement. Beginner- to > mid-skill level. Thanks in advance. > > /Mathias > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 23 00:00:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Mar 2009 23:00:33 -0000 Subject: [Tutor] Inspiration/examples References: Message-ID: "Mathias Andersson" wrote > Im currently trying to learn how to use python. But my only problem > seems to > be at what to make? I have a list of ideas in my tutor appendix References, Books and Projects Also there is the Python Challenge "adventure game" And finally the Useless Python site has various ideas and challenges, some of which have otther [peoples attempts to compare with. Or if you want to do something genuinely useful try searching SourceForge for a project using Python. Consider starting off documenting some stuff or trying to find a bug fix. Small simple stuff that gets you familiar with the innards of your chosen project. HTH, Alan G. From Sutak at aol.com Sun Mar 22 22:44:26 2009 From: Sutak at aol.com (Sutak at aol.com) Date: Sun, 22 Mar 2009 17:44:26 EDT Subject: [Tutor] irregular/parse/sort Message-ID: I've been using re.sub() to try and take the below pattern1 and convert it to pattern2 (which are below) below that is mycode1. Does anyone have any suggestions as to how I can figure this out? pattern1 NTR+A0001 0.01 GLU-A0003 8.21 GLU-A0008 3.619 ARG+A0010 14 ARG+A0023 14 ARG+A0024 14 ASP-A0028 0.01 ARG+A0034 13.193 ASP-A0039 2.973 LYS+A0040 10.634 LYS+A0043 12.693 ASP-A0051 3.994 ASP-A0055 0.01 GLU-A0057 9.017 ARG+A0062 14 TYR-A0064 13.028 GLU-A0066 4.081 LYS+A0073 11.193 ASP-A0076 0.01 TYR-A0084 14 HIS+A0086 0.01 TYR-A0087 14 LYS+A0091 11.193 LYS+A0092 10.275 LYS+A0095 11.193 ASP-A0097 2.96 TYR-A0098 14 ASP-A0101 0.01 LYS+A0114 14 TYR-A0116 14 ASP-A0123 0.01 HIS+A0125 7.15 GLU-A0126 3.269 LYS+A0127 11.693 ASP-A0128 2.324 HIS+A0129 7.15 GLU-A0134 3.612 LYS+A0137 12.134 GLU-A0150 2.546 ASP-A0153 0.01 HIS+A0162 9.547 ARG+A0166 14 LYS+A0167 11.693 TYR-A0169 13.641 LYS+A0177 9.547 GLU-A0184 2.952 LYS+A0185 10.634 LYS+A0188 10.634 GLU-A0193 4.078 ARG+A0199 14 ASP-A0201 1.973 LYS+A0209 11.693 GLU-A0213 3.279 GLU-A0219 4.706 LYS+A0223 11.693 ARG+A0226 13.193 GLU-A0227 4.377 GLU-A0228 9.459 GLU-A0230 4.274 ARG+A0232 14 TYR-A0234 14 ASP-A0239 2.317 GLU-A0248 3.982 LYS+A0253 10.547 ASP-A0261 2.335 ARG+A0267 14 LYS+A0272 14 TYR-A0275 10.21 HIS+A0276 7.15 ASP-A0280 3.317 LYS+A0281 11.193 ARG+A0292 12.693 ASP-A0294 2.473 ASP-A0304 2.3 LYS+A0305 11.693 GLU-A0308 2.083 LYS+A0312 11.193 GLU-A0314 4.517 LYS+A0315 11.693 GLU-A0322 15.177 ASP-A0327 0.01 LYS+A0328 10.298 ASP-A0330 0.01 HIS+A0331 0.01 LYS+A0341 6.65 ASP-A0344 0.01 ASP-A0346 2.03 GLU-A0347 3.149 ARG+A0351 14 GLU-A0354 4.52 LYS+A0357 11.193 LYS+A0358 11.634 GLU-A0359 3.945 ASP-A0369 5.467 HIS+A0370 0.01 HIS+A0372 14 ASP-A0380 0.751 LYS+A0382 13.193 LYS+A0393 12.693 ASP-A0394 2.724 TYR-A0402 14 GLU-A0406 3.551 GLU-A0407 4.924 ASP-A0408 1.824 GLU-A0411 5.186 HIS+A0412 6.852 ARG+A0418 23.69 TYR-A0422 14 HIS+A0425 6.65 ASP-A0434 0.01 ASP-A0437 0.01 TYR-A0440 10.555 LYS+A0443 11.155 LYS+A0449 11.693 CTR-A0449 3.014 _MG+A0452 5.257 NTR+B0001 8.547 GLU-B0003 4.312 GLU-B0008 2.577 ARG+B0010 14 ARG+B0023 14 ARG+B0024 14 ASP-B0028 0.724 ARG+B0034 13.193 ASP-B0039 3.21 LYS+B0040 11.193 LYS+B0043 12.377 ASP-B0051 8.766 ASP-B0055 0.01 GLU-B0057 1.955 ARG+B0062 14 TYR-B0064 12.243 GLU-B0066 3.279 LYS+B0073 12.193 ASP-B0076 0.01 TYR-B0084 14 HIS+B0086 0.01 TYR-B0087 14 LYS+B0091 11.693 LYS+B0092 10.547 LYS+B0095 11.134 ASP-B0097 1.839 TYR-B0098 14 ASP-B0101 0.01 LYS+B0114 14 TYR-B0116 14 ASP-B0123 0.01 HIS+B0125 7.15 GLU-B0126 4.746 LYS+B0127 11.693 ASP-B0128 2.457 HIS+B0129 6.65 GLU-B0134 2.737 LYS+B0137 12.193 GLU-B0150 3.33 ASP-B0153 0.611 HIS+B0162 9.664 ARG+B0166 14 LYS+B0167 10.599 TYR-B0169 14 LYS+B0177 10.547 GLU-B0184 3.501 LYS+B0185 11.693 LYS+B0188 12.634 GLU-B0193 3.281 ARG+B0199 14.134 ASP-B0201 1.52 LYS+B0209 10.547 GLU-B0213 3.073 GLU-B0219 3.317 LYS+B0223 11.134 ARG+B0226 12.634 GLU-B0227 4.577 GLU-B0228 7.332 GLU-B0230 3.865 ARG+B0232 14 TYR-B0234 14 ASP-B0239 1.797 GLU-B0248 4.706 LYS+B0253 10.275 ASP-B0261 2.68 ARG+B0267 14 LYS+B0272 10.547 TYR-B0275 10.988 HIS+B0276 7.65 ASP-B0280 3.077 LYS+B0281 12.193 ARG+B0292 13.193 ASP-B0294 2.473 ASP-B0304 2.77 LYS+B0305 11.193 GLU-B0308 3.108 LYS+B0312 12.193 GLU-B0314 3.568 LYS+B0315 11.693 GLU-B0322 9.138 ASP-B0327 13.172 LYS+B0328 10.24 ASP-B0330 0.01 HIS+B0331 4.598 LYS+B0341 6.15 ASP-B0344 0.01 ASP-B0346 1.247 GLU-B0347 2.911 ARG+B0351 14 GLU-B0354 4.113 LYS+B0357 11.134 LYS+B0358 11.693 GLU-B0359 4.509 ASP-B0369 4.63 HIS+B0370 0.01 HIS+B0372 0.01 ASP-B0380 2.097 LYS+B0382 11.693 LYS+B0393 11.693 ASP-B0394 0.473 TYR-B0402 14 GLU-B0406 2.85 GLU-B0407 4.328 ASP-B0408 2.562 GLU-B0411 5.428 HIS+B0412 2.554 ARG+B0418 14 TYR-B0422 14 HIS+B0425 7.15 ASP-B0434 0.01 ASP-B0437 0.01 TYR-B0440 10.199 LYS+B0443 12.693 LYS+B0449 12.693 CTR-B0449 3.18 _MG+B0452 8.86 pattern2 pKaRes NTR 1 A,value= 0.01 pKaRes GLU 3 A,value= 8.21 pKaRes GLU 8 A,value= 3.619 pKaRes ARG 10 A,value= 14 mycode1 from __future__ import with_statement import re dict={"NTR":"NTR","CTR":"CTR","_MG":"_MG","PHE":"PHE", "LEU":"LEU","SER":"SER","TYR":"TYR","CYS":"CYS", "TRP":"TRP","LEU":"LEU","PRO":"PRO","HIS":"HIS", "GLN":"GLN","ARG":"ARG","ILE":"ILE","MET":"MET", "THR":"THR","ASN":"ASN","LYS":"LYS","SER":"SER", "ARG":"ARG","VAL":"VAL","ALA":"ALA","ASP":"ASP", "GLU":"GLU","GLY":"GLY"} # in google search for '''re python search print pattern''' def new1(): #this takes...# with open('C:/Documents and Settings/Administrator/Desktop/Northeastern/Research2/python/E341K.txt') as fil: print fil contents = fil.read() letter = contents letter=str(letter) #list1=list(letter) x= len(contents) #''.join(contents) #splitted=letter.split("-") AA='AA' xx=dict.keys() NTR1='NTR1' #for B in letter and dict.keys(): for A in letter: if re.sub(' ',' ', letter): letter=re.sub('\t','\t',letter) #'value= ' #print letter #print re.sub('\t' and r'\+','',letter), re.sub(r'\+',' ',letter), re.sub('A0','A',letter) break for A in letter: if re.sub(r'\+',' ',letter): letter=re.sub(r'\+',' ',letter) #print letter break for A in letter: if re.sub(r'\-',' ',letter): letter=re.sub(r'\-',' ',letter) #print letter break for A in letter: if re.sub('[0-9]','',letter): letter2=re.sub('[0-9]','',letter) #print letter2, 'letter2' break for A in letter2: if re.sub(r'\.','',letter2): letter1=re.sub(r'\.','',letter2) #print letter1, 'letter1' break for A in letter: if re.sub('A000?', 'A', letter): letter3=re.sub('A000?', 'A', letter) #print letter3 break for A in letter: if re.sub('A010?','A',letter3): letter4=re.sub('A010?','A',letter3) print letter4 break re.purge() #digs=re.compile(r'\+A') #for line in letter: #if digs.search(line): #splitted=line.split(' ') #print line #line=list(line) #print line **************A Good Credit Score is 700 or Above. See yours in just 2 easy steps! (http://pr.atwola.com/promoclk/100126575x1220685763x1201394209/aol?redir=http:%2F%2Fwww.freecreditreport.com%2Fpm%2Fdefault.aspx%3Fsc%3D668072%26hmpgID %3D62%26bcd%3DMarchfooterNO62) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Mar 23 00:35:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Mar 2009 19:35:18 -0400 Subject: [Tutor] Inspiration/examples In-Reply-To: References: Message-ID: <1c2a2c590903221635i448409b9s72e8d27df3ff94ed@mail.gmail.com> On Sun, Mar 22, 2009 at 6:02 PM, Mathias Andersson wrote: > Hi all! > > Im currently trying to learn how to use python. But my only problem seems to > be at what to make? So anyone have a nifty list or some ideas on things to > program, school tasks or algorithms to try and implement. Beginner- to > mid-skill level. Thanks in advance. Some ideas here: http://personalpages.tds.net/~kent37/stories/00021.html#e21puzzles-and-problems Kent From metolone+gmane at gmail.com Mon Mar 23 01:44:13 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 22 Mar 2009 17:44:13 -0700 Subject: [Tutor] irregular/parse/sort References: Message-ID: wrote in message news:d08.50baad3e.36f80b3a at aol.com... > I've been using re.sub() to try and take the below pattern1 and convert it > to > pattern2 (which are below) below that is mycode1. Does anyone have any > suggestions as to how I can figure this out? > > pattern1 > NTR+A0001 0.01 > GLU-A0003 8.21 > GLU-A0008 3.619 > ARG+A0010 14 [snip lots of data] > pattern2 > pKaRes NTR 1 A,value= 0.01 > pKaRes GLU 3 A,value= 8.21 > pKaRes GLU 8 A,value= 3.619 > pKaRes ARG 10 A,value= 14 Since everything appears to be in a fixed column, given a single line from above, this will convert it (no re required): print 'pKaRes %s %d %s,value= %s' % (line[:3],int(line[5:9]),line[4],line[10:]) -Mark From johnjenkinson1 at gmail.com Mon Mar 23 04:35:32 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Sun, 22 Mar 2009 22:35:32 -0500 Subject: [Tutor] Syntax error Message-ID: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> I am trying to write a program that displays the string expression "Game Over", in a console window that remains open. my code is as follows: # Game Over console window print "Game Over" raw input("\n\nPress the enter key to exit.") The error I am recieve is "There is an error in your program: invalid syntax". I dont understand what is supposed to happen if the code were to be correct. Would a separate console be displayed with the text "Game Over", or would I see the output in the Interactive Mode window? Excuses my noviceness, I just started using python tonight. -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Mon Mar 23 05:18:01 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 22 Mar 2009 21:18:01 -0700 Subject: [Tutor] Syntax error References: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> Message-ID: It is helpful to know the exact error message (cut and paste) and the version of Python you are using. In Python 3.x the print statement would produce a syntax error. In any Python "raw input" is a syntax error. "raw_input" is the correct function name, unless you are using 3.x where it was renamed to "input". In Python 2.x: print "Game Over" raw_input("\n\nPress the enter key to exit.") In Python 3.x: print("Game Over") input("\n\nPress the enter key to exit.") -Mark "John Jenkinson" wrote in message news:58fd32380903222035k591f65b1x13f4e3b8b70b21ab at mail.gmail.com... I am trying to write a program that displays the string expression "Game Over", in a console window that remains open. my code is as follows: # Game Over console window print "Game Over" raw input("\n\nPress the enter key to exit.") The error I am recieve is "There is an error in your program: invalid syntax". I dont understand what is supposed to happen if the code were to be correct. Would a separate console be displayed with the text "Game Over", or would I see the output in the Interactive Mode window? Excuses my noviceness, I just started using python tonight. ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjenkinson1 at gmail.com Mon Mar 23 05:29:34 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Sun, 22 Mar 2009 23:29:34 -0500 Subject: [Tutor] Syntax error In-Reply-To: References: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> Message-ID: <58fd32380903222129j75d95f4bo55fb6ddc9df4b52@mail.gmail.com> Mark, The error poped up in a message box, I was unable to (cut and paste), or I would have done so. On Sun, Mar 22, 2009 at 11:18 PM, Mark Tolonen > wrote: > It is helpful to know the exact error message (cut and paste) and the > version of Python you are using. In Python 3.x the print statement would > produce a syntax error. In any Python "raw input" is a syntax > error. "raw_input" is the correct function name, unless you are using 3.x > where it was renamed to "input". > > In Python 2.x: > > print "Game Over" > raw_input("\n\nPress the enter key to exit.") > > In Python 3.x: > > print("Game Over") > input("\n\nPress the enter key to exit.") > > -Mark > > "John Jenkinson" wrote in message > news:58fd32380903222035k591f65b1x13f4e3b8b70b21ab at mail.gmail.com... > I am trying to write a program that displays the string expression "Game > Over", in a console window that remains open. > > my code is as follows: > > # Game Over console window > > print "Game Over" > raw input("\n\nPress the enter key to exit.") > > > > > The error I am recieve is "There is an error in your program: invalid > syntax". > > I dont understand what is supposed to happen if the code were to be > correct. Would a separate console be displayed with the text "Game Over", > or would I see the output in the Interactive Mode window? > > Excuses my noviceness, I just started using python tonight. > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Mar 23 05:30:35 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 22 Mar 2009 21:30:35 -0700 Subject: [Tutor] Syntax error In-Reply-To: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> References: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> Message-ID: <40af687b0903222130k2555124dka59bcf99318e9432@mail.gmail.com> On Sun, Mar 22, 2009 at 8:35 PM, John Jenkinson wrote: > I am trying to write a program that displays the string expression "Game > Over", in a console window that remains open. > > my code is as follows: > > # Game Over console window > > print "Game Over" > raw input("\n\nPress the enter key to exit.") > Assuming that you've posted exactly what's in your program, the problem is "raw input()" (which would mean 'execute a statement called raw, with an input() function following it') instead of "raw_input()". Since there isn't a built-in statement called "raw", you get the syntax error. Spelling counts. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjenkinson1 at gmail.com Mon Mar 23 05:34:28 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Sun, 22 Mar 2009 23:34:28 -0500 Subject: [Tutor] Syntax error In-Reply-To: <40af687b0903222130k2555124dka59bcf99318e9432@mail.gmail.com> References: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> <40af687b0903222130k2555124dka59bcf99318e9432@mail.gmail.com> Message-ID: <58fd32380903222134p46ad1ccaq4f0bffa2ec541a76@mail.gmail.com> I understand. I am following a tutorial that has a typo. Quoting from the text: The last line of the program: raw input("\n\nPress the enter key to exit.") I enjoyed your intuitive explanation, thank you. On Sun, Mar 22, 2009 at 11:30 PM, Marc Tompkins wrote: > On Sun, Mar 22, 2009 at 8:35 PM, John Jenkinson > wrote: > >> I am trying to write a program that displays the string expression "Game >> Over", in a console window that remains open. >> >> my code is as follows: >> >> # Game Over console window >> >> print "Game Over" >> raw input("\n\nPress the enter key to exit.") >> > > Assuming that you've posted exactly what's in your program, the problem is > "raw input()" (which would mean 'execute a statement called raw, with an > input() function following it') instead of "raw_input()". Since there isn't > a built-in statement called "raw", you get the syntax error. > > Spelling counts. > > -- > www.fsrtechnologies.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjenkinson1 at gmail.com Mon Mar 23 06:08:47 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Mon, 23 Mar 2009 00:08:47 -0500 Subject: [Tutor] no output Message-ID: <58fd32380903222208k4ae5d290lf0629e7fb48f8182@mail.gmail.com> My Code: # Game Over - Version 2.0 # Demonstrates the use of quotes in strings print "Program 'Game Over' 2.0" print \ """ ----- --- --- --- ----- / ___| / | / |/ | | ___| | | / /| | / /| / | | |__ | | _ / ___ | / / |__/ | | | __| """ raw_input("\n\nPress the enter key to exit.") shell's response: >>> ================================ RESTART ================================ -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjenkinson1 at gmail.com Mon Mar 23 06:29:54 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Mon, 23 Mar 2009 00:29:54 -0500 Subject: [Tutor] no output In-Reply-To: <58fd32380903222208k4ae5d290lf0629e7fb48f8182@mail.gmail.com> References: <58fd32380903222208k4ae5d290lf0629e7fb48f8182@mail.gmail.com> Message-ID: <58fd32380903222229s1a5ab10bt4143229a3df88573@mail.gmail.com> On Mon, Mar 23, 2009 at 12:08 AM, John Jenkinson wrote: > My Code: > > # Game Over - Version 2.0 > # Demonstrates the use of quotes in strings > > print "Program 'Game Over' 2.0" > > print \ > """ > ----- --- --- --- ----- > / ___| / | / |/ | | ___| > | | / /| | / /| / | | |__ > | | _ / ___ | / / |__/ | | | __| > > """ > > raw_input("\n\nPress the enter key to exit.") > > > shell's response: > > >>> ================================ RESTART > ================================ > I cant find any problems with the code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 23 09:35:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Mar 2009 08:35:13 -0000 Subject: [Tutor] Syntax error References: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> Message-ID: "John Jenkinson" wrote >I am trying to write a program that displays the string expression >"Game > Over", in a console window that remains open. > > print "Game Over" > raw input("\n\nPress the enter key to exit.") > > I dont understand what is supposed to happen if the code were to be > correct. Would a separate console be displayed with the text "Game > Over", > or would I see the output in the Interactive Mode window? This would display the Game Over message followed by the Press enter key message in the window wghere the program was executing and then wait for the user to hit the key before closing the window.. The problem you have is that I suspect you are using IDLE or Pythonwin to write the code. These tools are development tools and not what you would normally use to run the program. They do not display their output in a window but rather do so in the interactive shell within the tool. To see the program act as the auithor intended save the file with a .py extension and then double click on it in Windows Explorer (assuming you are on Windows!). This will open a Command window with the program running inside. Finally, to select error messages for posting you need to do something similar. Start a command window (Start->Run, type CMD, hit OK). At the OS command prompt type python and then drag your program file onto the window. This will run the program and leave the error message on screen. You can then use the control menu(click on the window icon) Edit->Mark, Edit->Copy to select the text and copy it to the clipboard so that you can paste it into a mail message. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 23 09:39:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Mar 2009 08:39:58 -0000 Subject: [Tutor] no output References: <58fd32380903222208k4ae5d290lf0629e7fb48f8182@mail.gmail.com> <58fd32380903222229s1a5ab10bt4143229a3df88573@mail.gmail.com> Message-ID: "John Jenkinson" wrote >> My Code: >> >> # Game Over - Version 2.0 >> # Demonstrates the use of quotes in strings >> >> print "Program 'Game Over' 2.0" >> >> raw_input("\n\nPress the enter key to exit.") >> >> shell's response: >> >> >>> ================================ RESTART >> ================================ >> See my response to your previous mail. You still haven't told us which version of Python you are using. If it is Python v2.x then: Run the program from the file manager (windows explorer) and see if you get a different response. If it is Python v3.x Place parentheses () around the content of your print statements: print ( "Program 'Game Over' 2.0" ) There are a lot of changes between v3 and previous versions so its important we know which version you are using. Most tutorials are still on v2. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From hgleroy at gmail.com Mon Mar 23 10:53:07 2009 From: hgleroy at gmail.com (H.G. le Roy) Date: Mon, 23 Mar 2009 10:53:07 +0100 Subject: [Tutor] Inspiration/examples In-Reply-To: References: Message-ID: <317299150903230253n5dddbb66t876a0e511d7df7c0@mail.gmail.com> 2009/3/22 Mathias Andersson > Im currently trying to learn how to use python. But my only problem seems to be at what to make? So anyone have a nifty list or some ideas on things to program, school tasks or algorithms to try and implement. Beginner- to mid-skill level. Thanks in advance. You should try: http://projecteuler.net/ From kent37 at tds.net Mon Mar 23 11:46:51 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Mar 2009 06:46:51 -0400 Subject: [Tutor] no output In-Reply-To: <58fd32380903222208k4ae5d290lf0629e7fb48f8182@mail.gmail.com> References: <58fd32380903222208k4ae5d290lf0629e7fb48f8182@mail.gmail.com> Message-ID: <1c2a2c590903230346l5eafdf6cp8049cff5bcb3ecbd@mail.gmail.com> On Mon, Mar 23, 2009 at 1:08 AM, John Jenkinson wrote: > My Code: > > # Game Over - Version 2.0 > # Demonstrates the use of quotes in strings > > print "Program 'Game Over' 2.0" > > print \ > """ > ?-----????????? ---???????? ---? ---??? ----- > /? ___|??????? /?? |?????? /?? |/?? |? |? ___| > | |?????????? / /| |????? / /|?? /? |? | |__ > | |? _?????? / ___ |???? / / |__/ | |? |? __| > > """ > raw_input("\n\nPress the enter key to exit.") > > shell's response: > >>>> ================================ RESTART >>>> ================================ > Please tell us exactly what you are doing to run the program, including Python version and OS. You might find these helpful: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ http://www.python.org/doc/faq/windows/#how-do-i-run-a-python-program-under-windows Kent From bala.biophysics at gmail.com Mon Mar 23 15:40:26 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 23 Mar 2009 15:40:26 +0100 Subject: [Tutor] dynamically creating list Message-ID: <288df32a0903230740y3a4dbe5dyd74d35916599fb61@mail.gmail.com> Dear Friends, I have a text output file from a program that does clustering. Now i have to parse the text output file to separate data points belonging to each cluster. I am thinking to design the algo. in the following way. i) ask the user the text output file ii) ask the user for the number of clusters created (say 5) iii) create 5 lists inside the program, write data points belonging to 5 different cluster in the 5 lists created 1) Now my question is, how to make this list creation dynamics, say if user enter number of clusters = 4, i would create four list. If the user enter 3, then i shd create three lists inside my program. How to do this dynamic creation of list depending on user input. 2) Is there any other better way or object that i can use to do this effectively. Thanks in advance, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Mon Mar 23 16:06:05 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 23 Mar 2009 16:06:05 +0100 Subject: [Tutor] dynamically creating list In-Reply-To: <288df32a0903230740y3a4dbe5dyd74d35916599fb61@mail.gmail.com> References: <288df32a0903230740y3a4dbe5dyd74d35916599fb61@mail.gmail.com> Message-ID: <49C7A55D.3030002@tue.nl> Bala subramanian wrote: > 1) Now my question is, how to make this list creation dynamics, say if user > enter number of clusters = 4, i would create four list. If the user enter 3, > then i shd create three lists inside my program. How to do this dynamic > creation of list depending on user input. Use a list to collect everything, where each value represents data from a cluster. Each value is a list of data points. all = [] for n in range(num_clusters): all.append([]) for point in data_points: cluster = assign_cluster(point) all[cluster].append(point) This would give you something like [ [ pointA1, pointA2, pointA3, ..., pointAn ], [ pointB1, pointB2, pointB3, ..., pointBm ], ... ] where 'pointAx' are points for the first cluster (number 0), 'pointBx' are points for the second cluster (number 1), etc. The list of points for cluster 'num' is then 'all[num]'. A single point can be accessed as all[2][1] which gives you the second point on the third cluster. (or: points = all[2] print points[1] ) Sincerely, Albert From bala.biophysics at gmail.com Mon Mar 23 17:39:32 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 23 Mar 2009 17:39:32 +0100 Subject: [Tutor] swapping lines between files Message-ID: <288df32a0903230939i655445d0td4b0114dfee3440@mail.gmail.com> Dear Friends, Thanks for your replies for my previous mail. I have two files as follows. file 1 file2 200 1 3.55 210 2 4.55 242 3 1.22 248 4 3.10 256 5 1.11 Now i have to replace 1,2,3,4,5 in *file 2* with 200,210,242,248,256 in * file1*. Simply *replacing position 1 in file2 with values in file1*. Can i do it with zip function, if yes how to do it. Here both files contain same number of lines. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Mar 23 18:42:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Mar 2009 13:42:43 -0400 Subject: [Tutor] swapping lines between files In-Reply-To: <288df32a0903230939i655445d0td4b0114dfee3440@mail.gmail.com> References: <288df32a0903230939i655445d0td4b0114dfee3440@mail.gmail.com> Message-ID: <1c2a2c590903231042k62e9a069s6d6293e4702ba79d@mail.gmail.com> On Mon, Mar 23, 2009 at 12:39 PM, Bala subramanian wrote: > Dear Friends, > > Thanks for your replies for my previous mail. > > I have two files as follows. > > file 1???????? file2 > 200?????????? 1???????? 3.55 > 210?????????? 2???????? 4.55 > 242?????????? 3???????? 1.22 > 248?????????? 4???????? 3.10 > 256??????????? 5??????? 1.11 > > Now i have to replace 1,2,3,4,5 in file 2 with 200,210,242,248,256 in file1. > Simply replacing position 1 in file2 with values in file1. Can i do it with > zip function, if yes how to do it. Here both files contain same number of > lines. You can use zip() to combine the lines of the files. itertools.izip() might be a better choice because it doesn't read the entire file at once. Something like this (untested): from itertools import izip file2 = open(...) out = open(..., 'w') # output file for line1, line2 in izip(file1, file2): # now create a line that merges the two and write it line1 = line1.strip() # remove newline line2items = line2.split() line2items[0] = line1 newLine = '\t'.join(line2items) out.write(newLine) out.write('\n') out.close() Kent From bala.biophysics at gmail.com Mon Mar 23 19:33:38 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 23 Mar 2009 19:33:38 +0100 Subject: [Tutor] returning values from function. Message-ID: <288df32a0903231133y59531ccdlefa92a1b51446fbe@mail.gmail.com> Friends, I wrote the following code to create two different list. One containing data points of all clusters and another containing list of individual cluster data points. The script is as follows. #!/usr/bin/env python from sys import argv # STEP 1: a) ACCUMULATING ALL DATA POINTS IN AND A LIST b) CREATING LIST OF INDIVIDUAL CLUSTERS print argv[1], argv[2] data=[] # list of all data points all=[ [] for value in range(int(argv[2])) ] # Creating an empty list of lists of size n (No of clusters) def cluster(infile=argv[1],n=int(argv[2])): for index, line in enumerate(infile): if line.startswith('#Consensus'): line=line.split() data.extend(line[2]) # data now should contain data points of all clusters for value in range(n): for index, line in enumerate(data): if data[index] == str(value): zero=index+1 all[value].append(zero) #return data, all ( I even tried by un commenting the return statement ) print all print data The final print statement returns a empty list ie all and data. I have the following queries i) Why the print statement returns empty lists ii) Is return really required here, if i understand the namespace well, the function cluster actually modifies the global variables data and all. iii) I even tried by using a return statement but still the script returns empty list. iv) Is there any fancy or better of way of doing this python. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 23 20:17:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Mar 2009 19:17:22 -0000 Subject: [Tutor] returning values from function. References: <288df32a0903231133y59531ccdlefa92a1b51446fbe@mail.gmail.com> Message-ID: "Bala subramanian" wrote > I wrote the following code to create two different list. One containing > data > points of all clusters and another containing list of individual cluster > data points. The script is as follows. > > data=[] # list of all data points > all=[ [] for value in range(int(argv[2])) ] # Creating an empty list of > > def cluster(infile=argv[1],n=int(argv[2])): > for index, line in enumerate(infile): > if line.startswith('#Consensus'): > line=line.split() > data.extend(line[2]) # data now should contain data points > for value in range(n): > for index, line in enumerate(data): > if data[index] == str(value): > zero=index+1 > all[value].append(zero) > #return data, all ( I even tried by un commenting the return Here you define a function. But you never call it... > print all > print data So these have the same values that you initialised them to. > The final print statement returns a empty list ie all and data. I have > the > following queries > > i) Why the print statement returns empty lists Because you never call the function. > ii) Is return really required here, if i understand the namespace well, > the > function cluster actually modifies the global variables data and all. You are correct it modifuies the global value. But that is bad practice and willl limit the reusability of the function. Indeed you will only ever be able to use it on one data set at a time. It would be much better to either pass in a refernce to a list or even better initialise the list inside the function and return the populated list. > iii) I even tried by using a return statement but still the script > returns > empty list. Until you call it the return value has no effect. > iv) Is there any fancy or better of way of doing this python. There are probably several ways to improve the code (for example you use enumerate in the first loop but never use index...), but I'd just try to get it working first! HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lauren at protopc.com Mon Mar 23 21:17:26 2009 From: lauren at protopc.com (Lauren Snyder) Date: Mon, 23 Mar 2009 13:17:26 -0700 Subject: [Tutor] Distributing MySQL with my application In-Reply-To: <49C64B43.8070003@gmail.com> References: <4DD66F0CBDF24876A804580EE0D01521@laurenpc> <49C64B43.8070003@gmail.com> Message-ID: Alan and Andr?, Thank you very much for your assistance. My script takes a long log file, parses it, puts the data to a database. The application has a GUI interface and uses the data in the database to make and display various calculations and graphs. Users will have their own log files...but to use my tool, I need to either ensure they have a db server (like noted below) to create my db on...or to somehow provide a db for them to use with my tool. 1. how do I create a database that is not in users localhost? Currently I just use MySQL's "create [database]" command after I connect using MySQLdb.connect Alan mentioned something about "Do you not use an environment variable or config file to allow the user to select where the database server runs?" --> This sounds like it might be an excellent solution, but I'm not sure how to do it. 2. I also like the idea of writing a script to check to see if MySQL is installed. However, I need pointers on writing this script and also the script to auto install MySQL on another user's computer. Thank you again for your help and brilliant ideas! Lauren -----Original Message----- From: andr? palma [mailto:andrefsp at gmail.com] Sent: Sunday, March 22, 2009 7:29 AM To: Lauren Snyder Subject: Re: [Tutor] Distributing MySQL with my application Hi! It depends for what do you want for your aplication. How about you create a database anywhere else(not in users localhost) for each user who uses your software? This way you just wouldn't have this problem. But if you really need the database on localhost my suggestion is: - make a script that check if the user already have MySQL installed, this way you just need to create an new database on localhost server for your software. if there is no MySQL : - make a script to install MySQL locally Lauren Snyder wrote: > > Hello! > > I have written an application in python that uses a MySQL database. I > want to distribute this application to many users so I created an > executable using GUI2exe. My executable works marvelously. However, > when attempting to run the app on a computer that doesn?t have the > MySQL server running, I obviously get the error: Can?t connect MySQL > server on localhost. > > So I have some questions around this problem: > > 1. Is it possible to bundle the database into my application? > 2. Do I have to write a script that installs the database server > locally? > 3. Do I have to make ?Users must have MySQL server running? as a > pre-requisite for using my software? > 4. Did I miss an option in GUI2exe that allows me to set up my exe > to use MySQL? > > Thank you, > > Lauren > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From johnjenkinson1 at gmail.com Mon Mar 23 22:10:06 2009 From: johnjenkinson1 at gmail.com (John Jenkinson) Date: Mon, 23 Mar 2009 16:10:06 -0500 Subject: [Tutor] Syntax error In-Reply-To: References: <58fd32380903222035k591f65b1x13f4e3b8b70b21ab@mail.gmail.com> Message-ID: <58fd32380903231410t34788aedq100273ffb48cf971@mail.gmail.com> I am using Python 2.4.1. I am using the IDLE process, and I was not saving as ".py". Thank you, everyone, for your continued help. On Mon, Mar 23, 2009 at 3:35 AM, Alan Gauld wrote: > > "John Jenkinson" wrote > > I am trying to write a program that displays the string expression "Game >> Over", in a console window that remains open. >> >> print "Game Over" >> raw input("\n\nPress the enter key to exit.") >> >> I dont understand what is supposed to happen if the code were to be >> correct. Would a separate console be displayed with the text "Game Over", >> or would I see the output in the Interactive Mode window? >> > > This would display the Game Over message followed by the > Press enter key message in the window wghere the program was executing > and then wait for the user to hit the key before closing the window.. > > The problem you have is that I suspect you are using IDLE or Pythonwin > to write the code. These tools are development tools and not what you > would normally use to run the program. They do not display their output > in a window but rather do so in the interactive shell within the tool. > > To see the program act as the auithor intended save the file with a > .py extension and then double click on it in Windows Explorer > (assuming you are on Windows!). This will open a Command window > with the program running inside. > > Finally, to select error messages for posting you need to do something > similar. > Start a command window (Start->Run, type CMD, hit OK). At the OS > command prompt type python and then drag your program file onto the window. > This will run the program and leave the error message on screen. You can > then > use the control menu(click on the window icon) Edit->Mark, Edit->Copy to > select the text and copy it to the clipboard so that you can paste it into > a > mail message. > > HTH, > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Mon Mar 23 22:15:57 2009 From: david at abbottdavid.com (David) Date: Mon, 23 Mar 2009 17:15:57 -0400 Subject: [Tutor] Distributing MySQL with my application In-Reply-To: References: <4DD66F0CBDF24876A804580EE0D01521@laurenpc> <49C64B43.8070003@gmail.com> Message-ID: <49C7FC0D.6050305@abbottdavid.com> Lauren Snyder wrote: > > 2. I also like the idea of writing a script to check to see if MySQL is > installed. However, I need pointers on writing this script and also the > script to auto install MySQL on another user's computer. > > Thank you again for your help and brilliant ideas! > Lauren > Are these Windows or Linux users? If Linux each distro has its own package managers. It would be very hard to install and setup MySQL for different platforms and distro's. An option is to use [0] down the page a little, or your own remote MySQL server [1] [0] Database Systems for Embedding Into Applications http://wiki.python.org/moin/DatabaseInterfaces [1] http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From dukelx2005 at gmail.com Mon Mar 23 23:30:20 2009 From: dukelx2005 at gmail.com (Jared White) Date: Mon, 23 Mar 2009 18:30:20 -0400 Subject: [Tutor] (no subject) Message-ID: <9239372b0903231530s8bb538aja5a2a2b9f8f2b489@mail.gmail.com> Help If u can please i got this code to work for the top half * ** *** **** ***** ****** ******* ******** ********* ********** def main(): i=1 while i <=10: j=1 while j<=i: print '*', j=j+1 print i=i+1 main() ********** ********* I cant get a code to work for this bottom half, Can anyone help me ******** ******* ****** ***** **** *** ** * -------------- next part -------------- An HTML attachment was scrubbed... URL: From shininggg2000 at gmail.com Mon Mar 23 23:57:38 2009 From: shininggg2000 at gmail.com (Shining Wisdom) Date: Mon, 23 Mar 2009 18:57:38 -0400 Subject: [Tutor] library for files information Message-ID: <49C813E2.1030201@gmail.com> Hi, i want to write a script that copy file from a folder on my hdd to a usb thumb drive based on the time the file was created. Just need help to find which library to google... From alan.gauld at btinternet.com Tue Mar 24 00:28:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Mar 2009 23:28:15 -0000 Subject: [Tutor] (no subject) References: <9239372b0903231530s8bb538aja5a2a2b9f8f2b489@mail.gmail.com> Message-ID: "Jared White" wrote > Help If u can please i got this code to work for the top half You were already given a couple of hints on how to maker this easier but you seem to have ignored both of them Look again at using a for loop and the range() function. Then look at printing a string using the multiplication operator ie. print '*' * 5 These things will greatly simplify your program If you then look at the range function again you should see how to implement the bottom half of your pattern. Try using these hints and copme back for more help if it doesn't work. > def main(): > i=1 > while i <=10: > j=1 > while j<=i: > print '*', > j=j+1 > print > i=i+1 > main() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 24 00:35:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Mar 2009 23:35:02 -0000 Subject: [Tutor] library for files information References: <49C813E2.1030201@gmail.com> Message-ID: "Shining Wisdom" wrote > Hi, i want to write a script that copy file from a folder on my hdd to a > usb thumb drive based on the time the file was created. > > Just need help to find which library to google... You don't need much. The os.path module will give you the creation time. The time module may be needed too if you want to format the time in your output.. For copying the files you can either use standard file operations or the shutil module. All of these are covered in my Using the OS topic in my tutorial -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 24 00:40:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Mar 2009 23:40:39 -0000 Subject: [Tutor] Distributing MySQL with my application References: <4DD66F0CBDF24876A804580EE0D01521@laurenpc><49C64B43.8070003@gmail.com> Message-ID: "Lauren Snyder" wrote > 1. how do I create a database that is not in users localhost? Currently I > just use MySQL's "create [database]" command after I connect using > MySQLdb.connect The connect string should include the machine/port information. > Alan mentioned something about > "Do you not use an environment variable or config file to allow > the user to select where the database server runs?" Read the machine/port details from the config file or environment var and use those in the connect string. > 2. I also like the idea of writing a script to check to see if MySQL is > installed. However, I need pointers on writing this script and also the > script to auto install MySQL on another user's computer. Does it need to be MySql? If you aren't using a lot of MySql specific SQL you might be better changing toSQLite whichis part of the standard Python library and has the advantage that it is easy to distrribute, being just a single file. The regular py2exe conversion will then bundle all the stuff you need into your single exe file. It's much easier than MySql for this kind of thing and pefectly adequate if you aren't managing huge databases(ie millions of records). Just a thought, Alan G From david at abbottdavid.com Tue Mar 24 03:27:40 2009 From: david at abbottdavid.com (David) Date: Mon, 23 Mar 2009 22:27:40 -0400 Subject: [Tutor] (no subject) In-Reply-To: <9239372b0903231530s8bb538aja5a2a2b9f8f2b489@mail.gmail.com> References: <9239372b0903231530s8bb538aja5a2a2b9f8f2b489@mail.gmail.com> Message-ID: <49C8451C.30408@abbottdavid.com> Jared White wrote: > > ********** > ********* I cant get a code to work for this bottom half, Can > anyone help me > ******** > ******* > ****** > ***** > **** > *** > ** > * See if this helps; http://www.network-theory.co.uk/docs/pytut/rangeFunction.html -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From padhu.47 at gmail.com Tue Mar 24 07:27:19 2009 From: padhu.47 at gmail.com (Padmanaban Ganesan) Date: Tue, 24 Mar 2009 11:57:19 +0530 Subject: [Tutor] (no subject) In-Reply-To: <49C8451C.30408@abbottdavid.com> References: <9239372b0903231530s8bb538aja5a2a2b9f8f2b489@mail.gmail.com> <49C8451C.30408@abbottdavid.com> Message-ID: <8aa4df020903232327p335145d4k25b26324a0367bc3@mail.gmail.com> Hello David, Please try this ..... I hope this answered your question now. SAM PRG: ---------------- def main(): i=1 while i <=10: j=1 while j<=i: print 'Paddy' , j=j+1 print i=i+1 def rev(): i=10 while i >=1: print 'Paddy' , print i=i-1 main() rev () O/P: ------- Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy please let me know if you need any other details. Ta, Paddy " The Secret of Creativity is knowing to hide the source " 2009/3/24 David > Jared White wrote: > > ********** >> ********* I cant get a code to work for this bottom half, Can >> anyone help me >> ******** >> ******* >> ****** >> ***** >> **** >> *** >> ** >> * >> > > See if this helps; > http://www.network-theory.co.uk/docs/pytut/rangeFunction.html > > > -- > Powered by Gentoo GNU/LINUX > http://www.linuxcrazy.com > pgp.mit.edu > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Ta, Paddy "The Secret to creativity is knowing how to hide your sources " -------------- next part -------------- An HTML attachment was scrubbed... URL: From bala.biophysics at gmail.com Tue Mar 24 10:08:51 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Tue, 24 Mar 2009 10:08:51 +0100 Subject: [Tutor] text editor and debugger for python Message-ID: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Friends, I do the scripting in Linux. I use vi editor to code. It is not very convenient for me. Kindly suggest me a best free *text editor* ( i can code and debug the code simultaneously ) *for python* based on your experience. Thanks Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From padhu.47 at gmail.com Tue Mar 24 10:16:44 2009 From: padhu.47 at gmail.com (Padmanaban Ganesan) Date: Tue, 24 Mar 2009 14:46:44 +0530 Subject: [Tutor] text editor and debugger for python In-Reply-To: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Message-ID: <8aa4df020903240216q2ff23a45y2e2d922265ce960d@mail.gmail.com> Hi Bala, ( I realise that, since i am a UNIX/AIX/LINUX/PERL/PYTHON Developer ) Please use EditPus 3.0 or the ULTRA EDIT. EDIT PLUS is the Shareware. please download it from http://www.editplus.com/ ( freeware for the oldversion ) Ta, Paddy 2009/3/24 Bala subramanian > Friends, > > I do the scripting in Linux. I use vi editor to code. It is not very > convenient for me. Kindly suggest me a best free *text editor* ( i can > code and debug the code simultaneously ) *for python* based on your > experience. > > Thanks > Bala > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ta, Paddy "The Secret to creativity is knowing how to hide your sources " -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 24 10:24:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Mar 2009 09:24:42 -0000 Subject: [Tutor] text editor and debugger for python References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Message-ID: "Bala subramanian" wrote > I do the scripting in Linux. I use vi editor to code. It is not very > convenient for me. Can you tell us what is not convenient? That would heklp us recommend other editors. There are dozens to choose from and vi(or vim) is one of the most powerful around, so if you don;t like vim we will need to know what it is you want different. > Kindly suggest me a best free *text editor* ( i can code > and debug the code simultaneously ) *for python* based > on your experience. My personal experience is that I use vim for large projects and Pyhonwin(on Windows) or IDLE for small projects. I also use Scite and Eclipse/PyDev occasionally. PyDev has one of the best debuggers if that is important to you, but in Python heavy duty debugging is rarely needed IME HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From a.t.hofkamp at tue.nl Tue Mar 24 10:32:57 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 24 Mar 2009 10:32:57 +0100 Subject: [Tutor] text editor and debugger for python In-Reply-To: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Message-ID: <49C8A8C9.3070508@tue.nl> Bala subramanian wrote: > Friends, > > I do the scripting in Linux. I use vi editor to code. It is not very > convenient for me. Kindly suggest me a best free *text editor* ( i can code > and debug the code simultaneously ) *for python* based on your experience. *best* means something different for everybody. If you'd ask me, I'd say vim, but apparently, you don't agree with that view :) The best approach I found to such problems is to simply install and try several editors until you find one that you like. Then use that program until you get annoyed by something it doesn't do right, or until you find a better alternative. As for actual choices, you can have a look at gedit kate kwrite emacs If you want something IDE-ish: IDLE (assuming it runs at Linux), Eclipse and many more (google will know). emacs and Eclipse are really big systems. Sincerely, Albert From anja.r.hofmann at web.de Tue Mar 24 11:21:11 2009 From: anja.r.hofmann at web.de (Anja Hofmann) Date: Tue, 24 Mar 2009 11:21:11 +0100 Subject: [Tutor] text editor and debugger for python Message-ID: <2059675989@web.de> Hi! # I do the scripting in Linux. I use vi editor to code. It is not very # convenient for me. Kindly suggest me a best free *text editor* ( i # can code and debug the code simultaneously ) *for python* based on # your experience. How about jedit (http://www.jedit.org/)? - CUA-compliant, i.e. it uses the same keybindings as most Linux and Windows applications (except vi and Emacs). - open source and written in Java - there are several plugins for Python, for example JPyDebug and PythonClient (see http://plugins.jedit.org/list.php?category=6) The only problem might be the amount of memory available: jedit works fine on my Linux (Ubuntu 8.04) laptop with 512 MB of memory, but I haven't tested it on less recent computers. In case you've got any more questions, feel free to email me. Best regards, Anja Hofmann From d.conca at gmail.com Tue Mar 24 12:07:08 2009 From: d.conca at gmail.com (Daniele) Date: Tue, 24 Mar 2009 12:07:08 +0100 Subject: [Tutor] (no subject) Message-ID: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> > ---------- Messaggio inoltrato ---------- > Jared White wrote: > >> ? ? ?********** >> ? ?********* ? ? ?I cant get a code to work for this bottom half, ?Can anyone help me Hi Jared, try this: for i in range(-10,11): print '*'*(11-abs(i)) From alan.gauld at btinternet.com Tue Mar 24 13:46:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Mar 2009 12:46:20 -0000 Subject: [Tutor] (no subject) References: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> Message-ID: "Daniele" wrote >>> ********* I cant get a code to work for this bottom half, Can anyone >>> help me OK, since we've started giving solutions... > Hi Jared, try this: > > for i in range(-10,11): > print '*'*(11-abs(i)) This is simpler using for n in range (10,0,-1): print '*' * n HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 24 13:54:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Mar 2009 12:54:03 -0000 Subject: [Tutor] (no subject) References: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> Message-ID: "Daniele" wrote > for i in range(-10,11): > print '*'*(11-abs(i)) Apologies, this is actually more powerful than my solution which only addressed the immediate concern of printing decreasing lines. This of course covers both sides of the triangle. It was only when I thought that it should be possible to do both in one loop that I came up with the same solution! :-) The question for Jared is do you understand how it works? That is probably more important than getting it to work! Alan G From simozack at yahoo.it Tue Mar 24 13:54:44 2009 From: simozack at yahoo.it (simozack) Date: Tue, 24 Mar 2009 13:54:44 +0100 Subject: [Tutor] text editor and debugger for python In-Reply-To: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Message-ID: <4a815f2d0903240554s73b96095s8e4f2943f3784d23@mail.gmail.com> 2009/3/24, Bala subramanian : > I do the scripting in Linux. I use vi editor to code. It is not very > convenient for me. Kindly suggest me a best free text editor ( i can code > and debug the code simultaneously ) for python based on your experience. Perhaps you don't have some configurations useful to write python programs. Search on Google "python vim". For example, on Windows, I think this options are very useful (add this at the bottom of your .vimrc file to try it out): syntax on filetype plugin indent on autocmd FileType python setlocal sw=4 sts=4 et sta HTH, Simone From padhu.47 at gmail.com Tue Mar 24 13:57:33 2009 From: padhu.47 at gmail.com (Padmanaban Ganesan) Date: Tue, 24 Mar 2009 18:27:33 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> Message-ID: <8aa4df020903240557x589a7eabu1c0e8bfd8a497214@mail.gmail.com> Hi Alan, I am sorry , some how how i missed it . code you pls explain this. for i in range(-10,11): print '*'*(11-abs(i)) thanks indeed 2009/3/24 Alan Gauld > "Daniele" wrote > >> for i in range(-10,11): >> print '*'*(11-abs(i)) >> > > Apologies, this is actually more powerful than my solution which only > addressed the immediate concern of printing decreasing lines. This of > course covers both sides of the triangle. > It was only when I thought that it should be possible to do both in one > loop that I came up with the same solution! :-) > > The question for Jared is do you understand how it works? > That is probably more important than getting it to work! > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Ta, Paddy "The Secret to creativity is knowing how to hide your sources " -------------- next part -------------- An HTML attachment was scrubbed... URL: From padhu.47 at gmail.com Tue Mar 24 14:29:06 2009 From: padhu.47 at gmail.com (Padmanaban Ganesan) Date: Tue, 24 Mar 2009 18:59:06 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> Message-ID: <8aa4df020903240629r61018e6dp9cbd79a18e60dad2@mail.gmail.com> Really a splendid code snippet. Could any one explain me whats this in it .... abs(i)....??? 2009/3/24 Alan Gauld > "Daniele" wrote > >> for i in range(-10,11): >> print '*'*(11-abs(i)) >> > > Apologies, this is actually more powerful than my solution which only > addressed the immediate concern of printing decreasing lines. This of > course covers both sides of the triangle. > It was only when I thought that it should be possible to do both in one > loop that I came up with the same solution! :-) > > The question for Jared is do you understand how it works? > That is probably more important than getting it to work! > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Ta, Paddy "The Secret to creativity is knowing how to hide your sources " -------------- next part -------------- An HTML attachment was scrubbed... URL: From padhu.47 at gmail.com Tue Mar 24 14:31:50 2009 From: padhu.47 at gmail.com (Padmanaban Ganesan) Date: Tue, 24 Mar 2009 19:01:50 +0530 Subject: [Tutor] (no subject) In-Reply-To: <8aa4df020903240629r61018e6dp9cbd79a18e60dad2@mail.gmail.com> References: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> <8aa4df020903240629r61018e6dp9cbd79a18e60dad2@mail.gmail.com> Message-ID: <8aa4df020903240631r5b489bd8nf3c64bd20e8ea6fe@mail.gmail.com> Ok i got it. thanks all 2009/3/24 Padmanaban Ganesan > Really a splendid code snippet. > > Could any one explain me whats this in it .... abs(i)....??? > > 2009/3/24 Alan Gauld > >> "Daniele" wrote >> >>> for i in range(-10,11): >>> print '*'*(11-abs(i)) >>> >> >> Apologies, this is actually more powerful than my solution which only >> addressed the immediate concern of printing decreasing lines. This of >> course covers both sides of the triangle. >> It was only when I thought that it should be possible to do both in one >> loop that I came up with the same solution! :-) >> >> The question for Jared is do you understand how it works? >> That is probably more important than getting it to work! >> >> Alan G >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Ta, > Paddy > "The Secret to creativity is knowing how to hide your sources " > -- Ta, Paddy "The Secret to creativity is knowing how to hide your sources " -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 24 14:33:40 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 24 Mar 2009 13:33:40 +0000 (GMT) Subject: [Tutor] (no subject) References: <537341c70903240407s7320a5bbje6d90aad16bc4404@mail.gmail.com> <8aa4df020903240557x589a7eabu1c0e8bfd8a497214@mail.gmail.com> Message-ID: <404090.23110.qm@web86703.mail.ird.yahoo.com> > I am sorry , some how how i missed it . code you pls explain this. > for i in range(-10,11): > print '*'*(11-abs(i)) OK, the range() function returns a list of numbers from -10 to +10. the for loop assigns i to each value in turn The print statement prints out the asterisk repeated (11-abs(i)) times abs(i) returns the positive value of i. This means abs(i) will take the values 10,9,8,7,....2,1,0,1,2,...8,9,10 So 11-abs(i) will take the values 1,2,3,4,...9,10,11,10,9,...3,2,1 This prints out the desired triangular pattern. Does that make sense? You can explore this at the >>> prompt quite easily (I'll use a smaller range of values...): >>> range(-3,4) [-3, -2, -1, 0, 1, 2, 3] >>> for n in range(-3,4): ... print abs(n) ... 3 2 1 0 1 2 3 >>> for n in range(-3,4): ... print 4-abs(n) ... 1 2 3 4 3 2 1 >>> for n in range(-3,4): ... print '*' * (4-abs(n)) ... * ** *** **** *** ** * HTH, Alan G. http://www.alan-g.me.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From d.conca at gmail.com Tue Mar 24 15:06:25 2009 From: d.conca at gmail.com (Daniele) Date: Tue, 24 Mar 2009 15:06:25 +0100 Subject: [Tutor] (no subject) Message-ID: <537341c70903240706x73245197u7b9a2e246fc7215f@mail.gmail.com> > From:?Padmanaban Ganesan > Subject:?Re: [Tutor] (no subject) > Could any one explain me whats this in it .... abs(i)....??? >>> for i in range(-10,11): >>> ? print '*'*(11-abs(i)) I'll try to explain it: with the first line you are looping through all integer from i = -10 to 10 the idea is to use i as the number of * for each line. using print '*' * i will print * exactly i times. so one could write for i in range(-10,11): print '*'*i but this will not work for negative values of i, so we use abs(i) (i.e. the absolute value of i). Now for i in range(-10,11): print '*'*abs(i) will produce ********** ********* ******** ******* ****** ***** **** *** ** * * ** *** **** ***** ****** ******* ******** ********* ********** which is not quite what we want, and that's the reason of the 11-abs(i) part.: for i in range(-10,11): print '*' * (11-abs(i)) so, for example, when i=-10 (the first line) we want only 1 *, and in fact 11-abs(i) = 11-abs(-10) = 11-10 = 1, so we get print '*' * 1. when i = -9 the expression gives 2, and so on. with i = 0 we get 11 * and we start then going down as for i = 1 we have 10 *, for i=2 we have 9 * and so on until i=10 which gives 1 *. Hope my english was clear enough :( From hihiren1 at gmail.com Tue Mar 24 15:33:43 2009 From: hihiren1 at gmail.com (Kumar) Date: Tue, 24 Mar 2009 20:03:43 +0530 Subject: [Tutor] Difference between SimpleCookie and SmartCookie Message-ID: Hello, I am new to python. I just came to know about this classes SimpleCookie and SmartCookie. I could get that usage. But I didn't get the difference between these classes? Can anybody please tell me what is the difference between this classes? -Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Tue Mar 24 16:14:28 2009 From: david at abbottdavid.com (David) Date: Tue, 24 Mar 2009 11:14:28 -0400 Subject: [Tutor] (no subject) In-Reply-To: <8aa4df020903232327p335145d4k25b26324a0367bc3@mail.gmail.com> References: <9239372b0903231530s8bb538aja5a2a2b9f8f2b489@mail.gmail.com> <49C8451C.30408@abbottdavid.com> <8aa4df020903232327p335145d4k25b26324a0367bc3@mail.gmail.com> Message-ID: <49C8F8D4.7060605@abbottdavid.com> Padmanaban Ganesan wrote: > Hello David, > > Please try this ..... I hope this answered your question now. > > SAM PRG: > ---------------- > def main(): > i=1 > while i <=10: > j=1 > while j<=i: > print 'Paddy' , > j=j+1 > print > i=i+1 > > def rev(): > i=10 > while i >=1: > print 'Paddy' , > print > i=i-1 > main() > rev () > > O/P: > ------- > > Paddy > Paddy Paddy > Paddy Paddy Paddy > Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy Paddy > Paddy Paddy Paddy Paddy > Paddy Paddy Paddy > Paddy Paddy > Paddy > > > please let me know if you need any other details. > > Ta, > Paddy > > " The Secret of Creativity is knowing to hide the source " > > > > > Here is how I did it; #!/usr/bin/python for i in range(10): print i*"*" for i in range(10-1, -1, -1): print i*"*" -- powered by Gentoo/GNU Linux http://linuxcrazy.com From kent37 at tds.net Tue Mar 24 16:20:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Mar 2009 11:20:44 -0400 Subject: [Tutor] Difference between SimpleCookie and SmartCookie In-Reply-To: References: Message-ID: <1c2a2c590903240820g53b2923kdc55abf49a83f8e9@mail.gmail.com> On Tue, Mar 24, 2009 at 10:33 AM, Kumar wrote: > I just came to know about this classes SimpleCookie and SmartCookie. > I could get that usage. But I didn't get the difference between these > classes? > Can anybody please tell me what is the difference between this classes? SmartCookie allows cookies to include objects other than strings. It uses the pickle module to serialize and deserialize the objects. You should never unpickle untrusted objects, it is a security hole. For this reason SmartCookie is not recommended and it is deprecated. Kent From emadnawfal at gmail.com Tue Mar 24 16:35:22 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Mar 2009 11:35:22 -0400 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? Message-ID: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? # The information provided herein about Swahili may not be accurate # it is just intended to illustrate the problem Hi Tutors, I would appreciate it if you gave me ideas about how to tackle this problem. Assigninig POS tags to words is a major step in many linguistic analyses. POS tags give the grammatical category of words, for example: The Determiner man Noun who RelativePronoun came Verb to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun What we usually do is train a Part-of-Speech Tagger, and then test it on an already tagged (gold standard) test set. After running the tagger, we get something like this: The Determiner Determiner man Noun PresentVerb who RelativePronoun RelativePronoun came Verb Verb to Preposition Preposition us AccusativePluralPronoun AccusativePluralPronoun is CopulaPresent CopulaPresent an Determiner Determiner engineer Noun Noun As can be seen from above, the POS tagger assigned the wrong Part of Speech to the word "man", and this makes it easy to calculate the POS tagger accuracy, simply 8 out of 9 are correct (88.8%). Swahili is a morphologically complex language. The same sentence above is usaually written as: theman whocametous isanengineer This means that we should run a word segmenter before running the POS tagger. The word segmenter of course makes mistakes which will affect the accuracy of the POS tagger. We get an output like the following where the second word (sic) is ill-segmented: # Segmenter + POS Tagger output file the Determiner whocame Noun to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun Now, how can I measure the accuracy of this output file against the gold standard file below given that the line alignment is lost every time the segmenter makes a mistake, which happens at the rate of 15 per 1000 words: # Gold Standard File The Determiner man Noun who RelativePronoun to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun Please note that the output file is usually in the range of 100,000 words -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Mar 24 16:45:01 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Mar 2009 11:45:01 -0400 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? Message-ID: <652641e90903240845w10436d9av9c86acedd4bb9b04@mail.gmail.com> Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? # The information provided herein about Swahili may not be accurate # it is just intended to illustrate the problem # The first message had an error. Sorry for that Hi Tutors, I would appreciate it if you gave me ideas about how to tackle this problem. Assigninig POS tags to words is a major step in many linguistic analyses. POS tags give the grammatical category of words, for example: The Determiner man Noun who RelativePronoun came Verb to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun What we usually do is train a Part-of-Speech Tagger, and then test it on an already tagged (gold standard) test set. After running the tagger, we get something like this: The Determiner Determiner man Noun PresentVerb who RelativePronoun RelativePronoun came Verb Verb to Preposition Preposition us AccusativePluralPronoun AccusativePluralPronoun is CopulaPresent CopulaPresent an Determiner Determiner engineer Noun Noun As can be seen from above, the POS tagger assigned the wrong Part of Speech to the word "man", and this makes it easy to calculate the POS tagger accuracy, simply 8 out of 9 are correct (88.8%). Swahili is a morphologically complex language. The same sentence above is usaually written as: theman whocametous isanengineer This means that we should run a word segmenter before running the POS tagger. The word segmenter of course makes mistakes which will affect the accuracy of the POS tagger. We get an output like the following where the second word (sic) is ill-segmented: # Segmenter + POS Tagger output file the Determiner man Noun whocame Noun to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun Now, how can I measure the accuracy of this output file against the gold standard file below given that the line alignment is lost every time the segmenter makes a mistake, which happens at the rate of 15 per 1000 words: # Gold Standard File The Determiner man Noun who RelativePronoun to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun Please note that the output file is usually in the range of 100,000 words -- -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Tue Mar 24 17:15:00 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 24 Mar 2009 10:15:00 -0600 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? In-Reply-To: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> References: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> Message-ID: <9356b9f30903240915u29de99b0gd83ca15a5845910e@mail.gmail.com> 2009/3/24 Emad Nawfal (???? ????) : > Evaluating Swahili Part of Speech Tagging. How can I write a Python script > for that? > # The information provided herein about Swahili may not be accurate > # it is just intended to illustrate the problem > Hello, Mr. Emad! Have you checked the NLTK (Natural Language Toolkit - http://www.nltk.org ) a Python package for Linguistics applications? Maybe they have something already implemented. I actually liked a lot their tutorials about python and using pythons for Linguistics. Very good explanations. From emadnawfal at gmail.com Tue Mar 24 17:17:57 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Mar 2009 12:17:57 -0400 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? In-Reply-To: <9356b9f30903240915u29de99b0gd83ca15a5845910e@mail.gmail.com> References: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> <9356b9f30903240915u29de99b0gd83ca15a5845910e@mail.gmail.com> Message-ID: <652641e90903240917t72a26ecfh770bbb15756551ac@mail.gmail.com> 2009/3/24 Eduardo Vieira > 2009/3/24 Emad Nawfal (???? ????) : > > Evaluating Swahili Part of Speech Tagging. How can I write a Python > script > > for that? > > # The information provided herein about Swahili may not be accurate > > # it is just intended to illustrate the problem > > > Hello, Mr. Emad! Have you checked the NLTK (Natural Language Toolkit - > http://www.nltk.org ) a Python package for Linguistics applications? > Maybe they have something already implemented. I actually liked a lot > their tutorials about python and using pythons for Linguistics. Very > good explanations. > I have checked the NLTK, and it does not seem to have something like this. Thanks for the suggestion though -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Tue Mar 24 17:41:23 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 24 Mar 2009 12:41:23 -0400 Subject: [Tutor] text editor and debugger for python In-Reply-To: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Message-ID: On Tue, Mar 24, 2009 at 5:08 AM, Bala subramanian wrote: > Friends, > > I do the scripting in Linux. I use vi editor to code. It is not very > convenient for me. Kindly suggest me a best free text editor ( i can code > and debug the code simultaneously ) for python based on your experience. > > Thanks > Bala > Hello Bala, I use the vim text editor to program in Python. Vim is very similar to vi. I use the following to make vim easier for programming (save as .vimrc) " .vimrc " " Created by Jeff Elkner 23 January 2006 " Last modified 2 February 2006 " " Turn on syntax highlighting and autoindenting syntax enable filetype indent on " set autoindent width to 4 spaces (see " http://www.vim.org/tips/tip.php?tip_id=83) set et set sw=4 set smarttab " set line number (added by bhaaluu) set nu " Bind key to running the python interpreter on the currently active " file. (courtesy of Steve Howell from email dated 1 Feb 2006). map :w\|!python % After saving the above file as .vimrc (dot vimrc) in your home directory (/home/bala/.vimrc <- for example) you can fire up vim and start programming in Python. Press the F2 function key to run your Python code. When the code completes its run, you are returned to vim for more coding. For debugging, I use print and raw_input(). I use print to watch variables. I use raw_input() to set breakpoints. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From emadnawfal at gmail.com Tue Mar 24 17:57:40 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Mar 2009 12:57:40 -0400 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? In-Reply-To: <652641e90903240917t72a26ecfh770bbb15756551ac@mail.gmail.com> References: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> <9356b9f30903240915u29de99b0gd83ca15a5845910e@mail.gmail.com> <652641e90903240917t72a26ecfh770bbb15756551ac@mail.gmail.com> Message-ID: <652641e90903240957i144ff707i903b1ae94c17ea48@mail.gmail.com> 2009/3/24 Emad Nawfal (???? ????) > > > 2009/3/24 Eduardo Vieira > > 2009/3/24 Emad Nawfal (???? ????) : >> > Evaluating Swahili Part of Speech Tagging. How can I write a Python >> script >> > for that? >> > # The information provided herein about Swahili may not be accurate >> > # it is just intended to illustrate the problem >> > >> Hello, Mr. Emad! Have you checked the NLTK (Natural Language Toolkit - >> http://www.nltk.org ) a Python package for Linguistics applications? >> Maybe they have something already implemented. I actually liked a lot >> their tutorials about python and using pythons for Linguistics. Very >> good explanations. >> > > > I have checked the NLTK, and it does not seem to have something like this. > Thanks for the suggestion though > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- > Thanks James, I'm using the TnT POS Tagger, and I treat it as a black box, otherwise I have to write my own, which is a huge task. The Segmenter I use is home-grown, and it is supposedly the best available. I used to evaluate on whole words, and this was easy. After the segmentation and tagging, I combined the various segments of each word, and this elimintaed the discrepancy in alignment. For example, I would have an output like this: the+man Det+Noun the+man Det+Noun who+came+to+us whocame+to+us It is easy to do it this way if you use a WORD_END_DELIMITER, but this is very tedious, and you have to recalculate the segment accuracy. I'm looking for something smarter than this. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 24 18:13:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Mar 2009 17:13:57 -0000 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I writea Python script for that? References: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> Message-ID: Hi, That was an interesting post, but I'm not sure what you want help with. Is it the word splitting? Is it writing the POS tagger? Is it comparing tthe POS tagger to the standard? Or all of these? Alan G. "Emad Nawfal (???? ????)" wrote in message news:652641e90903240835o610d013dsd6a81f4675c47c67 at mail.gmail.com... Evaluating Swahili Part of Speech Tagging. How can I write a Python script for that? # The information provided herein about Swahili may not be accurate # it is just intended to illustrate the problem Hi Tutors, I would appreciate it if you gave me ideas about how to tackle this problem. Assigninig POS tags to words is a major step in many linguistic analyses. POS tags give the grammatical category of words, for example: The Determiner man Noun who RelativePronoun came Verb to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun What we usually do is train a Part-of-Speech Tagger, and then test it on an already tagged (gold standard) test set. After running the tagger, we get something like this: The Determiner Determiner man Noun PresentVerb who RelativePronoun RelativePronoun came Verb Verb to Preposition Preposition us AccusativePluralPronoun AccusativePluralPronoun is CopulaPresent CopulaPresent an Determiner Determiner engineer Noun Noun As can be seen from above, the POS tagger assigned the wrong Part of Speech to the word "man", and this makes it easy to calculate the POS tagger accuracy, simply 8 out of 9 are correct (88.8%). Swahili is a morphologically complex language. The same sentence above is usaually written as: theman whocametous isanengineer This means that we should run a word segmenter before running the POS tagger. The word segmenter of course makes mistakes which will affect the accuracy of the POS tagger. We get an output like the following where the second word (sic) is ill-segmented: # Segmenter + POS Tagger output file the Determiner whocame Noun to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun Now, how can I measure the accuracy of this output file against the gold standard file below given that the line alignment is lost every time the segmenter makes a mistake, which happens at the rate of 15 per 1000 words: # Gold Standard File The Determiner man Noun who RelativePronoun to Preposition us AccusativePluralPronoun is CopulaPresent an Determiner engineer Noun Please note that the output file is usually in the range of 100,000 words -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emadnawfal at gmail.com Tue Mar 24 18:19:14 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Mar 2009 13:19:14 -0400 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I writea Python script for that? In-Reply-To: References: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> Message-ID: <652641e90903241019g31b5db06ne3ed0629714244b@mail.gmail.com> 2009/3/24 Alan Gauld > Hi, > That was an interesting post, but I'm not sure what you want help with. > Is it the word splitting? > Is it writing the POS tagger? > Is it comparing tthe POS tagger to the standard? > Or all of these? > > Alan G. > > "Emad Nawfal (???? ????)" wrote in message > news:652641e90903240835o610d013dsd6a81f4675c47c67 at mail.gmail.com... > > Evaluating Swahili Part of Speech Tagging. How can I write a Python script > for that? > # The information provided herein about Swahili may not be accurate > # it is just intended to illustrate the problem > > Hi Tutors, > I would appreciate it if you gave me ideas about how to tackle this > problem. > > > Assigninig POS tags to words is a major step in many linguistic analyses. > POS tags give the grammatical category of words, for example: > > The Determiner > man Noun > who RelativePronoun > came Verb > to Preposition > us AccusativePluralPronoun > is CopulaPresent > an Determiner > engineer Noun > > What we usually do is train a Part-of-Speech Tagger, and then test it on an > already tagged (gold standard) test set. After running the tagger, we get > something like this: > > The Determiner Determiner > man Noun PresentVerb > who RelativePronoun RelativePronoun > came Verb Verb > to Preposition Preposition > us AccusativePluralPronoun AccusativePluralPronoun > is CopulaPresent CopulaPresent > an Determiner Determiner > engineer Noun Noun > > As can be seen from above, the POS tagger assigned the wrong Part of Speech > to the word "man", and this makes it easy to calculate the POS tagger > accuracy, simply 8 out of 9 are correct (88.8%). > > Swahili is a morphologically complex language. The same sentence above is > usaually written as: > > theman whocametous isanengineer > > This means that we should run a word segmenter before running the POS > tagger. The word segmenter of course makes mistakes which will affect the > accuracy of the POS tagger. > We get an output like the following where the second word (sic) is > ill-segmented: > > # Segmenter + POS Tagger output file > the Determiner > whocame Noun > to Preposition > us AccusativePluralPronoun > is CopulaPresent > an Determiner > engineer Noun > > Now, how can I measure the accuracy of this output file against the gold > standard file below given that the line alignment is lost every time the > segmenter makes a mistake, which happens at the rate of 15 per 1000 words: > > # Gold Standard File > The Determiner > man Noun > who RelativePronoun > to Preposition > us AccusativePluralPronoun > is CopulaPresent > an Determiner > engineer Noun > > Please note that the output file is usually in the range of 100,000 words > Hi Alan, Comparing the POS tagger output to the standard. is what I want. I can do it if I combine the segments into words and the segment tags into complex tags, which is possible. BUT I'm wondering whether this can be done just using the segments. > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- > > > > > -------------------------------------------------------------------------------- > > > _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Mar 24 18:21:07 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Mar 2009 13:21:07 -0400 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging. How can I writea Python script for that? In-Reply-To: <652641e90903241019g31b5db06ne3ed0629714244b@mail.gmail.com> References: <652641e90903240835o610d013dsd6a81f4675c47c67@mail.gmail.com> <652641e90903241019g31b5db06ne3ed0629714244b@mail.gmail.com> Message-ID: <652641e90903241021u669b8f1fqbe5402f166553773@mail.gmail.com> 2009/3/24 Emad Nawfal (???? ????) > > > 2009/3/24 Alan Gauld > > Hi, >> That was an interesting post, but I'm not sure what you want help with. >> Is it the word splitting? >> Is it writing the POS tagger? >> Is it comparing tthe POS tagger to the standard? >> Or all of these? >> >> Alan G. >> >> "Emad Nawfal (???? ????)" wrote in message >> news:652641e90903240835o610d013dsd6a81f4675c47c67 at mail.gmail.com... >> >> Evaluating Swahili Part of Speech Tagging. How can I write a Python script >> for that? >> # The information provided herein about Swahili may not be accurate >> # it is just intended to illustrate the problem >> >> Hi Tutors, >> I would appreciate it if you gave me ideas about how to tackle this >> problem. >> >> >> Assigninig POS tags to words is a major step in many linguistic analyses. >> POS tags give the grammatical category of words, for example: >> >> The Determiner >> man Noun >> who RelativePronoun >> came Verb >> to Preposition >> us AccusativePluralPronoun >> is CopulaPresent >> an Determiner >> engineer Noun >> >> What we usually do is train a Part-of-Speech Tagger, and then test it on >> an >> already tagged (gold standard) test set. After running the tagger, we get >> something like this: >> >> The Determiner Determiner >> man Noun PresentVerb >> who RelativePronoun RelativePronoun >> came Verb Verb >> to Preposition Preposition >> us AccusativePluralPronoun AccusativePluralPronoun >> is CopulaPresent CopulaPresent >> an Determiner Determiner >> engineer Noun Noun >> >> As can be seen from above, the POS tagger assigned the wrong Part of >> Speech >> to the word "man", and this makes it easy to calculate the POS tagger >> accuracy, simply 8 out of 9 are correct (88.8%). >> >> Swahili is a morphologically complex language. The same sentence above is >> usaually written as: >> >> theman whocametous isanengineer >> >> This means that we should run a word segmenter before running the POS >> tagger. The word segmenter of course makes mistakes which will affect the >> accuracy of the POS tagger. >> We get an output like the following where the second word (sic) is >> ill-segmented: >> >> # Segmenter + POS Tagger output file >> the Determiner >> whocame Noun >> to Preposition >> us AccusativePluralPronoun >> is CopulaPresent >> an Determiner >> engineer Noun >> >> Now, how can I measure the accuracy of this output file against the gold >> standard file below given that the line alignment is lost every time the >> segmenter makes a mistake, which happens at the rate of 15 per 1000 words: >> >> # Gold Standard File >> The Determiner >> man Noun >> who RelativePronoun >> to Preposition >> us AccusativePluralPronoun >> is CopulaPresent >> an Determiner >> engineer Noun >> >> Please note that the output file is usually in the range of 100,000 words >> > Hi Alan, > Comparing the POS tagger output to the standard. is what I want. I can do > it if I combine the segments into words and the segment tags into complex > tags, which is possible. > BUT I'm wondering whether this can be done just using the segments. > >> Hi Alan, Comparing the POS tagger output to the standard. is what I want. I can do it if I combine the segments into words and the segment tags into complex tags, which is possible. BUT I'm wondering whether this can be done just using the segments and their respective simple tags. > >> -- >> ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? >> ??????? >> "No victim has ever been more repressed and alienated than the truth" >> >> Emad Soliman Nawfal >> Indiana University, Bloomington >> -------------------------------------------------------- >> >> >> >> >> -------------------------------------------------------------------------------- >> >> >> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From jecarnell at saintfrancis.com Tue Mar 24 19:02:31 2009 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Tue, 24 Mar 2009 13:02:31 -0500 Subject: [Tutor] Evaluating Swahili Part of Speech Tagging In-Reply-To: Message-ID: Ok I think I understand now (maybe?) #=============== Current Version ====================== # Segmenter + POS Tagger output file # Gold Standard File the Determiner = The Determiner whocame Noun != man Noun to Preposition != who RelativePronoun us AccusativePluralPronoun != to Preposition is CopulaPresent != us AccusativePluralPronoun an Determiner != is CopulaPresent engineer Noun != an Determiner != engineer Noun correct 1 numErrorSegments 1 ErrorSegmentLength 7 #=============== Corrected Version ====================== # Segmenter + POS Tagger output file # Gold Standard File the Determiner = The Determiner whocame Noun != man Noun != who RelativePronoun to Preposition = to Preposition us AccusativePluralPronoun = us AccusativePluralPronoun is CopulaPresent = is CopulaPresent an Determiner = an Determiner engineer Noun = engineer Noun correct 6 numErrorSegments 1 ErrorSegmentLength 2 From tim at johnsons-web.com Tue Mar 24 21:45:36 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 24 Mar 2009 12:45:36 -0800 Subject: [Tutor] Python Logo Message-ID: <200903241245.37025.tim@johnsons-web.com> Hi Folks: My company is setting up a new website, like to have a python logo on it. Can anyone recommed a logo that would be legal for us to use? Thanks Tim From kent37 at tds.net Tue Mar 24 22:30:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Mar 2009 17:30:36 -0400 Subject: [Tutor] Python Logo In-Reply-To: <200903241245.37025.tim@johnsons-web.com> References: <200903241245.37025.tim@johnsons-web.com> Message-ID: <1c2a2c590903241430l4a692447lc8016352ff711e3@mail.gmail.com> On Tue, Mar 24, 2009 at 4:45 PM, Tim Johnson wrote: > Hi Folks: > My company is setting up a new website, like to have a python logo > on it. Can anyone recommed a logo that would be legal for us to > use? http://www.python.org/community/logos/ Kent From kent37 at tds.net Tue Mar 24 22:35:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Mar 2009 17:35:05 -0400 Subject: [Tutor] Fwd: swapping lines between files In-Reply-To: <288df32a0903240823u7ed9a531o79f545975d5e71f6@mail.gmail.com> References: <288df32a0903230939i655445d0td4b0114dfee3440@mail.gmail.com> <1c2a2c590903231042k62e9a069s6d6293e4702ba79d@mail.gmail.com> <288df32a0903240823u7ed9a531o79f545975d5e71f6@mail.gmail.com> Message-ID: <1c2a2c590903241435r42c0db2bif7b485a87a7d00c2@mail.gmail.com> Forwarding to the list ---------- Forwarded message ---------- From: Bala subramanian Date: Tue, Mar 24, 2009 at 11:23 AM Subject: Re: [Tutor] swapping lines between files To: Kent Johnson Hai Kent, Thank you. I tried the same zip with a list and a file, instead of just two files. It works fine. But now i am stuck in overwriting the input file with value. What i want to do ? I have 3 files file 1???????? file2???????? file3 1??? 20.22???? 22? 22.22?????? 56? 66.77 2??? 21.24???? 20? 34.56?????? 44? 66.55 3??? 33.33???? 22? 35.77?????? 22? 45.66 Now i have a list all =[ [5,10,13], [44,56,77], [55,67,78]] file 1????????????? file 2????????????? file 3 5???? 20.22????? 44? 22.22?????? 55? 66.77 10??? 21.24???? 56? 34.56?????? 67? 66.55 13??? 33.33???? 77? 35.77?????? 78? 45.66 I am replacing the first position in file with the values in the list. The following worked for me, rmsd=argv[1:] for n in range(3): ?????? infile=open(rmsd[n]) ? ?? ? for x, y in zip(all[n],infile): ?????????? yitem=y.split() ?????????? yitem[0]=str(x) ?????????? print yitem But now i simply want to overwrite the input files. I am stuck here because when i create a filelist like the following, file_list=FileInput(rmsd,inplace=1) print file_list Now file_list is not a list to loop but a fileinput object, so i am stuck in looping this and my list all simultaneously. Bala On Mon, Mar 23, 2009 at 6:42 PM, Kent Johnson wrote: > > On Mon, Mar 23, 2009 at 12:39 PM, Bala subramanian > wrote: > > Dear Friends, > > > > Thanks for your replies for my previous mail. > > > > I have two files as follows. > > > > file 1???????? file2 > > 200?????????? 1???????? 3.55 > > 210?????????? 2???????? 4.55 > > 242?????????? 3???????? 1.22 > > 248?????????? 4???????? 3.10 > > 256??????????? 5??????? 1.11 > > > > Now i have to replace 1,2,3,4,5 in file 2 with 200,210,242,248,256 in file1. > > Simply replacing position 1 in file2 with values in file1. Can i do it with > > zip function, if yes how to do it. Here both files contain same number of > > lines. > > You can use zip() to combine the lines of the files. itertools.izip() > might be a better choice because it doesn't read the entire file at > once. Something like this (untested): > > from itertools import izip > file2 = open(...) > out = open(..., 'w') # output file > for line1, line2 in izip(file1, file2): > ?# now create a line that merges the two and write it > ?line1 = line1.strip() ?# remove newline > ?line2items = line2.split() > ?line2items[0] = line1 > ?newLine = '\t'.join(line2items) > ?out.write(newLine) > ?out.write('\n') > out.close() > > Kent From dkuhlman at rexx.com Tue Mar 24 23:21:12 2009 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 24 Mar 2009 15:21:12 -0700 Subject: [Tutor] text editor and debugger for python In-Reply-To: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> Message-ID: <20090324222112.GA32840@cutter.rexx.com> On Tue, Mar 24, 2009 at 10:08:51AM +0100, Bala subramanian wrote: > Friends, > > I do the scripting in Linux. I use vi editor to code. It is not very > convenient for me. Kindly suggest me a best free *text editor* ( i can code > and debug the code simultaneously ) *for python* based on your experience. > If you are looking for an IDE, you may want to look at Eric. http://eric-ide.python-projects.org/index.html On Ubuntu it's installable with one of the apt tools or a package manager. There is also kdevelop. For a text editor, you may also want to look at Jed, emacs, Kate, Joe, ... They are all installable on Ubuntu Debian GNU/Linux. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From mobiledreamers at gmail.com Tue Mar 24 23:24:52 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 24 Mar 2009 15:24:52 -0700 Subject: [Tutor] text editor and debugger for python In-Reply-To: <20090324222112.GA32840@cutter.rexx.com> References: <288df32a0903240208v27dbc500x1e229cb81d3edfea@mail.gmail.com> <20090324222112.GA32840@cutter.rexx.com> Message-ID: editor:Emacs, vi, Debugger: ipython -- Bidegg worlds best auction site http://bidegg.com On Tue, Mar 24, 2009 at 3:21 PM, Dave Kuhlman wrote: > On Tue, Mar 24, 2009 at 10:08:51AM +0100, Bala subramanian wrote: > > Friends, > > > > I do the scripting in Linux. I use vi editor to code. It is not very > > convenient for me. Kindly suggest me a best free *text editor* ( i can > code > > and debug the code simultaneously ) *for python* based on your > experience. > > > > If you are looking for an IDE, you may want to look at Eric. > > http://eric-ide.python-projects.org/index.html > > On Ubuntu it's installable with one of the apt tools or a package > manager. > > There is also kdevelop. > > For a text editor, you may also want to look at Jed, emacs, Kate, > Joe, ... They are all installable on Ubuntu Debian GNU/Linux. > > - Dave > > > -- > Dave Kuhlman > http://www.rexx.com/~dkuhlman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mobiledreamers at gmail.com Tue Mar 24 23:26:56 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 24 Mar 2009 15:26:56 -0700 Subject: [Tutor] Python Logo In-Reply-To: <1c2a2c590903241430l4a692447lc8016352ff711e3@mail.gmail.com> References: <200903241245.37025.tim@johnsons-web.com> <1c2a2c590903241430l4a692447lc8016352ff711e3@mail.gmail.com> Message-ID: http://img99.imageshack.us/img99/5422/webpy.png -- Bidegg worlds best auction site http://bidegg.com On Tue, Mar 24, 2009 at 2:30 PM, Kent Johnson wrote: > On Tue, Mar 24, 2009 at 4:45 PM, Tim Johnson wrote: > > Hi Folks: > > My company is setting up a new website, like to have a python logo > > on it. Can anyone recommed a logo that would be legal for us to > > use? > > http://www.python.org/community/logos/ > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Wed Mar 25 04:28:23 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 24 Mar 2009 19:28:23 -0800 Subject: [Tutor] Python Logo In-Reply-To: <1c2a2c590903241430l4a692447lc8016352ff711e3@mail.gmail.com> References: <200903241245.37025.tim@johnsons-web.com> <1c2a2c590903241430l4a692447lc8016352ff711e3@mail.gmail.com> Message-ID: <200903241928.23345.tim@johnsons-web.com> On Tuesday 24 March 2009, Kent Johnson wrote: > On Tue, Mar 24, 2009 at 4:45 PM, Tim Johnson wrote: > > Hi Folks: > > My company is setting up a new website, like to have a python logo > > on it. Can anyone recommed a logo that would be legal for us to > > use? > > http://www.python.org/community/logos/ thanks a lot! cheers tim From hihiren1 at gmail.com Wed Mar 25 05:35:46 2009 From: hihiren1 at gmail.com (Kumar) Date: Wed, 25 Mar 2009 10:05:46 +0530 Subject: [Tutor] Difference between SimpleCookie and SmartCookie In-Reply-To: <1c2a2c590903240820g53b2923kdc55abf49a83f8e9@mail.gmail.com> References: <1c2a2c590903240820g53b2923kdc55abf49a83f8e9@mail.gmail.com> Message-ID: Thanks a lot for the reply Kent . Could you please tell me If I will try to move from SmartCookie to SimpleCokkie in out application, what precautions should I take care? -Thanks Kumar On Tue, Mar 24, 2009 at 8:50 PM, Kent Johnson wrote: > On Tue, Mar 24, 2009 at 10:33 AM, Kumar wrote: > > I just came to know about this classes SimpleCookie and SmartCookie. > > I could get that usage. But I didn't get the difference between these > > classes? > > Can anybody please tell me what is the difference between this classes? > > SmartCookie allows cookies to include objects other than strings. It > uses the pickle module to serialize and deserialize the objects. > > You should never unpickle untrusted objects, it is a security hole. > For this reason SmartCookie is not recommended and it is deprecated. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lavendula6654 at yahoo.com Wed Mar 25 05:48:35 2009 From: lavendula6654 at yahoo.com (Elaine) Date: Tue, 24 Mar 2009 21:48:35 -0700 (PDT) Subject: [Tutor] Python and Ajax classes at Foothill College Message-ID: <901878.34047.qm@web31301.mail.mud.yahoo.com> Foothill College is offering two courses of interest to web application software developers: Ajax and Python. These 11- week courses are held weekday evenings from April through June at the Middlefield campus in Palo Alto. If you would like to learn Application Software Development with Ajax, the course meets Wednesday evenings, 6:00 pm - 9:40 pm. The course is designed for students who are already familiar with some type of programming, and have introductory knowledge of JavaScript and html. For more information, go to: http://www.foothill.edu/schedule/schedule.php and choose Department: ?COIN?, quarter: ?Spring 2009?, and course number ?71?. If you would like to learn Python, the course meets Monday evenings and is also designed for students who are familiar with some type of programming. We will use the textbook ?Core Python? by Wesley Chun, and part of the work of the course will involve an authentic team project. For more information, go to: http://www.foothill.edu/schedule/schedule.php and choose Department: ?CIS?, quarter: ?Spring 2009?, and course number ?68K?. If you would like to sign up for a class, please register beforehand by going to: http://www.foothill.fhda.edu/reg/index.php If you do not register ahead of time, the class you want may be cancelled! If you have questions, you can contact the instructor at: haightElaine at foothill.edu From kent37 at tds.net Wed Mar 25 11:40:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Mar 2009 06:40:42 -0400 Subject: [Tutor] Python Logo In-Reply-To: References: <200903241245.37025.tim@johnsons-web.com> <1c2a2c590903241430l4a692447lc8016352ff711e3@mail.gmail.com> Message-ID: <1c2a2c590903250340r43f442b3gf00ba6d134d990f8@mail.gmail.com> On Tue, Mar 24, 2009 at 6:26 PM, wrote: > http://img99.imageshack.us/img99/5422/webpy.png That is the logo for web.py (a Python web framework), not for the Python language itself. http://luke.jottit.com/webpy_logo Kent From kent37 at tds.net Wed Mar 25 11:41:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Mar 2009 06:41:44 -0400 Subject: [Tutor] Difference between SimpleCookie and SmartCookie In-Reply-To: References: <1c2a2c590903240820g53b2923kdc55abf49a83f8e9@mail.gmail.com> Message-ID: <1c2a2c590903250341s31e9b6e8g2ce4dbdeb4fceb96@mail.gmail.com> On Wed, Mar 25, 2009 at 12:35 AM, Kumar wrote: > Thanks a lot for the reply Kent . > Could you please tell me If I will try to move from SmartCookie to > SimpleCokkie in out application, what precautions should I take care? Make sure that all the values in the Morsels are strings. Kent From cocoyeh at pacbell.net Wed Mar 25 15:52:39 2009 From: cocoyeh at pacbell.net (Coco Yeh) Date: Wed, 25 Mar 2009 07:52:39 -0700 (PDT) Subject: [Tutor] problem of windmill on ssl website Message-ID: <3113.61728.qm@web82203.mail.mud.yahoo.com> I have problem using windmill with a ssl website (https). The console output of looks like this: windmill ie https://www.example.org https://www.example.org is not a windmill argument. Sticking in functest registry. Server running... The browser does not go to the website, showing a tutor page instead. How can I resolve this? Warmest Regards, Coco -------------- next part -------------- An HTML attachment was scrubbed... URL: From suger_cube at hotmail.com Wed Mar 25 17:19:35 2009 From: suger_cube at hotmail.com (T) Date: Wed, 25 Mar 2009 12:19:35 -0400 Subject: [Tutor] Question about Python. Message-ID: Hi. I'm working on Paper, Rock, Scissors in Python. I need to make it a loop, and test the values (1, 2, 3, /Rock/Paper/Scissors) yet, but i'm kind of stuck. Could you help me? import random #Imports the random modual from the library. def main(): #First function. print 'Lets play Paper Rock Scissors!\n' print '1 For Rock\n2 For Paper\n3 For Scissors\n4 To Quit' number=raw_input ('What do you choose? ') #Gets users input. pc = ComputerChoice() PlayerChoice(number, pc) def ComputerChoice(): #Compuers function ComputerChoice = random.randrange(1, 4) #Computers random range. return ComputerChoice def PlayerChoice(number, CC): #Uses the users input & compares number = int(number) #With the computers. print "\n" if CC == 1 and number == 3: print 'Computer wins: Rock beats Scissors' elif CC == 1 and number == 2: print 'Player wins: Paper beats Rock' elif CC == 2 and number == 3: print 'Player wins: Scissors beat paper' elif CC == 3 and number == 1: print 'Player wins: Rock beats scissors' elif CC == 2 and number == 1: print 'Computer wins: Paper beats rock' elif CC == number: print '''Draw!''' #Trying it with 3 elif CC == 3 and number == 2: print 'Computer wins: Scissors beats rock' elif number == 4: print 'Goodbye' else: print CC print number if number != 4: print '\n' main() #Start of program main() _________________________________________________________________ Windows Live? SkyDrive: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_skydrive_032009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Wed Mar 25 17:46:07 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 25 Mar 2009 17:46:07 +0100 Subject: [Tutor] Question about Python. In-Reply-To: References: Message-ID: <49CA5FCF.9020801@tue.nl> T wrote: > Hi. > I'm working on Paper, Rock, Scissors in Python. > I need to make it a loop, and test the values (1, 2, 3, /Rock/Paper/Scissors) yet, but i'm kind of stuck. Could you help me? > > > import random #Imports the random modual from the library. > > def main(): #First function. > print 'Lets play Paper Rock Scissors!\n' > print '1 For Rock\n2 For Paper\n3 For Scissors\n4 To Quit' > number=raw_input ('What do you choose? ') #Gets users input. > pc = ComputerChoice() > PlayerChoice(number, pc) > > def ComputerChoice(): #Compuers function > ComputerChoice = random.randrange(1, 4) #Computers random range. > return ComputerChoice > > > def PlayerChoice(number, CC): #Uses the users input & compares In ComputerChoice(), you obtain the choice of the computer. In PlayerChoice() however, you do not obtain the player choice, but instead decide on the result. I would suggest to modify PlayerChoice() to just obtain the player choice (code which you now have in main()). Next write a new function that takes the computer choice and the player choice, and decides on the outcome. (that function should have 3 possible return values). Then in the main loop combine all three functions. The construct you should investigate seems the 'while' statement. (while the game is not decided, call the functions) Sincerely, Albert From alan.gauld at btinternet.com Wed Mar 25 18:57:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Mar 2009 17:57:16 -0000 Subject: [Tutor] Question about Python. References: Message-ID: "T" wrote > I'm working on Paper, Rock, Scissors in Python. > I need to make it a loop, and test the values > (1, 2, 3, /Rock/Paper/Scissors) yet, but i'm kind > of stuck. Could you help me? What exactly puzzles you? You know you need a loop so you presumably realize that you need to repeat some part of your program. What bit needs to be repeated? Is it the bit that you ask the platyer to choose a value? Or where the computer calculates a value? Or where you work out the result? Or all of these? And how many times, or until what condition, should it repeat? How will you detect that value? If you answer those questions you might start to see what needs to be done? There are a few commens on the code below: def main(): #First function. print 'Lets play Paper Rock Scissors!\n' print '1 For Rock\n2 For Paper\n3 For Scissors\n4 To Quit' number=raw_input ('What do you choose? ') #Gets users input. number sems a bit vague, this is actually the players choice. So call it PlayersChoice or some such descriptive name. Even just pc maybe - see below... pc = ComputerChoice() And pc seems an odd name to choose for ComputersChoice() Why not cc? PlayerChoice(number, pc) And this function doesn't actually return the players choice, it displays the result. So maybe DisplayResult wouldbe a better name? def ComputerChoice(): #Compuers function ComputerChoice = random.randrange(1, 4) #Computers random range. return ComputerChoice Its not a good idea to use a variable name the same as the function. This will prevent you using recursion (which you might not know about yet but is important later!) You could simply use 'choice', its shorter to type too! def PlayerChoice(number, CC): #Uses the users input & compares number = int(number) #With the computers. Its probably better to convert the number where you read it from the user - that way you can tell them they made a mistake and get a better response before you call this function. And the function can just expect a number as input. print "\n" if CC == 1 and number == 3: print 'Computer wins: Rock beats Scissors' elif CC == 1 and number == 2: print 'Player wins: Paper beats Rock' elif CC == 2 and number == 3: print 'Player wins: Scissors beat paper' elif CC == 3 and number == 1: print 'Player wins: Rock beats scissors' elif CC == 2 and number == 1: print 'Computer wins: Paper beats rock' elif CC == number: print '''Draw!''' #Trying it with 3 elif CC == 3 and number == 2: print 'Computer wins: Scissors beats rock' elif number == 4: print 'Goodbye' OK, This is stuff you probably want to take out and put beside the code for reading the user input. Its not really part of the game. In fact this might be what you use to terminate your loop? else: print CC print number if number != 4: print '\n' main() Looks like you discovered recursion already, although I suspect you don't know it yet? :-) #Start of program main() HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From alan.gauld at btinternet.com Wed Mar 25 19:03:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Mar 2009 18:03:49 -0000 Subject: [Tutor] problem of windmill on ssl website References: <3113.61728.qm@web82203.mail.mud.yahoo.com> Message-ID: "Coco Yeh" wrote >I have problem using windmill with a ssl website (https). > > The browser does not go to the website, showing a tutor page instead. > > How can I resolve this? My initial response was to say "ask on a windmill list," but, not having heard of windmill, I googled and discovered that this is a Python package on the Wiki. Although it is still in Beta. I think my initial response is probably still right, its a bit off mainstream for the tutor list. But somebody might be using it, you never know. http://www.getwindmill.com/documentation/mailing-lists Alan G. From tim at johnsons-web.com Wed Mar 25 19:13:19 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 25 Mar 2009 10:13:19 -0800 Subject: [Tutor] Python Logo In-Reply-To: <1c2a2c590903250340r43f442b3gf00ba6d134d990f8@mail.gmail.com> References: <200903241245.37025.tim@johnsons-web.com> <1c2a2c590903250340r43f442b3gf00ba6d134d990f8@mail.gmail.com> Message-ID: <200903251013.19982.tim@johnsons-web.com> On Wednesday 25 March 2009, you wrote: > On Tue, Mar 24, 2009 at 6:26 PM, wrote: > > http://img99.imageshack.us/img99/5422/webpy.png > > That is the logo for web.py (a Python web framework), not for the > Python language itself. > http://luke.jottit.com/webpy_logo All the same, I was glad to see it. I never knew about webpy, and now I do. Have found django and turbogears way too big for me. Now I will check out webpy. thanks to all tim From amit.pureenergy at gmail.com Wed Mar 25 22:13:24 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Thu, 26 Mar 2009 02:43:24 +0530 Subject: [Tutor] Using C in python Message-ID: what are the ways in which i can use C in python programs . I know there is SWIG bindings are there any other . Also Could anyone explain how Swig bindings work? -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Mar 25 22:36:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Mar 2009 17:36:40 -0400 Subject: [Tutor] Using C in python In-Reply-To: References: Message-ID: <1c2a2c590903251436g4a142bc3g75d625c6315ae5a2@mail.gmail.com> On Wed, Mar 25, 2009 at 5:13 PM, amit sethi wrote: > what are the ways in which i can use C in python programs . I know there is > SWIG bindings are there any other . Also Could anyone explain how Swig > bindings work? There are quite a few options: SIP, SWIG and ctypes (in the std lib) build wrappers for C libraries. http://www.scipy.org/Weave lets you include C++ in a Python module. boost::python wraps C++ libraries. Pyrex and Cython compile Python-like source code to C extensions. I haven't used any of these and can't tell you much about them. Google will get you more info. Kent From cfuller084 at thinkingplanet.net Wed Mar 25 20:34:03 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 25 Mar 2009 14:34:03 -0500 Subject: [Tutor] Using C in python In-Reply-To: References: Message-ID: <200903251434.03586.cfuller084@thinkingplanet.net> There's a section in the Python docs just on this topic: http://docs.python.org/extending/index.html There's probably also some stuff in the wiki, although I'm not familiar with anything specific: http://wiki.python.org/moin/ The SWIG documentation is extensive, and while not the user-friendliest, should get you started: http://www.swig.org/doc.html The quick intro to SWIG is that you create and "interface file" which defines how Python interfaces to your C code. In the braindead simple cases, this can be simply the header files with your function prototypes. In actual usage, it's a good deal more complicated, but the SWIG docs show you the way. Cheers On Wednesday 25 March 2009 16:13, amit sethi wrote: > what are the ways in which i can use C in python programs . I know there is > SWIG bindings are there any other . Also Could anyone explain how Swig > bindings work? From stefan_ml at behnel.de Wed Mar 25 23:36:16 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 25 Mar 2009 23:36:16 +0100 Subject: [Tutor] Using C in python In-Reply-To: References: Message-ID: amit sethi wrote: > what are the ways in which i can use C in python programs . Here is a short example that uses Cython to call a couple of C functions in OpenGL and libc ("math.h"). The functions are declared in the "cdef extern" blocks at the top. http://misc.slowchop.com/misc/browser/muckaround/cython-game-optimise-tutorial/fast_circles.pyx See: http://cython.org/ Stefan From alan.gauld at btinternet.com Thu Mar 26 01:13:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Mar 2009 00:13:30 -0000 Subject: [Tutor] Using C in python References: Message-ID: "amit sethi" wrote > what are the ways in which i can use C in python programs . You can't use C directly what you can do is access libraries written in C. In fact quite a few of the standard libraries are written that way. So it depends what you want to do. If you have C source code that you want to execute from Python you can either:: a) Build a library and create a Python wrapper so it looks like a module b) Build an executable file and call that using subprocess/popen etc c) If its one of the common C libraries or a Windows DLL you can probably use an existing framework to call it. For example ctypes will access a lot of stuff. If you want to execute Python code from a C program, you can do that too, but it doesn't sound like thats what you need? > SWIG bindings are there any other . Also Could anyone explain how Swig > bindings work? SWIG bindings just expose C code in the right format for Python to see the code as a Python module. Its slightly easier than doing it by hand in C because it automates what is a pretty brain dead repetitive process. ( I've only used SWIG with Tcl but I assume its a similar process for Python.) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Thu Mar 26 04:54:55 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 25 Mar 2009 20:54:55 -0700 Subject: [Tutor] Posting to Tkinter NG in new.gmane.org Message-ID: <49CAFC8F.6010107@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 26 09:50:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Mar 2009 08:50:00 -0000 Subject: [Tutor] Posting to Tkinter NG in new.gmane.org References: <49CAFC8F.6010107@sbcglobal.net> Message-ID: "Wayne Watson" wrote > My e-mail address is valid. Any ideas? I've compacted related Trash > folders, etc It should be news.gmane.org... Or is that just a typo? Alan G. From sierra_mtnview at sbcglobal.net Thu Mar 26 11:25:24 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 26 Mar 2009 03:25:24 -0700 Subject: [Tutor] Posting to Tkinter NG in new.gmane.org In-Reply-To: References: <49CAFC8F.6010107@sbcglobal.net> Message-ID: <49CB5814.4030905@sbcglobal.net> An HTML attachment was scrubbed... URL: From bala.biophysics at gmail.com Thu Mar 26 18:42:58 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Thu, 26 Mar 2009 18:42:58 +0100 Subject: [Tutor] printing files Message-ID: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> Friends, My files are like below file1 file2 Remark Remark ---- ----------- ---- ----------- I have huge number of such files. I want to concatenate all files in one huge file. I could do it with a script. But i want to omit the first line (ie Remark in each file) and concatenate. How to do the same ? flist=glob.glob(*.txt) out=open('all','w') for files in flist: handle=open(flist).readlines() print>>out, handle <-- Here i want to write only from second line. I dnt want to loop over handle here and putting all lines except the first one in another variable. Is there any fancy way of doing it. out.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Mar 26 18:56:10 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 26 Mar 2009 10:56:10 -0700 Subject: [Tutor] printing files In-Reply-To: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> References: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> Message-ID: <40af687b0903261056y5c5322ebsdce1ed1c6daa5c42@mail.gmail.com> On Thu, Mar 26, 2009 at 10:42 AM, Bala subramanian < bala.biophysics at gmail.com> wrote: > print>>out, handle <-- Here i want to write only from second line. I > dnt want to loop over handle here and putting all lines except the first one > in > another variable. Is there any > fancy way of doing it. > Without changing anything else, you could do it with a slice: flist=glob.glob(*.txt) > out=open('all','w') > > for files in flist: > handle=open(flist).readlines() > print>>out, handle[1:] # start with second item (indexes start at 0, > remember) and go to end > out.close() > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Mar 26 18:57:34 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 26 Mar 2009 10:57:34 -0700 Subject: [Tutor] printing files In-Reply-To: <40af687b0903261056y5c5322ebsdce1ed1c6daa5c42@mail.gmail.com> References: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> <40af687b0903261056y5c5322ebsdce1ed1c6daa5c42@mail.gmail.com> Message-ID: <40af687b0903261057o3477bfcbv50049f1f294d5fcb@mail.gmail.com> On Thu, Mar 26, 2009 at 10:56 AM, Marc Tompkins wrote: > Without changing anything else, you could do it with a slice: > You should probably also close your input files when you're done with them. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Mar 26 19:05:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Mar 2009 18:05:24 -0000 Subject: [Tutor] printing files References: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> Message-ID: "Bala subramanian" wrote > for files in flist: > handle=open(flist).readlines() > print>>out, handle print>>out, handle[1:] Should do it? You might need to handle line endings though... Alan G. From alan.gauld at btinternet.com Thu Mar 26 19:07:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Mar 2009 18:07:00 -0000 Subject: [Tutor] Posting to Tkinter NG in new.gmane.org References: <49CAFC8F.6010107@sbcglobal.net> <49CB5814.4030905@sbcglobal.net> Message-ID: "Wayne Watson" wrote > > My e-mail address is valid. Any ideas? I've compacted related Trash > folders, etc > > > It should be news.gmane.org... Or is that just a typo? In that case you probably need to tell us more. Can you read the group OK in TBird? What other settings are you using? I can't help much as I don't use TBird... Alan G From alan.gauld at btinternet.com Thu Mar 26 19:58:04 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 26 Mar 2009 18:58:04 +0000 (GMT) Subject: [Tutor] printing files References: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> <288df32a0903261111j73483454o4e3a4525934ddc26@mail.gmail.com> Message-ID: <171429.32553.qm@web86706.mail.ird.yahoo.com> Use '\n'.join(handle[1:]) It will create a string from your list with newline as separator. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Bala subramanian To: Alan Gauld Sent: Thursday, 26 March, 2009 6:11:59 PM Subject: Re: [Tutor] printing files yes you are right, When i use the following print>>out, handle[1:] In the out file, it saves the lines as a list rather than as a string. How to avoid this. Bala On Thu, Mar 26, 2009 at 7:05 PM, Alan Gauld wrote: "Bala subramanian" wrote for files in flist: handle=open(flist).readlines() print>>out, handle print>>out, handle[1:] Should do it? You might need to handle line endings though... Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Mar 26 20:31:17 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 26 Mar 2009 15:31:17 -0400 Subject: [Tutor] Posting to Tkinter NG in new.gmane.org In-Reply-To: References: <49CAFC8F.6010107@sbcglobal.net> <49CB5814.4030905@sbcglobal.net> Message-ID: <49CBD805.3090809@cfl.rr.com> Is this a news group or a list group. If it is a news group, you can't use your regular email. I use T-Bird and to subscribe to 'news groups' you must have access to a news group server. If you look under the news properties under servers, you must provide a news group server (NNTP). Your email server(usually POP) will not work. Robert Berman Alan Gauld wrote: > > "Wayne Watson" wrote > >> >> My e-mail address is valid. Any ideas? I've compacted related >> Trash folders, etc >> >> >> It should be news.gmane.org... Or is that just a typo? > > In that case you probably need to tell us more. > Can you read the group OK in TBird? > > What other settings are you using? > I can't help much as I don't use TBird... > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nbarnes at gmail.com Thu Mar 26 22:28:41 2009 From: nbarnes at gmail.com (NBarnes) Date: Thu, 26 Mar 2009 14:28:41 -0700 Subject: [Tutor] Updating Python on Mac OS X 10.5.6 Message-ID: I'm wanting to put together a simple helper application for a game (a better version of Dwarf Foreman for the highly addictive Dwarf Fortress). It seems like Python would be a good choice for such a relatively simple project, and I've been wanting to learn Python. But I'm not sure what version of Python to use or how to update my Macbook's Python framework. Idle claims that I have Python 2.5 (which seems reasonable), but I understand that we've since moved on to Python 2.6? And that Python 3.0 is out? Is 3.0 mature enough to support this sort of programming? From kent37 at tds.net Thu Mar 26 22:49:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Mar 2009 17:49:29 -0400 Subject: [Tutor] printing files In-Reply-To: <171429.32553.qm@web86706.mail.ird.yahoo.com> References: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com> <288df32a0903261111j73483454o4e3a4525934ddc26@mail.gmail.com> <171429.32553.qm@web86706.mail.ird.yahoo.com> Message-ID: <1c2a2c590903261449l5139d0ew83f534b12467fc3@mail.gmail.com> On Thu, Mar 26, 2009 at 2:58 PM, ALAN GAULD wrote: > Use '\n'.join(handle[1:]) > It will create a string from your list with newline as separator. The lines from readlines() include the newlines already. > When i use the following > > print>>out, handle[1:] > > In the out file, it saves the lines as a list rather than as a string. How > to avoid this. use out.writelines(handle[1:]) Kent From alan.gauld at btinternet.com Thu Mar 26 22:53:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Mar 2009 21:53:29 -0000 Subject: [Tutor] Updating Python on Mac OS X 10.5.6 References: Message-ID: "NBarnes" wrote > Fortress). It seems like Python would be a good choice for such a > relatively simple project, and I've been wanting to learn Python. > > seems reasonable), but I understand that we've since moved on to > Python 2.6? And that Python 3.0 is out? Is 3.0 mature enough to > support this sort of programming? I'd go with Python 2.6 for learning. Most tutorials are still either upgrading to v3 or stuck at v2. Once you are comfortable with 2 you can set a flag on v2.6 that will flag any v3 incompatibilities so that you can fix them and get used to the diffrences before finally moving to v3. And by that time most of the 3rd party tools etc will be ported too! HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Mar 27 02:01:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Mar 2009 01:01:13 -0000 Subject: [Tutor] printing files References: <288df32a0903261042v1c72228bw8b7ebbb26834523@mail.gmail.com><288df32a0903261111j73483454o4e3a4525934ddc26@mail.gmail.com><171429.32553.qm@web86706.mail.ird.yahoo.com> <1c2a2c590903261449l5139d0ew83f534b12467fc3@mail.gmail.com> Message-ID: "Kent Johnson" wrote > On Thu, Mar 26, 2009 at 2:58 PM, ALAN GAULD > wrote: >> Use '\n'.join(handle[1:]) >> It will create a string from your list with newline as separator. > > The lines from readlines() include the newlines already. Ah, OK, I couldn't remember if readlines stripped them off or not. >>> print>>out, handle[1:] >>> >>> In the out file, it saves the lines as a list rather than as a string. > use > out.writelines(handle[1:]) Or if you really want to use the print style print>>out, ''.join(handle[1:]) ie join the lines using an empty string. Alan G From bala.biophysics at gmail.com Fri Mar 27 12:46:14 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Fri, 27 Mar 2009 12:46:14 +0100 Subject: [Tutor] plotting with python Message-ID: <288df32a0903270446h6287146ej422087297680996d@mail.gmail.com> Friends, I am not sure if this forum is appropriate to ask question about a particular package. After getting suggestions from some of you for python based plotting, I have just started with matplotlib. I am bit confused with the relation between matplotlib and pylab. In the matplotlib homepage, example plots are shown with both * matplotlib.pyplot* and* pylab*. Inaddition within matplotlib, there is a module called *matplotlib.pylab* i) matplotlib and pylab -> both are same or different modules ?. Is there any advantage of using one over the other ? ii) Is it like i can plot the graphs with both matplotlib and pylab ? iii) can some kindly show me an example of ploting multy Y axes plot, ie NXY. Thanks in advance, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Mar 27 13:47:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Mar 2009 08:47:47 -0400 Subject: [Tutor] plotting with python In-Reply-To: <288df32a0903270446h6287146ej422087297680996d@mail.gmail.com> References: <288df32a0903270446h6287146ej422087297680996d@mail.gmail.com> Message-ID: <1c2a2c590903270547n2b093ce5x23bfa309821388a@mail.gmail.com> On Fri, Mar 27, 2009 at 7:46 AM, Bala subramanian wrote: > Friends, > I am not sure if this forum is appropriate to ask question about a > particular package. After getting suggestions from some of you for python > based plotting, I have just started with matplotlib. I am bit confused with > the relation between matplotlib and pylab. > > In the matplotlib homepage, example plots are shown with both > matplotlib.pyplot and pylab. Inaddition within matplotlib, there is a module > called matplotlib.pylab > > i) matplotlib and pylab -> both are same or different modules ?. Is there > any advantage of using one over the other ? > > ii) Is it like i can plot the graphs with both matplotlib and pylab ? IIUC, pylab is part of matplotlib. It provides a simplified, functional (not object-oriented) interface to matplotlib. Using matplotlib directly gives you more control over the result. > iii) can some kindly show me an example of ploting multy Y axes plot, ie NXY. Take a look at the gallery for something similar to what you want. Clicking on a gallery image will show you a larger image and the code that created it. http://matplotlib.sourceforge.net/gallery.html Kent From greg at thewhittiers.com Fri Mar 27 13:58:52 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 27 Mar 2009 08:58:52 -0400 Subject: [Tutor] plotting with python In-Reply-To: <288df32a0903270446h6287146ej422087297680996d@mail.gmail.com> References: <288df32a0903270446h6287146ej422087297680996d@mail.gmail.com> Message-ID: matplotlib and pylab are two APIs to the same library. Using matplotlib is a more object-oriented, pythonic API. pylab is modeled after the Matlab plotting functions to make it easier for those coming from that environment. There's a matplotlib mailing list and you can often figure out what you need from perusing the examples and the thumbnail gallery. In your case, I think http://matplotlib.sourceforge.net/examples/api/two_scales.html is what you want. On Fri, Mar 27, 2009 at 7:46 AM, Bala subramanian wrote: > Friends, > I am not sure if this forum is appropriate to ask question about a > particular package. After getting suggestions from some of you for python > based plotting, I have just started with matplotlib. I am bit confused with > the relation between matplotlib and pylab. > > In the matplotlib homepage, example plots are shown with both > matplotlib.pyplot and pylab. Inaddition within matplotlib, there is a module > called matplotlib.pylab > > i) matplotlib and pylab -> both are same or different modules ?. Is there > any advantage of using one over the other ? > > ii) Is it like i can plot the graphs with both matplotlib and pylab ? > > iii) can some kindly show me an example of ploting multy Y axes plot, ie > NXY. > > Thanks in advance, > Bala > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From sierra_mtnview at sbcglobal.net Fri Mar 27 18:30:40 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 27 Mar 2009 10:30:40 -0700 Subject: [Tutor] Left Alignment -- Tkinter Message-ID: <49CD0D40.5090508@sbcglobal.net> An HTML attachment was scrubbed... URL: From david at abbottdavid.com Fri Mar 27 18:31:05 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Mar 2009 13:31:05 -0400 Subject: [Tutor] Adding key, value to Dictionary Message-ID: <49CD0D59.6070704@abbottdavid.com> I am trying to make a simple Todo program and I can not get the dictionary to update. This works; #!/usr/bin/python key = 'Clean house' value = (1,2,3,4) todo = {key:value} value = (5,6,7,8) todo['Walk Dog'] = value print todo results {'Walk Dog': (5, 6, 7, 8), 'Clean house': (1, 2, 3, 4)} OK good But I can not get this to update after the first time it is ran. def get_todo(): todo = {} key = raw_input('Enter Todo Title: ') todo[key] = key print '\n', key, 'has been added.' print 'Next, enter date for Todo: ' curr_date = time.strftime('%Y %m %d', time.gmtime()) print 'Format as ', curr_date yr = int(raw_input('\nEnter Year: ')) mt = int(raw_input('Enter Month: ')) dy = int(raw_input('Enter Day: ')) hr = int(raw_input('Enter Hour (24h): ')) mn = int(raw_input('Enter Minute (01-59): ')) value = [yr, mt, dy, hr, mn] todo = {key:value} todo[key] = value print todo response = raw_input('Do you want to add another Todo? (y/n) ') if response == 'y': get_todo() else: print 'Goodbye' get_todo() results Enter Todo Title: Clean House Clean House has been added. Next, enter date for Todo: Format as 2009 03 27 Enter Year: 2009 Enter Month: 3 Enter Day: 27 Enter Hour (24h): 13 Enter Minute (01-59): 28 {'Clean House': [2009, 3, 27, 13, 28]} Do you want to add another Todo? (y/n) y Enter Todo Title: Walk Dog Walk Dog has been added. Next, enter date for Todo: Format as 2009 03 27 Enter Year: 2009 Enter Month: 3 Enter Day: 27 Enter Hour (24h): 14 Enter Minute (01-59): 35 {'Walk Dog': [2009, 3, 27, 14, 35]} Do you want to add another Todo? (y/n) Not so good:( -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From greg at thewhittiers.com Fri Mar 27 18:50:10 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 27 Mar 2009 13:50:10 -0400 Subject: [Tutor] Adding key, value to Dictionary In-Reply-To: <49CD0D59.6070704@abbottdavid.com> References: <49CD0D59.6070704@abbottdavid.com> Message-ID: On Fri, Mar 27, 2009 at 1:31 PM, David wrote: > But I can not get this to update after the first time it is ran. > > def get_todo(): > ? ?todo = {} This set todo to an empty dictionary each time you execute get_todo. > ? ?key = raw_input('Enter Todo Title: ') > ? ?todo[key] = key > ? ?print '\n', key, 'has been added.' > ? ?print 'Next, enter date for Todo: ' > ? ?curr_date = time.strftime('%Y %m %d', time.gmtime()) > ? ?print 'Format as ', curr_date > ? ?yr = int(raw_input('\nEnter Year: ')) > ? ?mt = int(raw_input('Enter Month: ')) > ? ?dy = int(raw_input('Enter Day: ')) > ? ?hr = int(raw_input('Enter Hour (24h): ')) > ? ?mn = int(raw_input('Enter Minute (01-59): ')) > ? ?value = [yr, mt, dy, hr, mn] > ? ?todo = {key:value} > ? ?todo[key] = value todo = {key:value} again resets the value of todo. You only need todo[key]=value. > ? ?print todo > ? ?response = raw_input('Do you want to add another Todo? (y/n) ') > ? ?if response == 'y': > ? ? ? ?get_todo() > ? ?else: > ? ? ? ?print 'Goodbye' > > get_todo() From sierra_mtnview at sbcglobal.net Fri Mar 27 18:50:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 27 Mar 2009 10:50:23 -0700 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <49CD0D40.5090508@sbcglobal.net> References: <49CD0D40.5090508@sbcglobal.net> Message-ID: <49CD11DF.9090208@sbcglobal.net> An HTML attachment was scrubbed... URL: From david at abbottdavid.com Fri Mar 27 18:52:14 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Mar 2009 13:52:14 -0400 Subject: [Tutor] Adding key, value to Dictionary In-Reply-To: <49CD0D59.6070704@abbottdavid.com> References: <49CD0D59.6070704@abbottdavid.com> Message-ID: <49CD124E.40307@abbottdavid.com> David wrote: > I am trying to make a simple Todo program and I can not get the > dictionary to update. > This works; > > #!/usr/bin/python > key = 'Clean house' > value = (1,2,3,4) > todo = {key:value} > value = (5,6,7,8) > todo['Walk Dog'] = value > print todo > > results > {'Walk Dog': (5, 6, 7, 8), 'Clean house': (1, 2, 3, 4)} > OK good I also thought this would work if I did not start out with a blank dictionary; def get_todo(): key = raw_input('Enter Todo Title: ') print '\n', key, 'has been added.' print 'Next, enter date for Todo: ' curr_date = time.strftime('%Y %m %d', time.gmtime()) print 'Format as ', curr_date yr = int(raw_input('\nEnter Year: ')) mt = int(raw_input('Enter Month: ')) dy = int(raw_input('Enter Day: ')) hr = int(raw_input('Enter Hour (24h): ')) mn = int(raw_input('Enter Minute (01-59): ')) value = [yr, mt, dy, hr, mn] todo = {key:value} todo[key] = value print todo response = raw_input('Do you want to add another Todo? (y/n) ') if response == 'y': get_todo() else: print 'Goodbye' get_todo() same result -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From david at abbottdavid.com Fri Mar 27 19:05:42 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Mar 2009 14:05:42 -0400 Subject: [Tutor] Adding key, value to Dictionary In-Reply-To: References: <49CD0D59.6070704@abbottdavid.com> Message-ID: <49CD1576.2030207@abbottdavid.com> greg whittier wrote: > On Fri, Mar 27, 2009 at 1:31 PM, David wrote: >> But I can not get this to update after the first time it is ran. >> >> def get_todo(): >> todo = {} moved todo{} outside of the function > > This set todo to an empty dictionary each time you execute get_todo. Ok I see it now. > > todo = {key:value} again resets the value of todo. You only need > todo[key]=value. Yep, thanks -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From emile at fenx.com Fri Mar 27 19:46:05 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 27 Mar 2009 11:46:05 -0700 Subject: [Tutor] Adding key, value to Dictionary In-Reply-To: <49CD1576.2030207@abbottdavid.com> References: <49CD0D59.6070704@abbottdavid.com> <49CD1576.2030207@abbottdavid.com> Message-ID: David wrote: > greg whittier wrote: >> On Fri, Mar 27, 2009 at 1:31 PM, David wrote: >>> But I can not get this to update after the first time it is ran. >>> >>> def get_todo(): Other common ways this is done include: def get_todo(todo={}): ... This works well if one copy is to be used the entire time the application is live, although it's also often cited as a gotcha... and def get_todo(todo=None): if todo==None: todo = {} ... Both the above allow you to pass in a starting todo dict, so you could juggle multiple todo dicts... HTH, Emile From alan.gauld at btinternet.com Fri Mar 27 20:04:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Mar 2009 19:04:34 -0000 Subject: [Tutor] Left Alignment -- Tkinter References: <49CD0D40.5090508@sbcglobal.net> Message-ID: Try packing the frame to the left and set it to expand. HTH, Going on vacation.... Bye Alan G. "Wayne Watson" wrote in message news:49CD0D40.5090508 at sbcglobal.net... > Signature.htmlThe code below is clearly not shifting the contents of the > frame to the left. It's supposed to look like > > Geographic Location > Latitude BOX Longitude BOX > OK Cancel > > but instead looks like: > Geographic Location > Latitude BOX Longitude BOX > OK Cancel > > Where BOX is just a data entry field. I've deliberately made the label > size big enough so as not to obscure what happens with default values. A > 30x5 size. That is if I remove the size options, then it looks OK. I > don't think it really gets shift to the left though even though it looks > like it does. Comments? > > # Framing it > from Tkinter import * > from tkSimpleDialog import Dialog > import tkSimpleDialog > import tkMessageBox > > class DialogPrototype(Dialog): > > def body(self, master): > > # Frames > fLocationTitle = Frame(master,) # fL... f for frame > fLocationTitle.pack() > fLocation=Frame(master) > fLocation.pack() > fCoords = Frame(fLocation) # lat/long coords in a frame > fCoords.pack() > > > self.title("Enter Site/Misc. Data") > > # Latitude and Longitude > > Label(fLocationTitle, text="Geographic > Location").grid(row=0,column=0) > #Label(fCoords, text='Latitude:').grid(row=0, sticky=W) > self.lab=Label(fCoords, text='Latitude:',width=30, height=5) > self.lab.grid(row=0, sticky=W) > self.lat = Entry(fCoords, width=12) > self.lat.grid(row=0, column=1) > > Label(fCoords, text='Longitude:').grid(row=0, column=2) > self.long = Entry(fCoords, width=12) > self.long.grid(row=0, column=3) > > return > > def apply(self): > print "apply" > print self.lat.get() > print self.long.get() > > print "setting" > lat=1.0 > long=0.0 > > root = Tk() > root.withdraw() > DialogPrototype(root) > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > > "Life is one damn thing after another." > -- Mark Twain > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sierra_mtnview at sbcglobal.net Fri Mar 27 20:46:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 27 Mar 2009 12:46:43 -0700 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: References: <49CD0D40.5090508@sbcglobal.net> Message-ID: <49CD2D23.2050707@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Mar 28 13:49:12 2009 From: srilyk at gmail.com (W W) Date: Sat, 28 Mar 2009 07:49:12 -0500 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <49CD2D23.2050707@sbcglobal.net> References: <49CD0D40.5090508@sbcglobal.net> <49CD2D23.2050707@sbcglobal.net> Message-ID: <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> On Fri, Mar 27, 2009 at 2:46 PM, Wayne Watson wrote: > It's very difficult to tell. I've tried it. > fLocation=Frame(master) > fLocation.pack(side=LEFT) > I need to size the fLocation frame to make it big. As it is, it must be > giving the smallest possible size. > > I tried this > fLocation.pack(expand=YES,fill=BOTH,side=TOP) > Good news... I got it! Here's something that's often a good idea when debugging overlapping layouts (especially when you didn't design the parent!) - use different backgrounds! First I tried grid_rowconfigure and grid_columnconfigure (which are necessary if you want your widgets in grid to resize and sticky in the expected places... at least in my experience. You call them on the parent widget which can be displayed with .pack() ) on fCoords - the parent of your labels. That didn't do anything, so I suspected the problem went deeper. So I tried fCoords parent, fLocation. That didn't do anything, so I finally went to /it's/ parent - master. By setting master.pack(expand=1, fill=BOTH) along with some other tweaks I was able to get some behavior I think you'll want. I've left my background and border changes so you can get a better idea of what I did. Feel free to play around with the colors, borders, sticky options, and sizes of things. It'll probably help you to get a better grasp of what's going on. Here's my changes (also found here: http://rafb.net/p/clKroD65.html ) # Framing it from Tkinter import * from tkSimpleDialog import Dialog import tkSimpleDialog import tkMessageBox class DialogPrototype(Dialog): def body(self, master): # Frames master.configure(bg='white', bd=3) master.pack(expand=1, fill=BOTH) fLocationTitle = Frame(master, bg='green', bd=3) # fL... f for frame fLocationTitle.pack() fLocation=Frame(master, bg='red', bd=3) fLocation.pack(expand=1, fill=BOTH, anchor=W) fCoords = Frame(fLocation, bg='blue', bd=3) # lat/long coords in a frame fCoords.pack(fill=BOTH, expand=1, side=LEFT) fCoords.grid_columnconfigure(0, weight=0) fCoords.grid_columnconfigure(1, weight=1) fCoords.grid_columnconfigure(2, weight=0) fCoords.grid_columnconfigure(3, weight=1) fCoords.grid_rowconfigure(0, weight=1, minsize=1) self.title("Enter Site/Misc. Data") # Latitude and Longitude Label(fLocationTitle, text="Geographic Location").grid(row=0,column=0) #Label(fCoords, text='Latitude:').grid(row=0, sticky=W) self.lab=Label(fCoords, text='Latitude:', height=5) self.lab.grid(row=0, column=0, sticky=W) self.lat = Entry(fCoords, width=12) self.lat.grid(row=0, column=1, sticky=W+E) Label(fCoords, text='Longitude:').grid(row=0, column=2) self.long = Entry(fCoords, width=12) self.long.grid(row=0, column=3, sticky=W+E) return def apply(self): print "apply" print self.lat.get() print self.long.get() print "setting" lat=1.0 long=0.0 root = Tk() root.withdraw() DialogPrototype(root) HTH, The -other- Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Mar 28 15:47:18 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 28 Mar 2009 07:47:18 -0700 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> References: <49CD0D40.5090508@sbcglobal.net> <49CD2D23.2050707@sbcglobal.net> <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> Message-ID: <49CE3876.3040004@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Mar 28 21:46:26 2009 From: srilyk at gmail.com (W W) Date: Sat, 28 Mar 2009 15:46:26 -0500 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <49CE3876.3040004@sbcglobal.net> References: <49CD0D40.5090508@sbcglobal.net> <49CD2D23.2050707@sbcglobal.net> <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> <49CE3876.3040004@sbcglobal.net> Message-ID: <333efb450903281346t137b8da5va4700f8a00fa344f@mail.gmail.com> On Sat, Mar 28, 2009 at 9:47 AM, Wayne Watson wrote: > Hi, that's an interesting way to look at it. Actually, I was about to > probe the color idea myself, but needed to better understand how to achieve > it. Where did grid_columnconfigure(3, weight=1) come from? I don't recall > seeing that with Frame. Grid has columnconfigure. I started down that path > once, but got waved off. Interesting about master. > It's not part of frame, it's actually part of the grid manager, but you have to call it on the parent widget, and as such it won't get screwy when combined with a parent that has the .pack method called on it. http://effbot.org/tkinterbook/grid.htm is a pretty decent reference. > What I've discovered is that I did not really understand the role of > sticky, and the bounds of the label. I thought sticky=W meant put the > blasted label to the left margin. What sticky means, according to Grayson's > chapter 5 on the web, is that it allows the widget to stretch when the > larger window is resized. Knowing the boundaries with color coding can help > understand that, and other oddities. Label seems to always center the text. > Changing the label's width and height achieves interesting insights. I tried > anchor with Label and it does interesting things. The length of the text > messes with matters. > http://effbot.org/tkinterbook/label.htm The justify option will change the alignment of text in the label. > > > To put some focus on what I think is the real problem, try this. See if the > text in labels lines up on the left if a column of Labels is create with > these labels. > > vinegar > pie > latitude for x > Snowy > > I haven't tried it yet, but would expect to get something like: > > vinegar > pie > latitude for x > Snowy > > anchor with Label may move them to the left. > > In my case, I'm looking for stuff like: > > Latitude BOX Longitude BOX > x BOX y BOX > > and not > Latitude BOX Longitude BOX > x BOX y BOX > Grid is a useful manager for this type of scenario. Grid is very similar to the old HTML table. If you want to align it that way with grid, you could easily do something that looks like this: +------------+-------+--------------+--------+ | Latitude | Box | Longitude | Box | +-+------+--+-------+--------------+--------+ | x | BOX| y | BOX | | +-+------+--+-------+------------------------+ Forgive the poor ascii art, but with some simple configurations like columnspan, you can set it up to fit whatever you want (it usually helps to draw out your design on paper). > > I want the text in the left column aligned. It doesn't really matter about > the alignment of Longitude with y. One would think this would be a snap. I'm > quite surprised no one seems to have considered an example along these > lines. I guess everyone is center happy. > Using the grid manager and justify=LEFT you shouldn't have much of a problem > > I have yet to find a good source that explains Grid in a thorough way. Lots > of piecemeal things. Many too brief. Perhaps the best thing I've found is > Grayson's chapter 5 image editor, p86f. He has a very complex looking grid > of buttons, combo boxes and images, but it all makes sense as to the layout. > It took me awhile to see why he needed so many rows and columns for those 9 > (actually 10) thumbnails. It's all about what goes on in the lower right > corner. Unfortunately, he had no need to align the text to the left > uniformly in a column. > If you want to have the text align you have a few options - you can have several labels in the same grid row/column, or you can line them up with their own cells. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachflags at googlemail.com Sat Mar 28 11:34:48 2009 From: beachflags at googlemail.com (Martin Klimach) Date: Sat, 28 Mar 2009 11:34:48 +0100 Subject: [Tutor] Automated function creation / outsourcing code Message-ID: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> Hi, I started using python three months ago in order to create scripts for the abaqus fea software. The initial script became bigger and bigger and finding myself spending lots of time just trying to find the right part in the code, I started looking into making my first own module. Since I find it quite cumbersome to cut and paste code and then trying to find all necessary input and return variables I have a question: Is there a python editor, that can automatically turn a selection of code into a function? Matching the input and return variables? So far I have been using Notepad++ and i can't find this kind of feature there or in the description of other editors. It would already help if somebody could tell me what the exact name for this is. In texnicCenter a latex editor a similar feature it is called "outsourcing", is it here the same? Thanks a lot, Martin From srilyk at gmail.com Sun Mar 29 14:31:33 2009 From: srilyk at gmail.com (W W) Date: Sun, 29 Mar 2009 07:31:33 -0500 Subject: [Tutor] Automated function creation / outsourcing code In-Reply-To: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> References: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> Message-ID: <333efb450903290531n1f162135h81bb9178b51e27a2@mail.gmail.com> On Sat, Mar 28, 2009 at 5:34 AM, Martin Klimach wrote: > Is there a python editor, that can automatically turn a selection of > code into a function? Matching the input and return variables? > > I've never heard of one. I suppose you could probably write your own using regexes perhaps. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From moron.oxy at gmail.com Sun Mar 29 14:40:47 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Sun, 29 Mar 2009 23:40:47 +1100 Subject: [Tutor] Automated function creation / outsourcing code In-Reply-To: <333efb450903290531n1f162135h81bb9178b51e27a2@mail.gmail.com> References: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> <333efb450903290531n1f162135h81bb9178b51e27a2@mail.gmail.com> Message-ID: <2096a7260903290540p81e3d84i8ef9246455ee4b90@mail.gmail.com> I think you're looking for refactoring features, in this particular case, a compose method/function refactor. Generally, generic editors will have trouble doing this right since it requires some inferencing capability on the selected code, your best bet is probably googling Python-aware IDEs with refactoring support, something like PyDev (http://pydev.sourceforge.net) or eric (http://eric-ide.python-projects.org/). -- K On Sun, Mar 29, 2009 at 11:31 PM, W W wrote: > On Sat, Mar 28, 2009 at 5:34 AM, Martin Klimach > wrote: >> >> Is there a python editor, that can automatically turn a selection of >> code into a function? Matching the input and return variables? >> > > I've never heard of one. I suppose you could probably write your own using > regexes perhaps. > > -Wayne > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- There is more to life than increasing its speed. -- Mahatma Gandhi From sierra_mtnview at sbcglobal.net Sun Mar 29 16:30:49 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 29 Mar 2009 07:30:49 -0700 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <333efb450903281346t137b8da5va4700f8a00fa344f@mail.gmail.com> References: <49CD0D40.5090508@sbcglobal.net> <49CD2D23.2050707@sbcglobal.net> <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> <49CE3876.3040004@sbcglobal.net> <333efb450903281346t137b8da5va4700f8a00fa344f@mail.gmail.com> Message-ID: <49CF8619.90802@sbcglobal.net> An HTML attachment was scrubbed... URL: From andrefsp at gmail.com Sun Mar 29 21:11:15 2009 From: andrefsp at gmail.com (=?ISO-8859-1?Q?andr=E9_palma?=) Date: Sun, 29 Mar 2009 20:11:15 +0100 Subject: [Tutor] ImportError: No module named conf Message-ID: <49CFC7D3.1000605@gmail.com> Hey, i was trying to install python d2xx files but i got an error saying: ImportError: No module named conf "from conf import * " <------- the error line. I've already searched for this module but i didn't find anything. Anyone have an idea why is this about? From kent37 at tds.net Sun Mar 29 21:25:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 29 Mar 2009 15:25:23 -0400 Subject: [Tutor] ImportError: No module named conf In-Reply-To: <49CFC7D3.1000605@gmail.com> References: <49CFC7D3.1000605@gmail.com> Message-ID: <1c2a2c590903291225o73fc2adeh3cf24074c6194801@mail.gmail.com> On Sun, Mar 29, 2009 at 3:11 PM, andr? palma wrote: > Hey, i was trying to install python d2xx files but i got an error saying: What is d2xx? Be more specific about what you are trying to install. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ctcast at gmail.com Mon Mar 30 05:42:43 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sun, 29 Mar 2009 22:42:43 -0500 Subject: [Tutor] Binary Real to Decimal Message-ID: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> myinput = raw_input("Please enter a binary real number: ") myinput = myinput.split(".") binstr1 = myinput[0] binstr2 = myinput[1] decnum1 = 0 decnum2 = 0 for i in binstr1: decnum1 = decnum1 * 2 + int(i) for k in binstr2: decnum2 = decnum2 * 2 + int(k) print "\nThe binary real number ", binstr1, ".", binstr2, " converts to ", decnum1,".",decnum2," in decimal." that is what I have so far but I need to create a condition where I need only 10 sufficient numbers from the variable decnum2. I know I need something like if len(decnum2) > 11: decnum2 = decnum2[0:11] but I keep getting unsubscriptable errors. I know it has to do with types but it's late and I just need some help. thank you in advance. - chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Mar 30 05:46:57 2009 From: john at fouhy.net (John Fouhy) Date: Mon, 30 Mar 2009 16:46:57 +1300 Subject: [Tutor] Binary Real to Decimal In-Reply-To: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> References: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> Message-ID: <5e58f2e40903292046y58e398b9h3ba570e3c8305aab@mail.gmail.com> 2009/3/30 Chris Castillo : > that is what I have so far but I need to create a condition where I need > only 10 sufficient numbers from the variable decnum2. I know I need > something like > if len(decnum2) > 11: > ??? decnum2 = decnum2[0:11] Perhaps the round() function will help? >>> round(12345, -2) 12300.0 -- John. From ctcast at gmail.com Mon Mar 30 06:17:53 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sun, 29 Mar 2009 23:17:53 -0500 Subject: [Tutor] Binary Real to Decimal In-Reply-To: <5e58f2e40903292046y58e398b9h3ba570e3c8305aab@mail.gmail.com> References: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> <5e58f2e40903292046y58e398b9h3ba570e3c8305aab@mail.gmail.com> Message-ID: <50e459210903292117r37d03ff6maa77386b5de0e82f@mail.gmail.com> yeah that function would help but how would I join both sides again to get a decimal real(float) to round? for example myfloat = decnum1, ".", decnum2 doesn't work because the string "." isn't a valid int type. how would I join those to be a float again? On Sun, Mar 29, 2009 at 10:46 PM, John Fouhy wrote: > 2009/3/30 Chris Castillo : > > that is what I have so far but I need to create a condition where I need > > only 10 sufficient numbers from the variable decnum2. I know I need > > something like > > if len(decnum2) > 11: > > decnum2 = decnum2[0:11] > > Perhaps the round() function will help? > > >>> round(12345, -2) > 12300.0 > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Mar 30 06:25:37 2009 From: john at fouhy.net (John Fouhy) Date: Mon, 30 Mar 2009 17:25:37 +1300 Subject: [Tutor] Binary Real to Decimal In-Reply-To: <50e459210903292117r37d03ff6maa77386b5de0e82f@mail.gmail.com> References: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> <5e58f2e40903292046y58e398b9h3ba570e3c8305aab@mail.gmail.com> <50e459210903292117r37d03ff6maa77386b5de0e82f@mail.gmail.com> Message-ID: <5e58f2e40903292125s46127066sf03f52a023a843a4@mail.gmail.com> 2009/3/30 Chris Castillo : > yeah that function would help but how would I join both sides again to get a > decimal real(float) to round? > > for example myfloat = decnum1, ".", decnum2 doesn't work because the string > "." isn't a valid int type. how would I join those to be a float again? The easiest way would be to convert decnum1 and decnum2 into strings, join them together, and then call float() on the result. e.g. myfloat = float('%s.%s' % (decnum1, decnum2)) -- John. From denis.spir at free.fr Mon Mar 30 09:20:37 2009 From: denis.spir at free.fr (spir) Date: Mon, 30 Mar 2009 09:20:37 +0200 Subject: [Tutor] Binary Real to Decimal In-Reply-To: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> References: <50e459210903292042p6f6e8788x98fdffeeb0a10834@mail.gmail.com> Message-ID: <20090330092037.32c67ead@o> Le Sun, 29 Mar 2009 22:42:43 -0500, Chris Castillo s'exprima ainsi: > myinput = raw_input("Please enter a binary real number: ") > myinput = myinput.split(".") > > binstr1 = myinput[0] > binstr2 = myinput[1] > > decnum1 = 0 > decnum2 = 0 > > for i in binstr1: > decnum1 = decnum1 * 2 + int(i) > > for k in binstr2: > decnum2 = decnum2 * 2 + int(k) > > > > print "\nThe binary real number ", binstr1, ".", binstr2, " converts to ", > decnum1,".",decnum2," in decimal." > > > that is what I have so far but I need to create a condition where I need > only 10 sufficient numbers from the variable decnum2. I know I need > something like > if len(decnum2) > 11: > decnum2 = decnum2[0:11] > > but I keep getting unsubscriptable errors. I know it has to do with types > but it's late and I just need some help. thank you in advance. - chris This is a symptom that you mistake numeral values for textual ones. Your loops for k in binstr2: decnum2 = decnum2 * 2 + int(k) build integers. They are numbers for python, not text snippets that happen to represent numbers for humans. When you print (decnum1,".",decnum2), python silently converts both integers to standard representations of integers (eg 123 --> "123") that happen to be what you expect to see. Then if you join together two integer representations with '.' as glue, sure you will get something that looks like a (representation of a) real number -- but this is only superficial appearance. You have never built a real real (!) number (type float). You cannot use the result to compute anything, for instance. To get the result, you need to process together decnum1 (integral part) and decnum2 (fractional part) into a single (real) number. Then print the result. Denis ------ la vita e estrany From denis.spir at free.fr Mon Mar 30 09:36:51 2009 From: denis.spir at free.fr (spir) Date: Mon, 30 Mar 2009 09:36:51 +0200 Subject: [Tutor] how are unicode chars represented? Message-ID: <20090330093651.27bada23@o> Everything is in the title ;-) (Is it kind of integers representing the code point?) Denis ------ la vita e estrany From timomlists at gmail.com Mon Mar 30 09:54:10 2009 From: timomlists at gmail.com (Timo) Date: Mon, 30 Mar 2009 09:54:10 +0200 Subject: [Tutor] Shelve doesn't free up memory Message-ID: <49D07AA2.4080200@gmail.com> Hello, I have a PyGTK application where the user is able to click on a button, then a new dialog pops up with a treeview and the program fills this view with data from a shelve. Everything works, the data is being added to the treeview. The only problem is, that when I close the dialog, it doesn't free the memory. So when I click the button again, the same amount of memory is added being used. Then close the window, click again, again the same amount of memory, and so on... Now it only takes about 5 to 8 mb, but this shouldn't be. I do call the shelve.close(), but that doesn't do it apparently. Do I need to do something when I close my window? Here are parts of the code: # Result window => Called when button is clicked import Results class ResultWindow: def __init__(self): # Build the dialog and the treeview... self.get_results() def get_results(self): self.liststore.clear() for person in self.persons: dics = Results.read_result(person) if not dics: continue for dic in dics: date = dic['date'] point = dic['point'] place = dic['place'] out = dic['out'] self.liststore.append([date, point, place, out]) # Results file import shelve def read_result(person): results = [] s = shelve.open(RESULTFILE) try: results = s[person] except KeyError: # print "No results for this person" pass finally: s.close() return results From denis.spir at free.fr Mon Mar 30 11:51:26 2009 From: denis.spir at free.fr (spir) Date: Mon, 30 Mar 2009 11:51:26 +0200 Subject: [Tutor] __callattr__ ? Message-ID: <20090330115126.18edfbe8@o> Hello, Is there something like a __callattr__ magic method that would catch either unknown (like __getattr__) or all (like __getattribute__) method calls? If not, how would you do that? Also if not, do you know why we have __getattr__, __setattr__, but no __callattr__? Denis ------ la vita e estrany From bala.biophysics at gmail.com Mon Mar 30 12:27:36 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 30 Mar 2009 12:27:36 +0200 Subject: [Tutor] installation of scipy Message-ID: <288df32a0903300327p537f408co8ee4c480d17b249e@mail.gmail.com> Friends i installed scipy in fedora10 using yum. when i import stats module in it, i got the following warning. someone pls englihten me on this. >>> from scipy import stats /usr/lib/python2.5/site-packages/scipy/sparse/linalg/dsolve/linsolve.py:20: DeprecationWarning: scipy.sparse.linalg.dsolve.umfpack will be removed, install scikits.umfpack instead ' install scikits.umfpack instead', DeprecationWarning ) Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Mar 30 12:45:35 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 30 Mar 2009 05:45:35 -0500 Subject: [Tutor] Binary Real to Decimal In-Reply-To: References: Message-ID: <49D0A2CF.2050702@ieee.org> I don't know what "sufficient numbers" means, but perhaps it's "significant digits" that was intended. And you have to decide if you want ten digits to the right of the decimal point, or ten significant digits in the whole number. That determines whether you want to round decnum2 or the final value you get from combining decnum1 and decnum2. But you have two other problems to address before you do any rounding, I'll address only the first. 1) The present value displayed are simply wrong. 2) You need to combine the two integers decnum1 and decnum2 into a single real. If the user enters 1.1010 you display 1 . 10 which is not the correct decimal representation of the value entered. 1.1010 binary is 1.625 in decimal. A few more samples: 11.0001 is not 3.1 but is actually 3.0625 110.00001 is not 6.1 but is actually 6.03125 110.00011 is not 6.3 but is actually 6.09375 In particular, your logic doesn't take into account the number of digits entered to the right of the binary point. decnum2 must be divided by some power of two to get the right value. Once you get a useful representation for the decnum2 part, it should be obvious how to combine the two. Chris Castillo wrote: > myinput = raw_input("Please enter a binary real number: ") > myinput = myinput.split(".") > > binstr1 = myinput[0] > binstr2 = myinput[1] > > decnum1 = 0 > decnum2 = 0 > > for i in binstr1: > decnum1 = decnum1 * 2 + int(i) > > for k in binstr2: > decnum2 = decnum2 * 2 + int(k) > > > > print "\nThe binary real number ", binstr1, ".", binstr2, " converts to ", > decnum1,".",decnum2," in decimal." > > > that is what I have so far but I need to create a condition where I need > only 10 sufficient numbers from the variable decnum2. I know I need > something like > if len(decnum2) > 11: > decnum2 = decnum2[0:11] > > but I keep getting unsubscriptable errors. I know it has to do with types > but it's late and I just need some help. thank you in advance. - chris > > From kent37 at tds.net Mon Mar 30 12:52:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Mar 2009 06:52:19 -0400 Subject: [Tutor] how are unicode chars represented? In-Reply-To: <20090330093651.27bada23@o> References: <20090330093651.27bada23@o> Message-ID: <1c2a2c590903300352t2bd3f1a7j5f37703cf1c3b0c@mail.gmail.com> On Mon, Mar 30, 2009 at 3:36 AM, spir wrote: > Everything is in the title ;-) > (Is it kind of integers representing the code point?) Unicode is represented as 16-bit integers. I'm not sure, but I don't think Python has support for surrogate pairs, i.e. characters outside the BMP. Kent From sierra_mtnview at sbcglobal.net Mon Mar 30 13:22:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 30 Mar 2009 04:22:34 -0700 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <49CF8619.90802@sbcglobal.net> References: <49CD0D40.5090508@sbcglobal.net> <49CD2D23.2050707@sbcglobal.net> <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> <49CE3876.3040004@sbcglobal.net> <333efb450903281346t137b8da5va4700f8a00fa344f@mail.gmail.com> <49CF8619.90802@sbcglobal.net> Message-ID: <49D0AB7A.8040704@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Mar 30 13:45:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 30 Mar 2009 07:45:56 -0400 Subject: [Tutor] __callattr__ ? In-Reply-To: <20090330115126.18edfbe8@o> References: <20090330115126.18edfbe8@o> Message-ID: <1c2a2c590903300445s59616fdbm14ff260c458b5386@mail.gmail.com> On Mon, Mar 30, 2009 at 5:51 AM, spir wrote: > Hello, > > Is there something like a __callattr__ magic method that would catch either unknown (like __getattr__) or all (like __getattribute__) method calls? > If not, how would you do that? Also if not, do you know why we have __getattr__, __setattr__, but no __callattr__? Methods are just callable attributes. If you have for example class Foo(object): def sayFoo(self): print 'foo' f = Foo() then sayFoo is an attribute of class Foo. When you then write f.sayFoo() what that means is, - look up the sayFoo attribute on object f (returning the class attribute since f has no sayFoo attribute itself) - call the object that results So, to intercept calls to unknown methods you use __getattr__ or __getattribute__ just as for other attributes. For example, In [10]: class Foo(object): ....: def __getattr__(self, name): ....: def show(): ....: print 'called', name ....: return show In [18]: f = Foo() In [19]: f.superduper() called superduper Kent From tomar.arun at gmail.com Mon Mar 30 13:45:34 2009 From: tomar.arun at gmail.com (Arun Tomar) Date: Mon, 30 Mar 2009 17:15:34 +0530 Subject: [Tutor] installation of scipy In-Reply-To: <288df32a0903300327p537f408co8ee4c480d17b249e@mail.gmail.com> References: <288df32a0903300327p537f408co8ee4c480d17b249e@mail.gmail.com> Message-ID: <202c460903300445v744aa3a1pdec9bff0e1b2e3cf@mail.gmail.com> hi! Bala. On Mon, Mar 30, 2009 at 3:57 PM, Bala subramanian wrote: > Friends > i installed scipy in fedora10 using yum. when i import stats module in it, i > got the following warning. someone pls englihten me on this. > >>>> from scipy import stats > /usr/lib/python2.5/site-packages/scipy/sparse/linalg/dsolve/linsolve.py:20: > DeprecationWarning: scipy.sparse.linalg.dsolve.umfpack will be removed, > install scikits.umfpack instead > ? ' install scikits.umfpack instead', DeprecationWarning ) > deprecation is the way in python through which the developers warn the user or the other developers that, a certain feature that has been mentioned, would be removed or not available from the next release. so as of now, just enjoy & ignore the error. by the next release cycle, developers of scipy will need remove the deprecated code or use the suggested packages in the deprecation warning. > Thanks, > Bala > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, Arun Tomar blog: http://linuxguy.in website: http://www.solutionenterprises.co.in From emile at fenx.com Mon Mar 30 15:55:20 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 30 Mar 2009 06:55:20 -0700 Subject: [Tutor] Shelve doesn't free up memory In-Reply-To: <49D07AA2.4080200@gmail.com> References: <49D07AA2.4080200@gmail.com> Message-ID: Timo wrote: > # Results file > import shelve > > def read_result(person): > results = [] > > s = shelve.open(RESULTFILE) > try: > results = s[person] Maybe passing this out prevents s from being garbage collected? Emile > except KeyError: > # print "No results for this person" > pass > finally: > s.close() > > return results > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Mon Mar 30 16:50:45 2009 From: srilyk at gmail.com (W W) Date: Mon, 30 Mar 2009 09:50:45 -0500 Subject: [Tutor] Left Alignment -- Tkinter In-Reply-To: <49CF8619.90802@sbcglobal.net> References: <49CD0D40.5090508@sbcglobal.net> <49CD2D23.2050707@sbcglobal.net> <333efb450903280549o1c39f6b1uec186aaf339af5c1@mail.gmail.com> <49CE3876.3040004@sbcglobal.net> <333efb450903281346t137b8da5va4700f8a00fa344f@mail.gmail.com> <49CF8619.90802@sbcglobal.net> Message-ID: <333efb450903300750m6e109817g147dda53786a7c8f@mail.gmail.com> On Sun, Mar 29, 2009 at 9:30 AM, Wayne Watson wrote: > I'm looking at the NM Tech Tkinter ref, pages 5-6, on the grid > method. See pages 84-88 of Lundh. Nothing. It does not show that method. > Search of the pdf doc shows nothing. Are these sources too old? effbot does > have it. Yes, it's pretty decent. I've used it before. It looks like it may > be the newest, 2005, of the three, although NM Tech seems to get updated > pretty often. 5/2007, but I think there was a recent update. Maybe they > don't want the students to use it. > I haven't really looked at a lot of tkinter refs. Effbot tends to have most of the info I need - it just takes a little playing around and sometimes google or the python list to figure out what part I'm missing. > >> What I've discovered is that I did not really understand the role of >> sticky, and the bounds of the label. I thought sticky=W meant put the >> blasted label to the left margin. What sticky means, according to Grayson's >> chapter 5 on the web, is that it allows the widget to stretch when the >> larger window is resized. Knowing the boundaries with color coding can help >> understand that, and other oddities. Label seems to always center the text. >> Changing the label's width and height achieves interesting insights. I tried >> anchor with Label and it does interesting things. The length of the text >> messes with matters. >> > > http://effbot.org/tkinterbook/label.htm > > The justify option will change the alignment of text in the label. > > It didn't move the text in the label at all. There's got to be some padding > on either end I'm missing. > Actually, it turns out to be my mistake at not clearly reading the documentation he has for the justify option. Justify is for multiple lines of text, anchor will anchor the text. Try with width=30, anchor=W and you should see what you're looking for. > Interestingly, I had set the width of the label to 12, and the color > version showed gray to the left and right of the text, with the text in the > center. I removed width, and the left-right spaces disappeared, but the text > was still centered. Well, OK, the selected width, which matches the length > of the text, really doesn't allow for justification. Foiled again. It seems > like the width for the frame container for the latitude+BOX needs to be > specified to give latitude some ability to go left. A column for latitude > and one for BOX? Beats me. Back to exploration after I finish this > response. > It appears you're correct - when I used anchor with padx it was ignored, but when I changed padx to width it worked as expected. I'm not sure why it does or doesn't, and I haven't had a lot of time for a lot of experimenting, and now I have class so I'll just have to leave it for now. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From payo2000 at gmail.com Mon Mar 30 16:52:34 2009 From: payo2000 at gmail.com (pa yo) Date: Mon, 30 Mar 2009 16:52:34 +0200 Subject: [Tutor] incrementing one minute Message-ID: I need to add one minute to a string that has a date and a time in YYYYMMDDHHMM format. e.g: 200903281346 should become 200903281347 the following script converts the string into time and adds one minute; but somehow I also add an hour and I don't understand why. ==================== import time #set the initial time as a string and convert it into time format: fromtimestring = '200903281346' fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") #convert this time format into UNIX time (seconds since the start of UNIX time): fromtimeseconds = time.mktime(fromtimetime) #add 60 seconds and reformat the result into the YYYYMMDDHHMM format totimeseconds = fromtimeseconds + 60 totimetime = time.gmtime(totimeseconds) # convert the new time into a string: totimestring = time.strftime("%Y%m%d%H%M", totimetime) #print the results: print (fromtimestring) print (fromtimetime) print (totimetime) print (totimestring) ================ any help or suggestions would be much appreciated. Payo From payo2000 at gmail.com Mon Mar 30 17:05:01 2009 From: payo2000 at gmail.com (pa yo) Date: Mon, 30 Mar 2009 16:05:01 +0100 Subject: [Tutor] incrementing one minute In-Reply-To: References: Message-ID: I fixed it by re-setting my system clock to GMT. ... it seems a bit of a botch but it works. Payo On Mon, Mar 30, 2009 at 4:52 PM, pa yo wrote: > I need to add one minute to a string that has a date and a time in > YYYYMMDDHHMM format. > e.g: ?200903281346 should become 200903281347 > > the following script converts the string into time and adds one > minute; but somehow I also add an hour and I don't understand why. > > ==================== > > import time > > #set the initial time as a string and convert it into time format: > fromtimestring = '200903281346' > fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") > #convert this time format into UNIX time (seconds since the start of UNIX time): > fromtimeseconds = time.mktime(fromtimetime) > #add 60 seconds and reformat the result into the YYYYMMDDHHMM format > totimeseconds = fromtimeseconds + 60 > totimetime = time.gmtime(totimeseconds) > # convert the new time into a string: > totimestring = time.strftime("%Y%m%d%H%M", totimetime) > > #print the results: > print (fromtimestring) > print (fromtimetime) > print (totimetime) > print (totimestring) > > ================ > > any help or suggestions would be much appreciated. > > > Payo > From roadierich at googlemail.com Mon Mar 30 17:07:00 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Mon, 30 Mar 2009 16:07:00 +0100 Subject: [Tutor] incrementing one minute In-Reply-To: References: Message-ID: 2009/3/30 pa yo : > I need to add one minute to a string that has a date and a time in > YYYYMMDDHHMM format. > e.g: ?200903281346 should become 200903281347 > > the following script converts the string into time and adds one > minute; but somehow I also add an hour and I don't understand why. > > ==================== > > import time > > #set the initial time as a string and convert it into time format: > fromtimestring = '200903281346' > fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") > #convert this time format into UNIX time (seconds since the start of UNIX time): > fromtimeseconds = time.mktime(fromtimetime) > #add 60 seconds and reformat the result into the YYYYMMDDHHMM format > totimeseconds = fromtimeseconds + 60 > totimetime = time.gmtime(totimeseconds) > # convert the new time into a string: > totimestring = time.strftime("%Y%m%d%H%M", totimetime) > > #print the results: > print (fromtimestring) > print (fromtimetime) > print (totimetime) > print (totimestring) > > ================ > > any help or suggestions would be much appreciated. > > > Payo > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > When does it add an hour? Is it only on specific input strings, or is it arbitrary? If its the former, what input strings does it happen on? Can you spot any pattern to the inputs that it occurs on? It's possible that it's getting confused with dates either side of the British Summertime change. Also, your variable names are rather cryptic... you might consider using studlyCapsWithCapitalInitialLetters or underscores_between_words. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From sander.sweers at gmail.com Mon Mar 30 17:27:40 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 30 Mar 2009 17:27:40 +0200 Subject: [Tutor] incrementing one minute In-Reply-To: References: Message-ID: 2009/3/30 pa yo : > I need to add one minute to a string that has a date and a time in > YYYYMMDDHHMM format. > e.g: ?200903281346 should become 200903281347 > > the following script converts the string into time and adds one > minute; but somehow I also add an hour and I don't understand why. > > ==================== > > import time > > #set the initial time as a string and convert it into time format: > fromtimestring = '200903281346' > fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") > #convert this time format into UNIX time (seconds since the start of UNIX time): > fromtimeseconds = time.mktime(fromtimetime) > #add 60 seconds and reformat the result into the YYYYMMDDHHMM format > totimeseconds = fromtimeseconds + 60 > totimetime = time.gmtime(totimeseconds) > # convert the new time into a string: > totimestring = time.strftime("%Y%m%d%H%M", totimetime) > > #print the results: > print (fromtimestring) > print (fromtimetime) > print (totimetime) > print (totimestring) > > ================ > > any help or suggestions would be much appreciated. You could do this with datetime and timedelta from the datetime module. >>> from datetime import datetime, timedelta >>> fromtimetime = datetime.strptime('200903281346', '%Y%m%d%H%M') >>> fromtimetime datetime.datetime(2009, 3, 28, 13, 46) >>> delta = timedelta(seconds=60) >>> delta datetime.timedelta(0, 60) >>> fromtimetime + delta datetime.datetime(2009, 3, 28, 13, 47) >>> datetime.strftime(fromtimetime + delta, '%Y%m%d%H%M') '200903281347' Greets Sander From trilokgk at gmail.com Mon Mar 30 18:03:41 2009 From: trilokgk at gmail.com (Trilok Khairnar) Date: Mon, 30 Mar 2009 21:33:41 +0530 Subject: [Tutor] installation of scipy In-Reply-To: <202c460903300445v744aa3a1pdec9bff0e1b2e3cf@mail.gmail.com> References: <288df32a0903300327p537f408co8ee4c480d17b249e@mail.gmail.com> <202c460903300445v744aa3a1pdec9bff0e1b2e3cf@mail.gmail.com> Message-ID: <185938120903300903k6f4023f0lba0b2a8dad207fb4@mail.gmail.com> More specifically, in this case, numpy.stats should be used instead of scipy.stats You will not see the deprecation warning with numpy.stats On Mon, Mar 30, 2009 at 5:15 PM, Arun Tomar wrote: > hi! > Bala. > > On Mon, Mar 30, 2009 at 3:57 PM, Bala subramanian > wrote: > > Friends > > i installed scipy in fedora10 using yum. when i import stats module in > it, i > > got the following warning. someone pls englihten me on this. > > > >>>> from scipy import stats > > > /usr/lib/python2.5/site-packages/scipy/sparse/linalg/dsolve/linsolve.py:20: > > DeprecationWarning: scipy.sparse.linalg.dsolve.umfpack will be removed, > > install scikits.umfpack instead > > ' install scikits.umfpack instead', DeprecationWarning ) > > > > deprecation is the way in python through which the developers warn the > user or the other developers that, a certain feature that has been > mentioned, would be removed or not available from the next release. > > so as of now, just enjoy & ignore the error. by the next release > cycle, developers of scipy will need remove the deprecated code or use > the suggested packages in the deprecation warning. > > Thanks, > > Bala > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > Regards, > Arun Tomar > blog: http://linuxguy.in > website: http://www.solutionenterprises.co.in > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Mar 30 18:50:48 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 30 Mar 2009 11:50:48 -0500 Subject: [Tutor] incrementing one minute In-Reply-To: References: Message-ID: <49D0F868.9030707@ieee.org> mktime() and gmtime() are not inverses of each other. The first assumes local time, and the latter gmt (or utc). So unless you happen to be in England, and not in daylight savings time, you'd expect a problem. mktime() is documented as the inverse of localtime(), according to the docs. I'd assume they'd both make the same time adjustments for your location. However, there's some ambiguity if the time you're looking at is in standard time, while you're currently in daylight savings. So I'd look for an answer that only used UTC (or Greenwich Mean time). Try time.gmtime(), and calendar.timegm() pa yo wrote: > I need to add one minute to a string that has a date and a time in > YYYYMMDDHHMM format. > e.g: 200903281346 should become 200903281347 > > the following script converts the string into time and adds one > minute; but somehow I also add an hour and I don't understand why. > > ==================== > > import time > > #set the initial time as a string and convert it into time format: > fromtimestring = '200903281346' > fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") > #convert this time format into UNIX time (seconds since the start of UNIX time): > fromtimeseconds = time.mktime(fromtimetime) > #add 60 seconds and reformat the result into the YYYYMMDDHHMM format > totimeseconds = fromtimeseconds + 60 > totimetime = time.gmtime(totimeseconds) > # convert the new time into a string: > totimestring = time.strftime("%Y%m%d%H%M", totimetime) > > #print the results: > print (fromtimestring) > print (fromtimetime) > print (totimetime) > print (totimestring) > > ================ > > any help or suggestions would be much appreciated. > > > Payo > > From davea at ieee.org Mon Mar 30 18:52:04 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 30 Mar 2009 11:52:04 -0500 Subject: [Tutor] incrementing one minute In-Reply-To: References: Message-ID: <49D0F8B4.3010700@ieee.org> This is the second post I've seen on this homework assignment. You might look at the Python List for other ideas. mktime() and gmtime() are not inverses of each other. The first assumes local time, and the latter gmt (or utc). So unless you happen to be in England, and not in daylight savings time, you'd expect a problem. mktime() is documented as the inverse of localtime(), according to the docs. I'd assume they'd both make the same time adjustments for your location. However, there's some ambiguity if the time you're looking at is in standard time, while you're currently in daylight savings. So I'd look for an answer that only used UTC (or Greenwich Mean time). Try time.gmtime(), and calendar.timegm() pa yo wrote: > I need to add one minute to a string that has a date and a time in > YYYYMMDDHHMM format. > e.g: 200903281346 should become 200903281347 > > the following script converts the string into time and adds one > minute; but somehow I also add an hour and I don't understand why. > > ==================== > > import time > > #set the initial time as a string and convert it into time format: > fromtimestring = '200903281346' > fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") > #convert this time format into UNIX time (seconds since the start of UNIX time): > fromtimeseconds = time.mktime(fromtimetime) > #add 60 seconds and reformat the result into the YYYYMMDDHHMM format > totimeseconds = fromtimeseconds + 60 > totimetime = time.gmtime(totimeseconds) > # convert the new time into a string: > totimestring = time.strftime("%Y%m%d%H%M", totimetime) > > #print the results: > print (fromtimestring) > print (fromtimetime) > print (totimetime) > print (totimestring) > > ================ > > any help or suggestions would be much appreciated. > > > Payo > > From payo2000 at gmail.com Mon Mar 30 21:23:53 2009 From: payo2000 at gmail.com (pa yo) Date: Mon, 30 Mar 2009 20:23:53 +0100 Subject: [Tutor] incrementing one minute In-Reply-To: <49D0F8B4.3010700@ieee.org> References: <49D0F8B4.3010700@ieee.org> Message-ID: I am trying to filter Open Street Map nodes from http://planet.openstreetmap.org/minute/ ... into wikimark up for Yellowikis (http://www.yellowikis.org) I work from home - but this isn't a homework assignment. :-) Paul Y On Mon, Mar 30, 2009 at 5:52 PM, Dave Angel wrote: > This is the second post I've seen on this homework assignment. ?You might > look at the Python List for other ideas. > > mktime() and gmtime() are not inverses of each other. ?The first assumes > local time, and the latter gmt (or utc). ?So unless you happen to be in > England, and not in daylight savings time, you'd expect a problem. > > mktime() is documented as the inverse of localtime(), according to the docs. > ?I'd assume they'd both make the same time adjustments for your location. > ?However, there's some ambiguity if the time you're looking at is in > standard time, while you're currently in daylight savings. ?So I'd look for > an answer that only used UTC (or Greenwich Mean time). > > Try time.gmtime(), and calendar.timegm() > > > pa yo wrote: > >> I need to add one minute to a string that has a date and a time in >> YYYYMMDDHHMM format. >> e.g: ?200903281346 should become 200903281347 >> >> the following script converts the string into time and adds one >> minute; but somehow I also add an hour and I don't understand why. >> >> ==================== >> >> import time >> >> #set the initial time as a string and convert it into time format: >> fromtimestring = '200903281346' >> fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M") >> #convert this time format into UNIX time (seconds since the start of UNIX >> time): >> fromtimeseconds = time.mktime(fromtimetime) >> #add 60 seconds and reformat the result into the YYYYMMDDHHMM format >> totimeseconds = fromtimeseconds + 60 >> totimetime = time.gmtime(totimeseconds) >> # convert the new time into a string: >> totimestring = time.strftime("%Y%m%d%H%M", totimetime) >> >> #print the results: >> print (fromtimestring) >> print (fromtimetime) >> print (totimetime) >> print (totimestring) >> >> ================ >> >> any help or suggestions would be much appreciated. >> >> >> Payo >> >> > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jimcarnell at yahoo.com Tue Mar 31 05:44:28 2009 From: jimcarnell at yahoo.com (james carnell) Date: Mon, 30 Mar 2009 20:44:28 -0700 (PDT) Subject: [Tutor] range() fractional increment Message-ID: <430910.53900.qm@web54302.mail.re2.yahoo.com> 1) I feel dumb for asking this. 2) I looked for 20 minutes and didn't find an answer Trying to make a drawLine function in a 2d array. example: x0000?? row = 25 : col = 10 x0000?? row = 26 : col = 10.3 x0000?? row = 27 : col = 10.6 0x000?? row = 28 : col = 11 0x000?? row = 29 : col = 11.3 0x000?? row = 30 : col = 11.6 00x00?? row = 31 : col = 12 for row in range(25,31,1): ??? for col in range(10,12, 0.3):? #<- Crash Bang doesn't work 0.3 = zero = infinite loop? so then I tried... >>> c = 10 >>> while(c < 12.3): ...???? print c ...???? c += 1.0/3.0 ... 10 10.3333333333 10.6666666667 11.0 11.3333333333 11.6666666667 12.0 is there no way to do it with a range function (and have it still look like you're not on crack)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Mar 31 05:59:21 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 31 Mar 2009 16:59:21 +1300 Subject: [Tutor] range() fractional increment In-Reply-To: <430910.53900.qm@web54302.mail.re2.yahoo.com> References: <430910.53900.qm@web54302.mail.re2.yahoo.com> Message-ID: <5e58f2e40903302059o4890a42bn3b5a0d31833f89ad@mail.gmail.com> 2009/3/31 james carnell : > for row in range(25,31,1): > ??? for col in range(10,12, 0.3):? #<- Crash Bang doesn't work 0.3 = zero = > infinite loop? > [...] > is there no way to do it with a range function (and have it still look like > you're not on crack)? Well, you could do this: >>> [float(x)/3 for x in range(30, 37)] [10.0, 10.333333333333334, 10.666666666666666, 11.0, 11.333333333333334, 11.666666666666666, 12.0] Or even: >>> [math.floor(10*float(x)/3)/10 for x in range(30, 37)] [10.0, 10.300000000000001, 10.6, 11.0, 11.300000000000001, 11.6, 12.0] However, the builtin range() only works with integers. I think there is a range() function in the python cookbook that will do fractional step sizes. But really, there's nothing wrong with your while loop. -- John. From lie.1296 at gmail.com Tue Mar 31 07:27:58 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 31 Mar 2009 16:27:58 +1100 Subject: [Tutor] range() fractional increment In-Reply-To: <5e58f2e40903302059o4890a42bn3b5a0d31833f89ad@mail.gmail.com> References: <430910.53900.qm@web54302.mail.re2.yahoo.com> <5e58f2e40903302059o4890a42bn3b5a0d31833f89ad@mail.gmail.com> Message-ID: John Fouhy wrote: > 2009/3/31 james carnell : >> for row in range(25,31,1): >> for col in range(10,12, 0.3): #<- Crash Bang doesn't work 0.3 = zero = >> infinite loop? >> [...] >> is there no way to do it with a range function (and have it still look like >> you're not on crack)? > > Well, you could do this: > >>>> [float(x)/3 for x in range(30, 37)] > [10.0, 10.333333333333334, 10.666666666666666, 11.0, > 11.333333333333334, 11.666666666666666, 12.0] > > Or even: > >>>> [math.floor(10*float(x)/3)/10 for x in range(30, 37)] > [10.0, 10.300000000000001, 10.6, 11.0, 11.300000000000001, 11.6, 12.0] > > However, the builtin range() only works with integers. I think there > is a range() function in the python cookbook that will do fractional > step sizes. > > But really, there's nothing wrong with your while loop. > You could boil your own range function (beware: binary floating point may be imprecise) def frange(start, stop, step): width = stop - start n = round(width / step) return [start + step*i for i in xrange(n)] or returning generator instead (may be preferable if the size of the list is extremely large): def frange(start, stop, step): width = stop - start n = round(width / step) return (start + step*i for i in xrange(n)) slightly obscured version: def frange(start, stop, step): return (start + step*i for i in range(round((stop - start) / step))) more complex homebrew frange may return a class that really emulates xrange, by implementing __getitem__, iterator protocol, generator protocol, and all the sugar without ever creating a real list. From metolone+gmane at gmail.com Tue Mar 31 07:52:15 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 30 Mar 2009 22:52:15 -0700 Subject: [Tutor] how are unicode chars represented? References: <20090330093651.27bada23@o> <1c2a2c590903300352t2bd3f1a7j5f37703cf1c3b0c@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c590903300352t2bd3f1a7j5f37703cf1c3b0c at mail.gmail.com... > On Mon, Mar 30, 2009 at 3:36 AM, spir wrote: >> Everything is in the title ;-) >> (Is it kind of integers representing the code point?) > > Unicode is represented as 16-bit integers. I'm not sure, but I don't > think Python has support for surrogate pairs, i.e. characters outside > the BMP. Unicode is simply code points. How the code points are represented internally is another matter. The below code is from a 16-bit Unicode build of Python but should look exactly the same on a 32-bit Unicode build; however, the internal representation is different. Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x=u'\U00012345' >>> x.encode('utf8') '\xf0\x92\x8d\x85' However, I wonder if this should be considered a bug. I would think the length of a Unicode string should be the number of code points in the string, which for my string above should be 1. Anyone have a 32-bit Unicode build of Python handy? This exposes the implementation as UTF-16. >>> len(x) 2 >>> x[0] u'\ud808' >>> x[1] u'\udf45' >>> -Mark From timomlists at gmail.com Tue Mar 31 10:49:58 2009 From: timomlists at gmail.com (Timo) Date: Tue, 31 Mar 2009 10:49:58 +0200 Subject: [Tutor] Shelve doesn't free up memory In-Reply-To: References: <49D07AA2.4080200@gmail.com> Message-ID: <49D1D936.10806@gmail.com> Emile van Sebille schreef: > Timo wrote: > > > >> # Results file >> import shelve >> >> def read_result(person): >> results = [] >> >> s = shelve.open(RESULTFILE) >> try: >> results = s[person] > > > Maybe passing this out prevents s from being garbage collected? What do you mean by passing out? I also tried gc.collect(), but no difference. > > Emile > > >> except KeyError: >> # print "No results for this person" >> pass >> finally: >> s.close() >> >> return results >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Tue Mar 31 10:51:30 2009 From: denis.spir at free.fr (spir) Date: Tue, 31 Mar 2009 10:51:30 +0200 Subject: [Tutor] range() fractional increment In-Reply-To: <430910.53900.qm@web54302.mail.re2.yahoo.com> References: <430910.53900.qm@web54302.mail.re2.yahoo.com> Message-ID: <20090331105130.0b59d886@o> Le Mon, 30 Mar 2009 20:44:28 -0700 (PDT), james carnell s'exprima ainsi: > 1) I feel dumb for asking this. > 2) I looked for 20 minutes and didn't find an answer > > Trying to make a drawLine function in a 2d array. > > example: > x0000?? row = 25 : col = 10 > x0000?? row = 26 : col = 10.3 > x0000?? row = 27 : col = 10.6 > 0x000?? row = 28 : col = 11 > 0x000?? row = 29 : col = 11.3 > 0x000?? row = 30 : col = 11.6 > 00x00?? row = 31 : col = 12 > > for row in range(25,31,1): > ??? for col in range(10,12, 0.3):? #<- Crash Bang doesn't work 0.3 = zero = > infinite loop? > > so then I tried... > > >>> c = 10 > >>> while(c < 12.3): > ...???? print c > ...???? c += 1.0/3.0 > ... > 10 > 10.3333333333 > 10.6666666667 > 11.0 > 11.3333333333 > 11.6666666667 > 12.0 > > is there no way to do it with a range function (and have it still look like > you're not on crack)? Had a tool func for this, and a generator version: def fractRange(start,end,step): diff = end - start step_nr = int(diff/step) + 1 return [start + (step*i) for i in range(step_nr)] def fractRangeGen(start,end,step): diff = end - start step_nr = int(diff/step) + 1 for i in range(step_nr): yield start + (step*i) print fractRange(-1,1.1,1.0/3) for x in fractRangeGen(-1,1.1,1.0/3): print x, ==> [-1.0, -0.66666666666666674, -0.33333333333333337, 0.0, 0.33333333333333326, 0.66666666666666652, 1.0] -1.0 -0.666666666667 -0.333333333333 0.0 0.333333333333 0.666666666667 1.0 denis ------ la vita e estrany From ionut.vancea at gmail.com Tue Mar 31 10:58:13 2009 From: ionut.vancea at gmail.com (Ionut Vancea) Date: Tue, 31 Mar 2009 09:58:13 +0100 Subject: [Tutor] range() fractional increment In-Reply-To: <430910.53900.qm@web54302.mail.re2.yahoo.com> References: <430910.53900.qm@web54302.mail.re2.yahoo.com> Message-ID: <368177940903310158y2f956492kc6131e8ec91ef263@mail.gmail.com> Hi, On Tue, Mar 31, 2009 at 4:44 AM, james carnell wrote: > 1) I feel dumb for asking this. > 2) I looked for 20 minutes and didn't find an answer > > Trying to make a drawLine function in a 2d array. > > example: > x0000?? row = 25 : col = 10 > x0000?? row = 26 : col = 10.3 > x0000?? row = 27 : col = 10.6 > 0x000?? row = 28 : col = 11 > 0x000?? row = 29 : col = 11.3 > 0x000?? row = 30 : col = 11.6 > 00x00?? row = 31 : col = 12 > > for row in range(25,31,1): > ??? for col in range(10,12, 0.3):? #<- Crash Bang doesn't work 0.3 = zero = > infinite loop? > > so then I tried... > >>>> c = 10 >>>> while(c < 12.3): > ...???? print c > ...???? c += 1.0/3.0 > ... > 10 > 10.3333333333 > 10.6666666667 > 11.0 > 11.3333333333 > 11.6666666667 > 12.0 > > is there no way to do it with a range function (and have it still look like > you're not on crack)? maybe you can use arange() from Numeric: In [1]: from Numeric import * In [2]: arange(-1,1,0.2) Out[2]: array([-1. , -0.8, -0.6, -0.4, -0.2, 0. , 0.2, 0.4, 0.6, 0.8]) and if you need a list use: arange(-1,1,0.2).tolist() Cheers, -- === Ioan Vancea http://www.vioan.ro From kent37 at tds.net Tue Mar 31 12:57:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 31 Mar 2009 06:57:39 -0400 Subject: [Tutor] how are unicode chars represented? In-Reply-To: References: <20090330093651.27bada23@o> <1c2a2c590903300352t2bd3f1a7j5f37703cf1c3b0c@mail.gmail.com> Message-ID: <1c2a2c590903310357m682e16acr9d94b12b609939d5@mail.gmail.com> On Tue, Mar 31, 2009 at 1:52 AM, Mark Tolonen wrote: > Unicode is simply code points. ?How the code points are represented > internally is another matter. ?The below code is from a 16-bit Unicode build > of Python but should look exactly the same on a 32-bit Unicode build; > however, the internal representation is different. > > Python 2.6.1 (r261:67517, Dec ?4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> >>>> x=u'\U00012345' >>>> x.encode('utf8') > > '\xf0\x92\x8d\x85' > > However, I wonder if this should be considered a bug. ?I would think the > length of a Unicode string should be the number of code points in the > string, which for my string above should be 1. ?Anyone have a 32-bit Unicode > build of Python handy? ?This exposes the implementation as UTF-16. >>>> >>>> len(x) > > 2 >>>> >>>> x[0] > > u'\ud808' >>>> >>>> x[1] > > u'\udf45' In standard Python the representation of unicode is 16 bits, without correct handling of surrogate pairs (which is what your string contains). I think this is called UCS-2, not UTF-16. There is a a compile switch to enable 32-bit representation of unicode. See PEP 261 and the "Internal Representation" section of the second link below for more details. http://www.python.org/dev/peps/pep-0261/ http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python Kent From davea at ieee.org Tue Mar 31 15:29:49 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 31 Mar 2009 08:29:49 -0500 Subject: [Tutor] incrementing one minute In-Reply-To: References: Message-ID: <49D21ACD.3050505@ieee.org> Sorry for the bad assumption. But the thread "Caught out by daylight saving :-(" on the python-list was very similar, differing mainly by the fact he's incrementing by 5 minutes instead of 1. Did my suggested function replacements work for you? They did here. po yo wrote: > I am trying to filter Open Street Map nodes from > > http://planet.openstreetmap.org/minute/ > > ... into wikimark up for Yellowikis (http://www.yellowikis.org) > > I work from home - but this isn't a homework assignment. :-) > > Paul Y > > On Mon, Mar 30, 2009 at 5:52 PM, Dave Angel wrote: > >> This is the second post I've seen on this homework assignment. ?You might >> look at the Python List for other ideas. >> >> mktime() and gmtime() are not inverses of each other. ?The first assumes >> local time, and the latter gmt (or utc). ?So unless you happen to be in >> England, and not in daylight savings time, you'd expect a problem. >> >> mktime() is documented as the inverse of localtime(), according to the docs. >> ?I'd assume they'd both make the same time adjustments for your location. >> ?However, there's some ambiguity if the time you're looking at is in >> standard time, while you're currently in daylight savings. ?So I'd look for >> an answer that only used UTC (or Greenwich Mean time). >> >> Try time.gmtime(), and calendar.timegm() >> >> From payo2000 at gmail.com Tue Mar 31 19:16:10 2009 From: payo2000 at gmail.com (pa yo) Date: Tue, 31 Mar 2009 18:16:10 +0100 Subject: [Tutor] incrementing one minute In-Reply-To: <49D21ACD.3050505@ieee.org> References: <49D21ACD.3050505@ieee.org> Message-ID: Hi Dave, Yep - incrementing seems to be working fine now. Now I can access smaller XML files that should allow me to use DOM rather than SAX - which I was struggling to understand. Paul Y On Tue, Mar 31, 2009 at 2:29 PM, Dave Angel wrote: > Sorry for the bad assumption. ?But the thread "Caught out by daylight saving > :-(" on ?the python-list was very similar, differing mainly by the fact he's > incrementing by 5 minutes instead of 1. > > Did my suggested function replacements work for you? ?They did here. > > po yo wrote: >> >> I am trying to filter Open Street Map nodes from >> >> http://planet.openstreetmap.org/minute/ >> >> ... into wikimark up for Yellowikis (http://www.yellowikis.org) >> >> ?I work from home - but this isn't a homework assignment. :-) >> >> Paul Y >> >> On Mon, Mar 30, 2009 at 5:52 PM, Dave Angel wrote: >> >>> >>> This is the second post I've seen on this homework assignment. ?You might >>> look at the Python List for other ideas. >>> >>> mktime() and gmtime() are not inverses of each other. ?The first assumes >>> local time, and the latter gmt (or utc). ?So unless you happen to be in >>> England, and not in daylight savings time, you'd expect a problem. >>> >>> mktime() is documented as the inverse of localtime(), according to the >>> docs. >>> ?I'd assume they'd both make the same time adjustments for your location. >>> ?However, there's some ambiguity if the time you're looking at is in >>> standard time, while you're currently in daylight savings. ?So I'd look >>> for >>> an answer that only used UTC (or Greenwich Mean time). >>> >>> Try time.gmtime(), and calendar.timegm() >>> >>> > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Tue Mar 31 19:27:47 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 31 Mar 2009 10:27:47 -0700 Subject: [Tutor] Shelve doesn't free up memory In-Reply-To: <49D1D936.10806@gmail.com> References: <49D07AA2.4080200@gmail.com> <49D1D936.10806@gmail.com> Message-ID: Timo wrote: > Emile van Sebille schreef: >> Timo wrote: >> >> >> >>> # Results file >>> import shelve >>> >>> def read_result(person): >>> results = [] >>> >>> s = shelve.open(RESULTFILE) >>> try: >>> results = s[person] >> >> >> Maybe passing this out prevents s from being garbage collected? > What do you mean by passing out? You're returning (passing out) results to the caller, which holds (perhaps) a reference to s... > > I also tried gc.collect(), but no difference. ... which may be preventing garbage collection. Emile From eike.welk at gmx.net Tue Mar 31 19:01:38 2009 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 31 Mar 2009 18:01:38 +0100 Subject: [Tutor] Automated function creation / outsourcing code In-Reply-To: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> References: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> Message-ID: <200903311901.39561.eike.welk@gmx.net> On Saturday 28 March 2009, Martin Klimach wrote: > Is there a python editor, that can automatically turn a selection > of code into a function? Matching the input and return variables? > Look at "Rope IDE" it is fairly good at refactoring. It is very ugly and not very comfortable, but it works. Due to its limitations it is only suitable for small projects. It is written purely in Python, therefore it is very easy to install. You must install the "Rope library" and the "Rope IDE". IDE: http://rope.sourceforge.net/ropeide.html library: http://rope.sourceforge.net/ HTH, Eike. From noufal at nibrahim.net.in Tue Mar 31 20:14:44 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Tue, 31 Mar 2009 23:44:44 +0530 Subject: [Tutor] Automated function creation / outsourcing code In-Reply-To: <2096a7260903290540p81e3d84i8ef9246455ee4b90@mail.gmail.com> References: <278186bf0903280334y2b62621ch6303aff87f88277f@mail.gmail.com> <333efb450903290531n1f162135h81bb9178b51e27a2@mail.gmail.com> <2096a7260903290540p81e3d84i8ef9246455ee4b90@mail.gmail.com> Message-ID: <49D25D94.4060400@nibrahim.net.in> Oxymoron wrote: > I think you're looking for refactoring features, in this particular > case, a compose method/function refactor. > > Generally, generic editors will have trouble doing this right since it > requires some inferencing capability on the selected code, your best > bet is probably googling Python-aware IDEs with refactoring support, > something like PyDev (http://pydev.sourceforge.net) or eric > (http://eric-ide.python-projects.org/). I don't know if this actually addresses your concerns but Bicycle repair man (http://bicyclerepair.sourceforge.net/) is a python refactoring tool that has bindings for vim and Emacs which are quite common amongst programmers. -- ~noufal http://nibrahim.net.in/ From bijoy.webworkers at gmail.com Tue Mar 31 20:15:19 2009 From: bijoy.webworkers at gmail.com (bijoy franco) Date: Tue, 31 Mar 2009 23:45:19 +0530 Subject: [Tutor] Operational Error. --HELP In-Reply-To: <358348b30903302108u7523d956t68e60f97618610b2@mail.gmail.com> References: <358348b30903302108u7523d956t68e60f97618610b2@mail.gmail.com> Message-ID: <358348b30903311115h684a62daldf8baee82a69d483@mail.gmail.com> Hi, Python throws OperationalError while trying to do any database operations. I am using pgdb module. * **Code:*import pgdb __metaclass__=type class addbook: conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') curs=conn.cursor() def addBook(self): *infunction_curs=self.curs** * *infunction_curs.execute('SELECT * FROM table_book') **error code:* File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany raise OperationalError, "internal error in '%s': %s" % (sql,err) pg.OperationalError: internal error in 'SELECT * FROM table_book': error return without exception set i am not able to do any database operations apart from opening Conection and assaigning cursor object. how do i solve this. pls help Thanks in advance Bijoy -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Mar 31 20:50:29 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 31 Mar 2009 14:50:29 -0400 Subject: [Tutor] Operational Error. --HELP In-Reply-To: <358348b30903311115h684a62daldf8baee82a69d483@mail.gmail.com> References: <358348b30903302108u7523d956t68e60f97618610b2@mail.gmail.com> <358348b30903311115h684a62daldf8baee82a69d483@mail.gmail.com> Message-ID: <49D265F5.3070904@gmail.com> bijoy franco wrote: > > Hi, > > Python throws OperationalError while trying to do any database operations. I am using pgdb module. > > Code: > > import pgdb > > __metaclass__=type > > class addbook: > > conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') > curs=conn.cursor() > > def addBook(self): > > infunction_curs=self.curs > infunction_curs.execute('SELECT * FROM table_book') > > > error code: > > File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany > raise OperationalError, "internal error in '%s': %s" % (sql,err) > pg.OperationalError: internal error in 'SELECT * FROM table_book': error return without exception set > > i am not able to do any database operations apart from opening Conection and assaigning cursor object. > > how do i solve this. pls help 1 - please post in plain text - I reformatted it so I could read it. 2 - please post the rest of the code and the rest of the traceback so we can see where addbook is instantiated and where addBook is called. It is impossible for me to diagnose this without that information. 3 - have you verified in some other way that SELECT * FROM table_book is acceptable to postgresql? 4 - please reply to the list > > Thanks in advance > > Bijoy > Welcome in retrospect. From bgailer at gmail.com Tue Mar 31 21:12:52 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 31 Mar 2009 15:12:52 -0400 Subject: [Tutor] Operational Error. --HELP In-Reply-To: <358348b30903311207n1121932eh5d31609fa14eeafe@mail.gmail.com> References: <358348b30903302108u7523d956t68e60f97618610b2@mail.gmail.com> <358348b30903311115h684a62daldf8baee82a69d483@mail.gmail.com> <49D265F5.3070904@gmail.com> <358348b30903311207n1121932eh5d31609fa14eeafe@mail.gmail.com> Message-ID: <49D26B34.3060106@gmail.com> bijoy franco wrote: > Hi, > > When used in psql interface directly, all Database operation queries > works perfectly fine. > So now we have a different query than the first time! I serioiusly doubt that SELECT book_name FROM table_book WHERE book_name=fgfd works in the interface. Or if it does work then fgfd must have been previously defined. I think the query should be: SELECT book_name FROM table_book WHERE book_name='fgfd' > Pls find the full code and error below > > code: > > import pgdb > > __metaclass__=type > > class addbook: > > conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') > curs=conn.cursor() > > def addBook(self): > name=raw_input("Enter Book Name: ") > subject=raw_input("Enter Book Subject: ") > language=raw_input("Enter Book Language: ") > category=raw_input("Enter Book Category: ") > author=raw_input("Enter Book Author: ") > publication=raw_input("Enter Book Publication: ") > cost=raw_input("Enter Book Cost: ") > purchasedyear=raw_input("Enter Book Purchased Year: ") > > infunction_curs=self.curs > infunction_curs.execute('SELECT book_name FROM > table_book WHERE book_name=%s' %name) > > > conn.commit() > conn.close() > > def main(): > addbookinstance=addbook() > addbookinstance.addBook() > > if __name__=='__main__':main() > > error code: > > Traceback (most recent call last): > File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 44, > in > if __name__=='__main__':main() > File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 42, in main > addbookinstance.addBook() > File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 24, in addBook > infunction_curs.execute('SELECT book_name FROM table_book WHERE > book_name=%s' %name) > File "/usr/lib/python2.5/site-packages/pgdb.py", line 174, in execute > self.executemany(operation, (params,)) > File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany > raise OperationalError, "internal error in '%s': %s" % (sql,err) > pg.OperationalError: internal error in 'SELECT book_name FROM > table_book WHERE book_name=fgfd': error return without exception set > > > > thanks > > Bijoy > > > On Wed, Apr 1, 2009 at 12:20 AM, bob gailer wrote: > >> bijoy franco wrote: >> >>> Hi, >>> >>> Python throws OperationalError while trying to do any database operations. I am using pgdb module. >>> >>> Code: >>> >>> import pgdb >>> >>> __metaclass__=type >>> >>> class addbook: >>> >>> conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') >>> curs=conn.cursor() >>> >>> def addBook(self): >>> >>> infunction_curs=self.curs >>> infunction_curs.execute('SELECT * FROM table_book') >>> >>> >>> error code: >>> >>> File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany >>> raise OperationalError, "internal error in '%s': %s" % (sql,err) >>> pg.OperationalError: internal error in 'SELECT * FROM table_book': error return without exception set >>> >>> i am not able to do any database operations apart from opening Conection and assaigning cursor object. >>> >>> how do i solve this. pls help >>> >> 1 - please post in plain text - I reformatted it so I could read it. >> 2 - please post the rest of the code and the rest of the traceback so we can see where addbook is instantiated and where addBook is called. It is impossible for me to diagnose this without that information. >> 3 - have you verified in some other way that SELECT * FROM table_book is acceptable to postgresql? >> 4 - please reply to the list >> >> >>> Thanks in advance >>> >>> Bijoy >>> >>> >> Welcome in retrospect. >> > > -- Bob Gailer Chapel Hill NC 919-636-4239 From bijoy.webworkers at gmail.com Tue Mar 31 21:07:14 2009 From: bijoy.webworkers at gmail.com (bijoy franco) Date: Wed, 1 Apr 2009 00:37:14 +0530 Subject: [Tutor] Operational Error. --HELP In-Reply-To: <49D265F5.3070904@gmail.com> References: <358348b30903302108u7523d956t68e60f97618610b2@mail.gmail.com> <358348b30903311115h684a62daldf8baee82a69d483@mail.gmail.com> <49D265F5.3070904@gmail.com> Message-ID: <358348b30903311207n1121932eh5d31609fa14eeafe@mail.gmail.com> Hi, When used in psql interface directly, all Database operation queries works perfectly fine. Pls find the full code and error below code: import pgdb __metaclass__=type class addbook: ??????? conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') ??????? curs=conn.cursor() ??????? def addBook(self): ??????????????? name=raw_input("Enter Book Name: ") ??????????????? subject=raw_input("Enter Book Subject: ") ??????????????? language=raw_input("Enter Book Language: ") ??????????????? category=raw_input("Enter Book Category: ") ??????????????? author=raw_input("Enter Book Author: ") ??????????????? publication=raw_input("Enter Book Publication: ") ??????????????? cost=raw_input("Enter Book Cost: ") ??????????????? purchasedyear=raw_input("Enter Book Purchased Year: ") ??????????????? infunction_curs=self.curs ??????????????? infunction_curs.execute('SELECT book_name FROM table_book WHERE book_name=%s' %name) ??????? conn.commit() ??????? conn.close() def main(): ??????? addbookinstance=addbook() ??????? addbookinstance.addBook() if __name__=='__main__':main() error code: Traceback (most recent call last): ? File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 44, in ??? if __name__=='__main__':main() ? File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 42, in main ??? addbookinstance.addBook() ? File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 24, in addBook ??? infunction_curs.execute('SELECT book_name FROM table_book WHERE book_name=%s' %name) ? File "/usr/lib/python2.5/site-packages/pgdb.py", line 174, in execute ??? self.executemany(operation, (params,)) ? File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany ??? raise OperationalError, "internal error in '%s': %s" % (sql,err) pg.OperationalError: internal error in 'SELECT book_name FROM table_book WHERE book_name=fgfd': error return without exception set thanks Bijoy On Wed, Apr 1, 2009 at 12:20 AM, bob gailer wrote: > > bijoy franco wrote: > > > > Hi, > > > > Python throws OperationalError while trying to do any database operations. I am using pgdb module. > > > > Code: > > > > import pgdb > > > > __metaclass__=type > > > > class addbook: > > > > ? ? ? ? conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') > > ? ? ? ? curs=conn.cursor() > > > > ? ? ? ? def addBook(self): > > > > ? ? ? ? ? ? ? ? infunction_curs=self.curs > > ? ? ? ? ? ? ? ? infunction_curs.execute('SELECT * FROM table_book') > > > > > > error code: > > > > File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany > > raise OperationalError, "internal error in '%s': %s" % (sql,err) > > pg.OperationalError: internal error in 'SELECT * FROM table_book': error return without exception set > > > > i am not able to do any database operations apart from opening Conection and assaigning cursor object. > > > > how do i solve this. pls help > > 1 - please post in plain text - I reformatted it so I could read it. > 2 - please post the rest of the code and the rest of the traceback so we can see where addbook is instantiated and where addBook is called. It is impossible for me to diagnose this without that information. > 3 - have you verified in some other way that SELECT * FROM table_book is acceptable to postgresql? > 4 - please reply to the list > > > > > Thanks in advance > > > > Bijoy > > > > Welcome in retrospect. From bijoy.webworkers at gmail.com Tue Mar 31 21:23:05 2009 From: bijoy.webworkers at gmail.com (bijoy franco) Date: Wed, 1 Apr 2009 00:53:05 +0530 Subject: [Tutor] Operational Error. --HELP In-Reply-To: <49D26B34.3060106@gmail.com> References: <358348b30903302108u7523d956t68e60f97618610b2@mail.gmail.com> <358348b30903311115h684a62daldf8baee82a69d483@mail.gmail.com> <49D265F5.3070904@gmail.com> <358348b30903311207n1121932eh5d31609fa14eeafe@mail.gmail.com> <49D26B34.3060106@gmail.com> Message-ID: <358348b30903311223r27e18d5dvec410870713fd8b2@mail.gmail.com> I tried following query as well. code: infunction_curs.execute('SELECT * FROM table_book') This also throws the same error Bijoy On Wed, Apr 1, 2009 at 12:42 AM, bob gailer wrote: > bijoy franco wrote: >> >> Hi, >> >> When used in psql interface directly, all Database operation queries >> works perfectly fine. >> > > So now we have a different query than the first time! > > I serioiusly doubt that > > SELECT book_name FROM table_book WHERE book_name=fgfd > > works in the interface. > > Or if it does work then fgfd must have been previously defined. > > I think the query should be: > > SELECT book_name FROM table_book WHERE book_name='fgfd' > > >> Pls find the full code and error below >> >> code: >> >> import pgdb >> >> __metaclass__=type >> >> class addbook: >> >> >> ?conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') >> ? ? ? ?curs=conn.cursor() >> >> ? ? ? ?def addBook(self): >> ? ? ? ? ? ? ? ?name=raw_input("Enter Book Name: ") >> ? ? ? ? ? ? ? ?subject=raw_input("Enter Book Subject: ") >> ? ? ? ? ? ? ? ?language=raw_input("Enter Book Language: ") >> ? ? ? ? ? ? ? ?category=raw_input("Enter Book Category: ") >> ? ? ? ? ? ? ? ?author=raw_input("Enter Book Author: ") >> ? ? ? ? ? ? ? ?publication=raw_input("Enter Book Publication: ") >> ? ? ? ? ? ? ? ?cost=raw_input("Enter Book Cost: ") >> ? ? ? ? ? ? ? ?purchasedyear=raw_input("Enter Book Purchased Year: ") >> >> ? ? ? ? ? ? ? ?infunction_curs=self.curs >> ? ? ? ? ? ? ? ?infunction_curs.execute('SELECT book_name FROM >> table_book WHERE book_name=%s' %name) >> >> >> ? ? ? ?conn.commit() >> ? ? ? ?conn.close() >> >> def main(): >> ? ? ? ?addbookinstance=addbook() >> ? ? ? ?addbookinstance.addBook() >> >> if __name__=='__main__':main() >> >> error code: >> >> Traceback (most recent call last): >> ?File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 44, >> in >> ? ?if __name__=='__main__':main() >> ?File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 42, in >> main >> ? ?addbookinstance.addBook() >> ?File "/home/bijoy/python/secondbooks/secondbooks_main.py", line 24, in >> addBook >> ? ?infunction_curs.execute('SELECT book_name FROM table_book WHERE >> book_name=%s' %name) >> ?File "/usr/lib/python2.5/site-packages/pgdb.py", line 174, in execute >> ? ?self.executemany(operation, (params,)) >> ?File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in executemany >> ? ?raise OperationalError, "internal error in '%s': %s" % (sql,err) >> pg.OperationalError: internal error in 'SELECT book_name FROM >> table_book WHERE book_name=fgfd': error return without exception set >> >> >> >> thanks >> >> Bijoy >> >> >> On Wed, Apr 1, 2009 at 12:20 AM, bob gailer wrote: >> >>> >>> bijoy franco wrote: >>> >>>> >>>> Hi, >>>> >>>> Python throws OperationalError while trying to do any database >>>> operations. I am using pgdb module. >>>> >>>> Code: >>>> >>>> import pgdb >>>> >>>> __metaclass__=type >>>> >>>> class addbook: >>>> >>>> >>>> ?conn=pgdb.connect(dsn='localhost:secondbooks',user='postgres',password='postgres1') >>>> ? ? ? ?curs=conn.cursor() >>>> >>>> ? ? ? ?def addBook(self): >>>> >>>> ? ? ? ? ? ? ? ?infunction_curs=self.curs >>>> ? ? ? ? ? ? ? ?infunction_curs.execute('SELECT * FROM table_book') >>>> >>>> >>>> error code: >>>> >>>> File "/usr/lib/python2.5/site-packages/pgdb.py", line 197, in >>>> executemany >>>> raise OperationalError, "internal error in '%s': %s" % (sql,err) >>>> pg.OperationalError: internal error in 'SELECT * FROM table_book': error >>>> return without exception set >>>> >>>> i am not able to do any database operations apart from opening Conection >>>> and assaigning cursor object. >>>> >>>> how do i solve this. pls help >>>> >>> >>> 1 - please post in plain text - I reformatted it so I could read it. >>> 2 - please post the rest of the code and the rest of the traceback so we >>> can see where addbook is instantiated and where addBook is called. It is >>> impossible for me to diagnose this without that information. >>> 3 - have you verified in some other way that SELECT * FROM table_book is >>> acceptable to postgresql? >>> 4 - please reply to the list >>> >>> >>>> >>>> Thanks in advance >>>> >>>> Bijoy >>>> >>>> >>> >>> Welcome in retrospect. >>> >> >> > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > From waynejwerner at gmail.com Tue Mar 31 22:48:55 2009 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 31 Mar 2009 15:48:55 -0500 Subject: [Tutor] Tkinter cursor size? Message-ID: <333efb450903311348r398aa2f4pc29e1005ff2241ca@mail.gmail.com> Hi, Is there a way to resize a tkinter cursor? And if so, how? I'm trying to create a fairly simple drawing program, but I want my cursor to resize with my brush size. TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 31 23:21:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 31 Mar 2009 22:21:24 +0100 Subject: [Tutor] range() fractional increment References: <430910.53900.qm@web54302.mail.re2.yahoo.com> Message-ID: "james carnell" wrote > example: > x0000 row = 25 : col = 10 > x0000 row = 26 : col = 10.3 > x0000 row = 27 : col = 10.6 > 0x000 row = 28 : col = 11 > for col in range(10,12, 0.3): #<- Crash Bang doesn't work 0.3 = zero = > infinite loop? If you know the limits (rather than their being variables) you can do for n in range(100,120,3) n = n/10 But if you have variable range limits then a generator or while loop are your best bets I think. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/