From amadeo.bellotti at gmail.com Fri Dec 1 02:31:14 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 30 Nov 2006 20:31:14 -0500 Subject: [Tutor] OT What's next In-Reply-To: References: <163301647446.20061129193257@columbus.rr.com> Message-ID: I will I'm learning Java at school (icky i no) so i thought C+Java+Python would be redcilously strong(especially with Jython). On 11/30/06, Alan Gauld wrote: > > > "Amadeo Bellotti" wrote > > > i have Sams teach yourself C in 21 days fr starters > > is that any good? > > I haven't seen it but given you already know at least the > basics of programming through Python I'm pretty sure it > will be good enough to get you up and started in C. > > C is a very simple language with only about 20-3-0 reserved > words. Like Python most of the power is in its library of > functions. So learning the core language is easy, learning > the functions can take a long time! But like Python you > only need to learn as much as you need at any given time! > > Have fun, > > Alan G > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061130/f96fcc17/attachment.html From rdm at rcblue.com Fri Dec 1 05:44:26 2006 From: rdm at rcblue.com (Dick Moores) Date: Thu, 30 Nov 2006 20:44:26 -0800 Subject: [Tutor] Rounding a float to n significant digits In-Reply-To: <78b3a9580611301457oe052b75i8559a37b3d0d195@mail.gmail.com> References: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> <7.0.1.0.2.20061130113350.05e83588@rcblue.com> <78b3a9580611301457oe052b75i8559a37b3d0d195@mail.gmail.com> Message-ID: <7.0.1.0.2.20061130191010.06794a20@rcblue.com> At 02:57 PM 11/30/2006, wesley chun wrote: >i think on a 32-bit platform, C doubles (IEEE754) are limited to 10 ** >308.25 which is pretty close to 2 ** 1024 > >-wesley Yes, that's close. Did some pinching down: ====================================== >>> 2**1023.99999999999994 1.7976931348621742e+308 >>> 2**1023.99999999999995 Traceback (most recent call last): File "", line 1, in OverflowError: (34, 'Result too large') >>> 10**308.254715559916718359 1.7976931348620926e+308 >>> 10**308.254715559916718360 Traceback (most recent call last): File "", line 1, in OverflowError: (34, 'Result too large') ========================================== But isn't there a PRECISE answer to my question? Or is it OT? Dick From tim.peters at gmail.com Fri Dec 1 06:20:40 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 1 Dec 2006 00:20:40 -0500 Subject: [Tutor] Rounding a float to n significant digits In-Reply-To: <7.0.1.0.2.20061130191010.06794a20@rcblue.com> References: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> <7.0.1.0.2.20061130113350.05e83588@rcblue.com> <78b3a9580611301457oe052b75i8559a37b3d0d195@mail.gmail.com> <7.0.1.0.2.20061130191010.06794a20@rcblue.com> Message-ID: <1f7befae0611302120j7e3bde7aga8907d29c9761729@mail.gmail.com> [Dick Moores] > ... > But isn't there a PRECISE answer to my question? Of course ;-) > Or is it OT? Well, it's really more a question about your machine's floating-point hardware than about Python. Good explanations of exact limits for IEEE-754 floating-point hardware can be found many places on the web. Does it really help to know that, e.g., for an 8-byte IEEE double, the largest representable finite positive value is exactly (2**53-1)*2**971? BTW, the best way to manipulate "exact" values like this is via math.ldexp: >>> math.ldexp(2**53-1, 971) # largest finite positive double 1.7976931348623157e+308 >>> math.ldexp(2**53, 971) # add 1 to the mantissa and it's "too big" Traceback (most recent call last): File "", line 1, in OverflowError: math range error From cappy2112 at gmail.com Fri Dec 1 09:21:33 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Fri, 1 Dec 2006 00:21:33 -0800 Subject: [Tutor] How To structure a program for cmd line mode & gui mode Message-ID: <8249c4ac0612010021x25b39770mc1d7c33ae9eefdac@mail.gmail.com> I"m writing a cmd line program which will automate getting some modules out of cvs, based on some input criteria. Initiallly, I will do a cmd line version, but would like to make a gui version later with QT. I would like to find out how to structure the program so that when the gui version is finised, it will still be fully functional in cmd line mode (without gui). The gui itself will be very simple- A listbox, and button or two. python program.py would run incmd line mode python program.py -g would run in gui mode. How difficult is this to do? Can anyone think of a simple example of a python app that runs in gui mode & cmd line mode? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061201/8f2e3cf0/attachment.html From alan.gauld at btinternet.com Fri Dec 1 09:47:41 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Dec 2006 08:47:41 -0000 Subject: [Tutor] How To structure a program for cmd line mode & gui mode References: <8249c4ac0612010021x25b39770mc1d7c33ae9eefdac@mail.gmail.com> Message-ID: "Tony Cappellini" wrote > I would like to find out how to structure the program so that when > the gui > version is finised, it will still be fully functional in cmd line > mode For complex GUIs this can be quite difficult since GUIs are essentially stateless and command lines are usually stateful. But... > The gui itself will be very simple- A listbox, and button or two. For simple GUIs you are usually just collecting data and then executing one of several *transactions*. To do this via a command line is fairly simple. Just present a text menu of the possible transactions, then capture the data needed for the chosen transavction, then fire the transaction. The key thing is that the transaction code should be UI neutral, it should not have any form of input other than its parameters and it should retuirn its result as a string, or a tuple (or dictionary) of values that the UI can display. Combining GUI and Command versions in the same program just means reading the options at startup and calling the appropriate start UI function. Use modules to separate your concerns - one main, one for the GUI, one for the command line UI and one for the shared transactions. Import the shared module into both GUI modules and import both GUI modules into your main module. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Dec 1 10:14:52 2006 From: rdm at rcblue.com (Dick Moores) Date: Fri, 01 Dec 2006 01:14:52 -0800 Subject: [Tutor] Rounding a float to n significant digits In-Reply-To: <1f7befae0611302120j7e3bde7aga8907d29c9761729@mail.gmail.co m> References: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> <7.0.1.0.2.20061130113350.05e83588@rcblue.com> <78b3a9580611301457oe052b75i8559a37b3d0d195@mail.gmail.com> <7.0.1.0.2.20061130191010.06794a20@rcblue.com> <1f7befae0611302120j7e3bde7aga8907d29c9761729@mail.gmail.com> Message-ID: <7.0.1.0.2.20061201001853.057cb4e8@rcblue.com> At 09:20 PM 11/30/2006, Tim Peters wrote: >[Dick Moores] >>... >>But isn't there a PRECISE answer to my question? > >Of course ;-) > >>Or is it OT? > >Well, it's really more a question about your machine's floating-point >hardware than about Python. Good explanations of exact limits for >IEEE-754 floating-point hardware can be found many places on the web. Well, I did find (2 - 2**-52)*2**1023 on http://babbage.cs.qc.edu/IEEE-754/References.xhtml , which I realize now is equivalent to your (2**53-1)*2**971. I can't say I understand the explanation. >Does it really help to know that, e.g., for an 8-byte IEEE double, the >largest representable finite positive value is exactly >(2**53-1)*2**971? Well, I like your round_to_n() function, and it's useful to know at what point it will fail. round_to_n(1.7976931348623158e+308,16) will compute on my machine, but round_to_n(1.7976931348623159e+308,16) will not. I was also curious as to what the precise max integer to float would be, even if that integer is not precisely relevant to your function. Far from it. Even this computes: >>> i = (2**53-1)*2**971 >>> >>> round_to_n(i+10**291.999, 16) '1.797693134862316e+308' (but this will not: round_to_n(i+10**292, 16) ) For people who have lost my original post, here's Tim's round_to_n() again: ==================================================== def round_to_n(x, n): """ Rounds float x to n significant digits, in scientific notation. Written by Tim Peters. See his Tutor list post of 7/3/04 at http://mail.python.org/pipermail/tutor/2004-July/030324.html """ if n < 1: raise ValueError("number of significant digits must be >= 1") return "%.*e" % (n-1, x) ======================================================== >BTW, the best way to manipulate "exact" values like this is via math.ldexp: > >>>>math.ldexp(2**53-1, 971) # largest finite positive double >1.7976931348623157e+308 >>>>math.ldexp(2**53, 971) # add 1 to the mantissa and it's "too big" >Traceback (most recent call last): > File "", line 1, in >OverflowError: math range error Thanks for that. Dick From torhildrum at gmail.com Fri Dec 1 10:34:18 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Fri, 1 Dec 2006 10:34:18 +0100 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: <5e58f2e40611301356s21cf67devdcd3437065596c69@mail.gmail.com> References: <1164920505.19530.699.camel@www.venix.com> <5e58f2e40611301356s21cf67devdcd3437065596c69@mail.gmail.com> Message-ID: On 11/30/06, John Fouhy wrote: > For the same reason that dictionaries don't preserve order. > Basically, sets are (I think) implemented using a hash table. You can > read about hash tables on wikipedia (or many other places), but one of > the components of a hash table is a function mapping keys to integers > in a particular range. Why not just call a sigar for a sigar. A set is a set, it may be implemented using a hash or it may be implemed using some other datastructure. It could be implemented using lists which preserves order, all though that doesn't make much sense. How it is implemented does not really matter here. http://en.wikipedia.org/wiki/Set If you want a collection of ordered objects, you don't want a set. Not even if the current implementation of sets in Python did preserve order. Doing so could not be considered as anything else than a ugly hack or exploitation of the current implementation. And would be likely to break in the future. Tor From pyro9219 at gmail.com Fri Dec 1 20:58:10 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 1 Dec 2006 11:58:10 -0800 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: References: <1164920505.19530.699.camel@www.venix.com> <5e58f2e40611301356s21cf67devdcd3437065596c69@mail.gmail.com> Message-ID: Ok, well... I think people lost the scope of my question.. I'm happy using the first method that was given to my post, I have stated in two emails that the order doesn't matter.. What I asked was why the order was changed, or more directly, what is the command actually doing to my data? I'm sure the order isn't totally random, but based on how the items are checked and dropped. The reason I care is because I'm just nosey like that and what to know what it is doing differently then the method I mentioned in the start of this thread. Never did I question the validity of the answer the first reply gave me, it works for what I need, not only that, it works well for what I need. I never put any stipulation on the order of the final data, so I didn't expect an answer that was order related. On 12/1/06, Tor Hildrum wrote: > > On 11/30/06, John Fouhy wrote: > > > For the same reason that dictionaries don't preserve order. > > Basically, sets are (I think) implemented using a hash table. You can > > read about hash tables on wikipedia (or many other places), but one of > > the components of a hash table is a function mapping keys to integers > > in a particular range. > > Why not just call a sigar for a sigar. > > A set is a set, it may be implemented using a hash or it may be > implemed using some other datastructure. It could be implemented using > lists which preserves order, all though that doesn't make much sense. > How it is implemented does not really matter here. > > http://en.wikipedia.org/wiki/Set > > If you want a collection of ordered objects, you don't want a set. Not > even if the current implementation of sets in Python did preserve > order. Doing so could not be considered as anything else than a ugly > hack or exploitation of the current implementation. And would be > likely to break in the future. > > Tor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061201/3758dd46/attachment.html From pyro9219 at gmail.com Fri Dec 1 21:00:34 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 1 Dec 2006 12:00:34 -0800 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: <456F4914.1020304@wit.edu> References: <456F4914.1020304@wit.edu> Message-ID: Somewhat less sarcastic... I did omg find that answer, and I didn't feel like this was such a unique thing to do that I needed to re-invent the wheel by building several methods to do something that a common library should already have. On 11/30/06, Jordan Greenberg wrote: > > Chris Hengge wrote: > > Anyone point me to something more efficient then > > > > for item in list1: > > if item not in list2: > > list2.append() > > > > This just seems to take a bit a time when there are thousands or dozens > of > > thousands of records just to filter out the dozen or so copies.. > > > > Thanks. > > somewhat unsurprisingly, the first thing google lists for "python list > duplicates" is a quite good ASPN recipe to do just what you want. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061201/1ef2a96d/attachment.htm From python at venix.com Fri Dec 1 22:06:05 2006 From: python at venix.com (Python) Date: Fri, 01 Dec 2006 16:06:05 -0500 Subject: [Tutor] Best Known Method for Filtering redundant list items. In-Reply-To: References: <1164920505.19530.699.camel@www.venix.com> <5e58f2e40611301356s21cf67devdcd3437065596c69@mail.gmail.com> Message-ID: <1165007165.19530.800.camel@www.venix.com> On Fri, 2006-12-01 at 11:58 -0800, Chris Hengge wrote: > Ok, well... I think people lost the scope of my question.. I'm happy > using the first method that was given to my post, I have stated in two > emails that the order doesn't matter.. > > What I asked was why the order was changed, or more directly, what is > the command actually doing to my data? I'm sure the order isn't > totally random, but based on how the items are checked and dropped. > > The reason I care is because I'm just nosey like that and what to know > what it is doing differently then the method I mentioned in the start > of this thread. Your original method stepped through list1 and tested each element for existence in list2. Since you stated that the proportion of duplicates is low, most searches of list2 are unsuccessful and require checking every element of list2 from beginning to end. For long lists the search time adds up. sets and dictionaries are hash based. The location in the collection is based on a hash value. A check for membership computes the hash which is used to pinpoint the location in the collection. There are issues where different elements have identical hashes, but those are handled efficiently. So searching for matches is dramatically faster than stepping through a long list. I believe the ordering within sets and dictionaries happens to match the hash ordering. for x in aset: print hash(x) comes out in ascending order on the 3 sets I checked. That's not really a surprise. In terms of correct programs, the order of set and dictionary items should be viewed as arbitrary. > > Never did I question the validity of the answer the first reply gave > me, it works for what I need, not only that, it works well for what I > need. I never put any stipulation on the order of the final data, so I > didn't expect an answer that was order related. > > On 12/1/06, Tor Hildrum wrote: > On 11/30/06, John Fouhy wrote: > > > For the same reason that dictionaries don't preserve order. > > Basically, sets are (I think) implemented using a hash > table. You can > > read about hash tables on wikipedia (or many other places), > but one of > > the components of a hash table is a function mapping keys to > integers > > in a particular range. > > Why not just call a sigar for a sigar. > > A set is a set, it may be implemented using a hash or it may > be > implemed using some other datastructure. It could be > implemented using > lists which preserves order, all though that doesn't make much > sense. > How it is implemented does not really matter here. > > http://en.wikipedia.org/wiki/Set > > If you want a collection of ordered objects, you don't want a > set. Not > even if the current implementation of sets in Python did > preserve > order. Doing so could not be considered as anything else than > a ugly > hack or exploitation of the current implementation. And would > be > likely to break in the future. > > Tor > _______________________________________________ > 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 Kvam Venix Corp From dkuhlman at rexx.com Fri Dec 1 22:21:37 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 1 Dec 2006 13:21:37 -0800 Subject: [Tutor] How To structure a program for cmd line mode & gui mode In-Reply-To: <8249c4ac0612010021x25b39770mc1d7c33ae9eefdac@mail.gmail.com> References: <8249c4ac0612010021x25b39770mc1d7c33ae9eefdac@mail.gmail.com> Message-ID: <20061201212137.GA79267@cutter.rexx.com> On Fri, Dec 01, 2006 at 12:21:33AM -0800, Tony Cappellini wrote: > I"m writing a cmd line program which will automate getting some modules out > of cvs, based on some > input criteria. > > Initiallly, I will do a cmd line version, but would like to make a gui > version later with QT. > > I would like to find out how to structure the program so that when the gui > version is finised, it will still be fully functional in cmd line mode > (without gui). Suggestions: 1. Look at module cmd in the Python standard library if you have not already. (see http://docs.python.org/lib/module-cmd.html) 2. In your code, separate functionality from interface (GUI). Your goal should be to be able to use the functions (or classes) that implement function in both the command line code and the GUI code. Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From pyro9219 at gmail.com Fri Dec 1 23:34:15 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 1 Dec 2006 14:34:15 -0800 Subject: [Tutor] How To structure a program for cmd line mode & gui mode In-Reply-To: <8249c4ac0612010021x25b39770mc1d7c33ae9eefdac@mail.gmail.com> References: <8249c4ac0612010021x25b39770mc1d7c33ae9eefdac@mail.gmail.com> Message-ID: I'm wondering if this (snipped from another poster) 1. Look at module cmd in the Python standard library if you have not already. (see http://docs.python.org/lib/module-cmd.html) would be used for something like a built in console found in alot of games? On 12/1/06, Tony Cappellini wrote: > > > I"m writing a cmd line program which will automate getting some modules > out of cvs, based on some > input criteria. > > Initiallly, I will do a cmd line version, but would like to make a gui > version later with QT. > > I would like to find out how to structure the program so that when the gui > version is finised, it will still be fully functional in cmd line mode > (without gui). > > The gui itself will be very simple- A listbox, and button or two. > > python program.py > > would run incmd line mode > > python program.py -g > > would run in gui mode. > > > How difficult is this to do? Can anyone think of a simple example of a > python app that runs in gui mode & cmd line mode? > > thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061201/77625c74/attachment.html From jfabiani at yolo.com Sat Dec 2 01:27:58 2006 From: jfabiani at yolo.com (johnf) Date: Fri, 1 Dec 2006 16:27:58 -0800 Subject: [Tutor] which file runs Message-ID: <200612011627.58137.jfabiani@yolo.com> Hi, if there is a pyc and a py file within a module and the py file has a later date which file will python run? John -- John Fabiani From pyro9219 at gmail.com Sat Dec 2 01:32:02 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 1 Dec 2006 16:32:02 -0800 Subject: [Tutor] which file runs In-Reply-To: <200612011627.58137.jfabiani@yolo.com> References: <200612011627.58137.jfabiani@yolo.com> Message-ID: My understanding is that whenever you run a script that has a newer.py, the .py runs, otherwise it automagically will use the .pyc On 12/1/06, johnf wrote: > > Hi, > if there is a pyc and a py file within a module and the py file has a > later > date which file will python run? > > John > -- > John Fabiani > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061201/20a47934/attachment.html From chris.arndt at web.de Sat Dec 2 02:59:07 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 02 Dec 2006 02:59:07 +0100 Subject: [Tutor] which file runs In-Reply-To: References: <200612011627.58137.jfabiani@yolo.com> Message-ID: <4570DDEB.80308@web.de> Chris Hengge schrieb: > My understanding is that whenever you run a script that has a newer.py, > the .py runs, otherwise it automagically will use the .pyc Not exactly. Whenever there is a .py file and no .pyc file is present or the .pyc file is older, Python will read the .py file, compile it into bytecode and execute that and also tries to write the bytecode to the .pyc file. If there already is a .pyc file and it is newer, Python will use it directly. (The rule is similar for .pyo files, which will be looked for/generated when Python is started with the -O option). Chris From chris.arndt at web.de Sat Dec 2 03:07:31 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 02 Dec 2006 03:07:31 +0100 Subject: [Tutor] which file runs In-Reply-To: References: <200612011627.58137.jfabiani@yolo.com> Message-ID: <4570DFE3.9000401@web.de> Addendum: these rules only apply to Python *modules*. AFAIK, when you call a Python file as a script, no matching .pyc/.pyo file is used or generated. There are some clever tricks to run a .pyc file as a script. I think it is described in the Python CGI FAQ. Chris From devayani.barve at gmail.com Sat Dec 2 13:23:40 2006 From: devayani.barve at gmail.com (devayani barve) Date: Sat, 2 Dec 2006 17:53:40 +0530 Subject: [Tutor] html processing Message-ID: <301929340612020423i32c1fb4fqb8254c93f6ad0760@mail.gmail.com> I have a table in hmtl and i want to write a program so that I can insert a column within it.. Can someone tell me what to use ..... as in dom??? Just want to know how to go about it!!! Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061202/2ced62dc/attachment.htm From chris.arndt at web.de Sat Dec 2 14:42:26 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 02 Dec 2006 14:42:26 +0100 Subject: [Tutor] html processing In-Reply-To: <301929340612020423i32c1fb4fqb8254c93f6ad0760@mail.gmail.com> References: <301929340612020423i32c1fb4fqb8254c93f6ad0760@mail.gmail.com> Message-ID: <457182C2.9020603@web.de> devayani barve schrieb: > I have a table in hmtl and i want to write a program so that I > can insert a column within it.. > Can someone tell me what to use ..... as in dom??? > Just want to know how to go about it!!! What do you mean exactly? Do you want to manipulate the HTML document in the browser while displaying it or do you want to change an in-memory representation of a HTML document (read from and written to a file again perhaps)? The former would have to be done with JavaScript and you should probably ask on a JavaScript list how to do this (though I'd highly recommend you look at the MochiKit JavaScript library ). For the latter, you could parse the HTML into a DOM representation and then use DOM methods to add and change Nodes in it. There are several libraries in Python that allow you to do so. A recent favourite with the Python community is ElementTree , though you might have to clean up the HTML input a little bit before you feed it into ElementTree (e.g. with BeautfulSoup . HTH, Chris From kent37 at tds.net Sat Dec 2 16:06:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 02 Dec 2006 10:06:43 -0500 Subject: [Tutor] html processing In-Reply-To: <301929340612020423i32c1fb4fqb8254c93f6ad0760@mail.gmail.com> References: <301929340612020423i32c1fb4fqb8254c93f6ad0760@mail.gmail.com> Message-ID: <45719683.4060700@tds.net> devayani barve wrote: > I have a table in hmtl and i want to write a program so that I > can insert a column within it.. > Can someone tell me what to use ..... as in dom??? > Just want to know how to go about it!!! Take a look at Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/documentation.html Kent From paulino1 at sapo.pt Sat Dec 2 18:33:48 2006 From: paulino1 at sapo.pt (Paulino) Date: Sat, 02 Dec 2006 17:33:48 +0000 Subject: [Tutor] How to kill an app from python on windows? In-Reply-To: <45208761.1010207@gmail.com> References: <4520533C.9090500@sapo.pt> <45208761.1010207@gmail.com> Message-ID: <4571B8FC.9020209@sapo.pt> To launch an app one can state os.startfile('hello.pdf') and the file is opened in acrobat . And how can I kill the app from python, in order to, for instance, rename the file? Is it possible? thanks Paulino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061202/98fd9b4b/attachment.htm From aymchaos at yahoo.com Sun Dec 3 09:27:52 2006 From: aymchaos at yahoo.com (Mihai Iacob) Date: Sun, 3 Dec 2006 00:27:52 -0800 (PST) Subject: [Tutor] Writing a list in a text file Message-ID: <427292.14985.qm@web32715.mail.mud.yahoo.com> Hello def saveBugs(data): store = open(filename, 'w') for timeMark,aList in data.items(): store.write(timeMark + '\n') store.write(aList + '\n') store.close() data is a dictionary aList is a list After i run this part the following error pops up: Traceback (most recent call last): File "C:\Python\Bugs.py", line 133, in main() File "C:\Python\Bugs.py", line 130, in main saveBugs(dataBugs) File "C:\Python\Bugs.py", line 17, in saveBugs store.write(aList + '\n') TypeError: can only concatenate list (not "str") to list Can anybody tell me how to make it work ____________________________________________________________________________________ Yahoo! Music Unlimited Access over 1 million songs. http://music.yahoo.com/unlimited From gtnorton at earthlink.net Sun Dec 3 09:48:43 2006 From: gtnorton at earthlink.net (Glenn T Norton) Date: Sun, 03 Dec 2006 02:48:43 -0600 Subject: [Tutor] Writing a list in a text file In-Reply-To: <427292.14985.qm@web32715.mail.mud.yahoo.com> References: <427292.14985.qm@web32715.mail.mud.yahoo.com> Message-ID: <45728F6B.4040507@earthlink.net> Mihai Iacob wrote: >Hello > > >def saveBugs(data): > store = open(filename, 'w') > for timeMark,aList in data.items(): > store.write(timeMark + '\n') > store.write(aList + '\n') > store.close() > >data is a dictionary >aList is a list > >After i run this part the following error pops up: > >Traceback (most recent call last): > File "C:\Python\Bugs.py", line 133, in > main() > File "C:\Python\Bugs.py", line 130, in main > saveBugs(dataBugs) > File "C:\Python\Bugs.py", line 17, in saveBugs > store.write(aList + '\n') >TypeError: can only concatenate list (not "str") to >list > >Can anybody tell me how to make it work > > > >____________________________________________________________________________________ >Yahoo! Music Unlimited >Access over 1 million songs. >http://music.yahoo.com/unlimited >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Hi Mihai, The error says it all. You cant concatenate a string to a list [1,2,3,4,5] + '\n', Try [1,2,3,4,5] + '\n' in the interpretor, you ll get the same error. write() doesn't know what to do with a list as [i think] it will only handle strings. If you wrap your list in str() for writing, that should do the trick Wouldn't hurt to wrap timeMark in str() also, unless your positive that the keys will always be strings store.write(str(timeMark) + '\n') store.write(str(aList) + '\n') HTH Good Luck, Glenn -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 glenn at nebraska.gov From alan.gauld at btinternet.com Sun Dec 3 10:12:10 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Dec 2006 09:12:10 -0000 Subject: [Tutor] Writing a list in a text file References: <427292.14985.qm@web32715.mail.mud.yahoo.com> Message-ID: "Mihai Iacob" wrote in > > def saveBugs(data): > store = open(filename, 'w') > for timeMark,aList in data.items(): > store.write(timeMark + '\n') > store.write(aList + '\n') > store.close() > > After i run this part the following error pops up: > > Traceback (most recent call last): > store.write(aList + '\n') > TypeError: can only concatenate list (not "str") to > list As the error says you can't join lists and strings, you need to convert the list to a string first. But it might be worth considering whether you will ever want to read that list back into your program, because if you do the simple str() functions representation of your list might not be the best. In that case you might want to write a functiuon to save the list item by item, and another to load the list back again. But if you just want to store the values to read in an editor the str() function will probably be just fine. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Tim.Golden at viacom-outdoor.co.uk Mon Dec 4 09:46:07 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 4 Dec 2006 08:46:07 -0000 Subject: [Tutor] How to kill an app from python on windows? In-Reply-To: <4571B8FC.9020209@sapo.pt> Message-ID: [Paulino] | To launch an app one can state os.startfile('hello.pdf') and | the file is opened in acrobat . | | And how can I kill the app from python, in order to, for | instance, rename the file? | | Is it possible? This link may get you started: http://effbot.org/pyfaq/how-do-i-emulate-os-kill-in-windows.htm although it may not apply, depending on the exact circumstances of what you're doing. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rdm at rcblue.com Mon Dec 4 11:33:15 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 04 Dec 2006 02:33:15 -0800 Subject: [Tutor] Rounding a float to n significant digits In-Reply-To: <7.0.1.0.2.20061130113350.05e83588@rcblue.com> References: <7.0.1.0.2.20061127231658.083d26f0@rcblue.com> <7.0.1.0.2.20061130113350.05e83588@rcblue.com> Message-ID: <7.0.1.0.2.20061204022226.033309a8@rcblue.com> At 12:52 PM 11/30/2006, Dick Moores wrote: >At 11:19 PM 11/27/2006, Dick Moores wrote: > >I just dug this Tim Smith creation out of the Tutor archive. > > > >def round_to_n(x, n): > > """ > > Rounds float x to n significant digits, in scientific notation. > > Written by Tim Peters. See his Tutor list post of 7/3/04 at > > http://mail.python.org/pipermail/tutor/2004-July/030324.html > > """ > > if n < 1: > > raise ValueError("number of significant digits > must be >= 1") > > return "%.*e" % (n-1, x) > > > >Thought others might find it of use. > > > >Dick Moores > >I've run into the limitation on the size of an int that can be >converted to a float. I back with this topic. I'd completely forgotten that I had written numberRounding(), which doesn't suffer from that limitation: def numberRounding(n, significantDigits=4): import decimal def d(x): return decimal.Decimal(str(x)) decimal.getcontext().prec = significantDigits return d(n)/d(1) Thus, >>> n = 2**2000 >>> print numberRounding(n,6) 1.14813E+602 BTW the last line of numberRounding() seems strange (even though it works)? Why wouldn't "return d(n)" do the job? Thanks, Dick Moores From ajkadri at googlemail.com Mon Dec 4 17:43:42 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Mon, 4 Dec 2006 16:43:42 +0000 Subject: [Tutor] Getting the screen size....using Tkinter Message-ID: Hi folks, Is it possible to get the screen size using a standard API of Tkinter? And also any function to position the window in the center of the screen..?? Thanks in anticipation. Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061204/6dbfe8ac/attachment.html From ncain at web-magnets.com Mon Dec 4 17:51:58 2006 From: ncain at web-magnets.com (Nathan Cain) Date: Mon, 4 Dec 2006 10:51:58 -0600 Subject: [Tutor] Why is startfile unavailable on my mac? Message-ID: <19F36593-C49B-4AEB-9E91-109DCA40F75A@web-magnets.com> When I type the following in macpython IDLE,: >>> import os >>> os.startfile() I get the following error: Traceback (most recent call last): File "", line 1, in os.startfile() AttributeError: 'module' object has no attribute 'startfile' Why is this unavailable to me? I am trying to open a url in a browser window. If startfile is just not available on the mac, can someone please give me some simple example code that will open http://www.python.org in a safari window? Thank you. ******************************************* Nathan Cain http://www.Web-Magnets.com Refrigerator Magnets & Promotional Products Office: 1-877-WEB-MAGNETS (932-6246) Cell Phone: 1-501-276-0817 Fax: 1-267-295-8776 Click here if you want me to email you when we run sales or specials. ******************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061204/7bde4b84/attachment.htm From Mike.Hansen at atmel.com Mon Dec 4 18:01:13 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 4 Dec 2006 10:01:13 -0700 Subject: [Tutor] Why is startfile unavailable on my mac? Message-ID: <57B026980605A64F9B23484C5659E32E44E823@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Nathan Cain > Sent: Monday, December 04, 2006 9:52 AM > To: tutor at python.org > Subject: [Tutor] Why is startfile unavailable on my mac? > > When I type the following in macpython IDLE,: > > >>> import os > >>> os.startfile() > > I get the following error: > > Traceback (most recent call last): > File "", line 1, in > os.startfile() > AttributeError: 'module' object has no attribute 'startfile' > > > Why is this unavailable to me? > > > I am trying to open a url in a browser window. > > > If startfile is just not available on the mac, can someone > please give me some simple example code that will open > http://www.python.org in a safari window? > > > Thank you. > > ******************************************* > Nathan Cain I just read the docs. I'm assuming that "Availability: Windows" means that it's Windows only. Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From kent37 at tds.net Mon Dec 4 18:03:47 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 04 Dec 2006 12:03:47 -0500 Subject: [Tutor] Why is startfile unavailable on my mac? In-Reply-To: <19F36593-C49B-4AEB-9E91-109DCA40F75A@web-magnets.com> References: <19F36593-C49B-4AEB-9E91-109DCA40F75A@web-magnets.com> Message-ID: <457454F3.2030108@tds.net> Nathan Cain wrote: > When I type the following in macpython IDLE,: > >> >> import os >> >> os.startfile() > > I get the following error: > > Traceback (most recent call last): > File "", line 1, in > os.startfile() > AttributeError: 'module' object has no attribute 'startfile' > > Why is this unavailable to me? The docs for os.startfile() say it is available on Windows only. > > I am trying to open a url in a browser window. > > If startfile is just not available on the mac, can someone please give > me some simple example code that will open http://www.python.org in a > safari window? Try webbrowser.open('http://www.python.org') Kent From DFeise at ea.com Mon Dec 4 18:23:21 2006 From: DFeise at ea.com (Feise, David) Date: Mon, 4 Dec 2006 09:23:21 -0800 Subject: [Tutor] Getting the screen size....using Tkinter In-Reply-To: Message-ID: <23EEDA6DFA85B14EA82718973A598AC90931482F@EAHQ-CSMB7.rws.ad.ea.com> Try this: >>> from Tkinter import * >>> root = Tk() >>> root.winfo_screenwidth() 1280 >>> root.winfo_screenheight() 1024 >>> -Dave ________________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Asrarahmed Kadri Sent: Monday, December 04, 2006 8:44 AM To: tutor-python Subject: [Tutor] Getting the screen size....using Tkinter Hi folks, Is it possible to get the screen size using a standard API of Tkinter? And also any function to position the window in the center of the screen..?? Thanks in anticipation. Regards, Asrarahmed Kadri -- To HIM you shall return. From tavspam at gmail.com Mon Dec 4 19:06:43 2006 From: tavspam at gmail.com (Thomas) Date: Mon, 4 Dec 2006 18:06:43 +0000 Subject: [Tutor] difflib.SequenceMatcher with get_matching_blocks is incorrect Message-ID: <493b81e30612041006q412014cbvdf38c137155eee29@mail.gmail.com> I'm trying to write a program to test someone's typing speed and show them their mistakes. However I'm getting weird results when looking for the differences in longer (than 100 chars) strings: import difflib # a tape measure string (just makes it easier to locate a given index) a = '1-3-5-7-9-12-15-18-21-24-27-30-33-36-39-42-45-48-51-54-57-60-63-66-69-72-75-78-81-84-87-90-93-96-99-103-107-111-115-119-123-127-131-135-139-143-147-151-155-159-163-167-171-175-179-183-187-191-195--200' # now with a few mistakes b = '1-3-5-7-l-12-15-18-21-24-27-30-33-36-39o42-45-48-51-54-57-60-63-66-69-72-75-78-81-84-8k-90-93-96-9l-103-107-111-115-119-12b-1v7-131-135-139-143-147-151-m55-159-163-167-a71-175j179-183-187-191-195--200' s = difflib.SequenceMatcher(None, a ,b) ms = s.get_matching_blocks() print ms [(0, 0, 8), (200, 200, 0)] Have I made a mistake or is this function designed to give up when the input strings get too long? Thanks in advance, Thomas From ncain at web-magnets.com Mon Dec 4 19:17:05 2006 From: ncain at web-magnets.com (Nathan Cain) Date: Mon, 4 Dec 2006 12:17:05 -0600 Subject: [Tutor] clicking a javascript link in a browser Message-ID: <39775DDA-FF97-4EBA-B479-BE33783E5CF9@web-magnets.com> There is a link on a pop-up window from a page that I opened with webbrowser.open() the link is: javascript:Events.clearList(); is there a way for python to "click that link"? Thank you. ******************************************* Nathan Cain http://www.Web-Magnets.com Refrigerator Magnets & Promotional Products Office: 1-877-WEB-MAGNETS (932-6246) Cell Phone: 1-501-276-0817 Fax: 1-267-295-8776 Click here if you want me to email you when we run sales or specials. ******************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061204/e94cb713/attachment.html From john at fouhy.net Mon Dec 4 22:53:30 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 5 Dec 2006 10:53:30 +1300 Subject: [Tutor] Why is startfile unavailable on my mac? In-Reply-To: <457454F3.2030108@tds.net> References: <19F36593-C49B-4AEB-9E91-109DCA40F75A@web-magnets.com> <457454F3.2030108@tds.net> Message-ID: <5e58f2e40612041353o1ec5782hb4a05fa039772414@mail.gmail.com> On 05/12/06, Kent Johnson wrote: > The docs for os.startfile() say it is available on Windows only. Hmm, well you could do a basic Mac version of startfile like this: def startfile(fn): os.system('open %s' % fn) -- John. From klappnase at freenet.de Mon Dec 4 23:49:47 2006 From: klappnase at freenet.de (Michael Lange) Date: Mon, 4 Dec 2006 23:49:47 +0100 Subject: [Tutor] Getting the screen size....using Tkinter In-Reply-To: References: Message-ID: <20061204234947.6c0f5eb5.klappnase@freenet.de> On Mon, 4 Dec 2006 16:43:42 +0000 "Asrarahmed Kadri" wrote: > Hi folks, > > Is it possible to get the screen size using a standard API of Tkinter? > > And also any function to position the window in the center of the screen..?? > > Thanks in anticipation. > You might want to have a look at Pmw's _centreonscreen method: def _centreonscreen(self): # Centre the window on the screen. (Actually halfway across # and one third down.) parent = self.winfo_parent() if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) # Find size of window. self.update_idletasks() width = self.winfo_width() height = self.winfo_height() if width == 1 and height == 1: # If the window has not yet been displayed, its size is # reported as 1x1, so use requested size. width = self.winfo_reqwidth() height = self.winfo_reqheight() # Place in centre of screen: x = (self.winfo_screenwidth() - width) / 2 - parent.winfo_vrootx() y = (self.winfo_screenheight() - height) / 3 - parent.winfo_vrooty() if x < 0: x = 0 if y < 0: y = 0 return '+%d+%d' % (x, y) If you replace self resp. self._hull with your window and pass the return value to a call of its geometry() method it should do what you want. I hope this helps Michael From billa_lazarus at yahoo.com Tue Dec 5 04:59:59 2006 From: billa_lazarus at yahoo.com (Lazarus billa) Date: Mon, 4 Dec 2006 19:59:59 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 34, Issue 7 In-Reply-To: Message-ID: <20061205035959.98589.qmail@web56112.mail.re3.yahoo.com> Dear Sir, When I wanted to Browse "sevenworlds at att.net" I am not able to get it and it indicates "cannot find server due to Syntax Error." Plz Advise. Urs in His Service Rev. Billa. Lazarus Ph: 91 9948189975 --- 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. Getting the screen size....using Tkinter > (Asrarahmed Kadri) > 2. Why is startfile unavailable on my mac? > (Nathan Cain) > 3. Re: Why is startfile unavailable on my mac? > (Mike Hansen) > 4. Re: Why is startfile unavailable on my mac? > (Kent Johnson) > 5. Re: Getting the screen size....using Tkinter > (Feise, David) > 6. difflib.SequenceMatcher with > get_matching_blocks is incorrect > (Thomas) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 4 Dec 2006 16:43:42 +0000 > From: "Asrarahmed Kadri" > Subject: [Tutor] Getting the screen size....using > Tkinter > To: tutor-python > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > Hi folks, > > Is it possible to get the screen size using a > standard API of Tkinter? > > And also any function to position the window in the > center of the screen..?? > > Thanks in anticipation. > > Regards, > > Asrarahmed Kadri > > -- > To HIM you shall return. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20061204/6dbfe8ac/attachment-0001.html > > > ------------------------------ > > Message: 2 > Date: Mon, 4 Dec 2006 10:51:58 -0600 > From: Nathan Cain > Subject: [Tutor] Why is startfile unavailable on my > mac? > To: tutor at python.org > Message-ID: > <19F36593-C49B-4AEB-9E91-109DCA40F75A at web-magnets.com> > Content-Type: text/plain; charset="us-ascii" > > When I type the following in macpython IDLE,: > > >>> import os > >>> os.startfile() > > I get the following error: > > Traceback (most recent call last): > File "", line 1, in > os.startfile() > AttributeError: 'module' object has no attribute > 'startfile' > > Why is this unavailable to me? > > I am trying to open a url in a browser window. > > If startfile is just not available on the mac, can > someone please > give me some simple example code that will open > http://www.python.org > in a safari window? > > Thank you. > > ******************************************* > Nathan Cain > http://www.Web-Magnets.com > > Refrigerator Magnets & Promotional Products > > Office: 1-877-WEB-MAGNETS (932-6246) > Cell Phone: 1-501-276-0817 > Fax: 1-267-295-8776 > > Click here if you want me to email you > when we run sales or specials. > ******************************************* > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20061204/7bde4b84/attachment-0001.htm > > > ------------------------------ > > Message: 3 > Date: Mon, 4 Dec 2006 10:01:13 -0700 > From: "Mike Hansen" > Subject: Re: [Tutor] Why is startfile unavailable on > my mac? > To: > Message-ID: > > <57B026980605A64F9B23484C5659E32E44E823 at poccso.US.ad.atmel.com> > Content-Type: text/plain; charset="us-ascii" > > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of > Nathan Cain > > Sent: Monday, December 04, 2006 9:52 AM > > To: tutor at python.org > > Subject: [Tutor] Why is startfile unavailable on > my mac? > > > > When I type the following in macpython IDLE,: > > > > >>> import os > > >>> os.startfile() > > > > I get the following error: > > > > Traceback (most recent call last): > > File "", line 1, in > > os.startfile() > > AttributeError: 'module' object has no attribute > 'startfile' > > > > > > Why is this unavailable to me? > > > > > > I am trying to open a url in a browser window. > > > > > > If startfile is just not available on the mac, can > someone > > please give me some simple example code that will > open > > http://www.python.org in a safari window? > > > > > > Thank you. > > > > ******************************************* > > Nathan Cain > > I just read the docs. I'm assuming that > "Availability: Windows" means > that it's Windows only. > > Mike > -------------- next part -------------- > ------------- > > NOTICE: This e-mail transmission and any > documents or files attached to > it contain information for the sole use of the > above-identified individual or entity. > > Its contents may be privileged, confidential, and > exempt from disclosure under the law. > Any dissemination, distribution, or copying of > this === message truncated === ____________________________________________________________________________________ Any questions? Get answers on any topic at www.Answers.yahoo.com. Try it now. From alan.gauld at btinternet.com Tue Dec 5 09:29:22 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Dec 2006 08:29:22 -0000 Subject: [Tutor] Tutor Digest, Vol 34, Issue 7 References: <20061205035959.98589.qmail@web56112.mail.re3.yahoo.com> Message-ID: "Lazarus billa" wrote > When I wanted to Browse "sevenworlds at att.net" I am not > able to get it and it indicates "cannot find server > due to Syntax Error." Plz Advise. It means you've made a mistake in your code. Can you give us a clue by including some code? That way we might be able to tell you what the syntax error is. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From anders.u.persson at telia.com Tue Dec 5 09:44:12 2006 From: anders.u.persson at telia.com (Anders Persson) Date: Tue, 05 Dec 2006 09:44:12 +0100 Subject: [Tutor] Running drPython and other Pythonscript on Macintosh OS/X Message-ID: <4575315C.3050105@telia.com> Hi! I try to learn my son Development using Python. I have found that drPython was a great enviroment and easy for him to understand. Is't a problem running om Macintosh OS/X i have to start on commandline, OS/X dosen't understand when i clicked on the drPython.py files. I have found this is same for all pythonfiles on OS/X, does somone know how a tell a OS/X system that .py means run Python. Best regards Anders From kent37 at tds.net Tue Dec 5 12:01:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Dec 2006 06:01:53 -0500 Subject: [Tutor] how to save wxpython output In-Reply-To: <456F52CB.90807@science.uva.nl> References: <456F52CB.90807@science.uva.nl> Message-ID: <457551A1.3090209@tds.net> Ketan Maheshwari wrote: > Hi *: > How do I save the output of a wxpython program as a jpg or png image > from within the program? What output do you want to capture? Do you mean you want a screenshot of the windows? On Windows you can use ImageGrab from the Python Imaging Library to capture a screenshot. http://www.pythonware.com/library/pil/handbook/imagegrab.htm Kent From ajkadri at googlemail.com Tue Dec 5 19:48:48 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Tue, 5 Dec 2006 18:48:48 +0000 Subject: [Tutor] How to pass multiple variables in callback function? Message-ID: Hi folks, Is it possible to pass parameters using bind ? I mean to say that suppose I have two lists, and I want to pass them to the event handling function. Is that possible using bind? Thanks. Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061205/ada65818/attachment.htm From pyro9219 at gmail.com Tue Dec 5 20:34:46 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 5 Dec 2006 11:34:46 -0800 Subject: [Tutor] which file runs In-Reply-To: <4570DFE3.9000401@web.de> References: <200612011627.58137.jfabiani@yolo.com> <4570DFE3.9000401@web.de> Message-ID: I have a script that makes my python scripts into .pyc files and I can run those without a .py in the directory or anywhere else on the system for that matter. No clever tricks needed. On 12/1/06, Christopher Arndt wrote: > > Addendum: these rules only apply to Python *modules*. AFAIK, when you call > a > Python file as a script, no matching .pyc/.pyo file is used or generated. > > There are some clever tricks to run a .pyc file as a script. I think it is > described in the Python CGI FAQ. > > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061205/4a474798/attachment.html From rabidpoobear at gmail.com Tue Dec 5 20:54:18 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 05 Dec 2006 13:54:18 -0600 Subject: [Tutor] which file runs In-Reply-To: References: <200612011627.58137.jfabiani@yolo.com> <4570DFE3.9000401@web.de> Message-ID: <4575CE6A.3080702@gmail.com> Chris Hengge wrote: > I have a script that makes my python scripts into .pyc files and I can > run those without a .py in the directory or anywhere else on the > system for that matter. No clever tricks needed. > Why would you want to do this? From pythontut at pusspaws.net Tue Dec 5 21:01:22 2006 From: pythontut at pusspaws.net (Dave S) Date: Tue, 5 Dec 2006 20:01:22 +0000 Subject: [Tutor] XP & catching execl o/p ? Message-ID: <200612052001.22239.pythontut@pusspaws.net> Hi all, Struggling with python & XP again. My app needs to know if a certain program is running on my XP box Ideal world - I can get the output of 'tasklist.exe' into a string. I have tried os.execl('....') It throws the output to the terminal + I need the exact path to the executable (a bit of a trial) and os.startfile('...') it throws the output to a different window, but no exact path needed Any ideas how I can catch the output ? Cheers Dave From pyro9219 at gmail.com Tue Dec 5 21:40:01 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 5 Dec 2006 12:40:01 -0800 Subject: [Tutor] which file runs In-Reply-To: <4575CE6A.3080702@gmail.com> References: <200612011627.58137.jfabiani@yolo.com> <4570DFE3.9000401@web.de> <4575CE6A.3080702@gmail.com> Message-ID: Quick and dirty way to keep people from lookin at the code. On 12/5/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > I have a script that makes my python scripts into .pyc files and I can > > run those without a .py in the directory or anywhere else on the > > system for that matter. No clever tricks needed. > > > Why would you want to do this? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061205/f2e59665/attachment.htm From rabidpoobear at gmail.com Tue Dec 5 21:58:39 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 05 Dec 2006 14:58:39 -0600 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <200612052001.22239.pythontut@pusspaws.net> References: <200612052001.22239.pythontut@pusspaws.net> Message-ID: <4575DD7F.10604@gmail.com> Dave S wrote: > Hi all, > > Struggling with python & XP again. My app needs to know if a certain program > is running on my XP box > > Ideal world - I can get the output of 'tasklist.exe' into a string. > > I have tried > > os.execl('....') > It throws the output to the terminal + I need the exact path to the executable > (a bit of a trial) > > and > os.startfile('...') > it throws the output to a different window, but no exact path needed > > Any ideas how I can catch the output ? > You could try redirecting sys.stdout to a file-like class instance you create. > Cheers > > Dave > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From pythontut at pusspaws.net Tue Dec 5 22:36:41 2006 From: pythontut at pusspaws.net (Dave S) Date: Tue, 5 Dec 2006 21:36:41 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <4575DD7F.10604@gmail.com> References: <200612052001.22239.pythontut@pusspaws.net> <4575DD7F.10604@gmail.com> Message-ID: <200612052136.41486.pythontut@pusspaws.net> On Tuesday 05 December 2006 20:58, Luke Paireepinart wrote: > Dave S wrote: > > Hi all, > > > > Struggling with python & XP again. My app needs to know if a certain > > program is running on my XP box > > > > Ideal world - I can get the output of 'tasklist.exe' into a string. > > > > I have tried > > > > os.execl('....') > > It throws the output to the terminal + I need the exact path to the > > executable (a bit of a trial) > > > > and > > os.startfile('...') > > it throws the output to a different window, but no exact path needed > > > > Any ideas how I can catch the output ? > > You could try redirecting sys.stdout to a file-like class instance you > create. > OK ... could you give me a bit more on that ? ... probably me being a bit dense :) Cheers Dave > > Cheers > > > > Dave > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Tue Dec 5 23:42:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 05 Dec 2006 16:42:51 -0600 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <200612052136.41486.pythontut@pusspaws.net> References: <200612052001.22239.pythontut@pusspaws.net> <4575DD7F.10604@gmail.com> <200612052136.41486.pythontut@pusspaws.net> Message-ID: <4575F5EB.7040805@gmail.com> Dave S wrote: > On Tuesday 05 December 2006 20:58, Luke Paireepinart wrote: > >> Dave S wrote: >> >>> Hi all, >>> >>> Struggling with python & XP again. My app needs to know if a certain >>> program is running on my XP box >>> >>> Ideal world - I can get the output of 'tasklist.exe' into a string. >>> >>> I have tried >>> >>> os.execl('....') >>> It throws the output to the terminal + I need the exact path to the >>> executable (a bit of a trial) >>> >>> and >>> os.startfile('...') >>> it throws the output to a different window, but no exact path needed >>> >>> Any ideas how I can catch the output ? >>> >> You could try redirecting sys.stdout to a file-like class instance you >> create. >> >> > > OK ... could you give me a bit more on that ? ... probably me being a bit > dense :) > Um... #test.py class FileLikeObject(object): def __init__(self,current_stdout): self.data = [] self.oldstdout = current_stdout def write(self,arg): if arg != '\n': self.data.append(arg) def output(self): sys.stdout = self.oldstdout print self.data sys.stdout = self import sys f = FileLikeObject(sys.stdout) sys.stdout = f print "hello." f.output() print "hi" f.output() #----------- Be careful playing with the dark magic.... Don't forget that print goes to stdout. HTH, -Luke > Cheers > > Dave > > > > > >>> Cheers >>> >>> Dave >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> > > From pythontut at pusspaws.net Wed Dec 6 00:02:23 2006 From: pythontut at pusspaws.net (Dave S) Date: Tue, 5 Dec 2006 23:02:23 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <4575F5EB.7040805@gmail.com> References: <200612052001.22239.pythontut@pusspaws.net> <200612052136.41486.pythontut@pusspaws.net> <4575F5EB.7040805@gmail.com> Message-ID: <200612052302.23796.pythontut@pusspaws.net> On Tuesday 05 December 2006 22:42, Luke Paireepinart wrote: > Dave S wrote: > > On Tuesday 05 December 2006 20:58, Luke Paireepinart wrote: > >> Dave S wrote: > >>> Hi all, > >>> > >>> Struggling with python & XP again. My app needs to know if a certain > >>> program is running on my XP box > >>> > >>> Ideal world - I can get the output of 'tasklist.exe' into a string. > >>> > >>> I have tried > >>> > >>> os.execl('....') > >>> It throws the output to the terminal + I need the exact path to the > >>> executable (a bit of a trial) > >>> > >>> and > >>> os.startfile('...') > >>> it throws the output to a different window, but no exact path needed > >>> > >>> Any ideas how I can catch the output ? > >> > >> You could try redirecting sys.stdout to a file-like class instance you > >> create. > > > > OK ... could you give me a bit more on that ? ... probably me being a bit > > dense :) > > Um... > > #test.py > class FileLikeObject(object): > def __init__(self,current_stdout): > self.data = [] > self.oldstdout = current_stdout > > def write(self,arg): > if arg != '\n': > self.data.append(arg) > > def output(self): > sys.stdout = self.oldstdout > print self.data > sys.stdout = self > > > > import sys > > f = FileLikeObject(sys.stdout) > sys.stdout = f > > print "hello." > f.output() > print "hi" > f.output() > #----------- > > Be careful playing with the dark magic.... > Don't forget that print goes to stdout. > HTH, > -Luke Indeed it is dark :) Thanks for that - I will play Dave > > > Cheers > > > > Dave > > > >>> Cheers > >>> > >>> Dave > >>> > >>> > >>> _______________________________________________ > >>> Tutor maillist - Tutor at python.org > >>> http://mail.python.org/mailman/listinfo/tutor From paulino1 at sapo.pt Wed Dec 6 00:06:16 2006 From: paulino1 at sapo.pt (Paulino) Date: Tue, 05 Dec 2006 23:06:16 +0000 Subject: [Tutor] How to kill an app from python on windows? (Tim Golden) In-Reply-To: References: Message-ID: <4575FB68.3000702@sapo.pt> tutor-request at python.org escreveu: > > 1. Re: How to kill an app from python on windows? (Tim Golden) > > > This link may get you started: > > http://effbot.org/pyfaq/how-do-i-emulate-os-kill-in-windows.htm > > although it may not apply, depending on the exact > circumstances of what you're doing. > > TJG > > ________________________________________________________________________ > Thank you Tim, How do i get the pid of the process? Paulino From alan.gauld at btinternet.com Wed Dec 6 00:22:12 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Dec 2006 23:22:12 -0000 Subject: [Tutor] which file runs References: <200612011627.58137.jfabiani@yolo.com> <4570DFE3.9000401@web.de> <4575CE6A.3080702@gmail.com> Message-ID: "Luke Paireepinart" wrote >> I have a script that makes my python scripts into .pyc files and I >> can >> run those without a .py in the directory or anywhere else on the >> system for that matter. No clever tricks needed. >> > Why would you want to do this? I haven't measured it but I assume it would run a wee bit faster since it doesn't need to compile the source into byte code? Personally any savings aren't likely to be big enough to warrant the hassle of maintaining the pyc files. Alan g. From alan.gauld at btinternet.com Wed Dec 6 00:26:22 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Dec 2006 23:26:22 -0000 Subject: [Tutor] How to pass multiple variables in callback function? References: Message-ID: "Asrarahmed Kadri" wrote > I mean to say that suppose I have two lists, and I want to pass them > to the > event handling function. Is that possible using bind? Not answering your question directly but you can do it with a lambda expression. def myfunc(l1,l2): # the func I want to use foo = lambda p1=list1, p2=list2: myfunc(p1,p2) bind(e,foo) or just bind(e,lambda p1=list1, p2=list2: myfunc(p1,p2)) Obviously(?) list1 and list2 need to be in the same scope as the lambda expression! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Dec 6 00:32:56 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Dec 2006 23:32:56 -0000 Subject: [Tutor] XP & catching execl o/p ? References: <200612052001.22239.pythontut@pusspaws.net> Message-ID: "Dave S" wrote > Struggling with python & XP again. My app needs to know if a certain > program > is running on my XP box > os.execl('....') > It throws the output to the terminal + I need the exact path to the > executable > (a bit of a trial) > Any ideas how I can catch the output ? Look at the popen family of functions in the os module, and then look at the subporocess module which supercedees them (but the docs are expressed in tems of the oold functions!) Use subprocess because the older popen functions don't always work reliably on Windows - there is a separate popen as part of the winall package, but I think subprocess.Popen works Ok. There is more on this, including a simple example using subprocess, in my OS topic in my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From chris.arndt at web.de Wed Dec 6 02:13:01 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 06 Dec 2006 02:13:01 +0100 Subject: [Tutor] which file runs In-Reply-To: References: <200612011627.58137.jfabiani@yolo.com> <4570DFE3.9000401@web.de> Message-ID: <4576191D.90705@web.de> Chris Hengge wrote: > I have a script that makes my python scripts into .pyc files and I can > run those without a .py in the directory or anywhere else on the system > for that matter. No clever tricks needed. You're right. Probably this trick was only needed in (very) old versions of Python. Also works with .pyo files: python -OO -c "import myfile" python myfile.pyo Chris From eli.usmc.recon at gmail.com Wed Dec 6 02:20:09 2006 From: eli.usmc.recon at gmail.com (Eli Zabielski) Date: Tue, 5 Dec 2006 18:20:09 -0700 Subject: [Tutor] Integer? Message-ID: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> How can I check if a variable is an integer? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061205/d240b950/attachment.htm From rabidpoobear at gmail.com Wed Dec 6 02:25:13 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 05 Dec 2006 19:25:13 -0600 Subject: [Tutor] Integer? In-Reply-To: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> Message-ID: <45761BF9.60003@gmail.com> Eli Zabielski wrote: > How can I check if a variable is an integer? if type(aVar) == type(1): should do the trick. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john at fouhy.net Wed Dec 6 03:09:49 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 6 Dec 2006 15:09:49 +1300 Subject: [Tutor] Integer? In-Reply-To: <45761BF9.60003@gmail.com> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <45761BF9.60003@gmail.com> Message-ID: <5e58f2e40612051809k114633bftf17e8681e627e5bd@mail.gmail.com> On 06/12/06, Luke Paireepinart wrote: > Eli Zabielski wrote: > > How can I check if a variable is an integer? > if type(aVar) == type(1): Well, you could also do "type(aVar) == int", which is clearer. Or "type(aVar) in (int, long)", depending on exactly what you mean by "integer". -- John. From cappy2112 at gmail.com Wed Dec 6 04:18:23 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 5 Dec 2006 19:18:23 -0800 Subject: [Tutor] Docs for os popen and Popen2 modules Message-ID: <8249c4ac0612051918g442994b4x9c0984efb2de4720@mail.gmail.com> Running python 2.3.4, on Windows XP the popen2 docs show 6.8 popen2 -- Subprocesses with accessible I/O streams This module allows you to spawn processes and connect to their input/output/error pipes and >>obtain their return codes under Unix and Windows.<< Then it further goes to say The only way to retrieve the return codes for the child processes is by using the poll() or wait() methods on the Popen3 and Popen4 classes; these are >>only available on Unix<<. This information is not available when using the popen2(), popen3(), and popen4() functions, or the equivalent functions in the os module. After having spent much time reading about the differences between the popen calls in the os module, and the popen calls in popen2, if the return values aren't available under windows, I'm confused. Why bother making these functions available under Windows at all? Other than the order of the return values, I don't see any advantage of one over the other. Since the document contradicts itself regaring the return values on Windows, is there a way to get the return values or not? Is so- how? Since poll and wait are only available on Unix, how do we wait for a process to finish under Windows? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061205/f12cb8fe/attachment.htm From kent37 at tds.net Wed Dec 6 04:21:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Dec 2006 22:21:42 -0500 Subject: [Tutor] How to pass multiple variables in callback function? In-Reply-To: References: Message-ID: <45763746.70501@tds.net> Alan Gauld wrote: > "Asrarahmed Kadri" wrote > >> I mean to say that suppose I have two lists, and I want to pass them >> to the >> event handling function. Is that possible using bind? > > Not answering your question directly but you can do > it with a lambda expression. > > def myfunc(l1,l2): > # the func I want to use > > foo = lambda p1=list1, p2=list2: myfunc(p1,p2) > bind(e,foo) > > or just > > bind(e,lambda p1=list1, p2=list2: myfunc(p1,p2)) > > Obviously(?) list1 and list2 need to be in the same scope as > the lambda expression! Unless the bind() is in a loop that is rebinding list1 and list2, the named parameters are not needed since nested scopes were introduced in Python 2.1, you can just write bind(e,lambda: myfunc(list1, list2)) Kent From kent37 at tds.net Wed Dec 6 04:24:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Dec 2006 22:24:05 -0500 Subject: [Tutor] Integer? In-Reply-To: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> Message-ID: <457637D5.2040801@tds.net> Eli Zabielski wrote: > How can I check if a variable is an integer? Luke and John have answered your question, but we should also ask, why do you want to do that? Explicit type testing is a code smell, perhaps there is a better way to do what you want. Kent From wescpy at gmail.com Wed Dec 6 06:40:39 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 5 Dec 2006 21:40:39 -0800 Subject: [Tutor] Integer? In-Reply-To: <457637D5.2040801@tds.net> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <457637D5.2040801@tds.net> Message-ID: <78b3a9580612052140q16eb2533j77ee19c1dc929976@mail.gmail.com> > > How can I check if a variable is an integer? > > Luke and John have answered your question, but we should also ask, why > do you want to do that? Explicit type testing is a code smell, perhaps > there is a better way to do what you want. - another way of doing it is: type(aVar) is int (which is faster than using "==") - if you want to check for ints and all subclasses of int: isinstance(aVar, int) - if you want to check for ints, longs, and all subclasses: isinstance(aVar, (int, long)) because python is strongly yet duckly-typed, there are circumstances where you want to do some self introspection to find out what kind of objects you've got. this obviates the need for Python to support multiple signatures, function overloading, etc. with that said, however, it would also be a good idea to see what your application is and determine if this kind of checking is warranted. HTH! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rdm at rcblue.com Wed Dec 6 07:18:02 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 05 Dec 2006 22:18:02 -0800 Subject: [Tutor] order of arguments in function Message-ID: <7.0.1.0.2.20061205221333.066431b0@rcblue.com> Say I have a function, def my_function(max, min=0): return max - min The order of arguments is counterintuitive, but it seems it can't be changed if I want to have a default min. Is there way to write def my_function(min=0, max): stuff Thanks, Dick Moores From rdm at rcblue.com Wed Dec 6 07:23:50 2006 From: rdm at rcblue.com (Dick Moores) Date: Tue, 05 Dec 2006 22:23:50 -0800 Subject: [Tutor] Integer? In-Reply-To: <78b3a9580612052140q16eb2533j77ee19c1dc929976@mail.gmail.co m> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <457637D5.2040801@tds.net> <78b3a9580612052140q16eb2533j77ee19c1dc929976@mail.gmail.com> Message-ID: <7.0.1.0.2.20061205222100.06648570@rcblue.com> At 09:40 PM 12/5/2006, wesley chun wrote: > > > How can I check if a variable is an integer? > > > > Luke and John have answered your question, but we should also ask, why > > do you want to do that? Explicit type testing is a code smell, perhaps > > there is a better way to do what you want. > > >- another way of doing it is: type(aVar) is int (which is faster than >using "==") >- if you want to check for ints and all subclasses of int: >isinstance(aVar, int) >- if you want to check for ints, longs, and all subclasses: >isinstance(aVar, (int, long)) > >because python is strongly yet duckly-typed, there are circumstances >where you want to do some self introspection to find out what kind of >objects you've got. this obviates the need for Python to support >multiple signatures, function overloading, etc. with that said, >however, it would also be a good idea to see what your application is >and determine if this kind of checking is warranted. Very interesting. But what is "duckly-typed"? I'm so dumb I can't distinguish between a typo and a technical term.. Dick Moores From pythontut at pusspaws.net Wed Dec 6 08:12:57 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 6 Dec 2006 07:12:57 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: References: <200612052001.22239.pythontut@pusspaws.net> Message-ID: <200612060712.57237.pythontut@pusspaws.net> On Tuesday 05 December 2006 23:32, Alan Gauld wrote: > "Dave S" wrote > > > Struggling with python & XP again. My app needs to know if a certain > > program > > is running on my XP box > > > > os.execl('....') > > It throws the output to the terminal + I need the exact path to the > > executable > > (a bit of a trial) > > > > Any ideas how I can catch the output ? > > Look at the popen family of functions in the os module, and then > look at the subporocess module which supercedees them > (but the docs are expressed in tems of the oold functions!) > > Use subprocess because the older popen functions don't always > work reliably on Windows - there is a separate popen as part of > the winall package, but I think subprocess.Popen works Ok. > > There is more on this, including a simple example using subprocess, > in my OS topic in my tutorial. > > HTH, Thanks for your help - I will take a look. :) Dave From Tim.Golden at viacom-outdoor.co.uk Wed Dec 6 09:48:05 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 6 Dec 2006 08:48:05 -0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <200612052001.22239.pythontut@pusspaws.net> Message-ID: | Struggling with python & XP again. My app needs to know if a | certain program is running on my XP box As a complete alternative, consider using WMI: import os, sys import wmi c = wmi.WMI () for process in c.Win32_Process (Name="excel.exe"): print "Excel is running" break else: print "Excel is not running" (Uses: http://timgolden.me.uk/python/wmi.html) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rabidpoobear at gmail.com Wed Dec 6 10:07:02 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 06 Dec 2006 03:07:02 -0600 Subject: [Tutor] Integer? In-Reply-To: <7.0.1.0.2.20061205222100.06648570@rcblue.com> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <457637D5.2040801@tds.net> <78b3a9580612052140q16eb2533j77ee19c1dc929976@mail.gmail.com> <7.0.1.0.2.20061205222100.06648570@rcblue.com> Message-ID: <45768836.60303@gmail.com> > Very interesting. But what is "duckly-typed"? I'm so dumb I can't > distinguish between a typo and a technical term.. > > Dick Moores > > Refer to the Wikipedia article on Duck Typing: http://en.wikipedia.org/wiki/Duck_typing Basically, if you saw my example earlier of substituting stdout: #test.py class FileLikeObject(object): def __init__(self,current_stdout): self.data = [] self.oldstdout = current_stdout sys.stdout = self def write(self,arg): if arg != '\n': self.data.append(arg) def output(self): sys.stdout = self.oldstdout print self.data sys.stdout = self import sys f = FileLikeObject(sys.stdout) print "hello." f.output() print "hi" f.output() #----- sys.stdout expects a file-like object, that has methods such as 'write'. So I implemented a class with a 'write' method, and sys.stdout happily used it as an output stream. It's not the same type of object as the original sys.stdout was. From IDLE, >>> print sys.stdout So you see idle itself has replaced the default console stream of >>> print sys.stdout ', mode 'w' at 0x0097E068> with its own version, which I replaced with my own version (the class instance with the write method). All that matters is that the object has a 'write' method for it to be used as stdout (AFAIK). HTH, -Luke From Tim.Golden at viacom-outdoor.co.uk Wed Dec 6 10:38:59 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 6 Dec 2006 09:38:59 -0000 Subject: [Tutor] How to kill an app from python on windows? (Tim Golden) In-Reply-To: <4575FB68.3000702@sapo.pt> Message-ID: [Tim Golden] | > This link may get you started: | > | > http://effbot.org/pyfaq/how-do-i-emulate-os-kill-in-windows.htm | > | > although it may not apply, depending on the exact | > circumstances of what you're doing. [Paulino] | Thank you Tim, | | How do i get the pid of the process? I'm going to cheat slightly, because I'm fairly sure this is a sticky area, by going back to your original requirement. I think that what you want to do is: 1) Use a document name to start the appropriate viewer/app (without knowing what that app is) 2) Close that app at will so the file can be updated. The problem is that while os.startfile will satisfy (1), it returns no useful information about the process it started. And that's because the underlying win32api, ShellExecute, doesn't return anything useful. This is specifically stated in the MS documentation. What you can do, though, is to determine the correct executable, setup a new process under your control, and then terminate it when you want. This assume you have the pywin32 extensions available. In the example below, I'm using an .html file to demonstrate the point, because I can generate one so the code works for both of us. Obviously, it should work for any recognised document type, including .pdf. import os, sys import win32api import win32process import win32event filename = os.path.abspath ("temp.html") open (filename, "w").write ("

Hello, world!

") hInstance, exe_filename = win32api.FindExecutable (filename) print exe_filename, filename hProcess, hThread, pid, tid = win32process.CreateProcess ( None, '"%s" "%s2' % (exe_filename, filename), None, # process attributes None, # process attributes 0, # inherit handles 0, # creation flags None, # new environment None, # current directory win32process.STARTUPINFO () ) print pid # # This snippet waits until the app closes # win32event.WaitForSingleObject (hProcess, win32event.INFINITE) # # To kill the process either use the hProcess # above, or retrieve it from the pid using: # hProcess = win32api.OpenProcess (1, 0, pid) # # and then # win32process.TerminateProcess (hProcess, 0)
________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From klappnase at freenet.de Wed Dec 6 11:28:35 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 6 Dec 2006 11:28:35 +0100 Subject: [Tutor] order of arguments in function In-Reply-To: <7.0.1.0.2.20061205221333.066431b0@rcblue.com> References: <7.0.1.0.2.20061205221333.066431b0@rcblue.com> Message-ID: <20061206112835.3a894b74.klappnase@freenet.de> On Tue, 05 Dec 2006 22:18:02 -0800 Dick Moores wrote: > Say I have a function, > > def my_function(max, min=0): > return max - min > > The order of arguments is counterintuitive, but it seems it can't be > changed if I want to have a default min. Is there way to write > > def my_function(min=0, max): > stuff > def my_function(min, max=None): if max is None: max = min min = 0 # stuff I am not sure if this is more intuitive though. Michael From kent37 at tds.net Wed Dec 6 12:04:37 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Dec 2006 06:04:37 -0500 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <200612052001.22239.pythontut@pusspaws.net> References: <200612052001.22239.pythontut@pusspaws.net> Message-ID: <4576A3C5.60008@tds.net> Dave S wrote: > Hi all, > > Struggling with python & XP again. My app needs to know if a certain program > is running on my XP box > > Ideal world - I can get the output of 'tasklist.exe' into a string. > > I have tried > > os.execl('....') > It throws the output to the terminal + I need the exact path to the executable > (a bit of a trial) > > and > os.startfile('...') > it throws the output to a different window, but no exact path needed I'm not sure if this is helpful, but here is a program that uses subprocess.Popen() to capture the output of cmd.exe. It makes a text file which contains all the command help. By Scott David Daniels, taken from http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en& import subprocess as subp p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, stdout=subp.PIPE, stderr=subp.STDOUT) flag = "(@@@@@@}" print >>p.stdin, "PROMPT", flag print >>p.stdin, "HELP" print >>p.stdin, "EXIT" text = p.stdout.read() p.wait() helptext = text[text.index(flag + 'HELP') + len(flag) + 4 : text.index(flag + 'EXIT')] words = [line.split(None, 1)[0] for line in helptext.split('\n') if line.strip()] commands = [word for word in words if word.isupper()] dest = open('cmd_help.txt', 'wb') p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, stdout=dest, stderr=subp.STDOUT) print >>p.stdin, "PROMPT (@@@@@@@@)" print >>p.stdin, "HELP" for command in commands: print >>p.stdin, "HELP", command print >>p.stdin, "EXIT" p.wait() dest.close() Kent From contact at endarion.com Wed Dec 6 12:18:30 2006 From: contact at endarion.com (Michael Shulman) Date: Wed, 06 Dec 2006 06:18:30 -0500 Subject: [Tutor] changing a variable over simple network (with pyOpenGL) Message-ID: <4576A706.2080906@endarion.com> Hello, I am trying to write a very simple py-opengl program pair causing a variable in each program to be changed by the other. I am able to open a command window in which I manually assign a value to the variable, but I cannot seem to implement the udp/ip information I wish to send into a function which I can call at will. I have tried updating the function through both a cyclic update function, and the keyboard (keyboard is preferred, but I tried eliminating it to see if that was the incompatibility). I do not list any coding for the receiving program, since it works perfectly with the above code, and is probably correct. Currently, the program crashes when I press the assigned key. I can't tell if the issue here is python, or OpenGL, but any help would be very greatly appreciated!!! ##########Here is what DOES work: ############################# from socket import * udpsock = socket(AF_INET, SOCK_DGRAM) udpsock.bind(('', 0)) udpsock.connect(('localhost', 4550)) try: while True: s = raw_input('command> ') udpsock.send(s) except EOFError: pass ########################### #############This is what DOES NOT work: ############################## from socket import * udpsock = socket(AF_INET, SOCK_DGRAM) udpsock.bind(('', 0)) udpsock.connect(('localhost', 4550)) R = 0 def datasender(): global R try: while True: s = input(R) udpsock.send(s) except EOFError: pass def keyboard(key, x, y): #######the keyboard and window OpenGL calls are not mentioned here, but included properly in the program (they work with everything except this) global R if key == 'k': #####key is arbitrary, I have also tried with "special keys" as defined by glut R = R + .01 datasender() ################################ From pythontut at pusspaws.net Wed Dec 6 12:43:13 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 6 Dec 2006 11:43:13 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: References: <200612052001.22239.pythontut@pusspaws.net> Message-ID: <200612061143.13876.pythontut@pusspaws.net> On Tuesday 05 December 2006 23:32, Alan Gauld wrote: > "Dave S" wrote > > > Struggling with python & XP again. My app needs to know if a certain > > program > > is running on my XP box > > > > os.execl('....') > > It throws the output to the terminal + I need the exact path to the > > executable > > (a bit of a trial) > > > > Any ideas how I can catch the output ? > > Look at the popen family of functions in the os module, and then > look at the subporocess module which supercedees them > (but the docs are expressed in tems of the oold functions!) > > Use subprocess because the older popen functions don't always > work reliably on Windows - there is a separate popen as part of > the winall package, but I think subprocess.Popen works Ok. > > There is more on this, including a simple example using subprocess, > in my OS topic in my tutorial. > > HTH, OK playing around I knocked up some test code ... #!/usr/bin/env python # -*- coding: iso8859_1 -*- import subprocess a = subprocess.Popen('tasklist.exe', bufsize=0, shell=False, stdout=subprocess.PIPE, stderr=None, stdin=None, universal_newlines=True) op = a.stdout.readlines() for i in op: #print i #print pass #raw_input() This gives me what I need except when it runs windows flashes up a large black terminal window for a split second (yuk) This test would be performed while my app is running so thats not so good :) Any ideas on how to stop it displaying ? Dave From pythontut at pusspaws.net Wed Dec 6 12:44:26 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 6 Dec 2006 11:44:26 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: References: Message-ID: <200612061144.26836.pythontut@pusspaws.net> On Wednesday 06 December 2006 08:48, Tim Golden wrote: > | Struggling with python & XP again. My app needs to know if a > | certain program is running on my XP box > > As a complete alternative, consider using WMI: > > > import os, sys > import wmi > > c = wmi.WMI () > for process in c.Win32_Process (Name="excel.exe"): > print "Excel is running" > break > else: > print "Excel is not running" > > > > (Uses: http://timgolden.me.uk/python/wmi.html) > > TJG Just looked at WMI - didn't know it existed ! Am going down the subprocess route first as its 'built in'. If that does not work - hello WMI Cheers Dave > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From pythontut at pusspaws.net Wed Dec 6 12:47:59 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 6 Dec 2006 11:47:59 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <4576A3C5.60008@tds.net> References: <200612052001.22239.pythontut@pusspaws.net> <4576A3C5.60008@tds.net> Message-ID: <200612061147.59462.pythontut@pusspaws.net> On Wednesday 06 December 2006 11:04, Kent Johnson wrote: > Dave S wrote: > > Hi all, > > > > Struggling with python & XP again. My app needs to know if a certain > > program is running on my XP box > > > > Ideal world - I can get the output of 'tasklist.exe' into a string. > > > > I have tried > > > > os.execl('....') > > It throws the output to the terminal + I need the exact path to the > > executable (a bit of a trial) > > > > and > > os.startfile('...') > > it throws the output to a different window, but no exact path needed > > I'm not sure if this is helpful, but here is a program that uses > subprocess.Popen() to capture the output of cmd.exe. It makes a text > file which contains all the command help. By Scott David Daniels, taken > from > http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en& > > import subprocess as subp > > p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, > stdout=subp.PIPE, stderr=subp.STDOUT) > flag = "(@@@@@@}" > print >>p.stdin, "PROMPT", flag > print >>p.stdin, "HELP" > print >>p.stdin, "EXIT" > text = p.stdout.read() > p.wait() > helptext = text[text.index(flag + 'HELP') + len(flag) + 4 : > text.index(flag + 'EXIT')] > words = [line.split(None, 1)[0] > for line in helptext.split('\n') > if line.strip()] > commands = [word for word in words if word.isupper()] > > dest = open('cmd_help.txt', 'wb') > p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE, > stdout=dest, stderr=subp.STDOUT) > print >>p.stdin, "PROMPT (@@@@@@@@)" > print >>p.stdin, "HELP" > for command in commands: > print >>p.stdin, "HELP", command > print >>p.stdin, "EXIT" > p.wait() > dest.close() > > > Kent The above is usefull, I am starting to print out these snippets for reference :). I have got subprocess to get the data I am now trying to get rid of the windows terminal flashing on my screen. Cheers Dave From Tim.Golden at viacom-outdoor.co.uk Wed Dec 6 13:00:17 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 6 Dec 2006 12:00:17 -0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <200612061144.26836.pythontut@pusspaws.net> Message-ID: [Dave S] | Just looked at WMI - didn't know it existed ! | Am going down the subprocess route first as its 'built in'. | If that does not work - hello WMI Personally, I find having both (and other) tools in my toolbelt useful -- I've just answered another question elsewhere about starting and stopping a process on Win32 using the pywin32 win32process module, so that's another option... Generally subprocess is the recommended approach these days because it's specifically designed to superseded the various popen/spawn/system choices previously available. The only problem is that its general-purpose nature means fossicking around to mimic the relative simplicity of os.popen: import os pipe = os.popen ("tasklist") # skip unwanted headers pipe.readline () pipe.readline () pipe.readline () for line in pipe.readlines (): print line.split ()[0] TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rdm at rcblue.com Wed Dec 6 13:29:54 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 06 Dec 2006 04:29:54 -0800 Subject: [Tutor] order of arguments in function In-Reply-To: <20061206112835.3a894b74.klappnase@freenet.de> References: <7.0.1.0.2.20061205221333.066431b0@rcblue.com> <20061206112835.3a894b74.klappnase@freenet.de> Message-ID: <7.0.1.0.2.20061206041559.069f2630@rcblue.com> At 02:28 AM 12/6/2006, Michael Lange wrote: >On Tue, 05 Dec 2006 22:18:02 -0800 >Dick Moores wrote: > > > Say I have a function, > > > > def my_function(max, min=0): > > return max - min > > > > The order of arguments is counterintuitive, but it seems it can't be > > changed if I want to have a default min. Is there way to write > > > > def my_function(min=0, max): > > stuff > > > >def my_function(min, max=None): > if max is None: > max = min > min = 0 > # stuff Great! >I am not sure if this is more intuitive though. >>> def my_function(min, max=None): if max is None: max, min = min, 0 return max - min >>> my_function(3, 7) 4 I meant that the order "min, max" is more intuitive than "max, min". Don't you agree? And it's the order used in random.randint(), random.randrange(), and random.uniform(), for examples. Anyway, thanks, Michael. Dick From pythontut at pusspaws.net Wed Dec 6 13:42:15 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 6 Dec 2006 12:42:15 +0000 Subject: [Tutor] XP & catching execl o/p ? In-Reply-To: <200612061143.13876.pythontut@pusspaws.net> References: <200612052001.22239.pythontut@pusspaws.net> <200612061143.13876.pythontut@pusspaws.net> Message-ID: <200612061242.15516.pythontut@pusspaws.net> On Wednesday 06 December 2006 11:43, Dave S wrote: > On Tuesday 05 December 2006 23:32, Alan Gauld wrote: > > "Dave S" wrote > > > > > Struggling with python & XP again. My app needs to know if a certain > > > program > > > is running on my XP box > > > > > > os.execl('....') > > > It throws the output to the terminal + I need the exact path to the > > > executable > > > (a bit of a trial) > > > > > > Any ideas how I can catch the output ? > > > > Look at the popen family of functions in the os module, and then > > look at the subporocess module which supercedees them > > (but the docs are expressed in tems of the oold functions!) > > > > Use subprocess because the older popen functions don't always > > work reliably on Windows - there is a separate popen as part of > > the winall package, but I think subprocess.Popen works Ok. > > > > There is more on this, including a simple example using subprocess, > > in my OS topic in my tutorial. > > > > HTH, > > OK playing around I knocked up some test code ... > > #!/usr/bin/env python > # -*- coding: iso8859_1 -*- > import subprocess > > a = subprocess.Popen('tasklist.exe', bufsize=0, shell=False, > stdout=subprocess.PIPE, stderr=None, stdin=None, universal_newlines=True) > op = a.stdout.readlines() > for i in op: > #print i > #print > pass > > #raw_input() > > This gives me what I need except when it runs windows flashes up a large > black terminal window for a split second (yuk) > > This test would be performed while my app is running so thats not so good > :) > > Any ideas on how to stop it displaying ? > > Dave 10 carrot idiot here :) change from test.py to test.pyw :) dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Wed Dec 6 13:48:32 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 06 Dec 2006 04:48:32 -0800 Subject: [Tutor] Integer? In-Reply-To: <45768836.60303@gmail.com> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <457637D5.2040801@tds.net> <78b3a9580612052140q16eb2533j77ee19c1dc929976@mail.gmail.com> <7.0.1.0.2.20061205222100.06648570@rcblue.com> <45768836.60303@gmail.com> Message-ID: <7.0.1.0.2.20061206044741.069eb7f0@rcblue.com> At 01:07 AM 12/6/2006, Luke Paireepinart wrote: > > Very interesting. But what is "duckly-typed"? I'm so dumb I can't > > distinguish between a typo and a technical term.. > > > > Dick Moores > > > > >Refer to the Wikipedia article on Duck Typing: >http://en.wikipedia.org/wiki/Duck_typing Thanks, Luke. Dick From rdm at rcblue.com Wed Dec 6 14:13:47 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 06 Dec 2006 05:13:47 -0800 Subject: [Tutor] Decimal module question Message-ID: <7.0.1.0.2.20061206050533.06736518@rcblue.com> I wrote this function: def numberRounding(n, significantDigits=4): """ Rounds a number (float or integer, negative or positive) to any number of significant digits. If an integer, there is no limitation on it's size. """ import decimal def d(x): return decimal.Decimal(str(x)) decimal.getcontext().prec = significantDigits return d(n)/1 If the last line is written as the more normal-looking "return d(n)", it won't work. Why? Thanks, Dick Moores From kent37 at tds.net Wed Dec 6 14:35:00 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Dec 2006 08:35:00 -0500 Subject: [Tutor] Decimal module question In-Reply-To: <7.0.1.0.2.20061206050533.06736518@rcblue.com> References: <7.0.1.0.2.20061206050533.06736518@rcblue.com> Message-ID: <4576C704.3090101@tds.net> Dick Moores wrote: > I wrote this function: > > def numberRounding(n, significantDigits=4): > """ > Rounds a number (float or integer, negative or positive) to any number of > significant digits. If an integer, there is no limitation on it's size. > """ > import decimal > def d(x): > return decimal.Decimal(str(x)) > decimal.getcontext().prec = significantDigits > return d(n)/1 > > If the last line is written as the more normal-looking "return d(n)", > it won't work. Why? The context precision is applied to *operations* on decimals, not to construction. The docs for the constructor Decimal([value [, context]]) say, "The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, "Decimal("3.00000")" records all five zeroes even if the context precision is only three." The docs for Context say, "The prec field is a positive integer that sets the precision for *arithmetic operations* in the context." (my emphasis) So you have to perform an operation for the precision to have any effect. Dividing by 1 is an operation. Kent From emilia12 at mail.bg Wed Dec 6 14:20:19 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Wed, 06 Dec 2006 15:20:19 +0200 Subject: [Tutor] Python scrypts and daemons Message-ID: <1165411219.f38e76930b509@mail.bg> Hi all, I have a python script (with endless loop) and i want to start it from the rc.config file. So, the question is: how to covert this script to work as daemon ... or how to start the python interpreter ... to work as background process ? E. ----------------------------- ??????? ?????????! bg.sportingbet.com From rdm at rcblue.com Wed Dec 6 14:49:56 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 06 Dec 2006 05:49:56 -0800 Subject: [Tutor] Decimal module question In-Reply-To: <4576C704.3090101@tds.net> References: <7.0.1.0.2.20061206050533.06736518@rcblue.com> <4576C704.3090101@tds.net> Message-ID: <7.0.1.0.2.20061206054907.0674cb18@rcblue.com> At 05:35 AM 12/6/2006, Kent Johnson wrote: >Dick Moores wrote: >>I wrote this function: >>def numberRounding(n, significantDigits=4): >> """ >> Rounds a number (float or integer, negative or positive) >> to any number of >> significant digits. If an integer, there is no limitation >> on it's size. >> """ >> import decimal >> def d(x): >> return decimal.Decimal(str(x)) >> decimal.getcontext().prec = significantDigits >> return d(n)/1 >>If the last line is written as the more normal-looking "return >>d(n)", it won't work. Why? > >The context precision is applied to *operations* on decimals, not to >construction. > >The docs for the constructor Decimal([value [, context]]) say, "The >context precision does not affect how many digits are stored. That >is determined exclusively by the number of digits in value. For >example, "Decimal("3.00000")" records all five zeroes even if the >context precision is only three." > >The docs for Context say, "The prec field is a positive integer that >sets the precision for *arithmetic operations* in the context." (my emphasis) > >So you have to perform an operation for the precision to have any >effect. Dividing by 1 is an operation. > >Kent Thanks very much, Kent. Dick From chris.arndt at web.de Wed Dec 6 16:02:41 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 06 Dec 2006 16:02:41 +0100 Subject: [Tutor] Python scrypts and daemons In-Reply-To: <1165411219.f38e76930b509@mail.bg> References: <1165411219.f38e76930b509@mail.bg> Message-ID: <4576DB91.9000202@web.de> emilia12 at mail.bg schrieb: > > Hi all, > > I have a python script (with endless loop) and i want to > start it from the rc.config file. So, the question is: how > to covert this script to work as daemon ... or how to start > the python interpreter ... to work as background process ? Search google for "daemonize python" and the first hit (at least here) links to a recipe in the Python Cookbook that does exactly what you want. HTH, Chris From Mike.Hansen at atmel.com Wed Dec 6 16:04:54 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 6 Dec 2006 08:04:54 -0700 Subject: [Tutor] Integer? Message-ID: <57B026980605A64F9B23484C5659E32E44E977@poccso.US.ad.atmel.com> > > How can I check if a variable is an integer? > > Luke and John have answered your question, but we should also > ask, why > do you want to do that? Explicit type testing is a code > smell, perhaps > there is a better way to do what you want. > > Kent > Kent, Can you explain further? Refactoring is in my queue of books to read. In a web app I'm writing, I'm checking the input kind of like this... try: form_value = int(form.getvalue('num_widgets') except ValueError: display_error("Number of Widgets must be a number") Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From pytutmail at gmail.com Wed Dec 6 16:06:03 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Wed, 6 Dec 2006 16:06:03 +0100 Subject: [Tutor] Q: win32 download (attack of the newbies) Message-ID: <7c3104d20612060706n7bba46d5x1ffad27dfe8428e2@mail.gmail.com> Hey, friendly person who took the time to read this! I'm cutting right to the case. Trying to get certain information into Excel. However, I can't: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") # continues As soon as I start the program, I get a error: win32com.client not found. This - of course - leads to the conclusion that I don't have the win32com module installed. I tried to find it (Google), but all I could find when searching for "python win32 module (download)", I can only find the normal python install. I'm running Win XP Pro, and have Python ver 2.5. What am I doing wrong? BTW: I really need to get that information into Excel. This program is for some beginner computer users, and all they really know is Word and Excel. Thanks in advance! Toon Pieton. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061206/ee083ff0/attachment.htm From Tim.Golden at viacom-outdoor.co.uk Wed Dec 6 16:20:33 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 6 Dec 2006 15:20:33 -0000 Subject: [Tutor] Q: win32 download (attack of the newbies) In-Reply-To: <7c3104d20612060706n7bba46d5x1ffad27dfe8428e2@mail.gmail.com> Message-ID: [Toon Pieton] | As soon as I start the program, I get a error: | win32com.client not found. This - of course - leads to the | conclusion that I don't have the win32com module installed. I | tried to find it (Google), but all I could find when | searching for "python win32 module (download)", I can only | find the normal python install. I'm running Win XP Pro, and | have Python ver 2.5. Most immediate answer: https://sourceforge.net/project/showfiles.php?group_id=78018&package_id= 79063 and pick the right package / mirror | BTW: I really need to get that information into Excel. This | program is for some beginner computer users, and all they | really know is Word and Excel. Using win32com and Excel is very easy, but there are alternatives if you want: http://cheeseshop.python.org/pypi/xlrd/0.5.2 http://cheeseshop.python.org/pypi/pyExcelerator/0.6.0a TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From pythontut at pusspaws.net Wed Dec 6 16:32:26 2006 From: pythontut at pusspaws.net (Dave S) Date: Wed, 6 Dec 2006 15:32:26 +0000 Subject: [Tutor] subprocess & pyw conflict ? Message-ID: <200612061532.26501.pythontut@pusspaws.net> Hi all, I thought I had my solution with subprocess ... my test code ... #!/usr/bin/env python # -*- coding: iso8859_1 -*- import subprocess a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, universal_newlines=True) op = a.stdout.readlines() for i in op: if i.split(' ')[0] == 'gmanager.exe': f = open('E:\Documents and Settings\All Users\Desktop\gsr_running', 'w') f.close() works a treat when I run it as proc.py detects the process I am looking for & writes a dummy file to the desktop. :) but I get a black windows terminal flash up. The code will eventually run in an app.pyw so to check it would be OK I renamed my working proc.py to proc.pyw - it fails :(, No window (as expected), no dummy file (not expected) - the process gmanager.exe is running. So there seems to be a problem with subprocess & pyw Googling I found ... https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&group_id=5470 So I tried the suggested workaround with proc.pyw ... #!/usr/bin/env python # -*- coding: iso8859_1 -*- import subprocess a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) op = a.stdout.readlines() a.stdin.close() for i in op: if i.split(' ')[0] == 'gmanager.exe': f = open('E:\Documents and Settings\All Users\Desktop\gsr_running', 'w') f.close() Still zip, and because there is no terminal, I cannot view any errors ! Any suggestions welcome :) Dave From kent37 at tds.net Wed Dec 6 16:38:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Dec 2006 10:38:15 -0500 Subject: [Tutor] Q: win32 download (attack of the newbies) In-Reply-To: <7c3104d20612060706n7bba46d5x1ffad27dfe8428e2@mail.gmail.com> References: <7c3104d20612060706n7bba46d5x1ffad27dfe8428e2@mail.gmail.com> Message-ID: <4576E3E7.10102@tds.net> Toon Pieton wrote: > Hey, friendly person who took the time to read this! > > I'm cutting right to the case. Trying to get certain information into > Excel. However, I can't: > > from win32com.client import Dispatch > > xlApp = Dispatch(" > Excel.Application") > # continues > > As soon as I start the program, I get a error: win32com.client not > found. This - of course - leads to the conclusion that I don't have the > win32com module installed. I tried to find it (Google), but all I could > find when searching for "python win32 module (download)", I can only > find the normal python install. I'm running Win XP Pro, and have Python > ver 2.5. https://sourceforge.net/projects/pywin32/ > BTW: I really need to get that information into Excel. This program is > for some beginner computer users, and all they really know is Word and > Excel. You might also consider writing CSV files which can be opened in Excel. Kent From kent37 at tds.net Wed Dec 6 16:46:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Dec 2006 10:46:39 -0500 Subject: [Tutor] Integer? In-Reply-To: <57B026980605A64F9B23484C5659E32E44E977@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E44E977@poccso.US.ad.atmel.com> Message-ID: <4576E5DF.7010502@tds.net> Mike Hansen wrote: >>> How can I check if a variable is an integer? >> Luke and John have answered your question, but we should also >> ask, why >> do you want to do that? Explicit type testing is a code >> smell, perhaps >> there is a better way to do what you want. >> >> Kent >> > > Kent, > > Can you explain further? Refactoring is in my queue of books to read. In In general, the preference in Python code is to check for a specific behaviour, or just assume the behaviour, rather than to check for a specific type. Writing code this way supports duck typing. The two approaches are sometimes called Easier to Ask Forgiveness than Permission (EAFP) and Look Before You Leap (LBYL). For example Python has the idea of a file-like object, which is anything that behaves like a file. If you have a function that works on a file, you could check that the parameter is an actual file. This is an example of LBYL: def doSomething(f): if type(f) is not file: # error If you do that, you are preventing your clients from passing a file-like object, for example a StringIO object. On the other hand, if you write doSomething() to just use f as a file, any object that has the required methods will just work; an object that doesn't have the required methods will raise an AttributeError. That is EAFP. This is just a general guideline, there are certainly cases where explicit type checking is appropriate. > a web app I'm writing, I'm checking the input kind of like this... > > try: > form_value = int(form.getvalue('num_widgets') > except ValueError: > display_error("Number of Widgets must be a number") That is fine - you are checking that the string is something that can be converted to an int, and catching the error - EAFP. If you tried to check the contents of the string before calling int(), that would be LBYL. Kent From kent37 at tds.net Wed Dec 6 16:48:30 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Dec 2006 10:48:30 -0500 Subject: [Tutor] Q: win32 download (attack of the newbies) In-Reply-To: References: Message-ID: <4576E64E.8000901@tds.net> Tim Golden wrote: > Using win32com and Excel is very easy, but there > are alternatives if you want: > > http://cheeseshop.python.org/pypi/xlrd/0.5.2 xlrd is for reading only - OP wants to write Excel files. Kent From Tim.Golden at viacom-outdoor.co.uk Wed Dec 6 16:56:10 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 6 Dec 2006 15:56:10 -0000 Subject: [Tutor] Q: win32 download (attack of the newbies) In-Reply-To: <4576E64E.8000901@tds.net> Message-ID: [Kent Johnson] | Tim Golden wrote: | > Using win32com and Excel is very easy, but there | > are alternatives if you want: | > | > http://cheeseshop.python.org/pypi/xlrd/0.5.2 | | xlrd is for reading only - OP wants to write Excel files. Oops! Quite right. I was moving a bit too fast. Sorry, OP! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ajkadri at googlemail.com Wed Dec 6 17:06:08 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 6 Dec 2006 16:06:08 +0000 Subject: [Tutor] How to create variable length bar chart ?? Message-ID: Hi folks, I have a problem with drawing a BAR-chart. I am drawing a HORIZONTAL bar chart. I did manage to sort out the length issue of individual bars (with the help of inputs from this forum's members). What I want is the height of the bar chart should be determined dynamically (basically it means the length of the Y-axis), as per the number of data-items being displayed. There can be 5 items or there can be 100, so how to manage this issue? Any input would be highly appreciated .. Thanks. Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061206/58ea78fb/attachment.htm From kent37 at tds.net Wed Dec 6 17:13:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Dec 2006 11:13:56 -0500 Subject: [Tutor] Q: win32 download (attack of the newbies) In-Reply-To: <7c3104d20612060809k20708c67s52da43d701369e77@mail.gmail.com> References: <7c3104d20612060706n7bba46d5x1ffad27dfe8428e2@mail.gmail.com> <4576E3E7.10102@tds.net> <7c3104d20612060809k20708c67s52da43d701369e77@mail.gmail.com> Message-ID: <4576EC44.5000000@tds.net> Toon Pieton wrote: > Hey Kent, > > Thanks for your reply. Can you suggest which module I should look at? > And can I make diagrams using that module? Assuming you are asking about modules for writing CSV files, then look at the csv module. CSV (comma-separated value) is a simple text format that doesn't support diagrams. If you are just creating simple tables to read into Excel it will work, for anything more complicated you need COM or PyExcelerator. Kent From morpheus at mywdo.com Wed Dec 6 17:00:18 2006 From: morpheus at mywdo.com (Morpheus) Date: Wed, 06 Dec 2006 10:00:18 -0600 Subject: [Tutor] List to dictionary question Message-ID: <1165420818.7549.9.camel@abit> I'm new to programming, and trying to learn the Python language. The following code does what I want it to do, but I have not idea how it works. def scanList(names,temp): for i in names: temp[i] = 0 print temp Names = [] temp = {} I have a list of names (Names[]) and want to remove duplicate names in the list. Here is what I think is happening (please correct me if I'm wrong, or using the wrong technical terminology): I'm passing the variables Names and temp as arguments to the scanList function. The statement (for i in names:) is an iteration going through each item in the list. The next statement (temp[i] = 0) is where I get confused. Can someone please explain what is happening here. Thanks for your help. From pytutmail at gmail.com Wed Dec 6 17:21:38 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Wed, 6 Dec 2006 17:21:38 +0100 Subject: [Tutor] WXPython Listbox Problem Message-ID: <7c3104d20612060821u6468def7jf7e8363181530e82@mail.gmail.com> Hey friendly users! I'm trying to make a simple program to calculate the odds when playing poker. The idea is that you select both your cards from listboxes. However, no matter what I try, I just can't select a entry in either of the listboxes! I can click all I want, it just won't select. Here's the code which I use to create the boxes: ID_BOX1 = 120 ID_BOX2 = 130 ... #Boxes, to select cards self.box1 = wx.ListBox(parent=self, id=ID_BOX1, size=(60,163) , name='Card 1', choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0) self.box2 = wx.ListBox(parent=self, id=ID_BOX2, size=(60,163) , name='Card 2', choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0) self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=ID_BOX1) self.box2.Bind(wx.EVT_LISTBOX, self.b2func,id=ID_BOX2) I hope anybody can help me. If you need to see the full code, just send me a reply Thanks in advance to anybody reading/helping! Toon Pieton -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061206/f229c17a/attachment.html From Mike.Hansen at atmel.com Wed Dec 6 17:39:07 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 6 Dec 2006 09:39:07 -0700 Subject: [Tutor] List to dictionary question Message-ID: <57B026980605A64F9B23484C5659E32E44E9AF@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Morpheus > Sent: Wednesday, December 06, 2006 9:00 AM > To: tutor at python.org > Subject: [Tutor] List to dictionary question > > I'm new to programming, and trying to learn the Python language. > The following code does what I want it to do, but I have not > idea how it > works. > > def scanList(names,temp): > for i in names: > temp[i] = 0 > print temp > > Names = [] > temp = {} > > I have a list of names (Names[]) and want to remove duplicate names in > the list. Here is what I think is happening (please correct me if I'm > wrong, or using the wrong technical terminology): I'm passing the > variables Names and temp as arguments to the scanList function. The > statement (for i in names:) is an iteration going through each item in > the list. The next statement (temp[i] = 0) is where I get confused. > Can someone please explain what is happening here. > > Thanks for your help. > temp is a dictionary. Dictionaries have unique keys. scanList goes through each item in names and sets the key of the temp dictionary to the item. If there are more than one item of the same value, it just sets the key of the dictionary again. The statement temp[i] = 0 is setting the value of the key 'i' to 0. (temp[key] = value) To get your list without duplicates just get the keys of the dictionary after the list has been run through function. temp.keys() If you have names = [1,2,3,2,4] The temp dictionaries keys become 1,2,3,4. In the scanList function above temp[1] = 0 temp[2] = 0 temp[3] = 0 temp[2] = 0 <- It's just setting the same key to zero again. temp[4] = 0 temp.keys() [1,2,3,4] I hope that makes some sense. I think a more explicit way of removing duplicates from a list is using sets. In [1]: x = ['a', 'a', 'b', 'c', 'd', 'e', 'f', 'f', 'f'] In [2]: se = set(x) In [3]: se Out[3]: set(['a', 'c', 'b', 'e', 'd', 'f']) In [4]: sel = list(se) In [5]: sel Out[5]: ['a', 'c', 'b', 'e', 'd', 'f'] -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From klappnase at freenet.de Wed Dec 6 18:06:28 2006 From: klappnase at freenet.de (Michael Lange) Date: Wed, 6 Dec 2006 18:06:28 +0100 Subject: [Tutor] order of arguments in function In-Reply-To: <7.0.1.0.2.20061206041559.069f2630@rcblue.com> References: <7.0.1.0.2.20061205221333.066431b0@rcblue.com> <20061206112835.3a894b74.klappnase@freenet.de> <7.0.1.0.2.20061206041559.069f2630@rcblue.com> Message-ID: <20061206180628.49e1dcec.klappnase@freenet.de> On Wed, 06 Dec 2006 04:29:54 -0800 Dick Moores wrote: (...) > > > >def my_function(min, max=None): > > if max is None: > > max = min > > min = 0 > > # stuff > > Great! > > >I am not sure if this is more intuitive though. > > >>> > def my_function(min, max=None): > if max is None: > max, min = min, 0 > return max - min > >>> my_function(3, 7) > 4 > > I meant that the order "min, max" is more intuitive than "max, min". > Don't you agree? And it's the order used in random.randint(), > random.randrange(), and random.uniform(), for examples. > Sure I agree, although it may depend on what the function actually does and how you name it (and the arguments). If you e.g. rewrite your example to def subtract(from_, what=0): return from_ - what the changed order of arguments seems quite intuitive to me. What I meant in the first place is that it might be "unintuitive" that if you pass only one argument this is the one that comes last in case you pass two arguments. As I said, I was not sure and was too lazy to think much about it :-) Michael From jorgen.maillist at gmail.com Wed Dec 6 19:28:15 2006 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 6 Dec 2006 19:28:15 +0100 Subject: [Tutor] WXPython Listbox Problem In-Reply-To: <7c3104d20612060821u6468def7jf7e8363181530e82@mail.gmail.com> References: <7c3104d20612060821u6468def7jf7e8363181530e82@mail.gmail.com> Message-ID: <11e49df10612061028q1f5f7392gddf75964a4576264@mail.gmail.com> Try ID's higher then 10000 ... low ID's are usually taken by wxWidgets. To be safe simply create them with wx.ID_ANY (from the top of my head) and after that: self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=self.box1.GetId()) Which is a bit more dynamic anyway and saves you some constants. Furthermore, wxPython specific questions could be better answered in the wxPython-users mailinglist to get more succes ;-) Regards, - Jorgen On 12/6/06, Toon Pieton wrote: > Hey friendly users! > > I'm trying to make a simple program to calculate the odds when playing > poker. The idea is that you select both your cards from listboxes. However, > no matter what I try, I just can't select a entry in either of the > listboxes! I can click all I want, it just won't select. Here's the code > which I use to create the boxes: > > ID_BOX1 = 120 > ID_BOX2 = 130 > ... > #Boxes, to select cards > self.box1 = wx.ListBox(parent=self, id=ID_BOX1, size=(60,163) , > name='Card 1', > > choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0) > self.box2 = wx.ListBox(parent=self, id=ID_BOX2, size=(60,163) , > name='Card 2', > > choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0) > self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=ID_BOX1) > self.box2.Bind(wx.EVT_LISTBOX, self.b2func,id=ID_BOX2) > > I hope anybody can help me. If you need to see the full code, just send me a > reply > > Thanks in advance to anybody reading/helping! > Toon Pieton > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > On 12/6/06, Toon Pieton wrote: > Hey friendly users! > > I'm trying to make a simple program to calculate the odds when playing > poker. The idea is that you select both your cards from listboxes. However, > no matter what I try, I just can't select a entry in either of the > listboxes! I can click all I want, it just won't select. Here's the code > which I use to create the boxes: > > ID_BOX1 = 120 > ID_BOX2 = 130 > ... > #Boxes, to select cards > self.box1 = wx.ListBox(parent=self, id=ID_BOX1, size=(60,163) , > name='Card 1', > > choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0) > self.box2 = wx.ListBox(parent=self, id=ID_BOX2, size=(60,163) , > name='Card 2', > > choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0) > self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=ID_BOX1) > self.box2.Bind(wx.EVT_LISTBOX, self.b2func,id=ID_BOX2) > > I hope anybody can help me. If you need to see the full code, just send me a > reply > > Thanks in advance to anybody reading/helping! > Toon Pieton > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From rumpy at mrbitter.org Wed Dec 6 20:29:20 2006 From: rumpy at mrbitter.org (rumpy at mrbitter.org) Date: Wed, 06 Dec 2006 11:29:20 -0800 Subject: [Tutor] (no subject) Message-ID: <20061206112920.lh759rv7ok8wco4k@mrbitter.org> Hi Folks, I'm working through Magnus Lie Hetland's excellent book "Beginning Python" and I have a few basic (I think) questions. Specifically, regarding his first project in Chapter 20 (Instant Markup). The outline of the project is to take a plain text file and "mark it up" into HTML or XML. Step one is simply getting the tool to recognize basic elements of a text document - blocks of text seperated by empty lines. To this end the following file is created as a module(?) to be imported into the subsequent primary execution (main?) script. def lines(file): for line in file: yield line yield '\n' del blocks(file): block = [] for line in lines(file): if line.strip(): block.append(line) elif block: yield ''.join(block).strip() block = [] Now, for the most part I understand what's going on here. The part that puzzles me a bit is: elif block: yield ''.join(block).strip() block = [] 1.) Does the yield mean the block list is returned from the function AND then wiped out by 'block = []'? 2.) Is block list scrubbed clean by 'block = []' because the function is going to iterate over the next block and it needs to be empty? 3.) The statement after the 'yield' threw me. I haven't seen that to this point in the book. I figured 'yield' is always last in a function because it needs to iterate over itself again. Am I understanding generators correctly? 4.) Is it correct to say that a generator is a function that returns multiple values and iterates over itself? Thanks in advance for any feedback/help. Rumpy. From alan.gauld at btinternet.com Wed Dec 6 21:03:29 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Dec 2006 20:03:29 -0000 Subject: [Tutor] How to create variable length bar chart ?? References: Message-ID: "Asrarahmed Kadri" wrote in > What I want is the height of the bar chart should be determined > dynamically > (basically it means the length of the Y-axis), as per the number of > data-items being displayed. Hmm, I thought we ansdwered this recently... Anyhow you just calculate it. The height will be for an example with 3 bars: 3 times the height of a bar plus the inter bar space. You might want to add some extra height on at the top. Or you might want to have a bigger or smaller gap at top and bottom than between the bars but basically its a case of work out rthe pattern then calculate according to the data. The worst case is: <- top_gap XXXXXXXXXXXXX XXXXXXXXXXXX <- gap_size XXXXXXXXXXXXXX <- bar_size <- bottom_gap -------------------------------- <-- X axis height = (bottom_gap+ top_gap) + ((N-1) * (bar_size+gap_size)) + bar_size HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rumpy at mrbitter.org Wed Dec 6 20:59:54 2006 From: rumpy at mrbitter.org (rumpy at mrbitter.org) Date: Wed, 06 Dec 2006 11:59:54 -0800 Subject: [Tutor] Generator questions. Message-ID: <20061206115954.2c3op7ea3o8g8s8s@mrbitter.org> Hi Folks, I'm working through Magnus Lie Hetland's excellent book "Beginning Python" and I have a few basic (I think) questions. Specifically, regarding his first project in Chapter 20(Instant Markup). The outline of the project is to take a plain text file and "mark it up" into HTML or XML. Step one is simply getting the tool to recognize basic elements of a text document - blocks of text seperated by empty lines. To this end the following file is created as a module(?) to be imported into the subsequent primary execution (main?) script. def lines(file): for line in file: yield line yield '\n' del blocks(file): block = [] for line in lines(file): if line.strip(): block.append(line) elif block: yield ''.join(block).strip() block = [] Now, for the most part I understand what's going on here. The part that puzzles me a bit is: elif block: yield ''.join(block).strip() block = [] 1.) Does the yield mean the block list is returned from the function AND then wiped out by 'block = []'? 2.) Is block list scrubbed clean by 'block = []' because the function is going to iterate over the next block and it needs to be empty? 3.) The statement after the 'yield' threw me. I haven't seen that to this point in the book. I figured 'yield' is always last in a function because it needs to iterate over itself again. Am I understanding generators correctly? 4.) Is it correct to say that a generator is a function that returns multiple values and iterates over itself? Thanks in advance for any feedback/help. Rumpy. From ajkadri at googlemail.com Wed Dec 6 21:43:11 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Wed, 6 Dec 2006 20:43:11 +0000 Subject: [Tutor] How to create variable length bar chart ?? In-Reply-To: References: Message-ID: I got that point, what I want is how the dimensions of the canvas would be adjusted so as to incorporate this Y-axis variable length? Do I need a scrollbar for that?? Thanks in advance. Regards, Asrarahmed Kadri On 12/6/06, Alan Gauld wrote: > > > "Asrarahmed Kadri" wrote in > > > What I want is the height of the bar chart should be determined > > dynamically > > (basically it means the length of the Y-axis), as per the number of > > data-items being displayed. > > Hmm, I thought we ansdwered this recently... > > Anyhow you just calculate it. > The height will be for an example with 3 bars: > > 3 times the height of a bar plus the inter bar space. > > You might want to add some extra height on at the top. > > Or you might want to have a bigger or smaller gap at top > and bottom than between the bars but basically its a case > of work out rthe pattern then calculate according to the data. > > The worst case is: > > > <- top_gap > XXXXXXXXXXXXX > > XXXXXXXXXXXX > <- gap_size > XXXXXXXXXXXXXX <- bar_size > <- bottom_gap > -------------------------------- <-- X axis > > > height = (bottom_gap+ top_gap) + ((N-1) * (bar_size+gap_size)) + > bar_size > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061206/9082d462/attachment.html From wescpy at gmail.com Wed Dec 6 21:53:36 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 6 Dec 2006 12:53:36 -0800 Subject: [Tutor] Generator questions. In-Reply-To: <20061206115954.2c3op7ea3o8g8s8s@mrbitter.org> References: <20061206115954.2c3op7ea3o8g8s8s@mrbitter.org> Message-ID: <78b3a9580612061253o7c021a4av29d62ebbad16706b@mail.gmail.com> > def lines(file): > for line in file: yield line > yield '\n' > > del blocks(file): > block = [] > for line in lines(file): > if line.strip(): > block.append(line) > elif block: > yield ''.join(block).strip() > block = [] > > 1.) Does the yield mean the block list is returned from the function > AND then wiped out by 'block = []'? the code in question will take all the strings in block, concatenate them together [with ''.join()], remove leading/trailing whitespace [.strip()], and yield or "return" it as the next "generated" item being iterated over. when .next() is executed again, either explicitly by the caller or via a for-loop, it will resume immediately on the next line succeeding the yield statement where execution was paused. > 2.) Is block list scrubbed clean by 'block = []' because the function > is going to iterate over the next block and it needs to be empty? yes, block is then cleared so that it can process the next few lines of data. > 3.) The statement after the 'yield' threw me. I haven't seen that to > this point in the book. I figured 'yield' is always last in a function > because it needs to iterate over itself again. Am I understanding > generators correctly? a "yield" does *not* have to be the last in the function. wherever a yield is encountered, the function will resume right after it when .next() is called again. generators do "not start from scratch...," they pick up right where they left off. > 4.) Is it correct to say that a generator is a function that returns > multiple values and iterates over itself? a generator acts like an iterator in that multiple values are returned in an iterative process (meaning not all at the same time). it is dressed up as a function which contains logic that can "generate" each successive value to "return." i have to give kudos to magnus for putting "real world" code when he teaches generators in his book. for my core python book, i was more concerned about getting the point across as to what generators *are*, so for completeness, here are some of the examples i used, all of which can be downloaded at the book's website (see below) regardless of whether you buy the book (or not): 1) simpleGen.py (the world's 2nd simplest generator?): def simpleGen(): yield 1 yield '2 --> punch!' if __name__ == '__main__': for item in simpleGen(): print item 2) randGen.py: from random import randrange as rr def randGen(aList): while aList: yield aList.pop(rr(len(aList))) if __name__ == '__main__': for item in randGen(['rock', 'paper', 'scissors']): print item 3) counter.py (needs 2.5+): def counter(start_at=0): count = start_at while True: val = (yield count) if val is not None: count = val else: count += 1 if __name__ == '__main__': print 'initializing counter to start counting at 5' count = counter(5) print 'calling count.next():', count.next() print 'calling count.next():', count.next() print 'calling count.send(9):', count.send(9) print 'calling count.next():', count.next() print 'calling count.close():', count.close() print 'calling count.next():', count.next() you can get these by clicking on "Source Code" -> ch11 -> alt. i'll leave it as an exercise to reader to determine the output *and WHY*. :-) another fun place to go look for iterators is the itertools module. it contains a lot of useful iteration code that are all really just generators(!): http://docs.python.org/lib/itertools-functions.html hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From shitizb at yahoo.com Wed Dec 6 22:35:42 2006 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed, 6 Dec 2006 13:35:42 -0800 (PST) Subject: [Tutor] Beautiful Soup Message-ID: <20061206213543.38549.qmail@web53805.mail.yahoo.com> Hi, I am using beautiful soup to get links from an html document. I found that beautiful Soup changes the & in the links to & due to which some of the links become unusable. Is there any way I could stop this behaviour? Regards, Shitiz --------------------------------- Access over 1 million songs - Yahoo! Music Unlimited. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061206/b03b4053/attachment-0001.htm From markusro at element.fkp.physik.tu-darmstadt.de Wed Dec 6 23:39:09 2006 From: markusro at element.fkp.physik.tu-darmstadt.de (Markus Rosenstihl) Date: Wed, 6 Dec 2006 23:39:09 +0100 Subject: [Tutor] Running drPython and other Pythonscript on Macintosh OS/X In-Reply-To: <4575315C.3050105@telia.com> References: <4575315C.3050105@telia.com> Message-ID: Am 05.12.2006 um 09:44 schrieb Anders Persson: > Hi! > > I try to learn my son Development using Python. > I have found that drPython was a great enviroment and easy for him to > understand. > > Is't a problem running om Macintosh OS/X i have to start on > commandline, > OS/X > dosen't understand when i clicked on the drPython.py files. > > I have found this is same for all pythonfiles on OS/X, does somone know > how a > tell a OS/X system that .py means run Python. > Try to right click (Ctrl + Klick) and open it with PythonLauncher. I don't know if that is installed with a stock python but I think so. If that is working you can get the Info panel of that file (Apple + i) and select PythonLauncher in the "open with" section? HTH Markus From rumpy at mrbitter.org Wed Dec 6 23:51:53 2006 From: rumpy at mrbitter.org (rumpy at mrbitter.org) Date: Wed, 06 Dec 2006 14:51:53 -0800 Subject: [Tutor] Generator questions. In-Reply-To: <78b3a9580612061253o7c021a4av29d62ebbad16706b@mail.gmail.com> References: <20061206115954.2c3op7ea3o8g8s8s@mrbitter.org> <78b3a9580612061253o7c021a4av29d62ebbad16706b@mail.gmail.com> Message-ID: <20061206145153.f4mci23cu84440ck@mrbitter.org> Hi Wesley, Thank you very much for the feeback. It helped a lot! Quoting wesley chun : >> def lines(file): >> for line in file: yield line >> yield '\n' >> >> del blocks(file): >> block = [] >> for line in lines(file): >> if line.strip(): >> block.append(line) >> elif block: >> yield ''.join(block).strip() >> block = [] >> >> 1.) Does the yield mean the block list is returned from the function >> AND then wiped out by 'block = []'? > > the code in question will take all the strings in block, concatenate > them together [with ''.join()], remove leading/trailing whitespace > [.strip()], and yield or "return" it as the next "generated" item > being iterated over. when .next() is executed again, either > explicitly by the caller or via a for-loop, it will resume immediately > on the next line succeeding the yield statement where execution was > paused. > > >> 2.) Is block list scrubbed clean by 'block = []' because the function >> is going to iterate over the next block and it needs to be empty? > > yes, block is then cleared so that it can process the next few lines of data. > > >> 3.) The statement after the 'yield' threw me. I haven't seen that to >> this point in the book. I figured 'yield' is always last in a function >> because it needs to iterate over itself again. Am I understanding >> generators correctly? > > a "yield" does *not* have to be the last in the function. wherever a > yield is encountered, the function will resume right after it when > .next() is called again. generators do "not start from scratch...," > they pick up right where they left off. > > >> 4.) Is it correct to say that a generator is a function that returns >> multiple values and iterates over itself? > > a generator acts like an iterator in that multiple values are returned > in an iterative process (meaning not all at the same time). it is > dressed up as a function which contains logic that can "generate" each > successive value to "return." > > i have to give kudos to magnus for putting "real world" code when he > teaches generators in his book. for my core python book, i was more > concerned about getting the point across as to what generators *are*, > so for completeness, here are some of the examples i used, all of > which can be downloaded at the book's website (see below) regardless > of whether you buy the book (or not): > > 1) simpleGen.py (the world's 2nd simplest generator?): > > def simpleGen(): > yield 1 > yield '2 --> punch!' > > if __name__ == '__main__': > for item in simpleGen(): > print item > > 2) randGen.py: > > from random import randrange as rr > > def randGen(aList): > while aList: > yield aList.pop(rr(len(aList))) > > if __name__ == '__main__': > for item in randGen(['rock', 'paper', 'scissors']): > print item > > 3) counter.py (needs 2.5+): > > def counter(start_at=0): > count = start_at > while True: > val = (yield count) > if val is not None: > count = val > else: > count += 1 > > if __name__ == '__main__': > print 'initializing counter to start counting at 5' > count = counter(5) > print 'calling count.next():', count.next() > print 'calling count.next():', count.next() > print 'calling count.send(9):', count.send(9) > print 'calling count.next():', count.next() > print 'calling count.close():', count.close() > print 'calling count.next():', count.next() > > you can get these by clicking on "Source Code" -> ch11 -> alt. i'll > leave it as an exercise to reader to determine the output *and WHY*. > :-) another fun place to go look for iterators is the itertools > module. it contains a lot of useful iteration code that are all > really just generators(!): > > http://docs.python.org/lib/itertools-functions.html > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com Regards, Josh. From alan.gauld at btinternet.com Wed Dec 6 22:46:06 2006 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 6 Dec 2006 21:46:06 +0000 (GMT) Subject: [Tutor] How to create variable length bar chart ?? In-Reply-To: Message-ID: <955311.21406.qm@web86108.mail.ird.yahoo.com> --- Asrarahmed Kadri wrote: > I got that point, what I want is how the dimensions of the > canvas would be > adjusted so as to incorporate this Y-axis variable length? > You provide the size of the canvas when you create it normally. But you can use at least 2 approaches. 1) Given the fixed size of your canvas you can scale the graphs to fit - keeping track oof the longest X and Y measures and scaling against the corresponding size of the canvas. or 2) Scale the canvas to match the graphs. If the canvas gets bigger than a certain size (maybe related to screen size?) youi can add scroll bars. HTH, Alan G. ___________________________________________________________ All New Yahoo! Mail ? Tired of Vi at gr@! come-ons? Let our SpamGuard protect you. http://uk.docs.yahoo.com/nowyoucan.html From eike.welk at post.rwth-aachen.de Thu Dec 7 00:56:26 2006 From: eike.welk at post.rwth-aachen.de (Eike Welk) Date: Thu, 07 Dec 2006 00:56:26 +0100 Subject: [Tutor] order of arguments in function In-Reply-To: <7.0.1.0.2.20061206041559.069f2630@rcblue.com> References: <7.0.1.0.2.20061205221333.066431b0@rcblue.com> <20061206112835.3a894b74.klappnase@freenet.de> <7.0.1.0.2.20061206041559.069f2630@rcblue.com> Message-ID: <200612070056.26166.eike.welk@post.rwth-aachen.de> On Wednesday 06 December 2006 13:29, Dick Moores wrote: > I meant that the order "min, max" is more intuitive than "max, > min". Don't you agree? And it's the order used in random.randint(), > random.randrange(), and random.uniform(), for examples. What about two intuitively named functions, like the random module does it? my_function_range(min, max): #do the sophisticated myfunction work here my_function_max(max): return my_function_range(0, max) Eike. From pyro9219 at gmail.com Thu Dec 7 01:24:49 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 6 Dec 2006 16:24:49 -0800 Subject: [Tutor] Create a script to make bootable USB device. Message-ID: Is this something I can do using just python and libraries? I know I could automate other utilities, but I'd like to write some kind of neat utility myself that I could play with for more experience. Goal: make USB drive bootable to a dos prompt (dont care what dos, assuming I need a bootable image for this) make script prompt for file(s) to move to disk (already know how to do this) Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061206/c4352dc6/attachment.html From rabidpoobear at gmail.com Thu Dec 7 01:31:43 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 06 Dec 2006 18:31:43 -0600 Subject: [Tutor] subprocess & pyw conflict ? In-Reply-To: <200612061532.26501.pythontut@pusspaws.net> References: <200612061532.26501.pythontut@pusspaws.net> Message-ID: <457760EF.5090608@gmail.com> Dave S wrote: > Hi all, > > I thought I had my solution with subprocess ... my test code ... > > > > #!/usr/bin/env python > # -*- coding: iso8859_1 -*- > > import subprocess > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, > universal_newlines=True) > op = a.stdout.readlines() > > for i in op: > if i.split(' ')[0] == 'gmanager.exe': > f = open('E:\Documents and Settings\All > Users\Desktop\gsr_running', 'w') > f.close() > > > > works a treat when I run it as proc.py detects the process I am looking for & > writes a dummy file to the desktop. :) but I get a black windows terminal > flash up. > > The code will eventually run in an app.pyw so to check it would be OK I > renamed my working proc.py to proc.pyw - it fails :(, No window (as > expected), no dummy file (not expected) - the process gmanager.exe is > running. > > So there seems to be a problem with subprocess & pyw > > Googling I found ... > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&group_id=5470 > So I tried the suggested workaround with proc.pyw ... > > > > #!/usr/bin/env python > # -*- coding: iso8859_1 -*- > > import subprocess > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, > stdout=subprocess.PIPE, universal_newlines=True) > op = a.stdout.readlines() > a.stdin.close() > > for i in op: > if i.split(' ')[0] == 'gmanager.exe': > f = open('E:\Documents and Settings\All > Users\Desktop\gsr_running', 'w') > f.close() > > > Still zip, and because there is no terminal, I cannot view any errors ! > > Any suggestions welcome :) > Well, because I'm batting 0 on this thread so far, I think I'll just go ahead and suggest another bad solution! You could try redirecting the output of sys.stderr to a file, and you might be able to see the error message! :D If you hadn't said 'any suggestions welcome' I might've kept this to myself :P >>> import sys >>> class TestClass(object): def __init__(self): self.data = [] def write(self,item): self.data.append(item) >>> a = TestClass() >>> sys.stderr = a >>> salfjdsljfka321423 >>> print a.data ['\nTraceback (most recent call last):', '\n', ' File "", line 1, in -toplevel-\n', ' salfjdsljfka321423\n', "NameError: name 'salfjdsljfka321423' is not defined\n"] Except instead of a file-like class, you could just use a real file. But then it would only leave the last line intact. So you'd probably want to make a class that wraps a file object, where the write method just appends to an internal list, and it writes it all out to the file when you call the Class.close() or whatever. Actually, I guess the program stops executing on an exception... Hmm, not really sure what you'd do exactly. Sure, there are better solutions, and this doesn't really help you with your original problem, but it at least lets you see your error message! HTH, -Luke > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From samrobertsmith at gmail.com Thu Dec 7 02:49:22 2006 From: samrobertsmith at gmail.com (linda.s) Date: Wed, 6 Dec 2006 17:49:22 -0800 Subject: [Tutor] Is there any good turtorial about numeric python for beginners? Message-ID: <1d987df30612061749w5ce10c35k2a5e350c53edabd1@mail.gmail.com> Is there any good tutorial about numeric python for beginners? I have googled around and many of them are either too old or aims at experienced users... Thanks, Linda From morpheus at mywdo.com Thu Dec 7 04:31:55 2006 From: morpheus at mywdo.com (Morpheus) Date: Wed, 06 Dec 2006 21:31:55 -0600 Subject: [Tutor] List to dictionary Message-ID: <1165462316.7549.13.camel@abit> I'm new to programming, and trying to learn the Python language. The following code does what I want it to do, but I have not idea how it works. def scanList(names,temp): for i in names: temp[i] = 0 print temp Names = [] temp = {} I have a list of names (Names[]) and want to remove duplicate names in the list. Here is what I think is happening (please correct me if I'm wrong, or using the wrong technical terminology): I'm passing the variables Names and temp as arguments to the scanList function. The statement (for i in names:) is an iteration going through each item in the list. The next statement (temp[i] = 0) is where I get confused. Can someone please explain what is happening here. Thanks for your help. From dkuhlman at rexx.com Thu Dec 7 04:54:50 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 6 Dec 2006 19:54:50 -0800 Subject: [Tutor] Is there any good turtorial about numeric python for beginners? In-Reply-To: <1d987df30612061749w5ce10c35k2a5e350c53edabd1@mail.gmail.com> References: <1d987df30612061749w5ce10c35k2a5e350c53edabd1@mail.gmail.com> Message-ID: <20061207035450.GA83651@cutter.rexx.com> On Wed, Dec 06, 2006 at 05:49:22PM -0800, linda.s wrote: > Is there any good tutorial about numeric python for beginners? > I have googled around and many of them are either too old or aims at > experienced users... Look here: http://new.scipy.org/Wiki/Documentation Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From bill at celestial.net Thu Dec 7 06:11:40 2006 From: bill at celestial.net (Bill Campbell) Date: Wed, 6 Dec 2006 21:11:40 -0800 Subject: [Tutor] ***SPAM*** List to dictionary In-Reply-To: <1165462316.7549.13.camel@abit> References: <1165462316.7549.13.camel@abit> Message-ID: <20061207051140.GA6199@ayn.mi.celestial.com> On Wed, Dec 06, 2006, Morpheus wrote: >I'm new to programming, and trying to learn the Python language. >The following code does what I want it to do, but I have not idea how it >works. > >def scanList(names,temp): > for i in names: > temp[i] = 0 > print temp > >Names = [] >temp = {} > >I have a list of names (Names[]) and want to remove duplicate names in >the list. Here is what I think is happening (please correct me if I'm >wrong, or using the wrong technical terminology): I'm passing the >variables Names and temp as arguments to the scanList function. The >statement (for i in names:) is an iteration going through each item in >the list. The next statement (temp[i] = 0) is where I get confused. >Can someone please explain what is happening here. The way I usually do this is something like: outDict = dict(map(lambda x: (x, 1), inList)) names = outDict.keys() names.sort() Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``Find out just what people will submit to, and you have found out the exact amount of injustice and wrong which will be imposed upon them; and these will continue until they are resisted with either words or blows, or both. The limits of tyrants are prescribed by the endurance of those whom they oppress.'' -- Frederick Douglass. From rabidpoobear at gmail.com Thu Dec 7 06:53:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 06 Dec 2006 23:53:44 -0600 Subject: [Tutor] ***SPAM*** List to dictionary In-Reply-To: <20061207051140.GA6199@ayn.mi.celestial.com> References: <1165462316.7549.13.camel@abit> <20061207051140.GA6199@ayn.mi.celestial.com> Message-ID: <4577AC68.6060405@gmail.com> >> I have a list of names (Names[]) and want to remove duplicate names in >> the list. [snip] >> > > The way I usually do this is something like: > > outDict = dict(map(lambda x: (x, 1), inList)) > names = outDict.keys() > names.sort() > How about this :D # Remove duplicates from a list: >>> L = [1,2,2,3,3,3] >>> [x for x in L if x not in locals()['_[1]'].__self__] [1,2,3] [accessed at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 ] Also, why is there now a ******SPAM***** in the subject heading? Wonderingly, -Luke From rdm at rcblue.com Thu Dec 7 08:09:39 2006 From: rdm at rcblue.com (Dick Moores) Date: Wed, 06 Dec 2006 23:09:39 -0800 Subject: [Tutor] List to dictionary In-Reply-To: <4577AC68.6060405@gmail.com> References: <1165462316.7549.13.camel@abit> <20061207051140.GA6199@ayn.mi.celestial.com> <4577AC68.6060405@gmail.com> Message-ID: <7.0.1.0.2.20061206230454.03b0c418@rcblue.com> At 09:53 PM 12/6/2006, Luke Paireepinart wrote: > >> I have a list of names (Names[]) and want to remove duplicate names in > >> the list. [snip] > >> > > > > The way I usually do this is something like: > > > > outDict = dict(map(lambda x: (x, 1), inList)) > > names = outDict.keys() > > names.sort() > > >How about this :D > ># Remove duplicates from a list: > >>> L = [1,2,2,3,3,3] > >>> [x for x in L if x not in locals()['_[1]'].__self__] >[1,2,3] Why not >>> L = [1,2,2,3,3,3] >>> list(set(L)) [1, 2, 3] ? That's a real question. Dick Moores From rabidpoobear at gmail.com Thu Dec 7 10:19:47 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 07 Dec 2006 03:19:47 -0600 Subject: [Tutor] List to dictionary In-Reply-To: <7.0.1.0.2.20061206230454.03b0c418@rcblue.com> References: <1165462316.7549.13.camel@abit> <20061207051140.GA6199@ayn.mi.celestial.com> <4577AC68.6060405@gmail.com> <7.0.1.0.2.20061206230454.03b0c418@rcblue.com> Message-ID: <4577DCB3.4010409@gmail.com> Dick Moores wrote: > At 09:53 PM 12/6/2006, Luke Paireepinart wrote: >> # Remove duplicates from a list: >> >>> L = [1,2,2,3,3,3] >> >>> [x for x in L if x not in locals()['_[1]'].__self__] >> [1,2,3] > > Why not > >>> L = [1,2,2,3,3,3] > >>> list(set(L)) > [1, 2, 3] Because the other methods (via set or dict keys) don't preserve order, and the list comprehension version does. The others may have preserved order in this case, but won't always. -Luke From pythontut at pusspaws.net Thu Dec 7 11:25:07 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 7 Dec 2006 10:25:07 +0000 Subject: [Tutor] subprocess & pyw conflict ? In-Reply-To: <457760EF.5090608@gmail.com> References: <200612061532.26501.pythontut@pusspaws.net> <457760EF.5090608@gmail.com> Message-ID: <200612071025.08010.pythontut@pusspaws.net> On Thursday 07 December 2006 00:31, Luke Paireepinart wrote: > Dave S wrote: > > Hi all, > > > > I thought I had my solution with subprocess ... my test code ... > > > > > > > > #!/usr/bin/env python > > # -*- coding: iso8859_1 -*- > > > > import subprocess > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, > > universal_newlines=True) > > op = a.stdout.readlines() > > > > for i in op: > > if i.split(' ')[0] == 'gmanager.exe': > > f = open('E:\Documents and Settings\All > > Users\Desktop\gsr_running', 'w') > > f.close() > > > > > > > > works a treat when I run it as proc.py detects the process I am looking > > for & writes a dummy file to the desktop. :) but I get a black windows > > terminal flash up. > > > > The code will eventually run in an app.pyw so to check it would be OK I > > renamed my working proc.py to proc.pyw - it fails :(, No window (as > > expected), no dummy file (not expected) - the process gmanager.exe is > > running. > > > > So there seems to be a problem with subprocess & pyw > > > > Googling I found ... > > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&grou > >p_id=5470 So I tried the suggested workaround with proc.pyw ... > > > > > > > > #!/usr/bin/env python > > # -*- coding: iso8859_1 -*- > > > > import subprocess > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, > > stdout=subprocess.PIPE, universal_newlines=True) > > op = a.stdout.readlines() > > a.stdin.close() > > > > for i in op: > > if i.split(' ')[0] == 'gmanager.exe': > > f = open('E:\Documents and Settings\All > > Users\Desktop\gsr_running', 'w') > > f.close() > > > > > > Still zip, and because there is no terminal, I cannot view any errors ! > > > > Any suggestions welcome :) > > Well, because I'm batting 0 on this thread so far, I think I'll just go > ahead and suggest another bad solution! > You could try redirecting the output of sys.stderr to a file, and you > might be able to see the error message! :D > > If you hadn't said 'any suggestions welcome' I might've kept this to > myself :P Ahhh .. 'any suggestions' is an SOS call - all any any ideas are warmly greeted :) > > >>> import sys > >>> class TestClass(object): > > def __init__(self): > self.data = [] > def write(self,item): > self.data.append(item) > > >>> a = TestClass() > >>> sys.stderr = a > >>> salfjdsljfka321423 > >>> print a.data > > ['\nTraceback (most recent call last):', '\n', ' File "", > line 1, in -toplevel-\n', ' salfjdsljfka321423\n', "NameError: name > 'salfjdsljfka321423' is not defined\n"] > > Except instead of a file-like class, you could just use a real file. > But then it would only leave the last line intact. > So you'd probably want to make a class that wraps a file object, where > the write method just appends to an internal list, > and it writes it all out to the file when you call the Class.close() or > whatever. > Actually, I guess the program stops executing on an exception... > Hmm, not really sure what you'd do exactly. > > > Sure, there are better solutions, and this doesn't really help you with > your original problem, but it at least lets you see your error message! > HTH, > -Luke Thanks for that - I will give it a go & post back :) > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Thu Dec 7 11:58:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Dec 2006 05:58:39 -0500 Subject: [Tutor] ***SPAM*** List to dictionary In-Reply-To: <20061207051140.GA6199@ayn.mi.celestial.com> References: <1165462316.7549.13.camel@abit> <20061207051140.GA6199@ayn.mi.celestial.com> Message-ID: <4577F3DF.7050008@tds.net> Bill Campbell wrote: > The way I usually do this is something like: > > outDict = dict(map(lambda x: (x, 1), inList)) > names = outDict.keys() > names.sort() This is a really old approach. Since Python 2.3 you can say outDict = dict.fromkeys(inList) or dict.fromkeys(inList, 1) if you cared about the value. Since Python 2.4 you can use a set instead of a dict as shown in other replies. Kent From kent37 at tds.net Thu Dec 7 12:05:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Dec 2006 06:05:56 -0500 Subject: [Tutor] List to dictionary In-Reply-To: <4577AC68.6060405@gmail.com> References: <1165462316.7549.13.camel@abit> <20061207051140.GA6199@ayn.mi.celestial.com> <4577AC68.6060405@gmail.com> Message-ID: <4577F594.2000203@tds.net> Luke Paireepinart wrote: > How about this :D > > # Remove duplicates from a list: >>>> L = [1,2,2,3,3,3] >>>> [x for x in L if x not in locals()['_[1]'].__self__] > [1,2,3] > > [accessed at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 ] The problems with this are, it is not portable, even across versions of CPython (try the above in Python 2.4) and it will have poor performance for lists with many unique entries because it searches the entire list for each addition. These recipes are interesting, particularly the discussion for the first one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438599 Raymond Hettinger (who should know, he is a Python performance guru) said in 2002 that this is the fastest order-preserving method: def uniq(alist) # Fastest order preserving set = {} return [set.setdefault(e,e) for e in alist if e not in set] Perhaps there is now a faster method using a real set, but maybe not because set doesn't have a method that adds to the set and returns the value. Kent From kent37 at tds.net Thu Dec 7 12:14:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Dec 2006 06:14:05 -0500 Subject: [Tutor] Is there any good turtorial about numeric python for beginners? In-Reply-To: <20061207035450.GA83651@cutter.rexx.com> References: <1d987df30612061749w5ce10c35k2a5e350c53edabd1@mail.gmail.com> <20061207035450.GA83651@cutter.rexx.com> Message-ID: <4577F77D.3020103@tds.net> Dave Kuhlman wrote: > On Wed, Dec 06, 2006 at 05:49:22PM -0800, linda.s wrote: >> Is there any good tutorial about numeric python for beginners? >> I have googled around and many of them are either too old or aims at >> experienced users... > > Look here: > > http://new.scipy.org/Wiki/Documentation Particularly the "Documentation from NumPy's predecessor" link which AFAIK is the best available free documentation for NumPy. Alternately you can buy the current docs. Kent From ajkadri at googlemail.com Thu Dec 7 13:17:16 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Thu, 7 Dec 2006 12:17:16 +0000 Subject: [Tutor] How to center teh window using Tkinter Message-ID: Hi folks, I want to center the window. I am using Tkinter and want to center the window as per the screen size. The size of the window is not fixed, I mean the height is not fixed, so I cannot use fixed parameters that can be passed to geometry() method. IF the height is more, the window should be positioned at the top.. I hope I am clear about my question. Thanks in anticipation. Best Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061207/d0476c79/attachment.html From Mike.Hansen at atmel.com Thu Dec 7 16:22:57 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 7 Dec 2006 08:22:57 -0700 Subject: [Tutor] ***SPAM*** List to dictionary Message-ID: <57B026980605A64F9B23484C5659E32E44EA85@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Luke Paireepinart > Sent: Wednesday, December 06, 2006 10:54 PM > To: tutor at python.org > Subject: Re: [Tutor] ***SPAM*** List to dictionary > > Also, why is there now a ******SPAM***** in the subject heading? > > Wonderingly, > -Luke > Maybe Bill was labeling it SPAM since it was posted twice to the list? Wed Dec 6 17:00:18 CET 2006 Thu Dec 7 04:31:55 CET 2006 Also, I tried to explain in my reply yesterday. "The next statement (temp[i] = 0) is where I get confused. Can someone please explain what is happening here. " I'm confused. %) -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From magoldfish at gmail.com Thu Dec 7 17:09:48 2006 From: magoldfish at gmail.com (Marcus Goldfish) Date: Thu, 7 Dec 2006 11:09:48 -0500 Subject: [Tutor] __init__.py for running a file from commandline? In-Reply-To: <7e5ba9220611270940g2689faeased0bd28b5972c6b3@mail.gmail.com> References: <5e183f3d0611100624r2676a4dci22e6c66a584515fa@mail.gmail.com> <4555C88D.3080503@tds.net> <5e183f3d0611270916p1c14c3b3s4837f6118d7f557d@mail.gmail.com> <7e5ba9220611270940g2689faeased0bd28b5972c6b3@mail.gmail.com> Message-ID: <5e183f3d0612070809p205ad4dexb1fd4d13f59a4599@mail.gmail.com> On 11/27/06, Michael P. Reilly wrote: > > When you type something from the command-line, you are at the whims of the > WinXP command shell. You have to follow its rules, not Python's. It would > need to have "python" in %PATH%, and then it would need to have to run > "python C:\path\to\pyroot\utils\commands\mygrep.py". The arguments are > determined before Python is even started, and they are parsed by the WinXP > DOS-a-like shell. (Also why you cannot have ".", only Python understands > dots). Doesn't python receive the command line argument, path-to-script in this case, for its own use and parsing? It seems like the solution I really seek is a command line switch that tells python that I am using namespace conventions, and that it should begin searching in the directory that PYTHONPATH points to. For example, c:> python -namespace utils.commands.mygrep.py Do either of you know of such a convenience? I suppose I could write a batch file, python.bat, that could implement this wrapping logic. Kent mentioned issues with importing modules, and those would still hold > true since those are after Python starts. Also, the WinXP shell, does > handle forward slashs, but you were probably not in the proper directory for > the shell to find the file using "utils/commands/mygrep.py" pathname. Good spot-- forward slashes work, simply as relative path specifiers, so you have to be in the correct directory. I was not. Thus the problem. Also: it appears forward slashes only work as relative path specifiers (e.g., cd /temp), but fail if with a drive letter (e.g., c:/temp). Thanks guys. Marcus -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061207/fb2e2fbe/attachment.htm From pythontut at pusspaws.net Thu Dec 7 17:48:05 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 7 Dec 2006 16:48:05 +0000 Subject: [Tutor] subprocess & pyw conflict ? In-Reply-To: <200612071025.08010.pythontut@pusspaws.net> References: <200612061532.26501.pythontut@pusspaws.net> <457760EF.5090608@gmail.com> <200612071025.08010.pythontut@pusspaws.net> Message-ID: <200612071648.06673.pythontut@pusspaws.net> On Thursday 07 December 2006 10:25, Dave S wrote: > On Thursday 07 December 2006 00:31, Luke Paireepinart wrote: > > Dave S wrote: > > > Hi all, > > > > > > I thought I had my solution with subprocess ... my test code ... > > > > > > > > > > > > #!/usr/bin/env python > > > # -*- coding: iso8859_1 -*- > > > > > > import subprocess > > > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, > > > universal_newlines=True) > > > op = a.stdout.readlines() > > > > > > for i in op: > > > if i.split(' ')[0] == 'gmanager.exe': > > > f = open('E:\Documents and Settings\All > > > Users\Desktop\gsr_running', 'w') > > > f.close() > > > > > > > > > > > > works a treat when I run it as proc.py detects the process I am looking > > > for & writes a dummy file to the desktop. :) but I get a black windows > > > terminal flash up. > > > > > > The code will eventually run in an app.pyw so to check it would be OK I > > > renamed my working proc.py to proc.pyw - it fails :(, No window (as > > > expected), no dummy file (not expected) - the process gmanager.exe is > > > running. > > > > > > So there seems to be a problem with subprocess & pyw > > > > > > Googling I found ... > > > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&gr > > >ou p_id=5470 So I tried the suggested workaround with proc.pyw ... > > > > > > > > > > > > #!/usr/bin/env python > > > # -*- coding: iso8859_1 -*- > > > > > > import subprocess > > > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, > > > stdout=subprocess.PIPE, universal_newlines=True) > > > op = a.stdout.readlines() > > > a.stdin.close() > > > > > > for i in op: > > > if i.split(' ')[0] == 'gmanager.exe': > > > f = open('E:\Documents and Settings\All > > > Users\Desktop\gsr_running', 'w') > > > f.close() > > > > > > > > > Still zip, and because there is no terminal, I cannot view any errors ! > > > > > > Any suggestions welcome :) > > > > Well, because I'm batting 0 on this thread so far, I think I'll just go > > ahead and suggest another bad solution! > > You could try redirecting the output of sys.stderr to a file, and you > > might be able to see the error message! :D > > > > If you hadn't said 'any suggestions welcome' I might've kept this to > > myself :P > > Ahhh .. 'any suggestions' is an SOS call - all any any ideas are warmly > greeted :) > > > >>> import sys > > >>> class TestClass(object): > > > > def __init__(self): > > self.data = [] > > def write(self,item): > > self.data.append(item) > > > > >>> a = TestClass() > > >>> sys.stderr = a > > >>> salfjdsljfka321423 > > >>> print a.data > > > > ['\nTraceback (most recent call last):', '\n', ' File "", > > line 1, in -toplevel-\n', ' salfjdsljfka321423\n', "NameError: name > > 'salfjdsljfka321423' is not defined\n"] > > > > Except instead of a file-like class, you could just use a real file. > > But then it would only leave the last line intact. > > So you'd probably want to make a class that wraps a file object, where > > the write method just appends to an internal list, > > and it writes it all out to the file when you call the Class.close() or > > whatever. > > Actually, I guess the program stops executing on an exception... > > Hmm, not really sure what you'd do exactly. > > > > > > Sure, there are better solutions, and this doesn't really help you with > > your original problem, but it at least lets you see your error message! > > HTH, > > -Luke > > Thanks for that - I will give it a go & post back :) > Oh my head .... OK after much tinkering I got the following to work with .pyw # scan windows task list to see if GSR is running f = os.popen('tasklist.exe', 'r') plist = f.readlines() f.close gsr_running = False # scan for GSR program for line in plist: if line.split(' ')[0] == 'gmanager.exe': gsr_running = True Ahhhh .... Dave can relax, chill, project finished ... all works ... goooood ...... (homer simpson moment !) > > > _______________________________________________ > > > 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 pythontut at pusspaws.net Thu Dec 7 18:15:25 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 7 Dec 2006 17:15:25 +0000 Subject: [Tutor] OT GPL project finished, presentation looming Message-ID: <200612071715.25953.pythontut@pusspaws.net> OK this is an OT question I have just finished a Python QT project for work, written in my own free time over the last several months (and with a lot of help from you guys :). Its 5500 lines of python over several modules (for me that huge) and a CSV 'rules' file of 500 lines, all GPL'd We use a commercial program that connects to remote intruder alarm systems and downloads their configs. Up to 80,000 software attributes per site. My python QT app scans the database files (.dbf), decodes them, scans them against a CSV list of rules and throws any anomaly's out to a GUI. It essentially audits the site programming checking for incorrect programming, configuration errors etc. In addition it generates audited PDF certificates, engineer summary's PDFs and user manuals PDFs for each specific site. Sometime in January I have to give a presentation and I know one of the questions will be. "Its what we want but you are not a company, what if you leave ?" I need an answer,.. What am I asking ... If need be are any of you for hire ? Dave PS it looks great, would love to post some pngs but it would violate the list rules :( From kloosterjunkie at hotmail.com Thu Dec 7 18:21:42 2006 From: kloosterjunkie at hotmail.com (Moedeloos Overste) Date: Thu, 07 Dec 2006 18:21:42 +0100 Subject: [Tutor] Newbie question: random.sample illusion? Message-ID: Hi everybody, I'm in the process of learning Python and working my way through O'Reilly's "Learning Python". As an excercise I wrote (some copy/paste as well) a small lottery program just to learn how to work with lists and dictionarys etc. The user has to enter 6 numbers from a range(1-45). The numbers are stored in a list(num_list). Then the program asks the user how many times(vDraws) he wants to play the lottery with his numbers. After entering the program draws the lottery the desired number of times and compares the winning numbers with the users numbers. Now, by accident I stumbled upon the following; if the user enters the numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must have made a mistake. Could somebody have a look at the code please and tell me where I took a wrong turn? winnings=0 right2=1 right3=4 right4=15 right5=450 right6=1000000 user_nums=[] # empty List for numbers print "Kies je nummers tussen 0 en 46" print whereat=1 listindex=0 # when 7th number is inputted loop breaks while whereat <= 6: num=raw_input("Voer "+str(whereat)+". Lotto nummer in: ") # check that user inputted value is not smaller than 1 or bigger than 45 # and that it is not already in user_nums if num != "" and len(num) != 0: if int(num) >= 1 and int(num) <= 45 and num not in user_nums: user_nums.append(num) whereat+=1 listindex+=1 # if above statement if false just pass and ask for the number again! else: pass print '1 trekking kost U 1 euro inzet' print vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") # Create dictionary for statiscal purposes later on :-) d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, 14:0, 15:0, 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, 27:0, 28:0, 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, 40:0, 41:0, 42:0, 43:0, 44:0, 45:0} match=0 count=0 inzet=vDraws * 1 while vDraws > 0: x=random.sample(range(1,46), 6)# draws lottery from given range for i in x: y=int(i) d[y] = int(d[y])+ 1 #stores values in lottonumbers dictionary for p in user_nums: count+=1 y=str(y) if p in y: match+=1 # increase matching variable by one if its right number # caculating winnings if match ==2: winnings+=right2 match=0 elif match ==3: winnings+=right3 match=0 elif match == 4: winnings+=right4 match=0 elif match == 5: winnings+=right5 match=0 elif match == 6: winnings+=right6 match=0 vDraws = vDraws - 1 # sorting dictionary by its values items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] print print print saldo=winnings-inzet print print print '-' * 80 if saldo > 0: print 'U heeft', saldo, 'euro winst gemaakt!' else: print 'U heeft', saldo, ' euro verlies geleden!' print 'U heeft in totaal gewonnen', winnings, 'euro.' print 'Uw inzet was', inzet, 'euro' print 'De 6 meest gevallen getallen waren:', for x in sortedlist[0:6]: print x, #prints the 6 most drawn numbers _________________________________________________________________ Veilig & gerust mailen met de verbeterde antivirusscan van Live Mail! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl From python at venix.com Thu Dec 7 18:53:47 2006 From: python at venix.com (Python) Date: Thu, 07 Dec 2006 12:53:47 -0500 Subject: [Tutor] ***SPAM*** List to dictionary In-Reply-To: <57B026980605A64F9B23484C5659E32E44EA85@poccso.US.ad.atmel.com> References: <57B026980605A64F9B23484C5659E32E44EA85@poccso.US.ad.atmel.com> Message-ID: <1165514027.31666.132.camel@www.venix.com> On Thu, 2006-12-07 at 08:22 -0700, Mike Hansen wrote: > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Luke Paireepinart > > Sent: Wednesday, December 06, 2006 10:54 PM > > To: tutor at python.org > > Subject: Re: [Tutor] ***SPAM*** List to dictionary > > > > Also, why is there now a ******SPAM***** in the subject heading? > > > > Wonderingly, > > -Luke > > > > Maybe Bill was labeling it SPAM since it was posted twice to the list? > > Wed Dec 6 17:00:18 CET 2006 > Thu Dec 7 04:31:55 CET 2006 > > Also, I tried to explain in my reply yesterday. "The next statement > (temp[i] = 0) is where I get confused. temp is a dictionary. ## earlier code was temp = {} i is a name from a list called names. temp[i] is a reference into the dictionary using i as a key. temp[i] = 0 binds that reference to 0. Any previous value for temp[i] is discarded. temp is simply being used to track distinct names. Any name from names will have one and only one occurrence in the list of dictionary keys. So temp.keys() will contain each name exactly once. As covered in a recent thread, the ordering of the names will probably be different from the original names list. > Can someone please explain what is happening here. " > > I'm confused. %) > ------------- > > NOTICE: This e-mail transmission and any documents or files attached to > it contain information for the sole use of the above-identified individual or entity. > > Its contents may be privileged, confidential, and exempt from disclosure under the law. > Any dissemination, distribution, or copying of this communication is strictly prohibited. > > Please notify the sender immediately if you are not the intended recipient. > > FGNS > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From rabidpoobear at gmail.com Thu Dec 7 18:54:02 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 07 Dec 2006 11:54:02 -0600 Subject: [Tutor] OT GPL project finished, presentation looming In-Reply-To: <200612071715.25953.pythontut@pusspaws.net> References: <200612071715.25953.pythontut@pusspaws.net> Message-ID: <4578553A.2070005@gmail.com> Dave S wrote: > [snip explanation of program] Sounds really cool! > > Sometime in January I have to give a presentation and I know one of the > questions will be. "Its what we want but you are not a company, what if you > leave ?" I need an answer,.. > My understanding is that if it's GPL'ed, they can use it whether you work there or not. Is that not true? > What am I asking ... If need be are any of you for hire ? > Why would hiring someone else help in this situation? > Dave > > PS it looks great, would love to post some pngs but it would violate the list > rules :( > You can just upload the PNGs to a free webhost and link us to them, like Photobucket or Imageshack. I imagine people just don't want big attachments in their e-mail. If you give them a link to the picture then they only have to download it if they really want to see what it is. HTH, -Luke From pythontut at pusspaws.net Thu Dec 7 19:17:06 2006 From: pythontut at pusspaws.net (Dave S) Date: Thu, 7 Dec 2006 18:17:06 +0000 Subject: [Tutor] OT GPL project finished, presentation looming In-Reply-To: <4578553A.2070005@gmail.com> References: <200612071715.25953.pythontut@pusspaws.net> <4578553A.2070005@gmail.com> Message-ID: <200612071817.06077.pythontut@pusspaws.net> On Thursday 07 December 2006 17:54, Luke Paireepinart wrote: > Dave S wrote: > > [snip explanation of program] > > Sounds really cool! Its a bit niche - but cool > > > Sometime in January I have to give a presentation and I know one of the > > questions will be. "Its what we want but you are not a company, what if > > you leave ?" I need an answer,.. > > My understanding is that if it's GPL'ed, they can use it whether you > work there or not. > Is that not true? Sorry I did not mean that, the GPL thing is AOK > > > What am I asking ... If need be are any of you for hire ? > > Why would hiring someone else help in this situation? I work for national company, they are very interested in what I am doing, there is nothing else in the marketplace that does this, but they are used to dealing with large software company's. They will be concerned about using my app because I am one person. What if I get hit by a bus ! what if I leave ? what happens when a new version of controller comes out & new CSV rules need to be written - what would they do ? Its all GPL so no secrets, my guess is that if $$ was offered to the Python community someone would be willing to maintain the code but I am unsure of how it would actually work ? Is it a case of "hello, python programmer for hire ?" or is there an 'official' procedure that I can include in my presentation ? I would guess this is a common problem for GPL software being introduced into commercial settings (the whole support thing). (It appears that none of the company's IT professionals can program !) > > Dave > > > > PS it looks great, would love to post some pngs but it would violate the > > list rules :( > > You can just upload the PNGs to a free webhost and link us to them, like > Photobucket or Imageshack. > > I imagine people just don't want big attachments in their e-mail. If > you give them a link to the picture > then they only have to download it if they really want to see what it is. OK I will do my presentation then do that as a kind of thank you for all your help :) > > HTH, > -Luke From rabidpoobear at gmail.com Thu Dec 7 19:17:23 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 07 Dec 2006 12:17:23 -0600 Subject: [Tutor] Newbie question: random.sample illusion? In-Reply-To: References: Message-ID: <45785AB3.5090704@gmail.com> Moedeloos Overste wrote: > Hi everybody, > > I'm in the process of learning Python and working my way through O'Reilly's > "Learning Python". As an excercise I wrote (some copy/paste as well) a small > lottery program just to learn how to work with lists and dictionarys etc. > > The user has to enter 6 numbers from a range(1-45). The numbers are stored > in a list(num_list). Then the program asks the user how many times(vDraws) > he wants to play the lottery with his numbers. After entering the program > draws the lottery the desired number of times and compares the winning > numbers with the users numbers. > > Now, by accident I stumbled upon the following; if the user enters the > numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must > have made a mistake. Could somebody have a look at the code please and tell > me where I took a wrong turn? > > > > winnings=0 > right2=1 > right3=4 > right4=15 > right5=450 > right6=1000000 > it might be clearer to do prizes = [0,0,1,4,15,450,1000000] > user_nums=[] # empty List for numbers > print "Kies je nummers tussen 0 en 46" > print > whereat=1 > listindex=0 > What is the point of having two variables here? You never use listindex. You should start whereat at 0. > # when 7th number is inputted loop breaks > while whereat <= 6: > And loop until whereat is less than 6. That's the general consensus on looping in Computer Science. Starting at 0. > num=raw_input("Voer "+str(whereat)+". Lotto nummer in: ") > And just change this line to str(whereat+1) instead. > # check that user inputted value is not smaller than 1 or bigger than 45 > # and that it is not already in user_nums > if num != "" and len(num) != 0: > If they enter 'a' your program will crash. A better solution would be to use a try.... except block. eg. try: tmp = int(num) if tmp >= 1 and tmp <= 45 and tmp not in user_nums: user_nums.append(tmp) whereat += 1 except ValueError: pass > if int(num) >= 1 and int(num) <= 45 and num not in user_nums: > user_nums.append(num) > Also note here that you're using the integer representation of num to compare it to 1 and 45, but then you're storing the string representation of it in user_nums. This may be part of why you're having a problem. > whereat+=1 > listindex+=1 > # if above statement if false just pass and ask for the number > again! > else: > pass > print '1 trekking kost U 1 euro inzet' > print > vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") > > # Create dictionary for statiscal purposes later on :-) > d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, > 14:0, 15:0, > 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, 27:0, > 28:0, > 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, 40:0, > 41:0, 42:0, > 43:0, 44:0, 45:0} > This could be: d = {} for x in range(1,46): d[x] = 0 Or several varations of this, using lambda & map, and such. > match=0 > count=0 > You don't use count in your program anywhere. > inzet=vDraws * 1 > There's absolutely no reason to multiply something by 1. > while vDraws > 0: > x=random.sample(range(1,46), 6)# draws lottery from given range > for i in x: > y=int(i) > This line is unnecessary, 'i' is already an integer. > d[y] = int(d[y])+ 1 #stores values in lottonumbers dictionary > Can be shortened to d[y] += 1 > for p in user_nums: > count+=1 > no reason to do this because the for loop will end when it runs out of variables. > y=str(y) > Again, if you leave the original items as integers you don't have to do all this conversion. > if p in y: > I would change this to 'if p == y', because I'm not sure what 'in' is doing here. > match+=1 # increase matching variable by one if its right > number > > # caculating winnings > if match ==2: > winnings+=right2 > match=0 > elif match ==3: > winnings+=right3 > match=0 > elif match == 4: > winnings+=right4 > match=0 > elif match == 5: > winnings+=right5 > match=0 > elif match == 6: > winnings+=right6 > match=0 > Using that prizes list, this can be shortened to winnings += prizes[match] match = 0 > vDraws = vDraws - 1 > Or vDraws -= 1 > # sorting dictionary by its values > items=d.items() > backitems=[ [v[1],v[0]] for v in items] > backitems.sort() > sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] > > print > print > print > saldo=winnings-inzet > print > print > print '-' * 80 > if saldo > 0: > print 'U heeft', saldo, 'euro winst gemaakt!' > else: > print 'U heeft', saldo, ' euro verlies geleden!' > > > print 'U heeft in totaal gewonnen', winnings, 'euro.' > print 'Uw inzet was', inzet, 'euro' > print 'De 6 meest gevallen getallen waren:', > for x in sortedlist[0:6]: print x, #prints the 6 most drawn numbers > > _________________________________________________________________ > Veilig & gerust mailen met de verbeterde antivirusscan van Live Mail! > http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rabidpoobear at gmail.com Thu Dec 7 19:19:59 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 07 Dec 2006 12:19:59 -0600 Subject: [Tutor] Newbie question: random.sample illusion? In-Reply-To: References: Message-ID: <45785B4F.1080406@gmail.com> Moedeloos Overste wrote: > Hi everybody, > > I'm in the process of learning Python and working my way through O'Reilly's > "Learning Python". As an excercise I wrote (some copy/paste as well) a small > lottery program just to learn how to work with lists and dictionarys etc. > > The user has to enter 6 numbers from a range(1-45). The numbers are stored > in a list(num_list). Then the program asks the user how many times(vDraws) > he wants to play the lottery with his numbers. After entering the program > draws the lottery the desired number of times and compares the winning > numbers with the users numbers. > > Now, by accident I stumbled upon the following; if the user enters the > numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must > have made a mistake. Could somebody have a look at the code please and tell > me where I took a wrong turn? > > Ooops, I accidentally hit 'send' on that other e-mail before I was done with it. I was just going to say that you forgot to include 'random'. Also, here is the code with the changes I suggested. I ran it on 1,2,3,4,5,6 for 80 tries and didn't win every time. #code begins here. import random winnings=0 prizes = [0,0,1,4,15,450,1000000] user_nums=[] # empty List for numbers print "Kies je nummers tussen 0 en 46" print whereat=0 # when 6th number is inputted loop breaks while whereat < 6: num=raw_input("Voer "+str(whereat+1)+". Lotto nummer in: ") # check that user inputted value is not smaller than 1 or bigger than 45 # and that it is not already in user_nums try: tmp = int(num) if tmp >= 1 and tmp <= 45 and tmp not in user_nums: user_nums.append(tmp) whereat += 1 except ValueError: pass print '1 trekking kost U 1 euro inzet' print vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") # Create dictionary for statiscal purposes later on :-) d = {} for x in range(1,46): d[x] = 0 match=0 count=0 inzet=vDraws while vDraws > 0: x=random.sample(range(1,46), 6)# draws lottery from given range for i in x: d[i] += 1 #stores values in lottonumbers dictionary for p in user_nums: if p == i: match+=1 # increase matching variable by one if its right number winnings += prizes[match] match = 0 vDraws -= 1 # sorting dictionary by its values items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] print '\n\n' saldo=winnings-inzet print '\n' print '-' * 80 if saldo > 0: print 'U heeft', saldo, 'euro winst gemaakt!' else: print 'U heeft', saldo, ' euro verlies geleden!' print 'U heeft in totaal gewonnen', winnings, 'euro.' print 'Uw inzet was', inzet, 'euro' print 'De 6 meest gevallen getallen waren:', for x in sortedlist[0:6]: print x, #prints the 6 most drawn numbers From kloosterjunkie at hotmail.com Thu Dec 7 22:44:41 2006 From: kloosterjunkie at hotmail.com (Moedeloos Overste) Date: Thu, 07 Dec 2006 22:44:41 +0100 Subject: [Tutor] Newbie question: random.sample illusion? Message-ID: Dear Luke, Wow, thank you for all the input.You really made an effort .It's always nice when someone is willing to share his knowledge with you. You really opened my eyes on some things. I guess it's gonna be a long night for me. But I'm really enjoying myself though :-) Regards, Robert >From: Luke Paireepinart >To: Moedeloos Overste >CC: tutor at python.org >Subject: Re: [Tutor] Newbie question: random.sample illusion? >Date: Thu, 07 Dec 2006 12:17:23 -0600 > >Moedeloos Overste wrote: >>Hi everybody, >> >>I'm in the process of learning Python and working my way through >>O'Reilly's "Learning Python". As an excercise I wrote (some copy/paste as >>well) a small lottery program just to learn how to work with lists and >>dictionarys etc. >> >>The user has to enter 6 numbers from a range(1-45). The numbers are stored >>in a list(num_list). Then the program asks the user how many times(vDraws) >>he wants to play the lottery with his numbers. After entering the program >>draws the lottery the desired number of times and compares the winning >>numbers with the users numbers. >> >>Now, by accident I stumbled upon the following; if the user enters the >>numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must >>have made a mistake. Could somebody have a look at the code please and >>tell me where I took a wrong turn? >> >> >> >>winnings=0 >>right2=1 >>right3=4 >>right4=15 >>right5=450 >>right6=1000000 >> >it might be clearer to do >prizes = [0,0,1,4,15,450,1000000] >>user_nums=[] # empty List for numbers >>print "Kies je nummers tussen 0 en 46" >>print >>whereat=1 >>listindex=0 >> >What is the point of having two variables here? >You never use listindex. >You should start whereat at 0. >># when 7th number is inputted loop breaks >>while whereat <= 6: >> >And loop until whereat is less than 6. >That's the general consensus on looping in Computer Science. Starting at >0. >> num=raw_input("Voer "+str(whereat)+". Lotto nummer in: ") >> >And just change this line to str(whereat+1) instead. >> # check that user inputted value is not smaller than 1 or bigger than >>45 >> # and that it is not already in user_nums >> if num != "" and len(num) != 0: >> >If they enter 'a' your program will crash. >A better solution would be to use a try.... except block. >eg. try: > tmp = int(num) > if tmp >= 1 and tmp <= 45 and tmp not in user_nums: > user_nums.append(tmp) > whereat += 1 >except ValueError: > pass >> if int(num) >= 1 and int(num) <= 45 and num not in user_nums: >> user_nums.append(num) >> >Also note here that you're using the integer representation of num to >compare it to 1 and 45, >but then you're storing the string representation of it in user_nums. >This may be part of why you're having a problem. >> whereat+=1 >> listindex+=1 >> # if above statement if false just pass and ask for the >>number again! >> else: >> pass >>print '1 trekking kost U 1 euro inzet' >>print >>vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") >> >># Create dictionary for statiscal purposes later on :-) >>d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, >>14:0, 15:0, >> 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, >>27:0, 28:0, >> 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, >>40:0, 41:0, 42:0, >> 43:0, 44:0, 45:0} >> >This could be: >d = {} >for x in range(1,46): > d[x] = 0 >Or several varations of this, using lambda & map, and such. >>match=0 >>count=0 >> >You don't use count in your program anywhere. >>inzet=vDraws * 1 >> >There's absolutely no reason to multiply something by 1. >>while vDraws > 0: >> x=random.sample(range(1,46), 6)# draws lottery from given range >> for i in x: >> y=int(i) >> >This line is unnecessary, 'i' is already an integer. >> d[y] = int(d[y])+ 1 #stores values in lottonumbers dictionary >> >Can be shortened to d[y] += 1 >> for p in user_nums: >> count+=1 >> >no reason to do this because the for loop will end when it runs out of >variables. >> y=str(y) >> >Again, if you leave the original items as integers you don't have to do all >this conversion. >> if p in y: >> >I would change this to 'if p == y', because I'm not sure what 'in' is doing >here. >> match+=1 # increase matching variable by one if its right >>number >> >> # caculating winnings >> if match ==2: >> winnings+=right2 >> match=0 >> elif match ==3: >> winnings+=right3 >> match=0 >> elif match == 4: >> winnings+=right4 >> match=0 >> elif match == 5: >> winnings+=right5 >> match=0 >> elif match == 6: >> winnings+=right6 >> match=0 >> >Using that prizes list, this can be shortened to >winnings += prizes[match] >match = 0 >> vDraws = vDraws - 1 >> >Or vDraws -= 1 >># sorting dictionary by its values >>items=d.items() >>backitems=[ [v[1],v[0]] for v in items] >>backitems.sort() >>sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] >> >>print >>print >>print >>saldo=winnings-inzet >>print >>print >>print '-' * 80 >>if saldo > 0: >> print 'U heeft', saldo, 'euro winst gemaakt!' >>else: >> print 'U heeft', saldo, ' euro verlies geleden!' >> >> >>print 'U heeft in totaal gewonnen', winnings, 'euro.' >>print 'Uw inzet was', inzet, 'euro' >>print 'De 6 meest gevallen getallen waren:', >>for x in sortedlist[0:6]: print x, #prints the 6 most drawn numbers >> >>_________________________________________________________________ >>Veilig & gerust mailen met de verbeterde antivirusscan van Live Mail! >>http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > _________________________________________________________________ Veilig & gerust mailen met de verbeterde antivirusscan van Live Mail! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl From alan.gauld at btinternet.com Thu Dec 7 23:35:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Dec 2006 22:35:07 -0000 Subject: [Tutor] OT GPL project finished, presentation looming References: <200612071715.25953.pythontut@pusspaws.net><4578553A.2070005@gmail.com> <200612071817.06077.pythontut@pusspaws.net> Message-ID: "Dave S" wrote > They will be concerned about using my app because I am one person. > What if I > get hit by a bus ! what if I leave ? This is a common problem in big companies including my own. For years they wouldn't even use the GNU software because it was "unsupported". I even had to buy a commercial version of emacs for about $300... Eventually cygnus started offering support (for $5K per year) and they allowed us to use emacs, gcc etc Eventually even X windows. Now they are more relaxed and we use Linux to run our internal DHCP and DNS, even some web servers... > ...(It appears that none of the > company's IT professionals can program !) That's also not unusual. In fact our company appears to be slowly heading that way. We used to have 11,000 IT professionals of which around 5000 were developers. Now we have 13,000 IT professionals of whom about 1000 still write code. The coding is mainly offshored to India and Eastern Europe. Our internal people are being retrained on "higher value" roles like business analysis, design/architecture, deployment/integration and project management. So I now program in python as and when I can and call it prototyping... They call it progress. Alan G. From samrobertsmith at gmail.com Fri Dec 8 06:13:42 2006 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 7 Dec 2006 21:13:42 -0800 Subject: [Tutor] function and module Message-ID: <1d987df30612072113y3a85fecct4826f1aee2e31fb5@mail.gmail.com> I am reading a sample code and want to figure out where a function (for instance, abc) is from. There are many lines such as from XXX import * Is there a way not going through all these imported modules to find where the abc is from (by the way, the abc function is not in the current module)? Thanks, Linda From samrobertsmith at gmail.com Fri Dec 8 06:25:47 2006 From: samrobertsmith at gmail.com (linda.s) Date: Thu, 7 Dec 2006 21:25:47 -0800 Subject: [Tutor] mlab and numeric Message-ID: <1d987df30612072125j619afd3u106ad0bfa64a2b38@mail.gmail.com> can anyone tell me the relationship between MLab and Numeric? Especially MLab, there is very little information about it. From alan.gauld at btinternet.com Fri Dec 8 09:21:04 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Dec 2006 08:21:04 -0000 Subject: [Tutor] function and module References: <1d987df30612072113y3a85fecct4826f1aee2e31fb5@mail.gmail.com> Message-ID: "linda.s" wrote >I am reading a sample code and want to figure out where a function > (for instance, abc) is from. > There are many lines such as > from XXX import * This is one of the chief reasons why 'from x import *' is bad practice. > Is there a way not going through all these imported modules to find > where the abc is from (by the way, the abc function is not in the > current module)? There are a couple of possibilities. 1) if you can import the moduile into a >>> propmpt you could ask abc where it's from. >>> print abc.__file__ should work 2) if the import won't work I think the next best technoque is probably to use grep, especially if the modules are all in a common directory tree. grep "def abc" */*.py Or write a short Python script to traverse the tree using os.walk and try doing 'from foo import abc' on each file.... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From torhildrum at gmail.com Fri Dec 8 10:19:19 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Fri, 8 Dec 2006 10:19:19 +0100 Subject: [Tutor] Of integers, relations and trees Message-ID: I have this problem which I thought would be trivial, but I can't seem to figure out a decent way to do it. Say I have the following file: 10 -100 -101 -103 -108 --1080 ---1080.10 ---1080.11 12 -120 -125 20 30 -300 --3010 ---3010.3 These numbers represents a tree-like structure. In lack of a better explanation, here is how it works: A level in the tree follows the following: x * 10^level x * 10^1 belongs to level 1 in the three x * 10^2 belongs to level 2 in the three. etc. So, the top-nodes in the three are 10, 12, 20 and 30. The childs of 10 is 100, 101, 103 and 108. The child of 108 is 1080. The child of 1080 is 1080.10 and 1080.11 and these are the leaves. I decided to make this pretty straightforward so I wrote a Node class and a Tree class. A Node has a key which is an integer, as well as some additional information that isn't relevant to the structure. It also has a link to it's sibling, which is the next node on the same level. And a link to it's first child. So for 10, it looks like this.: 10 -> 20 (siblings of 10) | (child) 100 -> 101 -> 103 -> 108 (siblings of 100) Inserting a sibling is done like this: ----------------------------------------------------- def addSibling(self, newNode): tmp = self.node # current node last = self.node # previous node # find the node that is the direct sibling to the new node while( tmp != None && tmp['key'] < newNode['key']): last = tmp tmp = tmp['sibling'] # insert the new node after the node with a lower key last['sibling'] = newNode # If there is a node with a higher key, add it as a sibling to the new node if( tmp != None ): newNode['sibling'] = tmp ----------------------------------------------------- This code does not handle a special case where the newNode has the smallest key among the siblings and should be placed first and thus be the direct child of the parent level. But, that doesn't really matter. How do I know if I have a sibling or a child? Simple, I just check the length: --------------------------------------------- if( len(str(node1[key])) == len(str(node2[key])) ): --------------------------------------------- If the length, amount of integers, is the same, they are siblings. My problem is this: Say I have created a new node with the key 2080. I start of with my root node which has a key of 0. 2080 is not a sibling of 0, so I call a recursive function named addChild(). addChild checks the child of 0, which is 10 and determines that 2080 is not a sibling of 10. But, it's not a child either. Here comes my query: How do I determine that 2080 is not a child of 10. Or how do i determine that 536798 is not a child of 536780? And how do I determine that it is a child? I'll try to explain again: 5.36798 * 10^5 is at level 5 in the tree. It's direct children looks like this: 5.36798x * 10^6. 5.36797x * 10^6 is NOT a child, it is a child of 5.36797 * 10^5. Does this make sense to anyone? :) Also, consider the following: 5.36798xxx * 10^8 While this is not a direct child of 5.36798 * 10^5, it is a child of a child and belongs in that subtree. I can't seem to rack my brains around a solution for this. Maybe it's my tree-structure that is making this more complex than it should be? From kent37 at tds.net Fri Dec 8 12:08:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Dec 2006 06:08:49 -0500 Subject: [Tutor] function and module In-Reply-To: References: <1d987df30612072113y3a85fecct4826f1aee2e31fb5@mail.gmail.com> Message-ID: <457947C1.6070206@tds.net> Alan Gauld wrote: > There are a couple of possibilities. > 1) if you can import the moduile into a >>> propmpt you could > ask abc where it's from. >>>> print abc.__file__ should work __file__ is a module attribute, not a function attribute. abc.__module__ will give the name of the module abc is from. Kent From arildna at stud.ntnu.no Fri Dec 8 12:59:11 2006 From: arildna at stud.ntnu.no (=?ISO-8859-1?Q? Arild_B._N=E6ss ?=) Date: Fri, 8 Dec 2006 12:59:11 +0100 Subject: [Tutor] problems pickling functions Message-ID: <15902802-7CDB-4812-BA30-6D5ACDD633D5@stud.ntnu.no> Hi, I'm writing a program for tagging which requires a long time to calculate the parameters. I have therefore tried to write a long program that pickles all the data, and pickles a function that uses these parameters to tag an input sentence. But I'm having trouble with loading the function. The odd thing is that it works fine in the interpreter to pickle and load a function: >>> import pickle >>> def simple(): ... print "This works" ... >>> f=open("simple.txt","w") >>> pickle.dump(simple,f) >>> f.close() >>> s() Traceback (most recent call last): File "", line 1, in NameError: name 's' is not defined >>> f=open("simple.txt","r") >>> s=pickle.load(f) >>> s() This works However when I try to do this with the script simple.py (with the exact same commands as above) it doesn't work: $ cat simple.py import pickle def simple(): print "This works" f = open("simple.txt","w") pickle.dump(simple,f) f.close() $ python simple.py $ python Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> f2 = open("simple.txt","r") >>> s Traceback (most recent call last): File "", line 1, in NameError: name 's' is not defined >>> s = pickle.load(f2) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pickle.py", line 1370, in load return Unpickler(file).load() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pickle.py", line 858, in load dispatch[key](self) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pickle.py", line 1126, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'simple' >>> I don't get this error message, and I'm annoyed ? because I'm used to that things that work in the interpreter also work when written as a program. Can anyone help? regards, Arild N?ss From kent37 at tds.net Fri Dec 8 14:05:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Dec 2006 08:05:57 -0500 Subject: [Tutor] problems pickling functions In-Reply-To: <15902802-7CDB-4812-BA30-6D5ACDD633D5@stud.ntnu.no> References: <15902802-7CDB-4812-BA30-6D5ACDD633D5@stud.ntnu.no> Message-ID: <45796335.8030606@tds.net> Arild B. N?ss wrote: > Hi, > > I'm writing a program for tagging which requires a long time to > calculate the parameters. I have therefore tried to write a long > program that pickles all the data, and pickles a function that uses > these parameters to tag an input sentence. > > But I'm having trouble with loading the function. The odd thing is > that it works fine in the interpreter to pickle and load a function: > > >>> import pickle > >>> def simple(): > ... print "This works" > ... > >>> f=open("simple.txt","w") > >>> pickle.dump(simple,f) > >>> f.close() > >>> s() > Traceback (most recent call last): > File "", line 1, in > NameError: name 's' is not defined > >>> f=open("simple.txt","r") > >>> s=pickle.load(f) > >>> s() > This works > > However when I try to do this with the script simple.py (with the > exact same commands as above) it doesn't work: > > $ cat simple.py > > import pickle > > def simple(): > print "This works" > > f = open("simple.txt","w") > pickle.dump(simple,f) > f.close() > > $ python simple.py > $ python > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import pickle > >>> f2 = open("simple.txt","r") > >>> s > Traceback (most recent call last): > File "", line 1, in > NameError: name 's' is not defined > >>> s = pickle.load(f2) > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/pickle.py", line 1370, in load > return Unpickler(file).load() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/pickle.py", line 858, in load > dispatch[key](self) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/pickle.py", line 1090, in load_global > klass = self.find_class(module, name) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/pickle.py", line 1126, in find_class > klass = getattr(mod, name) > AttributeError: 'module' object has no attribute 'simple' > >>> > > I don't get this error message, and I'm annoyed ? because I'm used to > that things that work in the interpreter also work when written as a > program. From the docs for pickle (13.1.4 What can be pickled and unpickled?): "Note that functions (built-in and user-defined) are pickled by ``fully qualified'' name reference, not by value. This means that only the function name is pickled, along with the name of module the function is defined in. Neither the function's code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised." Your code works from the interpreter because 'simple' is still defined. If you 'del simple' before you unpickle I think you will get the same error as you get in the script. Searching comp.lang.python for 'pickle function' yields a few possible workarounds but they are messy. Why do you need to pickle the function? Is it created dynamically? Can you just pickle the data? Kent From kent37 at tds.net Fri Dec 8 15:43:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Dec 2006 09:43:19 -0500 Subject: [Tutor] problems pickling functions In-Reply-To: <918C920B-8630-4A3B-B1E0-46BE2BAAED3D@stud.ntnu.no> References: <15902802-7CDB-4812-BA30-6D5ACDD633D5@stud.ntnu.no> <45796335.8030606@tds.net> <918C920B-8630-4A3B-B1E0-46BE2BAAED3D@stud.ntnu.no> Message-ID: <45797A07.1050408@tds.net> Arild B. N?ss wrote: > Den 8. des. 2006 kl. 14.05 skrev Kent Johnson: >> Why do you need to pickle the function? Is it created dynamically? >> Can you just pickle the data? >> >> Kent >> > > Thanks. > > I guess it's not absolutely necessary to pickle the function. I tried > to do this because I wanted to use the function in the interpreter > without having to write it in there line by line. > > I'm used to working in R and Matlab, where you often run scripts from > the active interpreter. In that way you can actually examine the > data a script generates, instead of having the script print it to > screen or file. > > I'm having trouble getting used to python like this because I get > trouble trying to paste in several lines at once from emacs, and I > haven't found a way to run scripts in the interpreter. Two suggestions: - Use an editor / IDE that allows you to run Python scripts. IDLE will do this. I think emacs has good support for Python too but someone who uses emacs will have to help you with that one. - Save your function in a module and import the module from the interpreter. Then you can run the function in the interpreter. For example if you have funcs.py in the working directory and it contains a function def doItAll(): pass then in the interpreter you can type >>> import funcs >>> funcs.doItAll() to run the function. If you change the function in an external editor you have to reload it in the interpreter to get the revised version: >>> reload(funcs) Kent PS Please reply to the list, not to me directly. From ajkadri at googlemail.com Fri Dec 8 18:48:01 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Fri, 8 Dec 2006 17:48:01 +0000 Subject: [Tutor] Tkinter Canvas Message-ID: Hi Folks, I have a Tkinter canvas and a yscrollbar attached to it. It is working fine but what I want is that when the mouse is in the canvas region, the scroll button of the mouse should be able to control the upward and downward movement, How to achieve this? Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061208/df8389fd/attachment.html From alan.gauld at btinternet.com Fri Dec 8 19:55:47 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Dec 2006 18:55:47 -0000 Subject: [Tutor] function and module References: <1d987df30612072113y3a85fecct4826f1aee2e31fb5@mail.gmail.com> <457947C1.6070206@tds.net> Message-ID: "Kent Johnson" wrote >> There are a couple of possibilities. >> 1) if you can import the moduile into a >>> propmpt you could >> ask abc where it's from. >>>>> print abc.__file__ should work > > __file__ is a module attribute, not a function attribute. > abc.__module__ > will give the name of the module abc is from. Oops! Thanks for the catch Kent. Alan G. From pythontut at pusspaws.net Fri Dec 8 20:14:05 2006 From: pythontut at pusspaws.net (Dave S) Date: Fri, 8 Dec 2006 19:14:05 +0000 Subject: [Tutor] OT GPL project finished, presentation looming In-Reply-To: References: <200612071715.25953.pythontut@pusspaws.net> <200612071817.06077.pythontut@pusspaws.net> Message-ID: <200612081914.06101.pythontut@pusspaws.net> On Thursday 07 December 2006 22:35, Alan Gauld wrote: > "Dave S" wrote > > > They will be concerned about using my app because I am one person. > > What if I > > get hit by a bus ! what if I leave ? > > This is a common problem in big companies including my own. > For years they wouldn't even use the GNU software because it > was "unsupported". I even had to buy a commercial version of > emacs for about $300... Ouch .... that must have hurt :( > > Eventually cygnus started offering support (for $5K per year) > and they allowed us to use emacs, gcc etc Eventually even > X windows. > Cool :) > Now they are more relaxed and we use Linux to run our > internal DHCP and DNS, even some web servers... > > > ...(It appears that none of the > > company's IT professionals can program !) > > That's also not unusual. In fact our company appears to be > slowly heading that way. We used to have 11,000 IT professionals > of which around 5000 were developers. Now we have 13,000 IT > professionals of whom about 1000 still write code. The coding > is mainly offshored to India and Eastern Europe. Our internal > people are being retrained on "higher value" roles like business > analysis, design/architecture, deployment/integration and > project management. So sad - programming is soooo much creative fun. I have heard it being called an art form - I would agree with that. > > So I now program in python as and when I can and call > it prototyping... > > They call it progress. > 'progress' ... mmm .... 'modern man management' ... (cynical mmm ...) > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Fri Dec 8 20:49:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 08 Dec 2006 13:49:37 -0600 Subject: [Tutor] Tkinter Canvas In-Reply-To: References: Message-ID: <4579C1D1.2080800@gmail.com> Asrarahmed Kadri wrote: > > > Hi Folks, > > I have a Tkinter canvas and a yscrollbar attached to it. It is working > fine but what I want is that when the mouse is in the canvas region, > the scroll button of the mouse should be able to control the upward > and downward movement, How to achieve this? You should be able to bind the events that the mouse wheel generates in the canvas widget to the function that causes the scroll bar to scroll (forget what it's called.) Have you tried this yet? > > Regards, > Asrarahmed Kadri > > > -- > To HIM you shall return. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From eike.welk at gmx.net Fri Dec 8 22:37:34 2006 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 08 Dec 2006 22:37:34 +0100 Subject: [Tutor] mlab and numeric Message-ID: <200612082237.34292.eike.welk@gmx.net> On Friday 08 December 2006 06:25, linda.s wrote: > can anyone tell me the relationship between MLab and Numeric? > Especially MLab, there is very little information about it. There seem to be several Mlab modules. At least Numeric, Matplotlib and Numarray have an Mlab module. They all seem to be additional functions to make users with matlab experience happy. Maybe usefull for you is this longer explanation: http://matplotlib.sourceforge.net/pylab_commands.html Eike. From pyro9219 at gmail.com Sat Dec 9 00:17:34 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 8 Dec 2006 15:17:34 -0800 Subject: [Tutor] Create a script to make bootable USB device. In-Reply-To: References: Message-ID: Just curious as to why nobody has at least attempted an answer for this. Is what I'm asking simply unknown? Or it is impossible to do? No big deal either way... just curious because I'm seriously interested in this. Thanks. On 12/6/06, Chris Hengge wrote: > > Is this something I can do using just python and libraries? I know I could > automate other utilities, but I'd like to write some kind of neat utility > myself that I could play with for more experience. > > Goal: > make USB drive bootable to a dos prompt (dont care what dos, assuming I > need a bootable image for this) > make script prompt for file(s) to move to disk (already know how to do > this) > > Thanks! > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061208/01ac960b/attachment.html From ajkadri at googlemail.com Sat Dec 9 11:27:09 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sat, 9 Dec 2006 10:27:09 +0000 Subject: [Tutor] How to save tkinter canvas.... Message-ID: Hi Folks, I have a window that contains bar chart on a Canvas (tkinter). Is there a way in which I can provide the user the option of saving it as an image file. Some pointers needed.. thanks in anticipation. Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061209/6d48f34f/attachment.html From project5 at redrival.net Sat Dec 9 11:55:09 2006 From: project5 at redrival.net (Andrei) Date: Sat, 09 Dec 2006 11:55:09 +0100 Subject: [Tutor] Of integers, relations and trees In-Reply-To: References: Message-ID: Tor Hildrum wrote: > I have this problem which I thought would be trivial, but I can't > seem to figure out a decent way to do it. > > Say I have the following file: > 10 > -100 > -108 > --1080 > 12 > 20 > > In lack of a better explanation, here is how it works: > A level in the tree follows the following: > x * 10^level > > x * 10^1 belongs to level 1 in the three > x * 10^2 belongs to level 2 in the three. > etc. Here's a different way to look at it: the level in the tree is determined by the length of the string representation of the node. 2 long -> level 1. 3 long -> level 2. etc. > I decided to make this pretty straightforward so I wrote a Node class > and a Tree class. Are you sure you need a Tree class? The Node class itself may have all the facilities needed to manage an entire tree. The tree is then represented by a 'root' node. You'd then have: - root - 10 - 103 - 105 - 12 etc. > A Node has a key which is an integer, as well as some additional > information that isn't relevant to the structure. It also has a link > to it's sibling, which is the next node on the same level. And a link > to it's first child. A different way to implement this is for each node to have a (sorted) list of children and potentially a link to its parent. The story then looks like this: - root with the following children - 10 (with parent = root) with the following children: - 100 - 108 - 12 (with parent = root) etc. You then do not insert siblings, you add children (not tested, but the intention is what counts): class Node(object): def __init__(self, name): self.Name = name self.Parent = None self.Children = [] def addChild(self, newname): """Tries to add the node as a newNode. Returns True if successful, False otherwise.""" # check if the node is a (sub)child if newname[:len(self.Name)] <> self.Name: return False # check if it is a direct descendant if len(newname) == len(self.Name) + 1: newnode = Node(newname) newnode.Parent = self self.Children.append(newnode) self.Children.sort() return True else: # not a direct descendant -> add to one of the children for child in self.Children: if child.addChild(newname): return True # if we arrive here, it means that there's a missing level in the hierarchy -> add it self.addChild(newname[:len(newname)-1]) return self.addChild(newname) def show(self, indentation=0): print ' ' * indentation, '-', self.Name for child in self.Children: child.show(indentation + 2) def __cmp__(self, othernode): """Get sort() to work properly.""" return cmp(self.Name, othernode.Name) def hasChildren(self): return len(self.Children) > 0 def hasSiblings(self): return (self.Parent <> None) and (len(self.Parent.Children) > 1) root = Node('') root.addChild('10') root.addChild('12') root.addChild('0') root.addChild('20') root.addChild('108') root.addChild('5') root.addChild('678') root.show() This implementation will not handle the dot-style leaves properly, you'll need some extra logic for that. It will however 'fill in the blanks', so you can add node '678' without adding nodes '6' and '67' first and auto-sort the nodes. > How do I know if I have a sibling or a child? > Simple, I just check the length: > --------------------------------------------- > if( len(str(node1[key])) == len(str(node2[key])) ): > --------------------------------------------- > > If the length, amount of integers, is the same, they are siblings. With the alternative representation presented, it's more comfortable: - has child: len(self.Children) > 0 - has sibling: (self.Parent <> None) and (len(self.Parent.Children) > 1) > How do I determine that 2080 is not a child of 10. Or how do i determine > that 536798 is not a child of 536780? And how do I determine that it is a child? See my code: just manipulate them as strings and it's suddenly very easy. Same length and the first (length - 1) characters are the same -> siblings. Different length: take the shortest node name; if the other node name starts with that string, it's a child, otherwise they're unrelated. > I can't seem to rack my brains around a solution for this. Maybe it's > my tree-structure that is making this more complex than it should be? Hierarchies are easier if you look at them as families: it's easier to ask a parent how many children it has, than it is to ask one of the siblings if there is any sibling younger than it, then ask that younger sibling if it has any younger siblings, etc. Yours, Andrei From alan.gauld at btinternet.com Sat Dec 9 14:18:29 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Dec 2006 13:18:29 -0000 Subject: [Tutor] How to save tkinter canvas.... References: Message-ID: "Asrarahmed Kadri" wrote > I have a window that contains bar chart on a Canvas (tkinter). Is > there a > way in which I can provide the user the option of saving it as an > image > file. Have you looked at the PIL library? I seem to recall seeing a function there that could work with Tkinter Canvas objects, and once in PIL it should be possible to save it. HTH. Alan G, From arildna at stud.ntnu.no Sat Dec 9 16:45:37 2006 From: arildna at stud.ntnu.no (=?ISO-8859-1?Q? Arild_B._N=E6ss ?=) Date: Sat, 9 Dec 2006 16:45:37 +0100 Subject: [Tutor] problems pickling functions In-Reply-To: <45797A07.1050408@tds.net> References: <15902802-7CDB-4812-BA30-6D5ACDD633D5@stud.ntnu.no> <45796335.8030606@tds.net> <918C920B-8630-4A3B-B1E0-46BE2BAAED3D@stud.ntnu.no> <45797A07.1050408@tds.net> Message-ID: <30A4356E-4A4A-46F2-8422-BDF212A53CA0@stud.ntnu.no> Den 8. des. 2006 kl. 15.43 skrev Kent Johnson: > Arild B. N?ss wrote: >> Den 8. des. 2006 kl. 14.05 skrev Kent Johnson: >>> Why do you need to pickle the function? Is it created >>> dynamically? Can you just pickle the data? >>> >>> Kent >>> >> Thanks. >> I guess it's not absolutely necessary to pickle the function. I >> tried to do this because I wanted to use the function in the >> interpreter without having to write it in there line by line. >> I'm used to working in R and Matlab, where you often run scripts >> from the active interpreter. In that way you can actually >> examine the data a script generates, instead of having the script >> print it to screen or file. >> I'm having trouble getting used to python like this because I get >> trouble trying to paste in several lines at once from emacs, and >> I haven't found a way to run scripts in the interpreter. > > Two suggestions: > - Use an editor / IDE that allows you to run Python scripts. IDLE > will do this. I think emacs has good support for Python too but > someone who uses emacs will have to help you with that one. > > - Save your function in a module and import the module from the > interpreter. Then you can run the function in the interpreter. > > For example if you have funcs.py in the working directory and it > contains a function > def doItAll(): > pass > > then in the interpreter you can type > >>> import funcs > >>> funcs.doItAll() > > to run the function. > > If you change the function in an external editor you have to reload > it in the interpreter to get the revised version: > >>> reload(funcs) Thanks. That worked. I haven't found out how to change the working directory in IDLE, though ? and for some reason it seems to be a different one this session from the last one. Does anyone know? (I use a mac by the way.) > > PS Please reply to the list, not to me directly. Sorry about that. I didn't realize my client picked your adress and not the list's when I clicked reply. My mistake. regards, Arild N?ss From kamraider at hotmail.com Sat Dec 9 16:19:06 2006 From: kamraider at hotmail.com (Kamran Haider) Date: Sat, 09 Dec 2006 20:19:06 +0500 Subject: [Tutor] help Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061209/7163bee9/attachment.html From python at venix.com Sat Dec 9 19:04:36 2006 From: python at venix.com (Python) Date: Sat, 09 Dec 2006 13:04:36 -0500 Subject: [Tutor] help In-Reply-To: References: Message-ID: <1165687476.31666.280.camel@www.venix.com> On Sat, 2006-12-09 at 20:19 +0500, Kamran Haider wrote: > Hi > > I have got some python related queries. I am working on an MRes > project > which involves a bit of programing in python. Actually, I am using a > python program developed by someone, which gives pairwise genetic > distances between a set of sequences (I don't know how...) and outputs > a > simple text file of the following format... > > s1,s2,s3,s4,s5 > 4,7,2,3 > 8,6,4 > 3,6 > 7 > where s1, s2, s3...represent sequences and the second line describes > the pairwise distance between s1 and all other sequences,thid line is > for the distance between s2 and other sequences. > and so on. > 1. I want to read this line into a data structure(most probably by > making a list of lists like [[s1,s2,4],[s1,s2,7],[s1,s3,2] and so on) > which gives each pair and the corresponding pairwise distances. I think a dictionary will server you better. {(s1,s2):4, (s1,s3):7, (s1,s4):2, } > Of course, I would do this by writing a function that reads this file > into a data structure which gives the all the pairs of sequences and > theircorresponding distance values, but I am not sure how to do > this. Well ask for help as you break this down. You should wind up with quite a few functions, not just one. Using a dictionary should be no harder than a list of lists. > 2. Secondly, I want to write another function which takes up three > arguments, the data structure returned by the previous function and > the names of two sequences. It then returns the corresponding value. With the dictionary, this function is trivial def distance(seqdistance, s1, s2): return seqdistance[(s1,s2)] Do you need to handle reversing the sequences? Presumably distance(s1,s2) == distance(s2,s1) > > Please help > Kamran > > > > > ______________________________________________________________________ > Express yourself instantly with MSN Messenger! MSN Messenger Download > today it's FREE! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From alan.gauld at btinternet.com Sat Dec 9 20:19:49 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Dec 2006 19:19:49 -0000 Subject: [Tutor] How to save tkinter canvas.... References: Message-ID: "Alan Gauld" wrote > I seem to recall seeing a function there that could work with > Tkinter > Canvas objects, and once in PIL it should be possible to save it. Looks like it works the other way, you can put PIL images into a canvas. BUT there is a Canvas.postscript method that will create a postcript version of a canvas. That should do your printing for you... Alan G. From jjk.saji at gmail.com Sun Dec 10 10:51:07 2006 From: jjk.saji at gmail.com (Joseph John) Date: Sun, 10 Dec 2006 13:51:07 +0400 Subject: [Tutor] commads simillar to phpinfo() Message-ID: <8fbe2e10612100151o6b09495fred342f5b52686cf8@mail.gmail.com> Hi In python , is there any command simillar to phpinfo() as in PHP I wanted to check wheter , my apache installation , run python script correctly thanks Joseph John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061210/ec18eaf1/attachment.html From chris.arndt at web.de Sun Dec 10 11:41:35 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Sun, 10 Dec 2006 11:41:35 +0100 Subject: [Tutor] commads simillar to phpinfo() In-Reply-To: <8fbe2e10612100151o6b09495fred342f5b52686cf8@mail.gmail.com> References: <8fbe2e10612100151o6b09495fred342f5b52686cf8@mail.gmail.com> Message-ID: <457BE45F.5030209@web.de> Joseph John wrote: > Hi > In python , is there any command simillar to phpinfo() as in PHP > I wanted to check wheter , my apache installation , run python script > correctly No, not built-in, but there are third-part CGI-scripts that do a similar thing. For example (sorry, German source code comments): https://opensvn.csie.org/traccgi/PyLucid/browser/CodeSnippets/module_info.py You might also want to look at this Cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440501 Chris From jjk.saji at gmail.com Sun Dec 10 12:12:38 2006 From: jjk.saji at gmail.com (Joseph John) Date: Sun, 10 Dec 2006 15:12:38 +0400 Subject: [Tutor] python scripts with apache HELP needed Message-ID: <8fbe2e10612100312m9476b2fmb53e8555164a5e3a@mail.gmail.com> Hi I am facing some problems in python I want to run some python script , with httpd In my system I have mod_python installed and I have in /etc/httpd/conf.d , python.conf which shows # # Mod_python is a module that embeds the Python language interpreter # within the server, allowing Apache handlers to be written in Python. # LoadModule python_module modules/mod_python.so # Override type-map handler for /var/www/manual SetHandler default-handler rpm -qa | grep python gives the result libxml2-python-2.6.16-6 python-sqlite-1.1.6-1 gnome-python2-2.6.0-3 dbus-python-0.22-12.EL.5 python-urlgrabber-2.9.6-2 rpm-python-4.3.3-13_nonptl mod_python-3.1.3-5.1 gnome-python2-bonobo-2.6.0-3 python-2.3.4-14.1 python-elementtree-1.2.6-4 gnome-python2-canvas-2.6.0-3 But my scripts when accessed through the web page , does not execute Please Guide Thanks Joseph John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061210/1785e3c7/attachment.htm From kent37 at tds.net Sun Dec 10 13:06:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Dec 2006 07:06:09 -0500 Subject: [Tutor] commads simillar to phpinfo() In-Reply-To: <8fbe2e10612100151o6b09495fred342f5b52686cf8@mail.gmail.com> References: <8fbe2e10612100151o6b09495fred342f5b52686cf8@mail.gmail.com> Message-ID: <457BF831.7040202@tds.net> Joseph John wrote: > Hi > In python , is there any command simillar to phpinfo() as in PHP > I wanted to check wheter , my apache installation , run python script > correctly I don't know what phpinfo() does, but for a simple test that your server will run Python CGI scripts, try a CGI script that just contains import cgi cgi.test() Kent From clajo04 at mac.com Sun Dec 10 14:38:26 2006 From: clajo04 at mac.com (John Clark) Date: Sun, 10 Dec 2006 05:38:26 -0800 Subject: [Tutor] New York City Python Users Group meeting is planned for Dec. 12th @ 6pm - please RSVP! Message-ID: <22EED86B-010F-1000-8700-AC749965897E-Webmail-10014@mac.com> Greetings! The next New York City Python Users Group meeting is this Tuesday, Dec. 12th, 6pm at at the Millennium Partners office at 666 Fifth Avenue on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. If you would please RSVP to clajo04ATmacDOTcom to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John From nephish at gmail.com Sun Dec 10 17:20:34 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 10 Dec 2006 10:20:34 -0600 Subject: [Tutor] app runs ok from cli but not from os.system Message-ID: <384c93600612100820r1aeb0953j8a05dd80328b5d54@mail.gmail.com> Hello there all i have an app that i can run from the command line ok, but when i try to call it with os.system('myapp.py') it will not work. The widgets work, it reads ok from the database, but will not write to it. I don't get it at all. Can someone tell me why my app may not work completely right when called from another gtk app ? thanks sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061210/e9901d36/attachment.html From nephish at gmail.com Sun Dec 10 17:22:20 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 10 Dec 2006 10:22:20 -0600 Subject: [Tutor] app runs ok from cli but not from os.system In-Reply-To: <384c93600612100820r1aeb0953j8a05dd80328b5d54@mail.gmail.com> References: <384c93600612100820r1aeb0953j8a05dd80328b5d54@mail.gmail.com> Message-ID: <384c93600612100822l689d6e9cvaae68cc503eac24c@mail.gmail.com> opps, sorry, meant to send this to the pygtk list sk On 12/10/06, shawn bright wrote: > > Hello there all > i have an app that i can run from the command line ok, but when i try to > call it with os.system('myapp.py') > it will not work. The widgets work, it reads ok from the database, but > will not write to it. I don't get it at all. > Can someone tell me why my app may not work completely right when called > from another gtk app ? > thanks > sk > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061210/fc1ed8d0/attachment.htm From alan.gauld at btinternet.com Sun Dec 10 18:38:05 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Dec 2006 17:38:05 -0000 Subject: [Tutor] app runs ok from cli but not from os.system References: <384c93600612100820r1aeb0953j8a05dd80328b5d54@mail.gmail.com> Message-ID: "shawn bright" wrote > ...The widgets work, it reads ok from the database, but will > not write to it. I don't get it at all. Without more data e can't say too much but is there any chance that the rows are locked somehow? You don't have another session open on the database from another session? About all I can think of on the data available. Alan G. From nephish at gmail.com Sun Dec 10 19:04:18 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 10 Dec 2006 12:04:18 -0600 Subject: [Tutor] app runs ok from cli but not from os.system In-Reply-To: References: <384c93600612100820r1aeb0953j8a05dd80328b5d54@mail.gmail.com> Message-ID: <384c93600612101004h5ab597a4rdbc3b6d788d3d014@mail.gmail.com> Well, i don't know if i do or not. I will check that out. Now, if I run an app from the cli, and that app uses os.system() to start another app, i usually get the output from that app in the cli ( the print statements and such ) . But this one does not. I was wondering if that may be a clue. It does print fine if i run it from the cli. By the way, mr Gauld, i have really learned a lot over the past year by reading what you have responded to folks out there with questions a lot like mine. Thanks for making your experience available here. sk On 12/10/06, Alan Gauld wrote: > > > "shawn bright" wrote > > ...The widgets work, it reads ok from the database, but will > > not write to it. I don't get it at all. > > Without more data e can't say too much but is there any > chance that the rows are locked somehow? You don't have > another session open on the database from another session? > > About all I can think of on the data available. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061210/879e0a6c/attachment.html From bgailer at alum.rpi.edu Sun Dec 10 22:24:09 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 10 Dec 2006 13:24:09 -0800 Subject: [Tutor] python scripts with apache HELP needed In-Reply-To: <8fbe2e10612100312m9476b2fmb53e8555164a5e3a@mail.gmail.com> References: <8fbe2e10612100312m9476b2fmb53e8555164a5e3a@mail.gmail.com> Message-ID: <457C7AF9.7070405@alum.rpi.edu> Joseph John wrote: > Hi > I am facing some problems in python > I want to run some python script , with httpd > > In my system I have mod_python installed and I have in > /etc/httpd/conf.d , python.conf > which shows > # > # Mod_python is a module that embeds the Python language interpreter > # within the server, allowing Apache handlers to be written in Python. > # > > LoadModule python_module modules/mod_python.so > > # Override type-map handler for /var/www/manual > > > SetHandler default-handler > > I wish I could help. My mod_python config setup is different than yours, and it works. FWIW I've extracted everything from conf that might apply: ----------------------------------------------------- SetHandler mod_python PythonHandler mod_python.testhandler #python config LoadFile python\bin\python23.dll LoadModule python_module modules/mod_python.so AddHandler python-program .spy PythonHandler run_spyceModpy::spyceMain AddHandler mod_python .psp PythonDebug On AddHandler mod_python .py PythonHandler mptest PythonDebug On ----------------------------------------------------- > > rpm -qa | grep python gives the result > libxml2-python-2.6.16-6 > python-sqlite-1.1.6-1 > gnome-python2-2.6.0-3 > dbus-python-0.22-12.EL.5 > python-urlgrabber-2.9.6-2 > rpm-python-4.3.3-13_nonptl > mod_python-3.1.3-5.1 > gnome-python2-bonobo-2.6.0-3 > python-2.3.4-14.1 > python-elementtree-1.2.6-4 > gnome-python2-canvas-2.6.0-3 > > > But my scripts when accessed through the web page , does not > execute > Please Guide > Thanks > Joseph John > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From paulino1 at sapo.pt Mon Dec 11 00:41:13 2006 From: paulino1 at sapo.pt (Paulino) Date: Sun, 10 Dec 2006 23:41:13 +0000 Subject: [Tutor] Tutor Digest, Vol 34, Issue 11 In-Reply-To: References: Message-ID: <457C9B19.9070804@sapo.pt> tutor-request at python.org escreveu: > > Message: 7 > Date: Wed, 6 Dec 2006 09:38:59 -0000 > From: "Tim Golden" > Subject: Re: [Tutor] How to kill an app from python on windows? (Tim > Golden) > To: > Message-ID: > > Content-Type: text/plain; charset="us-ascii" > > [Tim Golden] > | > This link may get you started: > | > > | > http://effbot.org/pyfaq/how-do-i-emulate-os-kill-in-windows.htm > | > > | > although it may not apply, depending on the exact > | > circumstances of what you're doing. > > [Paulino] > | Thank you Tim, > | > | How do i get the pid of the process? > > I'm going to cheat slightly, because I'm fairly sure > this is a sticky area, by going back to your original > requirement. I think that what you want to do is: > > 1) Use a document name to start the appropriate > viewer/app (without knowing what that app is) > > 2) Close that app at will so the file can be updated. > > The problem is that while os.startfile will satisfy (1), > it returns no useful information about the process it > started. And that's because the underlying win32api, > ShellExecute, doesn't return anything useful. This is > specifically stated in the MS documentation. > > What you can do, though, is to determine the correct > executable, setup a new process under your control, > and then terminate it when you want. This assume you > have the pywin32 extensions available. In the example > below, I'm using an .html file to demonstrate the point, > because I can generate one so the code works for both > of us. Obviously, it should work for any recognised > document type, including .pdf. > > > import os, sys > import win32api > import win32process > import win32event > > filename = os.path.abspath ("temp.html") > open (filename, "w").write ("

Hello, > world!

") > > hInstance, exe_filename = win32api.FindExecutable (filename) > print exe_filename, filename > > hProcess, hThread, pid, tid = win32process.CreateProcess ( > None, > '"%s" "%s2' % (exe_filename, filename), > None, # process attributes > None, # process attributes > 0, # inherit handles > 0, # creation flags > None, # new environment > None, # current directory > win32process.STARTUPINFO () > ) > print pid > > # > # This snippet waits until the app closes > # > win32event.WaitForSingleObject (hProcess, win32event.INFINITE) > > # > # To kill the process either use the hProcess > # above, or retrieve it from the pid using: > # > hProcess = win32api.OpenProcess (1, 0, pid) > > # > # and then > # > win32process.TerminateProcess (hProcess, 0) > >
> > ________________________________________________________________________ > That's great!! It work's Thank you so much! I got Python programming on win32, but I hadn't found the solution yet... Paulino From torhildrum at gmail.com Mon Dec 11 13:59:44 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Mon, 11 Dec 2006 13:59:44 +0100 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 12/9/06, Kamran Haider wrote: > > Hi > > I have got some python related queries. I am working on an MRes project > which involves a bit of programing in python. Actually, I am using a > python program developed by someone, which gives pairwise genetic > distances between a set of sequences (I don't know how...) and outputs a > simple text file of the following format... > > s1,s2,s3,s4,s5 > 4,7,2,3 > 8,6,4 > 3,6 > 7 > where s1, s2, s3...represent sequences and the second line describes > the pairwise distance between s1 and all other sequences,thid line is > for the distance between s2 and other sequences. > and so on. > 1. I want to read this line into a data structure(most probably by making a > list of lists like [[s1,s2,4],[s1,s2,7],[s1,s3,2] and so on) which gives > each pair and the corresponding pairwise distances. Of course, I would do > this by writing a function that reads this file into a data structure which > gives the all the pairs of sequences and theircorresponding distance values, > but I am not sure how to do this. This is a weighted graph. see http://en.wikipedia.org/wiki/Glossary_of_graph_theory Here is a nice text written for Python: http://www.python.org/doc/essays/graphs.html Should go a long way to solve your second problem as well. Tor From pytutmail at gmail.com Mon Dec 11 14:06:39 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Mon, 11 Dec 2006 14:06:39 +0100 Subject: [Tutor] pyExcelerator and Graphs Message-ID: <7c3104d20612110506k303d34aap90a90823387209b2@mail.gmail.com> Hey friendly users, I have been using pyExcelerator for a short period now, and I'm very satisfied with the results. There is one thing that I just can't do thought, and that is making graphs. I want to add a column (horizontal) type graph. Does anybody know how this can be achieved? Thanks in advance for reading this! Toon Pieton -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061211/fd385cb1/attachment.html From kent37 at tds.net Mon Dec 11 14:34:45 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Dec 2006 08:34:45 -0500 Subject: [Tutor] pyExcelerator and Graphs In-Reply-To: <7c3104d20612110506k303d34aap90a90823387209b2@mail.gmail.com> References: <7c3104d20612110506k303d34aap90a90823387209b2@mail.gmail.com> Message-ID: <457D5E75.9060704@tds.net> Toon Pieton wrote: > Hey friendly users, > > I have been using pyExcelerator for a short period now, and I'm very > satisfied with the results. There is one thing that I just can't do > thought, and that is making graphs. I want to add a column (horizontal) > type graph. Does anybody know how this can be achieved? In the readme this is listed as a future feature. Kent From pytutmail at gmail.com Mon Dec 11 17:48:23 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Mon, 11 Dec 2006 17:48:23 +0100 Subject: [Tutor] Getting the directory the program is in Message-ID: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> Hey friedly users! I was wondering: how can I get the directory the program is in? For example "C:\Python Programs\Calculator\". Thanks in advance for reading, Toon Pieton -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061211/7ec53bb4/attachment.html From torhildrum at gmail.com Mon Dec 11 17:56:48 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Mon, 11 Dec 2006 17:56:48 +0100 Subject: [Tutor] Getting the directory the program is in In-Reply-To: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> References: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> Message-ID: On 12/11/06, Toon Pieton wrote: > Hey friedly users! > > I was wondering: how can I get the directory the program is in? For example > "C:\Python Programs\Calculator\". >>> os.path.split.__doc__ 'Split a pathname. Returns tuple "(head, tail)" where "tail" is\n everything after the final slash. Either part may be empty.' The full pathname is in sys.argv[0] From greenbergj at wit.edu Mon Dec 11 18:19:41 2006 From: greenbergj at wit.edu (Jordan Greenberg) Date: Mon, 11 Dec 2006 12:19:41 -0500 Subject: [Tutor] Getting the directory the program is in In-Reply-To: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> References: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> Message-ID: <457D932D.6020009@wit.edu> Toon Pieton wrote: > Hey friedly users! > > I was wondering: how can I get the directory the program is in? For example > "C:\Python Programs\Calculator\". > > Thanks in advance for reading, > Toon Pieton > Slightly hackish and nasty, but seems to do the trick. Someone'll probably suggest a better way, this is just the first thing I could come up with: from os.path import abspath from sys import argv print abspath(argv[0]) From greenbergj at wit.edu Mon Dec 11 18:24:42 2006 From: greenbergj at wit.edu (Jordan Greenberg) Date: Mon, 11 Dec 2006 12:24:42 -0500 Subject: [Tutor] Getting the directory the program is in In-Reply-To: References: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> Message-ID: <457D945A.8010706@wit.edu> Tor Hildrum wrote: > The full pathname is in sys.argv[0] At least on my system, it only includes the filename if executed from the current directory. Example: jordan at jordan-laptop:/$ cd ~ jordan at jordan-laptop:~$ cat > test.py from sys import argv print argv[0] jordan at jordan-laptop:~$ python test.py test.py jordan at jordan-laptop:~$ cd / jordan at jordan-laptop:/$ python test.py /home/jordan/test.py jordan at jordan-laptop:/$ So, if you _ALWAYS_ need an absolute path, just using sys.argv[0] might not work. Jordan Greenberg From chris.arndt at web.de Mon Dec 11 18:55:46 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Mon, 11 Dec 2006 18:55:46 +0100 Subject: [Tutor] Getting the directory the program is in In-Reply-To: <457D932D.6020009@wit.edu> References: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> <457D932D.6020009@wit.edu> Message-ID: <457D9BA2.7060000@web.de> Jordan Greenberg schrieb: > Slightly hackish and nasty, but seems to do the trick. Someone'll > probably suggest a better way, this is just the first thing I could come > up with: No, IMHO it's perfectly normal and safe practice, though this gets the full path name of the program. If you want the directory it is in, do this: from os.path import abspath, dirname import sys app_dir = abspath(dirname(sys.argv[0])) Of course you have to do this before you (or some other code in your program) do anything siilar to os.chris('/somewhere/else'). Chris From chris.arndt at web.de Mon Dec 11 19:49:35 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Mon, 11 Dec 2006 19:49:35 +0100 Subject: [Tutor] Getting the directory the program is in In-Reply-To: <457D9BA2.7060000@web.de> References: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> <457D932D.6020009@wit.edu> <457D9BA2.7060000@web.de> Message-ID: <457DA83F.40202@web.de> Christopher Arndt schrieb: > Of course you have to do this before you (or some other code in your program) > do anything siilar to os.chris('/somewhere/else'). ^^^^^ That was some freudian slip of my narcissistic mind *LOL* Of course, I mean: os.chdir('/somewhere/else') Chris From torhildrum at gmail.com Mon Dec 11 22:37:39 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Mon, 11 Dec 2006 22:37:39 +0100 Subject: [Tutor] Getting the directory the program is in In-Reply-To: <457D945A.8010706@wit.edu> References: <7c3104d20612110848y4f392407x98d32f0b721d8fa@mail.gmail.com> <457D945A.8010706@wit.edu> Message-ID: On 12/11/06, Jordan Greenberg wrote: > Tor Hildrum wrote: > > The full pathname is in sys.argv[0] > At least on my system, it only includes the filename if executed from > the current directory. Hm, yeah, I thought the full path was standard behavior but I see it's not. I need to go change some code :) From rdm at rcblue.com Tue Dec 12 04:28:11 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 11 Dec 2006 19:28:11 -0800 Subject: [Tutor] Video of recent talk by Guido van Rossum Message-ID: <7.0.1.0.2.20061211192334.01e20790@rcblue.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061211/ddffde2a/attachment.html From wesbrooks at gmail.com Tue Dec 12 09:49:57 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 12 Dec 2006 08:49:57 +0000 Subject: [Tutor] User identification and running in the background. Message-ID: Good morning Users, I've had a quick scan around and can't find a way to identify the user who is logged in on the machine while a script is running? I've seen a few mentions of it being possible using bits of the win32 library but I would have liked my software to be portable with no adjustments. How can I run a script in the background? I will be writing a (prototype) machine control interface and would like the users to be able to log out, but leave the script running. When the next user logs in they can open up a portal (preferably in the system tray) to give them control of the system again. When I link this to the user identification I would be able to vary the access to the machine depending on the access rights of the user. Thank you in advance of any help. Wesley Brooks. From pytutmail at gmail.com Tue Dec 12 16:45:16 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Tue, 12 Dec 2006 16:45:16 +0100 Subject: [Tutor] Opening a pdf on a certain page Message-ID: <7c3104d20612120745v557f3bffo3ddcc5addad9de8b@mail.gmail.com> Hey friendly users, Is there anyway to open a .pdf at a certain page? Been searching the internet, but couldnt find anything. Thanks in advance, Toon Pieton -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061212/eae0a7b8/attachment.htm From pytutmail at gmail.com Tue Dec 12 16:57:43 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Tue, 12 Dec 2006 16:57:43 +0100 Subject: [Tutor] getting all txt files in a folder Message-ID: <7c3104d20612120757p200abda9j6d76cc666a6d163e@mail.gmail.com> Hey friendly users, Is there any way to get all the txt files in a certain folder and all of its "sub"-folders? With sub-folder I mean all the folders inside the previously found folder. Any help would be greatly appreciated Greetings, Toon Pieton -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061212/a1a37003/attachment.html From Tim.Golden at viacom-outdoor.co.uk Tue Dec 12 17:00:29 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 12 Dec 2006 16:00:29 -0000 Subject: [Tutor] Opening a pdf on a certain page In-Reply-To: <7c3104d20612120745v557f3bffo3ddcc5addad9de8b@mail.gmail.com> Message-ID: [Toon Pieton] | Is there anyway to open a .pdf at a certain page? Been | searching the internet, but couldnt find anything. Pretty certain there isn't. Even if you'd generated the PDF yourself and set an internal anchor there doesn't seem to be a URI which will jump to that point. I'd be really happy to be wrong about that. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From Tim.Golden at viacom-outdoor.co.uk Tue Dec 12 17:13:28 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 12 Dec 2006 16:13:28 -0000 Subject: [Tutor] getting all txt files in a folder In-Reply-To: <7c3104d20612120757p200abda9j6d76cc666a6d163e@mail.gmail.com> Message-ID: [Toon Pieton] | Is there any way to get all the txt files in a certain folder | and all of its "sub"-folders? With sub-folder I mean all the | folders inside the previously found folder. Any help would be | greatly appreciated Have a look at os.walk and fnmatch TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From Urban.Landreman at co.hennepin.mn.us Tue Dec 12 17:04:04 2006 From: Urban.Landreman at co.hennepin.mn.us (Urban.Landreman at co.hennepin.mn.us) Date: Tue, 12 Dec 2006 10:04:04 -0600 Subject: [Tutor] How to allow user to choose an option from a window Message-ID: I'm trying to allow a user to select one option from a list. My simple code works: OptionList = ['One', 'Two', 'Three'] while 1: print 'Here are your options:' for option in OptionList: print option optionChosen = raw_input("Which one do you want? ") if optionChosen in OptionList: break print "That is not a valid option. Please re-enter your choice." print "You have chosen: ", optionChosen However, Now I'd like to display the options within a MsgBox-type display and have the user click on the option of choice. Any suggestions of a model I can adapt to accomplish this? Thanks. Urban Landreman From simon at brunningonline.net Tue Dec 12 17:39:25 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 12 Dec 2006 16:39:25 +0000 Subject: [Tutor] getting all txt files in a folder In-Reply-To: <7c3104d20612120757p200abda9j6d76cc666a6d163e@mail.gmail.com> References: <7c3104d20612120757p200abda9j6d76cc666a6d163e@mail.gmail.com> Message-ID: <8c7f10c60612120839n3d41d49fs98ef42933179e711@mail.gmail.com> On 12/12/06, Toon Pieton wrote: > Is there any way to get all the txt files in a certain folder and all of its > "sub"-folders? With sub-folder I mean all the folders inside the previously > found folder. Any help would be greatly appreciated http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499305 -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Tue Dec 12 17:42:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Dec 2006 11:42:55 -0500 Subject: [Tutor] getting all txt files in a folder In-Reply-To: <7c3104d20612120757p200abda9j6d76cc666a6d163e@mail.gmail.com> References: <7c3104d20612120757p200abda9j6d76cc666a6d163e@mail.gmail.com> Message-ID: <457EDC0F.2040800@tds.net> Toon Pieton wrote: > Hey friendly users, > > Is there any way to get all the txt files in a certain folder and all of > its "sub"-folders? With sub-folder I mean all the folders inside the > previously found folder. Any help would be greatly appreciated Using the path module from http://www.jorendorff.com/articles/python/path/index.html it's easy: import path basePath = path.path('path/to/root/folder') for txtPath in basePath.walkfiles('*.txt'): # do something with txtPath e.g. list the names print txtPath Otherwise use os.walk() and fnmatch as Tim suggested. Kent From lantal at tmail.com Tue Dec 12 18:11:44 2006 From: lantal at tmail.com (Laszlo Antal) Date: Tue, 12 Dec 2006 09:11:44 -0800 Subject: [Tutor] Getting the directory the program is in Message-ID: <1165943504.2130A37B@fb6.dngr.org> Hi, I use this: # This is the file name this code is in curfile = "findcurdir.py" #__file__ gives everything so slice off the file name curdir = __file__[:-len(curfile)] print curdir #will print the curdir the file is in #even if this file(module) has been imported I hope it helps Laszlo Antal From dkuhlman at rexx.com Tue Dec 12 18:19:54 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 12 Dec 2006 09:19:54 -0800 Subject: [Tutor] Opening a pdf on a certain page In-Reply-To: References: <7c3104d20612120745v557f3bffo3ddcc5addad9de8b@mail.gmail.com> Message-ID: <20061212171954.GA69601@cutter.rexx.com> On Tue, Dec 12, 2006 at 04:00:29PM -0000, Tim Golden wrote: > [Toon Pieton] > > | Is there anyway to open a .pdf at a certain page? Been > | searching the internet, but couldnt find anything. > > Pretty certain there isn't. Even if you'd generated the > PDF yourself and set an internal anchor there doesn't > seem to be a URI which will jump to that point. I'd > be really happy to be wrong about that. > I'm assuming that the original poster was asking a Python question, but just to show that in general this must be possible ... I use evince (on Linux) to read PDF docs. When I open a document the second time, evince automatically shows the last page I was viewing when I previously closed evince. And, the following command: $ evince -p 12 somedocument.pdf will open that document to page 12. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From Tim.Golden at viacom-outdoor.co.uk Tue Dec 12 18:20:13 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 12 Dec 2006 17:20:13 -0000 Subject: [Tutor] User identification and running in the background. In-Reply-To: Message-ID: | I've had a quick scan around and can't find a way to identify the user | who is logged in on the machine while a script is running? I've seen a | few mentions of it being possible using bits of the win32 library but | I would have liked my software to be portable with no adjustments. | | How can I run a script in the background? I will be writing a | (prototype) machine control interface and would like the users to be | able to log out, but leave the script running. When the next user logs | in they can open up a portal (preferably in the system tray) to give | them control of the system again. When I link this to the user | identification I would be able to vary the access to the machine | depending on the access rights of the user. I very much doubt if even the rest of what you're doing is going to be particularly portable, so I wouldn't worry too much if the logged-on user bit isn't either. It looks to me as though you're working at O/S-specific level. Python doesn't offer any particular abstraction over detached processes etc. In Windows you'd have to use a Service, in *nix a daemon (I think). To talk about possibilities on Windows which I know better, it should be possible to have a service running which can be messaged to by a desktop app run from the system tray or elsewhere. When the desktop app sends its signal to the service it could send through the SID or Token of the logged on user which the service could then use to authorise or not. But this is all quite Win32-specific (as well as being hand-wavingly unspecific). I don't know how you'd go about it on *nix but I bet it's nothing like the same. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From Tim.Golden at viacom-outdoor.co.uk Tue Dec 12 18:27:46 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 12 Dec 2006 17:27:46 -0000 Subject: [Tutor] Opening a pdf on a certain page In-Reply-To: <20061212171954.GA69601@cutter.rexx.com> Message-ID: [Dave Kuhlman] | On Tue, Dec 12, 2006 at 04:00:29PM -0000, Tim Golden wrote: | > [Toon Pieton] | > | > | Is there anyway to open a .pdf at a certain page? Been | > | searching the internet, but couldnt find anything. | > | > Pretty certain there isn't. Even if you'd generated the | > PDF yourself and set an internal anchor there doesn't | > seem to be a URI which will jump to that point. I'd | > be really happy to be wrong about that. | > | | I'm assuming that the original poster was asking a Python question, | but just to show that in general this must be possible ... | | I use evince (on Linux) to read PDF docs. When I open a document | the second time, evince automatically shows the last page I was | viewing when I previously closed evince. And, the following | command: | | $ evince -p 12 somedocument.pdf | | will open that document to page 12. Well I was certainly very narrow in my thinking, assuming that everyone was running Acrobat Reader and/or Firefox like myself. Clearly you're right that since PDFs *have* pages, any reader may offer a facility to jump to one. Thanks for the education! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jason.massey at gmail.com Tue Dec 12 18:40:04 2006 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 12 Dec 2006 11:40:04 -0600 Subject: [Tutor] How to allow user to choose an option from a window In-Reply-To: References: Message-ID: <7e3eab2c0612120940h5d8e8913xdfb999797994c1cf@mail.gmail.com> If you mean which type of GUI model to use you have at least two popular choices. Tkinter: It's bundled with Python, and there's a tutorial at: http://www.pythonware.com/library/tkinter/introduction/ wxPython: My GUI of choice. http://wxpython.org A quick and dirty example in wxPython of what you wanted: import wx class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=(200,200)) self.radiobox = wx.RadioBox(self,wx.ID_ANY ,'Options',choices=['One','Two','Three'],style=wx.RA_SPECIFY_ROWS) self.Bind(wx.EVT_RADIOBOX,self.OnRadioBoxChoose,self.radiobox) self.Show() def OnRadioBoxChoose(self,event): choice = self.radiobox.GetStringSelection() wx.MessageBox("You selected: %s" % choice) app = wx.PySimpleApp() frame = MainWindow(None,-1,"Options") app.MainLoop() On 12/12/06, Urban.Landreman at co.hennepin.mn.us < Urban.Landreman at co.hennepin.mn.us> wrote: > > I'm trying to allow a user to select one option from a list. > > My simple code works: > OptionList = ['One', 'Two', 'Three'] > while 1: > print 'Here are your options:' > for option in OptionList: > print option > optionChosen = raw_input("Which one do you want? ") > if optionChosen in OptionList: > break > print "That is not a valid option. Please re-enter your choice." > print "You have chosen: ", optionChosen > > However, Now I'd like to display the options within a MsgBox-type display > and have the user click on the option of choice. > > Any suggestions of a model I can adapt to accomplish this? > > Thanks. > > Urban Landreman > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061212/b28e8787/attachment.htm From Barry.Carroll at psc.com Tue Dec 12 23:53:14 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 12 Dec 2006 14:53:14 -0800 Subject: [Tutor] Accessing the name of a Function Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A4A@eugsrv400.psc.pscnet.com> Greetings: Is it possible, from inside a stand-alone function (not a member of a class), to access the string representation of the function's name? If so, how? Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061212/7a4c406f/attachment.htm From andreas at kostyrka.org Wed Dec 13 01:04:42 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Dec 2006 01:04:42 +0100 Subject: [Tutor] Accessing the name of a Function In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A4A@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A4A@eugsrv400.psc.pscnet.com> Message-ID: <20061213000442.GB16961@andi-lap.la.revver.com> * Carroll, Barry [061212 23:54]: > Greetings: > > > > Is it possible, from inside a stand-alone function (not a member of a > class), to access the string representation of the function's name? If > so, how? Probably, but it's dirty like help (sys._getframe would be your ticket into this), but you ask on the tutor mailing list, so you'll probably don't want this: def func(x): return 2 * x gunc = func del func print gunc(10) The best you can hope to derive is "func" here, but as you can see, functions are only objects that can be assigned freely. (Spoiler: it's sys._getframe(0).f_code.co_name, but it will always only know the name the function was defined under. No way to know how it was named when it was called. So it's not worth much.) Andreas > > > > Regards, > > > > Barry > > [1]barry.carroll at psc.com > > 541-302-1107 > > ________________________ > > We who cut mere stones must always be envisioning cathedrals. > > --Quarry worker's creed > > > > References > > Visible links > 1. mailto:barry.carroll at psc.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From andreas at kostyrka.org Wed Dec 13 01:10:55 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Dec 2006 01:10:55 +0100 Subject: [Tutor] Getting the directory the program is in In-Reply-To: <1165943504.2130A37B@fb6.dngr.org> References: <1165943504.2130A37B@fb6.dngr.org> Message-ID: <20061213001053.GD16961@andi-lap.la.revver.com> * Laszlo Antal [061212 18:12]: > Hi, > > I use this: > > # This is the file name this code is in > curfile = "findcurdir.py" > #__file__ gives everything so slice off the file name > curdir = __file__[:-len(curfile)] > print curdir > #will print the curdir the file is in > #even if this file(module) has been imported What about using os.path.dirname and os.path.basename for this splitting? Andreas From Barry.Carroll at psc.com Wed Dec 13 02:02:56 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 12 Dec 2006 17:02:56 -0800 Subject: [Tutor] Accessing the name of a Function Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A4B@eugsrv400.psc.pscnet.com> Andreas: You're right, that is kind of messy and somewhat limited. In the present case, however, it is the function's defined name that I want, so this would work okay. I'm guessing that there is a way to determine the number and names of the arguments to the function as well. I'll go look at the sys module and see what I can find. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Andreas Kostyrka [mailto:andreas at kostyrka.org] > Sent: Tuesday, December 12, 2006 4:05 PM > To: Carroll, Barry > Cc: tutor at python.org > Subject: Re: [Tutor] Accessing the name of a Function > > * Carroll, Barry [061212 23:54]: > > Greetings: > > > > > > > > Is it possible, from inside a stand-alone function (not a member of a > > class), to access the string representation of the function's name? > If > > so, how? > Probably, but it's dirty like help (sys._getframe would be your ticket > into this), but you ask on the tutor mailing list, so you'll probably > don't want this: > > def func(x): > return 2 * x > > gunc = func > del func > > print gunc(10) > > The best you can hope to derive is "func" here, but as you can see, > functions are only objects that can be assigned freely. > > (Spoiler: it's sys._getframe(0).f_code.co_name, but it will always > only know the name the function was defined under. No way to know how > it was named when it was called. So it's not worth much.) > > Andreas > > > > > > > > Regards, > > > > > > > > Barry > > > > [1]barry.carroll at psc.com > > > > 541-302-1107 > > > > ________________________ > > > > We who cut mere stones must always be envisioning cathedrals. > > > > --Quarry worker's creed > > > > > > > > References > > > > Visible links > > 1. mailto:barry.carroll at psc.com > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > From tavspam at gmail.com Wed Dec 13 02:39:48 2006 From: tavspam at gmail.com (Thomas) Date: Wed, 13 Dec 2006 01:39:48 +0000 Subject: [Tutor] Organizing 15500 records, how? Message-ID: <493b81e30612121739p352b7f7ek6f7069f1d27443b9@mail.gmail.com> I'm writing a program to analyse the profiles of the 15500 users of my forum. I have the profiles as html files stored locally and I'm using ClientForm to extract the various details from the html form in each file. My goal is to identify lurking spammers but also to learn how to better spot spammers by calculating statistical correlations in the data against known spammers. I need advise with how to organise my data. There are 50 fields in each profile, some fields will be much more use than others so I though about creating say 10 files to start off with that contained dictionaries of userid to field value. That way I'm dealing with 10 to 50 files instead of 15500. Also, I am inexperienced with using classes but eager to learn and wonder if they would be any help in this case. Any advise much appreciated and thanks in advance, Thomas From pyro9219 at gmail.com Wed Dec 13 03:37:14 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 12 Dec 2006 18:37:14 -0800 Subject: [Tutor] Confusing Unicode Conversion Problem. Message-ID: I've got a script that uses com to read columns from an excel workbook(very slow for 6500ish items :/ ) and I'm getting this error: 'ascii' codec can't encode character u'\xa0' in position 11: ordinal not in range(128) Error with: FRAMEMRISER of type: Excel Row : 6355 FRAMEMRISER is exactly how the item looks in excel. What I don't get is why it prints to my screen fine, but I can't get the darn thing to convert to a string. I think xa0 is a space (like ' '), which location 11 puts it at the end of the of the word, basically invisible. I've successfully used my script to import several columns, but this one is being a pain. My code in question: try: while xlSht.Cells(row,col).Value != None: tempValue = xlSht.Cells(row,col).Value tempString = str(tempValue).split('.')[0] ExcelValues.append(tempString) Row = 1 + row # Increment Rows. except UnicodeEncodeError, msg: # Exit the system if error. print msg print "Error with: " + tempValue + " of type: " + str(type(tempValue)) print "Excel Row : " + str(row) Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061212/1a353eec/attachment.html From pjlists at gmail.com Wed Dec 13 08:59:17 2006 From: pjlists at gmail.com (Peter Jessop) Date: Wed, 13 Dec 2006 08:59:17 +0100 Subject: [Tutor] Organizing 15500 records, how? In-Reply-To: <493b81e30612121739p352b7f7ek6f7069f1d27443b9@mail.gmail.com> References: <493b81e30612121739p352b7f7ek6f7069f1d27443b9@mail.gmail.com> Message-ID: <7a8d5a0c0612122359x108f22bfq8adeb4e25751571d@mail.gmail.com> With more than 15000 records you would be better off using a relational database. Although it will create more work to start with (you'll have to learn it), it will save you a lot of work in the medium and long term. Almost any relational database can be accessed from python.As it is just for your own use SQLite might be the most appropiate (it has a very small footprint) but MySQL is excellent and so are many others. To use a relational database you might think about learning SQL. It is very easy (especially if you you know any Boolean algebra) and is a language that has been used almost unchanged for decades and shows every sign of staying here for a long time. In computing it is one of the most useful things you can learn. There is a good introductory, interactive tutorial athttp://sqlcourse.com/ If you feel you need another abstraction layer on top of this you could look at SQLObject . Personally I would recommend that you start with MySQL. It is open source, easy to install and use, stable and fast. But with SQL motors you have lots of good choices. Peter Jessop On 12/13/06, Thomas wrote: > I'm writing a program to analyse the profiles of the 15500 users of my > forum. I have the profiles as html files stored locally and I'm using > ClientForm to extract the various details from the html form in each > file. > > My goal is to identify lurking spammers but also to learn how to > better spot spammers by calculating statistical correlations in the > data against known spammers. > > I need advise with how to organise my data. There are 50 fields in > each profile, some fields will be much more use than others so I > though about creating say 10 files to start off with that contained > dictionaries of userid to field value. That way I'm dealing with 10 to > 50 files instead of 15500. > > Also, I am inexperienced with using classes but eager to learn and > wonder if they would be any help in this case. > > Any advise much appreciated and thanks in advance, > Thomas > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061213/a1891736/attachment.htm From alan.gauld at btinternet.com Wed Dec 13 09:28:33 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Dec 2006 08:28:33 -0000 Subject: [Tutor] Organizing 15500 records, how? References: <493b81e30612121739p352b7f7ek6f7069f1d27443b9@mail.gmail.com> Message-ID: "Thomas" wrote in message news:493b81e30612121739p352b7f7ek6f7069f1d27443b9 at mail.gmail.com... > I'm writing a program to analyse the profiles of the 15500 users > though about creating say 10 files to start off with that contained > dictionaries of userid to field value. That way I'm dealing with 10 > to > 50 files instead of 15500. To be honest, with that numbers you will be better using a database. Both for storage and search speed but also for the analysis. SQL is designed for this kind of job. You can read a shortish intro to using databases in my tutorial. It uses SqlLite but is easily adapted to any database engine. Even if your ISP doesn't support installed databases I would still consider downloading your data into a local database for the analysis job and writing HTML import/export functions to deal with administering the web site. But if you can put a database on the web site then so much the better. It will almost certainly simplify your code and improve performance and/or resource usage. Alan G From torhildrum at gmail.com Wed Dec 13 10:01:56 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Wed, 13 Dec 2006 10:01:56 +0100 Subject: [Tutor] User identification and running in the background. In-Reply-To: References: Message-ID: On 12/12/06, Tim Golden wrote: > But this is all quite Win32-specific (as well as > being hand-wavingly unspecific). I don't know > how you'd go about it on *nix but I bet it's nothing > like the same. The same general principle applies. You need to get a UID or similar from a specific user, or you have to check all connected TTYs and just pick a random user out of the users logged in. Most systems today are multi-user so the notion of 'the user logged in' doesn't make sense system-wide. I think the best way to solve this is to use a client-server approach. Have a deamon/service run in the background, and then have a client started at login that pings the server and notifies it of your presence. Tor From wesbrooks at gmail.com Wed Dec 13 10:02:47 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 13 Dec 2006 09:02:47 +0000 Subject: [Tutor] User identification and running in the background. In-Reply-To: References: Message-ID: Cheers for the reply, I had feared as such! I didn't want to have to code two different apps (windows or linux), or at best have large block of code around a few cases base on the result of sys.platform. The system is based on Windows at the moment, but I would of liked to have produced a version on Linux for evaluation purposes. Thanks again, I'll look up the SID and Token you mentioned. Wesley Brooks On 12/12/06, Tim Golden wrote: > | I've had a quick scan around and can't find a way to identify the user > | who is logged in on the machine while a script is running? I've seen a > | few mentions of it being possible using bits of the win32 library but > | I would have liked my software to be portable with no adjustments. > | > | How can I run a script in the background? I will be writing a > | (prototype) machine control interface and would like the users to be > | able to log out, but leave the script running. When the next user logs > | in they can open up a portal (preferably in the system tray) to give > | them control of the system again. When I link this to the user > | identification I would be able to vary the access to the machine > | depending on the access rights of the user. > > I very much doubt if even the rest of what you're > doing is going to be particularly portable, so I > wouldn't worry too much if the logged-on user bit > isn't either. It looks to me as though you're > working at O/S-specific level. Python doesn't > offer any particular abstraction over detached > processes etc. In Windows you'd have to use a Service, > in *nix a daemon (I think). > > To talk about possibilities on Windows which I know > better, it should be possible to have a service > running which can be messaged to by a desktop app > run from the system tray or elsewhere. When the > desktop app sends its signal to the service it could > send through the SID or Token of the logged on user > which the service could then use to authorise or > not. > > But this is all quite Win32-specific (as well as > being hand-wavingly unspecific). I don't know > how you'd go about it on *nix but I bet it's nothing > like the same. > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wesbrooks at gmail.com Wed Dec 13 10:09:27 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 13 Dec 2006 09:09:27 +0000 Subject: [Tutor] User identification and running in the background. In-Reply-To: References: Message-ID: Cheers, I'll consider that. So the client would effectively hand shake with the lower level program and be supplied with a list of permissions which the user has access to. You mentioned about many systems being multi-user. When the client attempts to connect to the lower machine is it a trivial issue to either supply information on what user the attempt is coming from within the initial communication, or for the low level program to identify where/who the request is coming from? Thanks, Wesley Brooks. On 13/12/06, Tor Hildrum wrote: > On 12/12/06, Tim Golden wrote: > > > But this is all quite Win32-specific (as well as > > being hand-wavingly unspecific). I don't know > > how you'd go about it on *nix but I bet it's nothing > > like the same. > > The same general principle applies. You need to get a > UID or similar from a specific user, or you have to > check all connected TTYs and just pick a random user > out of the users logged in. Most systems today are > multi-user so the notion of 'the user logged in' doesn't > make sense system-wide. > > I think the best way to solve this is to use a client-server > approach. Have a deamon/service run in the background, > and then have a client started at login that pings the server > and notifies it of your presence. > > Tor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From Tim.Golden at viacom-outdoor.co.uk Wed Dec 13 10:32:07 2006 From: Tim.Golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 13 Dec 2006 09:32:07 -0000 Subject: [Tutor] Confusing Unicode Conversion Problem. In-Reply-To: Message-ID: [Chris Hengge] | 'ascii' codec can't encode character u'\xa0' in position 11: | ordinal not in range(128) | Error with: FRAMEMRISER of type: | Excel Row : 6355 OK. Let's get to the basics first: import unicodedata print unicodedata.name (u'\xa0') # outputs: NO-BREAK SPACE So somewhere (maybe at the end) of your unicode string is a non-breaking space. (Notice that extra space between "FRAMERISER" and "of" in the message above. Next, when you print to the screen, you're implicitly using the sys.stdout encoding, which on my XP machine is cp437: import sys print sys.stdout.encoding # outputs: cp437 print u'\xa0'.encode (sys.stdout.encoding) # outputs a blank line, presumably including a non-breaking space But when you convert to a str using str (...) Python will use an ascii encoding. So let's try that: print str (u'\xa0') # sure enough: UnicodeError, blah, blah In essence, when you're using Unicode data, you either need to encode immediately to a consistent encoding of your choice (or possibly forced upon you) or to retain Unicode data throughout until you need to output, to screen or database or file, and then convert as needed. Let's take your code (snipped a bit): 1 while xlSht.Cells(row,col).Value != None: 2 tempValue = xlSht.Cells(row,col).Value 3 tempString = str(tempValue).split('.')[0] 4 ExcelValues.append(tempString) 5 Row = 1 + row # Increment Rows. It's not clear what ExcelValues is, but let's assume it's a list of things you're going to output later to a file. Your line 3 is doing an implicit conversion when it doesn't look like it needs to. Have a look at this trivial example: import codecs fake_excel_data = ([u"Stuff.0", u"\xa0and\xa0.1", u"nonsense.2"]) values = [] for data in fake_excel_data: pre, post = data.split (".") values.append (pre) # # later... # f = codecs.open ("excel_values.txt", "w", "utf-8") try: f.writelines (values) finally: f.close () Notice I haven't done the encoding until I finally output to a file, where I've used the codecs module to specify an encoding. You could do this string by string or some other way. If I were simply writing back to, say, another Excel sheet, or any other target which was expecting Unicode data, I wouldn't encode it anywhere. The Unicode objects offer nearly all the same methods as the string objects so you just use them as you would strings. What you have to look out for is situations like your str () conversion where an implicit encoding-to-ascii goes on. HTH TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kent37 at tds.net Wed Dec 13 11:54:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Dec 2006 05:54:56 -0500 Subject: [Tutor] Accessing the name of a Function In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A4B@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A4B@eugsrv400.psc.pscnet.com> Message-ID: <457FDC00.8000405@tds.net> Carroll, Barry wrote: > Andreas: > > You're right, that is kind of messy and somewhat limited. In the > present case, however, it is the function's defined name that I want, so > this would work okay. > > I'm guessing that there is a way to determine the number and names of > the arguments to the function as well. I'll go look at the sys module > and see what I can find. Look at the inspect module, specifically getargspec() and getargvalues(). Kent From niakmaheshwari at gmail.com Wed Dec 13 16:10:47 2006 From: niakmaheshwari at gmail.com (Archana Maheshwari) Date: Wed, 13 Dec 2006 20:40:47 +0530 Subject: [Tutor] Applications Message-ID: <9ae4fefd0612130710y28892ccfk406070ceba1ec406@mail.gmail.com> tell me about the applications of python programming in mapping field. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061213/4de58064/attachment.html From enfors at enfors.net Wed Dec 13 15:26:26 2006 From: enfors at enfors.net (Christer Enfors) Date: Wed, 13 Dec 2006 15:26:26 +0100 Subject: [Tutor] Implementing a MUD engine from scratch Message-ID: <45800D92.3020607@enfors.net> I'm new to Python, but I've been programming other languages for over 15 years. Now, I've decided that I want to code my own MUD engine from scratch in Python. A MUD is a bit like a MMORPG (like World of Warcraft), only it uses text instead of graphics. A MUD is the graphical MMORPGs what books are to movies. A MUD acts like a telnet server - you use telnet to connect and play. This makes it very easy to try new MUDs; unlike graphical MMORPGs, you don't need specific client software for each MUD. MUDs are also typically free to play. To explain more clearly just what it is I want to create, I have to explain where I'm coming from. For the past 12 years, I've been playing on, and coding with, an existing MUD engine called LPMUD. The LPMUD engine itself is coded in C, but it implements a interpreted language called LPC. Once you've telnetted to an LPMUD, you can create monsters, areas, powers, quests, etc by writing LPC programs. LPC programs can be written and edited while the LPMUD is online, so there is no need to restart an LPMUD (and thus disconnect all players) to fix coding errors or add new game content. LPC is also inherently sandboxed, so a malevolent coder can't affect filesystems outside of the dedicated LPMUD directory, and so on. I want to make something similar in Python. Like I said, the LPMUD engine is coded in C, but uses the LPC language to create the actual game content. I my case, Python will be used for both purposes. Now on to my actual questions: 1) I want to be able to update parts of the code (the game content) while the MUD (the engine) is running. Errors in the game shouldn't stop the entire MUD - I guess I should use exceptions for this? Any pointers as to where I should begin to research how to accomplish this? I'm guessing that perhaps IDLE could be worth a look (since it is a Python program that allows you to edit and run Python programs inside it). 2) Would it be realistically possible to sandbox my MUD, so that arbitrary Python programs (written by appointed MUD staff) can't affect the hosting machine? Thanks in advance. -- Christer Enfors From alan.gauld at btinternet.com Wed Dec 13 18:22:34 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Dec 2006 17:22:34 -0000 Subject: [Tutor] Applications References: <9ae4fefd0612130710y28892ccfk406070ceba1ec406@mail.gmail.com> Message-ID: "Archana Maheshwari" wrote > tell me about the applications of python programming in mapping > field. > Tell us about the mapping field. I sounds fairly specialised. Do you have any specific software systems requirements? Do you use software systems at the moment? What makes you think Python might be helpful to you in the first place? We might be able to respond to those more general issues more successfully than about a field that many of us (most of us?) know nothing about. Alan G. From kent37 at tds.net Wed Dec 13 18:41:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Dec 2006 12:41:10 -0500 Subject: [Tutor] Applications In-Reply-To: <9ae4fefd0612130710y28892ccfk406070ceba1ec406@mail.gmail.com> References: <9ae4fefd0612130710y28892ccfk406070ceba1ec406@mail.gmail.com> Message-ID: <45803B36.6050006@tds.net> Archana Maheshwari wrote: > tell me about the applications of python programming in mapping field. What kind of mapping do you have in mind? Googling "python mapping" finds this: http://infohost.nmt.edu/tcc/help/lang/python/mapping.html Depending on what kind of mapping you mean, googling "python gis" might be interesting. Kent From pyro9219 at gmail.com Wed Dec 13 20:24:14 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Dec 2006 11:24:14 -0800 Subject: [Tutor] Confusing Unicode Conversion Problem. In-Reply-To: References: Message-ID: Thanks for the detailed reply. The reason I an forcing each line to string and splitting it is because the pure numeric values coming from the excel sheet all come in a decimal, and have an appended .0 at the end. So 123456 in Excel is becoming 123456.0 when using the loop to extract it. I was told by another person here in the office that Excel and COM aren't the most intelligent collaborators =P The destination for the list (you guessed correct) is another loop that creates SQL commands, and then posts them into a database. Essentially this script is just reading some 6K rows of data (max column count) from excel and posting them into SQL tables. The script works fine for just about every column, which is what has me so puzzled. I guess when MicroStrategies is pulling this data into Excel format it must be adding extra data or something. Anyways, maybe now that I've explained what I'm doing, I could get a little more focused solution to my problem? I think I've got a full understanding of what is happening, but I'm still not sure of the fix. If it was in the last e-mail, it must be over my head and I'll need it pointed out with neon lights :) thanks On 12/13/06, Tim Golden wrote: > > [Chris Hengge] > > | 'ascii' codec can't encode character u'\xa0' in position 11: > | ordinal not in range(128) > | Error with: FRAMEMRISER of type: > | Excel Row : 6355 > > OK. Let's get to the basics first: > > > import unicodedata > print unicodedata.name (u'\xa0') > # outputs: NO-BREAK SPACE > > > > So somewhere (maybe at the end) of your unicode > string is a non-breaking space. (Notice that > extra space between "FRAMERISER" and "of" in > the message above. > > Next, when you print to the screen, you're implicitly > using the sys.stdout encoding, which on my XP machine > is cp437: > > > import sys > print sys.stdout.encoding > # outputs: cp437 > > print u'\xa0'.encode (sys.stdout.encoding) > # outputs a blank line, presumably including a non-breaking space > > > > But when you convert to a str using str (...) Python > will use an ascii encoding. So let's try that: > > > print str (u'\xa0') > # sure enough: UnicodeError, blah, blah > > > > In essence, when you're using Unicode data, you either > need to encode immediately to a consistent encoding of > your choice (or possibly forced upon you) or to retain > Unicode data throughout until you need to output, to > screen or database or file, and then convert as needed. > > Let's take your code (snipped a bit): > > 1 while xlSht.Cells(row,col).Value != None: > 2 tempValue = xlSht.Cells(row,col).Value > 3 tempString = str(tempValue).split('.')[0] > 4 ExcelValues.append(tempString) > 5 Row = 1 + row # Increment Rows. > > It's not clear what ExcelValues is, but let's assume > it's a list of things you're going to output later > to a file. Your line 3 is doing an implicit conversion > when it doesn't look like it needs to. Have a look > at this trivial example: > > > import codecs > > fake_excel_data = ([u"Stuff.0", u"\xa0and\xa0.1", u"nonsense.2"]) > values = [] > > for data in fake_excel_data: > pre, post = data.split (".") > values.append (pre) > > # > # later... > # > f = codecs.open ("excel_values.txt", "w", "utf-8") > try: > f.writelines (values) > finally: > f.close () > > > > Notice I haven't done the encoding until I finally > output to a file, where I've used the codecs module > to specify an encoding. You could do this string by > string or some other way. > > If I were simply writing back to, say, another > Excel sheet, or any other target which was expecting > Unicode data, I wouldn't encode it anywhere. The Unicode > objects offer nearly all the same methods as the > string objects so you just use them as you would strings. > > What you have to look out for is situations like > your str () conversion where an implicit encoding-to-ascii > goes on. > > HTH > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061213/f3e4d84a/attachment.html From cbc at unc.edu Wed Dec 13 20:47:09 2006 From: cbc at unc.edu (Chris Calloway) Date: Wed, 13 Dec 2006 14:47:09 -0500 Subject: [Tutor] Applications In-Reply-To: <9ae4fefd0612130710y28892ccfk406070ceba1ec406@mail.gmail.com> References: <9ae4fefd0612130710y28892ccfk406070ceba1ec406@mail.gmail.com> Message-ID: <458058BD.8070001@unc.edu> Archana Maheshwari wrote: > tell me about the applications of python programming in mapping field. Python is now the primary scripting language for ESRI products: http://www.esri.com/news/arcuser/0405/files/python.pdf Python wraps GDAL: http://www.gdal.org/gdal_tutorial.html and OGR: http://ogr.maptools.org/ Generic Mapping Tools is wrapped by Python: http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/gmt/gmt-src/doc/html/public/gmt.gmt-module.html Python is a scripting language for MapServer: http://mapserver.gis.umn.edu/cgi-bin/wiki.pl?PythonMapScript The Python Cartographic Library: http://trac.gispython.org/projects/PCL/wiki forms the basis of PrimaGIS: http://primagis.fi/ which are both collected by the GIS Python community: http://www.gispython.org/ GRASS, the main open source GIS analysis product, is scripted in Python: http://grass.gdf-hannover.de/wiki/GRASS_and_Python Basically, Python is the GIS scripting language of choice. If you google on "python +gis", there are over a million hits. Any mapping tool worth paying attention to has a Python API. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From mail at timgolden.me.uk Wed Dec 13 21:04:43 2006 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 13 Dec 2006 20:04:43 +0000 Subject: [Tutor] Confusing Unicode Conversion Problem. References: CCAC78D42E32184F8E26DC163DB98306C1B6C7@vogbs009.gb.vo.local Message-ID: <45805CDB.1050601@timgolden.me.uk> [Chris H] > The reason I an forcing each line to string and splitting it is because the > pure numeric values coming from the excel sheet all come in a decimal, and > have an appended .0 at the end. Ah! You're using str to convert a number to a string. I see. And you're relying on the fact that other data, such as the mysterious "FRAMERISER\xa0" won't be affected by a split on a dot. Try using the unicode function as a converter, rather than str. If the input is already a unicode object, it won't alter it; if it's a number, it'll convert to a unicode string, and the split will work as expected. while xlSht.Cells(row,col).Value != None: tempValue = xlSht.Cells(row,col).Value tempString = unicode (tempValue).split('.')[0] # tempString is now a unicode object one way # or the other, representing the part of your # data before the dot. You might want to convert numbers back to some kind of numeric type here (Decimal or float or int) depending on your requirements later. > The destination for the list (you guessed correct) is another loop that > creates SQL commands, and then posts them into a database. Depending on what your database is expecting, you might need to encode your Unicode, or not. If you're using sqlite, for example, it's expecting Unicode in any case. Other databases and interface modules may vary. Hope that's a bit clearer. I'm always happy to explain again, but if my explanation isn't clear this time round, better if someone else has a go; maybe my style of explanation doesn't match with your style of understanding. :) TJG From pyro9219 at gmail.com Wed Dec 13 22:06:26 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Wed, 13 Dec 2006 13:06:26 -0800 Subject: [Tutor] Confusing Unicode Conversion Problem. In-Reply-To: <45805CDB.1050601@timgolden.me.uk> References: <45805CDB.1050601@timgolden.me.uk> Message-ID: You fixed it! Kudos and a cookie! (Name Brand even!) Thanks a lot, seems to be moving along fine now.. :] On 12/13/06, Tim Golden wrote: > > [Chris H] > > The reason I an forcing each line to string and splitting it is because > the > > pure numeric values coming from the excel sheet all come in a decimal, > and > > have an appended .0 at the end. > > Ah! You're using str to convert a number to a string. I see. > And you're relying on the fact that other data, such as > the mysterious "FRAMERISER\xa0" won't be affected by a split > on a dot. > > Try using the unicode function as a converter, rather > than str. If the input is already a unicode object, it > won't alter it; if it's a number, it'll convert to a > unicode string, and the split will work as expected. > > > while xlSht.Cells(row,col).Value != None: > tempValue = xlSht.Cells(row,col).Value > tempString = unicode (tempValue).split('.')[0] > # tempString is now a unicode object one way > # or the other, representing the part of your > # data before the dot. > > > You might want to convert numbers back to some kind > of numeric type here (Decimal or float or int) > depending on your requirements later. > > > The destination for the list (you guessed correct) is another loop that > > creates SQL commands, and then posts them into a database. > > Depending on what your database is expecting, you might need to > encode your Unicode, or not. If you're using sqlite, for example, > it's expecting Unicode in any case. Other databases and interface > modules may vary. > > Hope that's a bit clearer. I'm always happy to explain > again, but if my explanation isn't clear this time > round, better if someone else has a go; maybe my style > of explanation doesn't match with your style of > understanding. :) > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061213/aff76b33/attachment.htm From Barry.Carroll at psc.com Wed Dec 13 23:44:41 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 13 Dec 2006 14:44:41 -0800 Subject: [Tutor] Accessing the name of a Function Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A4D@eugsrv400.psc.pscnet.com> Greetings: Andreas and Kent helped me solve my problem. We are writing a keyword driven framework for embedded SW testing. The framework supports scores of keywords, built-in and user-defined. We are still writing the framework, so none of the functions for manipulating the target device has been written, although the keywords are defined. As a result, he framework's output log is full of "keyword not found" errors, which mask real errors in framework operation. To get rid of these 'pseudo errors' I wanted a stub handler that would output an information message, with the name of the function and its arguments. Using the sys._getframe method and the inspect.getargvalues methods, I was able to write a single routine that will handle any function signature. Here is the result: A sample keyword triggered function: ########## import sys from actioncommon import handlestub def doaction_dbopen(ctrl, proc, schemafile, configfile, dataset="default"): '''A, Config, DB, Open, schemafile, configfile, dataset="default" Open the testbench data base. Where: schemafile (str) - the xml schema file for the product to be tested; configfile (str) - the configuration file for the product to be tested; dataset (str) - optional configuration data set to activate. defaults to "default" Example: A, Config, DB, Open, "master.xml", "test.tex", "current" ''' # TODO: replace stub handler with action logic. handlestub(ctrl, proc, sys._getframe()) return True ########## The stub handler: ########## from inspect import getargvalues def handlestub(ctrl, proc, thestubframe): """Identifies actions that are defined but not yet implemented.""" themsg = "Execuiting %s (implementation pending) with arguments: " % \ thestubframe.f_code.co_name (theargnames, trash1, trash2, thelocalsdict)=getargvalues(thestubframe) # The first two arguments are internal to the application: do not display. if len(theargnames) <= 2: themsg += "None" else: for theargname in theargnames[2:]: themsg += "%s=%s " % (theargname, thelocalsdict[theargname]) ctrl.log.logaction(ctrl.log.INFO, themsg) ########## The resulting log output: ########## INFO Execuiting doaction_dbopen (implementation pending) with arguments: schemafile=USBIBM.XML configfile=USBIBM.TEX dataset=usbimbstart ########## Thanks to Andreas and Kent for their help Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Wednesday, December 13, 2006 2:55 AM > To: Carroll, Barry > Cc: tutor at python.org > Subject: Re: [Tutor] Accessing the name of a Function > > Carroll, Barry wrote: > > Andreas: > > > > You're right, that is kind of messy and somewhat limited. In the > > present case, however, it is the function's defined name that I want, so > > this would work okay. > > > > I'm guessing that there is a way to determine the number and names of > > the arguments to the function as well. I'll go look at the sys module > > and see what I can find. > > Look at the inspect module, specifically getargspec() and getargvalues(). > > Kent > From pjlists at gmail.com Thu Dec 14 00:10:07 2006 From: pjlists at gmail.com (Peter Jessop) Date: Thu, 14 Dec 2006 00:10:07 +0100 Subject: [Tutor] [python-win32] Python as scripting glue, WAS Python for sysadmin In-Reply-To: References: <45803358.4010105@probo.com> Message-ID: <7a8d5a0c0612131510r54162ce8i49a159c0f984cb90@mail.gmail.com> I am a windows system administrator and started learning python (as an alternative to VBScript) for the following reasons. 1) VBScript has serious limitations as a language 2) Needed access to TCP/IP protocols 3) Ability to to write scripts with GUI. 4) Portability Windows system administrators need to know VBScript because that is what most other Windows admins use and thus most examples are written in this language. However point 1-4 above are serious limitations of VBScript Now Powershell has arrived windows has its own usable shell. Of course the popular tools (and shells) for Unix have been available for a long time on Windows but the problem is not just the shell. If it is more appropiat to use awk or bash or sed on Linux, why not use awk or bash or sed on Windows.? Python does not compete with the shell but complements it. Indeed for a system administrator learning Python is a great investment in the future precisely because what you learn can then be used with other operating systems. Powershell can use .NET objects but, as I understand it, cannot use .NET libraries to produce interactive gui scripts. However I think it addresses point 2) above as .NET does come with TCP/IP libraries. The only drawback to using Python for Windows System administration is the lack of uptodate books dedicated to it. A good book dedicated to this topic will sell well. Peter Jessop MSCE -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061214/5dffa989/attachment.htm From kent37 at tds.net Thu Dec 14 00:42:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Dec 2006 18:42:26 -0500 Subject: [Tutor] Accessing the name of a Function In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A4D@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A4D@eugsrv400.psc.pscnet.com> Message-ID: <45808FE2.1000106@tds.net> Carroll, Barry wrote: > Greetings: > > Andreas and Kent helped me solve my problem. We are writing a keyword > driven framework for embedded SW testing. The framework supports scores > of keywords, built-in and user-defined. We are still writing the > framework, so none of the functions for manipulating the target device > has been written, although the keywords are defined. As a result, he > framework's output log is full of "keyword not found" errors, which mask > real errors in framework operation. > > To get rid of these 'pseudo errors' I wanted a stub handler that would > output an information message, with the name of the function and its > arguments. Using the sys._getframe method and the inspect.getargvalues > methods, I was able to write a single routine that will handle any > function signature. Here is the result: You could also do this very simply and cleanly with a decorator, assuming Python >= 2.4. This example is pretty much what you want: http://wiki.python.org/moin/PythonDecoratorLibrary#head-d4ce77c6d6e75aad25baf982f6fec0ff4b3653f4 In your approach, you can call _getframe() in handlestub, see for example http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent > > A sample keyword triggered function: > ########## > import sys > from actioncommon import handlestub > > def doaction_dbopen(ctrl, proc, schemafile, configfile, > dataset="default"): > '''A, Config, DB, Open, schemafile, configfile, dataset="default" > > Open the testbench data base. > Where: > schemafile (str) - the xml schema file for the product to be > tested; > configfile (str) - the configuration file for the product to be > tested; > dataset (str) - optional configuration data set to activate. > > defaults to "default" > Example: > A, Config, DB, Open, "master.xml", "test.tex", "current" > ''' > # TODO: replace stub handler with action logic. > handlestub(ctrl, proc, sys._getframe()) > return True > ########## > > The stub handler: > ########## > from inspect import getargvalues > > def handlestub(ctrl, proc, thestubframe): > """Identifies actions that are defined but not yet implemented.""" > > themsg = "Execuiting %s (implementation pending) with arguments: " % > \ > thestubframe.f_code.co_name > (theargnames, trash1, trash2, > thelocalsdict)=getargvalues(thestubframe) > # The first two arguments are internal to the application: do not > display. > if len(theargnames) <= 2: > themsg += "None" > else: > for theargname in theargnames[2:]: > themsg += "%s=%s " % (theargname, > thelocalsdict[theargname]) ctrl.log.logaction(ctrl.log.INFO, themsg) > ########## > > The resulting log output: > ########## > INFO Execuiting doaction_dbopen (implementation pending) with > arguments: schemafile=USBIBM.XML configfile=USBIBM.TEX > dataset=usbimbstart > ########## > > Thanks to Andreas and Kent for their help > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > > -Quarry worker's creed > > >> -----Original Message----- >> From: Kent Johnson [mailto:kent37 at tds.net] >> Sent: Wednesday, December 13, 2006 2:55 AM >> To: Carroll, Barry >> Cc: tutor at python.org >> Subject: Re: [Tutor] Accessing the name of a Function >> >> Carroll, Barry wrote: >>> Andreas: >>> >>> You're right, that is kind of messy and somewhat limited. In the >>> present case, however, it is the function's defined name that I > want, so >>> this would work okay. >>> >>> I'm guessing that there is a way to determine the number and names > of >>> the arguments to the function as well. I'll go look at the sys > module >>> and see what I can find. >> Look at the inspect module, specifically getargspec() and > getargvalues(). >> Kent >> > > > From alan.gauld at btinternet.com Thu Dec 14 00:47:28 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Dec 2006 23:47:28 -0000 Subject: [Tutor] [python-win32] Python as scripting glue, WAS Python for sysadmin References: <45803358.4010105@probo.com> <7a8d5a0c0612131510r54162ce8i49a159c0f984cb90@mail.gmail.com> Message-ID: "Peter Jessop" wrote >I am a windows system administrator and started learning > python (as an alternative to VBScript) for the following reasons. > > 1) VBScript has serious limitations as a language > 2) Needed access to TCP/IP protocols > 3) Ability to to write scripts with GUI. > 4) Portability > > Windows system administrators need to know VBScript ... > > Now Powershell has arrived windows has its own usable shell. > ... > Powershell can use .NET objects And for that reason I suspect IronPython might be the best option for a Windows sys admin. Although using IronPython in combination with .NET wouldn't be portable to other OS it would give very good access to the innards of Windows that are much harder to reach via normal Python and winall. But I'm not an IronPython user so cannot speak from experience, but it seems that IronPython would be a very useful tool for a Windows Sys admin. Maybe some of those with real experience with ironPython can comment? Alan G From jeannot18 at hotmail.com Thu Dec 14 02:08:09 2006 From: jeannot18 at hotmail.com (John Carmona) Date: Thu, 14 Dec 2006 01:08:09 +0000 Subject: [Tutor] Starting over with Python Message-ID: After quite a while away from Python, I have decided to re-study Python. I am interested to learn Python to support my love for Cryptography. I have a first very easy question (did some search on Google but could not find anything helpful). I realise that this is very basic so be gentle with me. If i insert the following script: ------------------------------------------------------------------------------------------------- odd =1 >>>while odd <=100: if (odd%2)==1: print odd odd = odd + 1 ------------------------------------------------------------------------------------------------- I get a list of the odd numbers from 1 to 99. But now if I wanted to add those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should I include? I have tried to add "odd + odd" but it did not work. In advance thanks. If anyone could direct me to some site where python is associated with Cryptography I would be very grateful. Many thanks JC _________________________________________________________________ Be the first to hear what's new at MSN - sign up to our free newsletters! http://www.msn.co.uk/newsletters From kent37 at tds.net Thu Dec 14 02:32:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Dec 2006 20:32:15 -0500 Subject: [Tutor] Implementing a MUD engine from scratch In-Reply-To: <45800D92.3020607@enfors.net> References: <45800D92.3020607@enfors.net> Message-ID: <4580A99F.4050804@tds.net> Christer Enfors wrote: > Now on to my actual questions: > > 1) I want to be able to update parts of the code (the game content) > while the MUD (the engine) is running. Errors in the game shouldn't stop > the entire MUD - I guess I should use exceptions for this? Any pointers > as to where I should begin to research how to accomplish this? I'm > guessing that perhaps IDLE could be worth a look (since it is a Python > program that allows you to edit and run Python programs inside it). > > 2) Would it be realistically possible to sandbox my MUD, so that > arbitrary Python programs (written by appointed MUD staff) can't affect > the hosting machine? Unfortunately these are both problematic. You can reload a module with the reload() function but this will not fix up references to the contents of the module. In particular if you define classes in the module, instances of the classes will refer to the old definition even if you reload the module with a new definition. There are some recipes in the online cookbook to work around this, search for 'reload': http://tinyurl.com/ydxmwk Python does not provide a secure sandboxed environment and there is no clear way to do that. This is a matter of frequent discussion on comp.lang.python, searching there for sandbox may be educational: http://tinyurl.com/yht5r9 Sorry, I don't have time or energy to dig up more details at the moment. Kent From amonroe at columbus.rr.com Thu Dec 14 02:44:31 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 13 Dec 2006 20:44:31 -0500 Subject: [Tutor] Starting over with Python In-Reply-To: References: Message-ID: <92223625065.20061213204431@columbus.rr.com> > odd =1 >>>>while odd <=100: > if (odd%2)==1: > print odd > odd = odd + 1 > ------------------------------------------------------------------------------------------------- > I get a list of the odd numbers from 1 to 99. But now if I wanted to add > those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should I > include? Hint: create an additional variable called oddsum to tally it up. Add each number to that. There are several approaches but this fits into your existing program the easiest, I think. Alan From Barry.Carroll at psc.com Thu Dec 14 01:22:22 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 13 Dec 2006 16:22:22 -0800 Subject: [Tutor] Accessing the name of a Function Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A4F@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Wednesday, December 13, 2006 3:42 PM > To: Carroll, Barry > Cc: tutor at python.org > Subject: Re: [Tutor] Accessing the name of a Function > <> > > You could also do this very simply and cleanly with a decorator, > assuming Python >= 2.4. This example is pretty much what you want: > http://wiki.python.org/moin/PythonDecoratorLibrary#head- > d4ce77c6d6e75aad25baf982f6fec0ff4b3653f4 > > In your approach, you can call _getframe() in handlestub, see for example > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 > > Kent > > > <> Right again, Kent. Due to the constraints of the target test system, this application has to stay at Python 2.3, at least for now. But using _getframe(1) to get the caller's stack frame does simplify the stub handler call considerably, from handlestub(ctrl, proc, sys._getframe()) to handlestub() The handler now looks like this: ########## def handlestub(): """Identifies actions that are defined but not yet implemented.""" # Get the calling function's stack frame. thestubframe = sys._getframe(1) themsg = "Execuiting %s (implementation pending) with arguments: " % \ thestubframe.f_code.co_name (theargnames, trash1, trash2, thelocalsdict) = \ getargvalues(thestubframe) # The first two arguments are internal to the application: do not #display. if len(theargnames) <= 2: themsg += "None" else: for theargname in theargnames[2:]: themsg += "%s=%s " % (theargname, thelocalsdict[theargname]) ctrl = thelocalsdict["ctrl"] ctrl.log.logaction(ctrl.log.INFO, themsg) ########## Thanks again. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From wescpy at gmail.com Thu Dec 14 03:34:59 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 13 Dec 2006 18:34:59 -0800 Subject: [Tutor] Starting over with Python In-Reply-To: References: Message-ID: <78b3a9580612131834t2b7d1bf4l6782a1703e70dd1b@mail.gmail.com> > odd =1 > >>>while odd <=100: > if (odd%2)==1: > print odd > odd = odd + 1 > ------------------------------------------------------------------------------------------------- > I get a list of the odd numbers from 1 to 99. But now if I wanted to add > those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should I > include? I have tried to add "odd + odd" but it did not work. In advance i can't help you with the cryptography stuff, but in cases like your example, i think reduce() might be useful, but your *specific* case can be handled with a 1-liner: >>> sum([x for x in range(100) if x % 2]) 2500 or the same using less memory in Python 2.4+: >>> sum(x for x in range(100) if x % 2) 2500 hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From andreas at kostyrka.org Thu Dec 14 07:21:44 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 14 Dec 2006 07:21:44 +0100 Subject: [Tutor] Starting over with Python In-Reply-To: References: Message-ID: <20061214062144.GH29195@andi-lap.la.revver.com> * John Carmona [061214 02:21]: > After quite a while away from Python, I have decided to re-study Python. I > am interested to learn Python to support my love for Cryptography. I have a > first very easy question (did some search on Google but could not find > anything helpful). I realise that this is very basic so be gentle with me. > > If i insert the following script: > > ------------------------------------------------------------------------------------------------- > odd =1 > >>>while odd <=100: > if (odd%2)==1: > print odd > odd = odd + 1 > ------------------------------------------------------------------------------------------------- > I get a list of the odd numbers from 1 to 99. But now if I wanted to add > those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should I > include? I have tried to add "odd + odd" but it did not work. In advance > thanks. > > If anyone could direct me to some site where python is associated with www.python.org has a nice tutorial in the documentation section if I remember right. Well it had it in the early 90s :) print range(1, 100, 2) print sum(range(1, 100, 2)) Andreas From rabidpoobear at gmail.com Thu Dec 14 08:27:50 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 14 Dec 2006 01:27:50 -0600 Subject: [Tutor] Starting over with Python In-Reply-To: References: Message-ID: <4580FCF6.3010604@gmail.com> John Carmona wrote: > After quite a while away from Python, I have decided to re-study Python. I > am interested to learn Python to support my love for Cryptography. I have a > first very easy question (did some search on Google but could not find > anything helpful). I realise that this is very basic so be gentle with me. > > If i insert the following script: > > ------------------------------------------------------------------------------------------------- > odd =1 > >>>> while odd <=100: >>>> > if (odd%2)==1: > print odd > odd = odd + 1 > ------------------------------------------------------------------------------------------------- > I get a list of the odd numbers from 1 to 99. But now if I wanted to add > those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should I > include? I have tried to add "odd + odd" but it did not work. In advance > thanks. > Odd is the variable you're iterating over. If you added odd+odd it would just do something weird, like counting 1 2 4 8 16 32 etc. Uh... What you need to do is have a separate variable that stores the sums and add to that each time. The problem is since you're iterating over odd, you're changing what the 'if (odd%2)' statement is seeing, if you change odd +1 to odd+odd. Hope that helps, -Luke > If anyone could direct me to some site where python is associated with > Cryptography I would be very grateful. Many thanks > JC > > _________________________________________________________________ > Be the first to hear what's new at MSN - sign up to our free newsletters! > http://www.msn.co.uk/newsletters > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jorgen.maillist at gmail.com Thu Dec 14 09:38:20 2006 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 14 Dec 2006 09:38:20 +0100 Subject: [Tutor] COM and Python Message-ID: <11e49df10612140038h5d470c32t80c23faead9154dc@mail.gmail.com> Hi All, I am investigating how to use Python and COM to provide a unit testing framework for our low level COM classes. All examples I see cover something like automation but I think my situation is a bit more different. For example, we have a COM class Called "Common" which has IPatient, IName etc interfaces. I used the COM makepy utility to generate a module from it, which returned with; >>> Generating to E:\Python24\lib\site-packages\win32com\gen_py\2DADCD20-D731-11D2-8E13-004095010EB1x0x1x0.py Building definitions from type library... Generating... Importing module Now I am lost. In Delphi I know I can do; var MyPatient : IPatient; MyPatient := CoPatient.Create; Which gives me a coclass instance of IPatient. How do I go about creating coclasses in Python given this example? With regards, - Jorgen From plorenz at mma.edu Thu Dec 14 17:38:12 2006 From: plorenz at mma.edu (Patrick Lorenz) Date: Thu, 14 Dec 2006 11:38:12 -0500 Subject: [Tutor] Tkinter ... deactivating a Text window when a radiobutton is chosen Message-ID: <45817DF4.4090408@mma.edu> I'd appreciate some help. I am just learning Tkinter, and want to deactivate a Text window when a certain radiobutton is selected. I cannot figure it out. I believe I need to reset the state option of the Text window to be 'disabled', but I'm not able to find a way to do it, even though I have tried different ways, including using the radiobutton command option, etc. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From alan.gauld at btinternet.com Thu Dec 14 19:00:36 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Dec 2006 18:00:36 -0000 Subject: [Tutor] Tkinter ... deactivating a Text window when a radiobuttonis chosen References: <45817DF4.4090408@mma.edu> Message-ID: "Patrick Lorenz" wrote in > I'd appreciate some help. I am just learning Tkinter, and want to > deactivate a Text window when a certain radiobutton is selected. I > cannot figure it out. In future its best if you post some code to show what you are attempting. Meanwhile this works for me: from Tkinter import * t = Tk() f = Frame(t) f.pack() T = Text(f, width=100, height=20) T.pack() def doit(): if T['state'] == DISABLED: T['state'] = NORMAL else: T['state'] = DISABLED b = Button(f, text='Toggle state', command = doit) b.pack() t.mainloop() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jameshcunningham at uky.edu Thu Dec 14 20:49:23 2006 From: jameshcunningham at uky.edu (James Cunningham) Date: Thu, 14 Dec 2006 14:49:23 -0500 Subject: [Tutor] Starting over with Python In-Reply-To: References: Message-ID: <9a5576390612141149q63aa42f9xbae8e1650024ffd2@mail.gmail.com> Sum works just fine, as others have said. A more generic way to do this: reduce(lambda x, y: x + y, (i for i in range(100) if i % 2)) Reduce iterates through the list, calling x + y on the next element in the list and the previous sum, in effect summing the whole thing. I might do the following: def reduce_list(list, operator): return reduce(lambda x, y: operator(x, y), list) reduce_list((i for i in range(100) if i % 2), int.__add__) reduce_list((i for i in range(100) if i % 2), int.__mul__) etc. best, james On 12/13/06, John Carmona wrote: > > After quite a while away from Python, I have decided to re-study Python. I > am interested to learn Python to support my love for Cryptography. I have > a > first very easy question (did some search on Google but could not find > anything helpful). I realise that this is very basic so be gentle with me. > > If i insert the following script: > > > ------------------------------------------------------------------------------------------------- > odd =1 > >>>while odd <=100: > if (odd%2)==1: > print odd > odd = odd + 1 > > ------------------------------------------------------------------------------------------------- > I get a list of the odd numbers from 1 to 99. But now if I wanted to add > those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should > I > include? I have tried to add "odd + odd" but it did not work. In advance > thanks. > > If anyone could direct me to some site where python is associated with > Cryptography I would be very grateful. Many thanks > JC > > _________________________________________________________________ > Be the first to hear what's new at MSN - sign up to our free newsletters! > http://www.msn.co.uk/newsletters > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061214/edf1e7e7/attachment.htm From rumpy at mrbitter.org Fri Dec 15 01:37:21 2006 From: rumpy at mrbitter.org (rumpy at mrbitter.org) Date: Thu, 14 Dec 2006 16:37:21 -0800 Subject: [Tutor] Noobie projects Message-ID: <20061214163721.4jc5awt96so8c8os@mrbitter.org> Hi Folks, I'm finishing up Magnus Heitland's Beginning Python Book. Two thumbs up btw. I quite liked it. However, the suggested projects, IMO, jump straight into topics a little over my head. I'm not feeling confident tacking the projects because so much of each project chapter delves into areas of expertise where I have limited knowledge. Is there a set of more basic projects for flexing one's novice Python skills? Regards, Rumpy. From niakmaheshwari at gmail.com Fri Dec 15 03:27:15 2006 From: niakmaheshwari at gmail.com (Archana Maheshwari) Date: Fri, 15 Dec 2006 07:57:15 +0530 Subject: [Tutor] Apology to all Message-ID: <9ae4fefd0612141827q7cd5e02ei3590a2a491686c59@mail.gmail.com> Dear all, I would like to apologize for showing bad manners in the forum of very educated and respected people. My first question to this forum was put in a very rude manner. I am a new comer in this forum and feel extremely sorry for my way of asking the question. Sorry to all, Archana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061215/9645f35d/attachment.html From alan.gauld at btinternet.com Fri Dec 15 09:35:56 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Dec 2006 08:35:56 -0000 Subject: [Tutor] Apology to all References: <9ae4fefd0612141827q7cd5e02ei3590a2a491686c59@mail.gmail.com> Message-ID: "Archana Maheshwari" wrote > I would like to apologize for showing bad manners in the forum of > very > educated and respected people. My first question to this forum was > put in a > very rude manner. Don't worry about it. It was not really rude, it was just a bit vague. The key to getting good answers is to ask good questions. One of the hallmarks of a good question is that it is specific. So the more specific your question the more chance of getting a useful answer. Also providing enough context is essential if you want to avoid very generic responses. If you are asking about code, show us the code. If you have an error send us the error text. > I am a new comer in this forum And very welcome. We look forward to any future questions :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From torhildrum at gmail.com Fri Dec 15 10:20:04 2006 From: torhildrum at gmail.com (Tor Hildrum) Date: Fri, 15 Dec 2006 10:20:04 +0100 Subject: [Tutor] Noobie projects In-Reply-To: <20061214163721.4jc5awt96so8c8os@mrbitter.org> References: <20061214163721.4jc5awt96so8c8os@mrbitter.org> Message-ID: On 12/15/06, rumpy at mrbitter.org wrote: > Is there a set of more basic projects for flexing one's novice Python skills? They key to finding a project is to find something you will enjoy doing. I used statistics to get to know Python. The code parsed some text, added some numbers, calculated various things. Very basic stuff, but it was a nice way to dip into Python while doing something I had to do. Other projects I did afterwards mostly consisted of fiddling around with text. Parsing, building new strings and outputting in a special format. Not sure if this helps, but that's how I started with Python :) Tor From kent37 at tds.net Fri Dec 15 12:06:43 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Dec 2006 06:06:43 -0500 Subject: [Tutor] Integer? In-Reply-To: <3cc822320612142207r23a437fctcfef9a020387909f@mail.gmail.com> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <457637D5.2040801@tds.net> <3cc822320612142207r23a437fctcfef9a020387909f@mail.gmail.com> Message-ID: <458281C3.9030402@tds.net> Eli Zabielski wrote: > Checking if a number is prime by deviding it by possible factors. If any > outcome is an integer, and it is not 1 or itself, it is prime. A better way to check for divisibility is to use the modulo operator % which gives the remainder when one number is divided by another. If a % b == 0 then b is a factor of a. Kent > > On 12/5/06, *Kent Johnson * > wrote: > > Eli Zabielski wrote: > > How can I check if a variable is an integer? > > Luke and John have answered your question, but we should also ask, why > do you want to do that? Explicit type testing is a code smell, perhaps > there is a better way to do what you want. > > Kent > > > > > -- > Eli Zabielski From cbc at unc.edu Fri Dec 15 15:37:33 2006 From: cbc at unc.edu (Chris Calloway) Date: Fri, 15 Dec 2006 09:37:33 -0500 Subject: [Tutor] Noobie projects Message-ID: <4582B32D.8030201@unc.edu> rumpy at mrbitter.org wrote: > Is there a set of more basic projects for flexing one's novice Python skills? Three python projects for noobs: http://www.handysoftware.com/cpif/ -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From gonzillaaa at gmail.com Fri Dec 15 16:24:11 2006 From: gonzillaaa at gmail.com (Gonzillaaa) Date: Fri, 15 Dec 2006 15:24:11 +0000 Subject: [Tutor] wrapping a command line tool Message-ID: Hello, I am using a command line tool that allows me to specify a serial port and either read from or write data to it. I would like to create a python module that wraps that functionality and allows me to manipulate the incoming data to present it in a table for instance (like top works) or maybe store it in a dictionary and drop it into a database at timed intervals. I am Python newbie so pointers to capture command line output and how to format it as a table for instance would be greatly appreciated. G. From mail at timgolden.me.uk Fri Dec 15 17:09:50 2006 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 15 Dec 2006 16:09:50 -0000 (GMT) Subject: [Tutor] wrapping a command line tool In-Reply-To: References: Message-ID: <60596.81.171.156.66.1166198990.squirrel@81.171.156.66> > I am using a command line tool that allows me to specify a serial > port and either read from or write data to it. I would like to create > a python module that wraps that functionality and allows me to > manipulate the incoming data to present it in a table for instance > (like top works) or maybe store it in a dictionary and drop it into a > database at timed intervals. Simplest (though not necessarily the most modern) way: import os data = os.popen ("do_thing.exe param1 param2").read () # # Do stuff with results according to need # Obviously how to format as a table depends largely on what the data looks like and what your intended display medium is. (PDF? HTML? console?) TJG From doug.shawhan at gmail.com Fri Dec 15 17:17:20 2006 From: doug.shawhan at gmail.com (doug shawhan) Date: Fri, 15 Dec 2006 10:17:20 -0600 Subject: [Tutor] wrapping a command line tool In-Reply-To: <60596.81.171.156.66.1166198990.squirrel@81.171.156.66> References: <60596.81.171.156.66.1166198990.squirrel@81.171.156.66> Message-ID: <5e1ceb8a0612150817i2a3d6c46ua1a09b60b422d30e@mail.gmail.com> Actually, I've had excellent results with pyserial. http://pyserial.sourceforge.net/ I've used it to write a screen-scraping tool. It comes with a little demo terminal program that shows many interesting ways to fiddle about with the module. I use it in conjunction with the wy60 emulator on OpenBSD to access an ancient SuperDOS system. On 12/15/06, Tim Golden wrote: > > > I am using a command line tool that allows me to specify a serial > > port and either read from or write data to it. I would like to create > > a python module that wraps that functionality and allows me to > > manipulate the incoming data to present it in a table for instance > > (like top works) or maybe store it in a dictionary and drop it into a > > database at timed intervals. > > Simplest (though not necessarily the most modern) way: > > > import os > > data = os.popen ("do_thing.exe param1 param2").read () > > # > # Do stuff with results according to need > # > > > Obviously how to format as a table depends > largely on what the data looks like and what > your intended display medium is. (PDF? HTML? > console?) > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061215/cf054f6b/attachment.html From kent37 at tds.net Fri Dec 15 17:21:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Dec 2006 11:21:15 -0500 Subject: [Tutor] wrapping a command line tool In-Reply-To: References: Message-ID: <4582CB7B.6040002@tds.net> Gonzillaaa wrote: > Hello, > > I am using a command line tool that allows me to specify a serial > port and either read from or write data to it. I would like to create > a python module that wraps that functionality and allows me to > manipulate the incoming data to present it in a table for instance > (like top works) or maybe store it in a dictionary and drop it into a > database at timed intervals. > > I am Python newbie so pointers to capture command line output and how > to format it as a table for instance would be greatly appreciated. If you are using a command-line tool that expects user input then I think you need something like pexpect, however pexpect requires the pty module which doesn't work on Windows so that may be a problem for you. http://pexpect.sourceforge.net/ I suggest that a better approach might be to use pyserial which is intended to give access to the serial port directly from Python and runs on Windows, Linux and MacOSX. http://pyserial.sourceforge.net/ Kent From bgailer at alum.rpi.edu Fri Dec 15 20:15:29 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 15 Dec 2006 11:15:29 -0800 Subject: [Tutor] Integer? In-Reply-To: <458281C3.9030402@tds.net> References: <3cc822320612051720x6a28c433ia22ad8bf36c90d33@mail.gmail.com> <457637D5.2040801@tds.net> <3cc822320612142207r23a437fctcfef9a020387909f@mail.gmail.com> <458281C3.9030402@tds.net> Message-ID: <4582F451.8020404@alum.rpi.edu> Kent Johnson wrote: > A better way to check for divisibility is to use the modulo operator % > which gives the remainder when one number is divided by another. Only when the left argument is positive does it give the remainder. The manual is in error when it says remainder, but the algorithm it gives is correct. > If a % > b == 0 then b is a factor of a. > > Kent > > >> On 12/5/06, *Kent Johnson * > wrote: >> >> Eli Zabielski wrote: >> > How can I check if a variable is an integer? >> >> Luke and John have answered your question, but we should also ask, why >> do you want to do that? Explicit type testing is a code smell, perhaps >> there is a better way to do what you want. >> >> Kent >> >> >> >> >> -- >> Eli Zabielski >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From lavendula6654 at yahoo.com Fri Dec 15 21:13:22 2006 From: lavendula6654 at yahoo.com (Elaine) Date: Fri, 15 Dec 2006 12:13:22 -0800 (PST) Subject: [Tutor] Python Course starting in January 2007 Message-ID: <302568.46036.qm@web31712.mail.mud.yahoo.com> If you would like to learn Python, Foothill College is offering a course starting Wednesday evening, 10 January 2007, at the Middlefield campus on the corner of San Antonio and Middlefield Road in south Palo Alto. Note that this location is only 1.5 miles from Google in Mountain View. The course is designed for students who are already familiar with some type of programming. Here is the course description: CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 Units This course will introduce students to the Python language and environment. Python is a portable, interpreted, object-oriented programming language that is often compared to Perl, Java, Scheme and Tcl. The language has an elegant syntax, dynamic typing, and a small number of powerful, high-level data types. It also has modules, classes, and exceptions. The modules provide interfaces to many system calls and libraries, as well as to various windowing systems(X11, Motif, Tk, Mac, MFC). New built-in modules are easily written in C or C++. Such extension modules can define new functions and variables as well as new object types. Four hours lecture, four hours terminal time. Advisory: CIS 15A or 27A, and CIS 68A. 2182 CIS -068K-01 LEC6:00PM- 9:50W HAIGHT MC I2 CIS - If you would like to sign up for the class, please register beforehand by going to: http://www.foothill.fhda.edu/reg/index.php If you have questions, you can contact the instructor at: haightElaine at foothill.edu __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From python-tutor at ccoker.net Fri Dec 15 21:39:38 2006 From: python-tutor at ccoker.net (Chuck Coker) Date: Fri, 15 Dec 2006 12:39:38 -0800 Subject: [Tutor] Starting over with Python In-Reply-To: References: Message-ID: <4583080A.9070405@ccoker.net> JC> If anyone could direct me to some site where python is associated JC> with Cryptography I would be very grateful. John, I did a quick Google search using +"python" +"cryptography" as the search term and Google reported Results 1 - 10 of about 1,030,000 for +"python" +"cryptography". (0.09 seconds) Chuck -- ====================================================================== Chuck Coker, Software Developer python-tutor at ccoker.net Tyrell Software Corporation http://www.tyrell.com Office: +1 949 458 1911 x 203 Cell: +1 714 326 5939 ====================================================================== From kent37 at tds.net Fri Dec 15 22:49:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Dec 2006 16:49:48 -0500 Subject: [Tutor] wrapping a command line tool In-Reply-To: References: <4582CB7B.6040002@tds.net> Message-ID: <4583187C.2080107@tds.net> Gonzillaaa wrote: > Tanks for the suggestions Kent, windows compatibility is not much of > an issue, but dependencies are. the reason why I'm using a command > line tool written in C is because pyserial depends on JavaComm or > that seems to be implied on their website, I haven't actually tested. > > so I wanted a python wrapper to extend the functionality without much > more needed. Although for things like db logging I'll have to use > another module... I think you may have misread the website, it says, "The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (win32all) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)." So if you are using CPython (the regular Python distribution, as opposed to Jython) and you are not on Windows, you should be all set with just pyserial. Kent PS Please reply on the list From andrew.arobert at gmail.com Sat Dec 16 00:25:00 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Fri, 15 Dec 2006 18:25:00 -0500 Subject: [Tutor] pysvn samples In-Reply-To: <302568.46036.qm@web31712.mail.mud.yahoo.com> References: <302568.46036.qm@web31712.mail.mud.yahoo.com> Message-ID: <45832ECC.3020307@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi guys, I am looking to experiment with pysvn and was wondering if anyone knew of a location for code samples/snippets using it? I'm reviewing the pysvn programmers guide and tutorial but some live examples would be great. If anyone can point me at something, it would be appreciated. Thanks, Andy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (MingW32) iD8DBQFFgy7MDvn/4H0LjDwRAmUeAKCRa7qfTx0g3TwPtLL4PxWxlfeZrwCgrEBI RjJI2onZj/WnLx4FLWoRkIE= =oJnx -----END PGP SIGNATURE----- From pyro9219 at gmail.com Sat Dec 16 01:14:41 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 15 Dec 2006 16:14:41 -0800 Subject: [Tutor] Best method for filtering lists in lists... Message-ID: I've got a list of lists that looks like this [[1,2,3], [4,5,6],[1,2,3]] I'm looking for a good way to drop the redundant inner lists (thousands of inner lists) Someone either have a good way to tackle this? or willing to point me in the right direction? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061215/b613e50a/attachment.html From rabidpoobear at gmail.com Sat Dec 16 02:04:24 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 15 Dec 2006 19:04:24 -0600 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: References: Message-ID: <45834618.9070901@gmail.com> Chris Hengge wrote: > I've got a list of lists that looks like this > > [[1,2,3], [4,5,6],[1,2,3]] > > I'm looking for a good way to drop the redundant inner lists > (thousands of inner lists) > > Someone either have a good way to tackle this? or willing to point me > in the right direction? > > Thanks! > Didn't we give multiple solutions to a similar problem with lists with redundant elements a few weeks ago? Well, the solutions will be the same, regardless that the elements inside are lists themselves. HTH, -Luke From rabidpoobear at gmail.com Sat Dec 16 02:21:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 15 Dec 2006 19:21:37 -0600 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: References: <45834618.9070901@gmail.com> Message-ID: <45834A21.4090800@gmail.com> Chris Hengge wrote: > Yes, we went over that a bit ago, but I wasn't sure if there were any > different or more appropriate approaches to this when dealing with > multidimensional lists. > Well, it depends what you term a redundant list. Like, is [[1,2,3],[3,2,1]] a list with 1 unique elements or two? If it is 1, then just sort all the lists before you check for redundancy. I don't think there are any algorithms that are specific to lists of lists, though there may be. -Luke P.S. please reply on-list :) > > On 12/15/06, *Luke Paireepinart* > wrote: > > Chris Hengge wrote: > > I've got a list of lists that looks like this > > > > [[1,2,3], [4,5,6],[1,2,3]] > > > > I'm looking for a good way to drop the redundant inner lists > > (thousands of inner lists) > > > > Someone either have a good way to tackle this? or willing to > point me > > in the right direction? > > > > Thanks! > > > Didn't we give multiple solutions to a similar problem with lists > with > redundant elements a few weeks ago? > Well, the solutions will be the same, regardless that the elements > inside are lists themselves. > > HTH, > -Luke > > From pyro9219 at gmail.com Sat Dec 16 02:28:20 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 15 Dec 2006 17:28:20 -0800 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: <45834A21.4090800@gmail.com> References: <45834618.9070901@gmail.com> <45834A21.4090800@gmail.com> Message-ID: Oops, sorry about not replying to the list. I must have hit the wrong button. I'm terming a redundant list just like I posted in the original message: [[1,2,3], [4,5,6],[1,2,3]] [0][0] and [0][2] are redundant, so I only want to keep one of them. Thanks again Luke. On 12/15/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > Yes, we went over that a bit ago, but I wasn't sure if there were any > > different or more appropriate approaches to this when dealing with > > multidimensional lists. > > > Well, it depends what you term a redundant list. > Like, is > [[1,2,3],[3,2,1]] > a list with 1 unique elements or two? > > If it is 1, then just sort all the lists before you check for redundancy. > > I don't think there are any algorithms that are specific to lists of > lists, though there may be. > -Luke > > P.S. please reply on-list :) > > > > On 12/15/06, *Luke Paireepinart* > > wrote: > > > > Chris Hengge wrote: > > > I've got a list of lists that looks like this > > > > > > [[1,2,3], [4,5,6],[1,2,3]] > > > > > > I'm looking for a good way to drop the redundant inner lists > > > (thousands of inner lists) > > > > > > Someone either have a good way to tackle this? or willing to > > point me > > > in the right direction? > > > > > > Thanks! > > > > > Didn't we give multiple solutions to a similar problem with lists > > with > > redundant elements a few weeks ago? > > Well, the solutions will be the same, regardless that the elements > > inside are lists themselves. > > > > HTH, > > -Luke > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061215/afd6ecba/attachment.htm From alan.gauld at btinternet.com Sat Dec 16 02:40:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Dec 2006 01:40:09 -0000 Subject: [Tutor] Best method for filtering lists in lists... References: <45834618.9070901@gmail.com><45834A21.4090800@gmail.com> Message-ID: "Chris Hengge" wrote > I'm terming a redundant list just like I posted in the original > message: > [[1,2,3], [4,5,6],[1,2,3]] > > [0][0] and [0][2] are redundant, so I only want to keep one of them. In that case put the inner lists in a Set. That will eliminate duplicates. I actually read you intial post as meaning you wanted to flatten the list, as in [1,2,3,4,5,6,1,2,3,....] Just as well you clarified! :-) Alan G. From rschroev_nospam_ml at fastmail.fm Sat Dec 16 11:54:09 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 16 Dec 2006 11:54:09 +0100 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: References: <45834618.9070901@gmail.com><45834A21.4090800@gmail.com> Message-ID: Alan Gauld schreef: > "Chris Hengge" wrote > >> I'm terming a redundant list just like I posted in the original >> message: >> [[1,2,3], [4,5,6],[1,2,3]] >> >> [0][0] and [0][2] are redundant, so I only want to keep one of them. > > In that case put the inner lists in a Set. That will eliminate > duplicates. That won't work: list objects are unhashable so you can't put them in a set. You'll have to convert them to tuples first. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rabidpoobear at gmail.com Sat Dec 16 18:01:53 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 16 Dec 2006 11:01:53 -0600 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: References: <45834618.9070901@gmail.com><45834A21.4090800@gmail.com> Message-ID: <45842681.6070907@gmail.com> Roel Schroeven wrote: > Alan Gauld schreef: > >> "Chris Hengge" wrote >> >> >>> I'm terming a redundant list just like I posted in the original >>> message: >>> [[1,2,3], [4,5,6],[1,2,3]] >>> >>> [0][0] and [0][2] are redundant, so I only want to keep one of them. >>> >> In that case put the inner lists in a Set. That will eliminate >> duplicates. >> > > That won't work: list objects are unhashable so you can't put them in a > set. You'll have to convert them to tuples first. > > Ooh.... The plot thickens... surely there's a faster way than casting them all as tuples, generating a set, and then casting them all back to lists? Or perhaps Chris can just keep them as tuples? From billburns at pennswoods.net Sat Dec 16 20:20:52 2006 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 16 Dec 2006 14:20:52 -0500 Subject: [Tutor] pysvn samples In-Reply-To: <45832ECC.3020307@gmail.com> References: <302568.46036.qm@web31712.mail.mud.yahoo.com> <45832ECC.3020307@gmail.com> Message-ID: <45844714.2030803@pennswoods.net> > I am looking to experiment with pysvn and was wondering if anyone knew > of a location for code samples/snippets using it? > > I'm reviewing the pysvn programmers guide and tutorial but some live > examples would be great. > > If anyone can point me at something, it would be appreciated. > Hi Andy, Here's some examples, which are not very elaborate, but I use them frequently (most of them you can get out of the programmer's guide). I'm using Windows and I have a 'working copy' checked out into the directory 'C:\dist'. import pysvn client = pysvn.Client() # Updates my working copy. client.update(r'C:\dist') # Maybe just get the revision number? rev = client.info(r'C:\dist').revision.number print rev # Commit or checkin some changes. client.checkin(r'C:\dist', 'A log message goes here') # Do a checkout from a local repos. Note: if some_dir # does not exist, it will be created. 'C:\svn\FilePrinter' # is a repos of mine, substitute your own ;-) client.checkout('file:///C:/svn/FilePrinter', r'C:\some_dir') # Do a checkout from a remote repos. client.checkout('http://svn.pybrary.net', r'C:\pyPDF') And you can also fire up the interpreter and do things like: >>> import pysvn >>> pysvn.version # get the pysvn version (1, 5, 0, 742) >>> pysvn.svn_version # get your Subversion version (1, 4, 0, '') >>> help(pysvn.Client().checkout) # get some help on checkout There's also several pysvn mailing lists http://pysvn.tigris.org/servlets/ProjectMailingListList and five (5) pages of hits from 'Google Code Search'... HTH, Bill From alan.gauld at btinternet.com Sun Dec 17 01:00:54 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Dec 2006 00:00:54 -0000 Subject: [Tutor] Best method for filtering lists in lists... References: <45834618.9070901@gmail.com><45834A21.4090800@gmail.com> Message-ID: "Roel Schroeven" wrote >> In that case put the inner lists in a Set. That will eliminate >> duplicates. > > That won't work: list objects are unhashable so you can't put them > in a > set. You'll have to convert them to tuples first. Hmm, I took that a self evident but I guess maybe it wasn't... As for Luke's point about the speed of conversion, I'm not sure how that would stack up. I have a gut feel that it might be faster than trying to compare the lists element by element, that sounds like an algebraic expansion with list size to me, a hashed set sounds like it should be faster. But as with all such things, if speed matters: measure and profile it. Alan G. From taserian at gmail.com Sun Dec 17 13:52:54 2006 From: taserian at gmail.com (Antonio Rodriguez) Date: Sun, 17 Dec 2006 12:52:54 +0000 (UTC) Subject: [Tutor] Splitting a file Message-ID: I'm attempting to split a binary file into 5 component files, as a "challenge". I thought that the following would work: f = open('/home/taser/Desktop/inputfile.bin') f1 = [] f2 = [] f3 = [] f4 = [] f5 = [] while 1: try: bytes = list(f.read(5)) f1.append(bytes[0]) f2.append(bytes[1]) f3.append(bytes[2]) f4.append(bytes[3]) f5.append(bytes[4]) except: break ff1 = open('/home/taser/Desktop/ff1.file','w') ff1.write(''.join(f1)) ff1.close() I've only dealt with one of the lists, since I want to test it before doing the rest. I'm unsure if I'm going about this correctly, since I'm manipulating binary data as if it were a text file. Also, I'm told that I should be able to have Python itself determine the type of file it is, since the file contains a "magic number". However, I haven't had any luck in my searches for how to do that in Python. Any help would be appreciated. From kent37 at tds.net Sun Dec 17 14:10:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Dec 2006 08:10:55 -0500 Subject: [Tutor] Splitting a file In-Reply-To: References: Message-ID: <458541DF.9080306@tds.net> Antonio Rodriguez wrote: > I'm attempting to split a binary file into 5 component files, as a > "challenge". I thought that the following would work: > > f = open('/home/taser/Desktop/inputfile.bin') > f1 = [] > f2 = [] > f3 = [] > f4 = [] > f5 = [] > while 1: > try: > bytes = list(f.read(5)) > f1.append(bytes[0]) > f2.append(bytes[1]) > f3.append(bytes[2]) > f4.append(bytes[3]) > f5.append(bytes[4]) > except: > break > ff1 = open('/home/taser/Desktop/ff1.file','w') > ff1.write(''.join(f1)) > ff1.close() > > I've only dealt with one of the lists, since I want to test it before > doing the rest. > > I'm unsure if I'm going about this correctly, since I'm manipulating > binary data as if it were a text file. You should read and write the file in binary mode or you will corrupt the data: f = open('/home/taser/Desktop/inputfile.bin', 'rb') ff1 = open('/home/taser/Desktop/ff1.file','wb') Kent From ajkadri at googlemail.com Sun Dec 17 20:58:00 2006 From: ajkadri at googlemail.com (Asrarahmed Kadri) Date: Sun, 17 Dec 2006 19:58:00 +0000 Subject: [Tutor] Question about exception handling Message-ID: Hi Folks, Is it possible to catch exception raised in module A to be caught in module B. If yes, then please let me know how to do it. TIA. Regards, Asrarahmed Kadri -- To HIM you shall return. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061217/75ee1f27/attachment.htm From adam.jtm30 at gmail.com Sun Dec 17 21:04:08 2006 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 17 Dec 2006 20:04:08 +0000 Subject: [Tutor] Question about exception handling In-Reply-To: References: Message-ID: On 17/12/06, Asrarahmed Kadri wrote: > > > Hi Folks, > > Is it possible to catch exception raised in module A to be caught in > module B. > > If yes, then please let me know how to do it. You can easily test this yourself. First right a quick module, something like this will do: def exception_test(): raise Exception then start an interpreter and do the following >>> import your_module >>> try: ... your_module.exception_test() ... except: ... print "Caught it!" ... HTH, Adam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061217/64698fc2/attachment.html From stefan.heyne at epfl.ch Mon Dec 18 09:00:52 2006 From: stefan.heyne at epfl.ch (Stefan Heyne) Date: Mon, 18 Dec 2006 09:00:52 +0100 Subject: [Tutor] Problems writing data into a file Message-ID: <45864AB4.8070800@epfl.ch> Hi there, I am newby to python and have some problems getting data into a file.... I am using python to extract data from a database but currently i only get it to print the data on the screen so I have to copy/paste it into a file later on. There for sure is a way to do that but I couldn't figure out how to....the commented lines show my trials that did not really work :-P...... Any help appreciated....thanks in advance! Stefan for x in range(1,226): # g=open('output', 'w') y1=m.extract('TEMP',32, 1131, component='1', cycle=x, subcycle=1) y2=m.extract('PRES',32, 1131, component='1', cycle=x, subcycle=1) # testout = (x,y1,y2,'\n') # line = str(testout) # g.write(line) print x,y1,y2 # g.close() -- ************************************************ Stefan Heyne Laboratoire d'Energ?tique Industrielle - http://leni.epfl.ch t?l. +41-21-693 3513 fax +41-21-693 3502 email: stefan.heyne at epfl.ch Bureau: ME A2.394 - http://plan.epfl.ch/index.html?room=mea2394 Adresse postale: EPFL, STI-ISE-LENI ME A2.394 (B?timent ME) Station 9 CH-1015 Lausanne ************************************************ From rabidpoobear at gmail.com Mon Dec 18 09:13:49 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 18 Dec 2006 02:13:49 -0600 Subject: [Tutor] Problems writing data into a file In-Reply-To: <45864AB4.8070800@epfl.ch> References: <45864AB4.8070800@epfl.ch> Message-ID: <45864DBD.3050600@gmail.com> > for x in range(1,226): > # g=open('output', 'w') > y1=m.extract('TEMP',32, 1131, component='1', cycle=x, subcycle=1) > y2=m.extract('PRES',32, 1131, component='1', cycle=x, subcycle=1) > # testout = (x,y1,y2,'\n') > # line = str(testout) > # g.write(line) > print x,y1,y2 > # g.close() > You're opening the same file, 'output', 225 times and overwriting the contents each time. the write method of file access erases its previous contents. you should use a variable for the filename, I.E. g = open('output%i' % x, 'w') which will open output1, output2, output3, etc... for each time through the loop, or you should open the file before the loop begins and only have writes inside the loop. Then you can close the file after the loop exits. HTH, -Luke From stefan.heyne at epfl.ch Mon Dec 18 09:50:16 2006 From: stefan.heyne at epfl.ch (Stefan Heyne) Date: Mon, 18 Dec 2006 09:50:16 +0100 Subject: [Tutor] [Fwd: Re: Problems writing data into a file] Message-ID: <45865648.6080703@epfl.ch> OK, thanks....no I get the data into a file output..but I still am stuck with the formatting... 1) there are brackets around the data that are due to the necessary (??) conversion to a string 2) I cannot figure out how to insert a newline command.... Here's the code: g=open('output.txt', 'w') for x in range(1,226): y1=m.extract('TEMP',32, 1131, component='1', cycle=x, subcycle=1) y2=m.extract('PRES',32, 1131, component='1', cycle=x, subcycle=1) testline = x,y1,y2 line = str(testline) g.write(line) g.close() And here an extract of the output: (1, [458.35813161745779], [112712.77970477825])(2, [457.03731677841921], [113061.80332906457])(3, [458.24706379677764], [112931.83711259064])(4, [460.89541534790976], [112584.88323863815]) What I would like: 1, [458.35813161745779], [112712.77970477825] 2, [457.03731677841921], [113061.80332906457] 3, [458.24706379677764], [112931.83711259064] 4, [460.89541534790976], [112584.88323863815] ... Thanks in advance, Stefan -------- Original Message -------- Subject: Re: [Tutor] Problems writing data into a file Date: Mon, 18 Dec 2006 02:13:49 -0600 From: Luke Paireepinart To: Stefan Heyne CC: tutor at python.org References: <45864AB4.8070800 at epfl.ch> > for x in range(1,226): > # g=open('output', 'w') > y1=m.extract('TEMP',32, 1131, component='1', cycle=x, subcycle=1) > y2=m.extract('PRES',32, 1131, component='1', cycle=x, subcycle=1) > # testout = (x,y1,y2,'\n') > # line = str(testout) > # g.write(line) > print x,y1,y2 > # g.close() > You're opening the same file, 'output', 225 times and overwriting the contents each time. the write method of file access erases its previous contents. you should use a variable for the filename, I.E. g = open('output%i' % x, 'w') which will open output1, output2, output3, etc... for each time through the loop, or you should open the file before the loop begins and only have writes inside the loop. Then you can close the file after the loop exits. HTH, -Luke -- ************************************************ Stefan Heyne Laboratoire d'Energ?tique Industrielle - http://leni.epfl.ch t?l. +41-21-693 3513 fax +41-21-693 3502 email: stefan.heyne at epfl.ch Bureau: ME A2.394 - http://plan.epfl.ch/index.html?room=mea2394 Adresse postale: EPFL, STI-ISE-LENI ME A2.394 (B?timent ME) Station 9 CH-1015 Lausanne ************************************************ From andreas at kostyrka.org Mon Dec 18 12:17:09 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 18 Dec 2006 12:17:09 +0100 Subject: [Tutor] [Fwd: Re: Problems writing data into a file] In-Reply-To: <45865648.6080703@epfl.ch> References: <45865648.6080703@epfl.ch> Message-ID: <20061218111708.GN29195@andi-lap.la.revver.com> * Stefan Heyne [061218 09:51]: > OK, thanks....no I get the data into a file output..but I still am stuck > with the formatting... > 1) there are brackets around the data that are due to the necessary (??) > conversion to a string > 2) I cannot figure out how to insert a newline command.... line = "%s, [%s], [%s]\n" % (testline) Andreas From bashu at yandex.ru Mon Dec 18 14:59:44 2006 From: bashu at yandex.ru (Basil Shubin) Date: Mon, 18 Dec 2006 19:59:44 +0600 Subject: [Tutor] MVC/MVP examples of how to implement it Message-ID: Hi friends! I have read articles about MVC/MVP, but still can't get a clue to how implement it in really working application :-( Because I better understand with ready to use examples, can you provide link to free python+GUI application which implements MVC/MVP design? Thanks! From nospamformeSVP at gmail.com Mon Dec 18 17:47:32 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Mon, 18 Dec 2006 11:47:32 -0500 Subject: [Tutor] Data hiding in Python. Message-ID: I am working my way through 'wxPython in Action' by Noel Rappin and Robin Dunn and came across this comment about data hiding in their explanation of the MVC pattern: ".. the View... should never get to see the private internals of the Model. Admittedly, this is difficult to enforce in Python, but one way to help enforcement it is to create an abstract Model class that defines the API that the View can see. Subclasses of the Model can either act as proxies for an internal class that can be changed, or can simply contain the internal workings themselves. The first option is more structured, the second easier to implement." I like the idea of data hiding but Googling 'Python data hiding' yields lots of discussion to the effect that it cannot/should not be done. So what do the authors mean? They do not give any examples of this technique (at least not so far as I have read in the book) so I have been trying to figure something out. And then, is it worth the trouble? Any suggestions? Preferably with code fragments. Here is what I have got so far: A calling module: -caller.py--------------------------------------------------------------------- import model if __name__ == '__main__': model.methodA() # test a method call interface testInstance = model.TestClass() #test a class generation interface testInstance.methodB() # test a method call within the new class ------------------------------------------------------------------------------- The actual model module, which does not contain any (or much) implementation code: -model.py---------------------------------------------------------------------- import innermodel __implementation = innermodel.Implementation() def methodA(): "Example of a method interface." __implementation.methodA() def TestClass(): "Example of a class interface." return __implementation.TestClass() ------------------------------------------------------------------------------- and then the actual implementation code: -innermodel.py----------------------------------------------------------------- class Implementation: def __init__(self): print "Implementation initializing..." def methodA(self): print "Implementation methodA called." class TestClass: def __init__(self): print "TestClass initializing..." def methodB(self): print "TestClass methodB called." ------------------------------------------------------------------------------- I am not sure if this is what they mean, and if so which is this - a proxy for an internal class that can be changed, or does it simply contain the internal workings. It seems to provide some degree of data hiding, but perhaps too much? You cannot figure out from the model.py file what are the available methods for the TestClass class. I guess that these could be documented in the TestClass docstring. Don. From alan.gauld at btinternet.com Tue Dec 19 01:33:10 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Dec 2006 00:33:10 -0000 Subject: [Tutor] MVC/MVP examples of how to implement it References: Message-ID: "Basil Shubin" wrote > I have read articles about MVC/MVP, but still can't get a clue to > how > implement it in really working application Look at TurboGears. It uses a model/view/controller setup. In TG the views are implemented as kid templates (a mixture of HTML and embedded python-like markup) The models are Python classes linked to SQLObject database tables The controllers are the functions called prior to loading a web page, they get their input from the previous pages POST or GET messages. Thats a web version but it seems to work. For a more traditional example I don;t know of any Python GUI toolkits that explicitly support MVC, although a model/view paradigm is easily implemented. Controllers tend to be more tricky and require rigorous adherence to a style convention for handling events. Dolphin Smalltalk implements an MVC style and has a fairly readable tutorial here, provided youi can grok the Smalltalk syntax: http://www.object-arts.com/docs/index.html?modelviewpresenter.htm But since you mention MVP you have maybe already been there! The other good explanaytion that I know is the one by Apple for their Cocoa framework on MacOS X - also programmable in Python! Described here: http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/chapter_5_section_4.html And finally, a python example: http://www.bigbold.com/snippets/posts/show/1050 But I actually don't like this one since it puts too mucxh code in the controller. Controllers should be lightweight objects with most of the real processing happening in the models. The controllers should just collect data changes from the views and send them to the models or vice-versa. Bad MVC turns the controller into a kind of huge monolithioc procedural program that occasionally fetches data from models and displays on the views. Thats the best I can do. Maybe others can find better examples. BTW there is an OO school of thought that says controllers in MVC are basically a bad idea and a Model/View paradigm is better. In this case the View handles the interaction with the user and sends messages to the models. This is how most Windows applications are programmed in VB/Visual C++ etc. It's certainly easier to implement, but probably less reusable in the long run. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From chris.arndt at web.de Tue Dec 19 01:57:32 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Tue, 19 Dec 2006 01:57:32 +0100 Subject: [Tutor] MVC/MVP examples of how to implement it In-Reply-To: References: Message-ID: <458738FC.2@web.de> Basil Shubin schrieb: > I have read articles about MVC/MVP, but still can't get a clue to how > implement it in really working application :-( Because I better > understand with ready to use examples, can you provide link to free > python+GUI application which implements MVC/MVP design? The MVC pattern is especially useful in game programming, since the user is not the only controller influencing the program flow, there's also the non-player entities (i.e. "enemies") that react with the game world. I found the following tutorial (although it's still unfinished) for pygame very helpful: http://sjbrown.ezide.com/games/writing-games.html Chris From nospamformeSVP at gmail.com Tue Dec 19 02:11:26 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Mon, 18 Dec 2006 20:11:26 -0500 Subject: [Tutor] MVC/MVP examples of how to implement it In-Reply-To: References: Message-ID: Basil Shubin wrote: > Hi friends! > > I have read articles about MVC/MVP, but still can't get a clue to how > implement it in really working application :-( Because I better > understand with ready to use examples, can you provide link to free > python+GUI application which implements MVC/MVP design? > This is the best description - by far - that I have seen for the MVC pattern. http://groups.google.ca/group/comp.lang.python/msg/f8990a2c666a793c?hl=en& Don. From alan.gauld at btinternet.com Tue Dec 19 11:39:12 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Dec 2006 10:39:12 -0000 Subject: [Tutor] MVC/MVP examples of how to implement it References: Message-ID: "Don Taylor" wrote in >> > This is the best description - by far - that I have seen for the MVC > pattern. > > http://groups.google.ca/group/comp.lang.python/msg/f8990a2c666a793c?hl=en& > You are right, that's a very good description, especially given it's all text and no diagrams to help! However it is a slightly blinkered picture of MVC and not totally accurate in that some MVC implementations do allow the model to talk to controllers/views. eg. The original Smalltalk MVC had a concept of pluggable controllers whereby the controller had to fit a standard protocol and models therefore knew what messages to send. And thus multiple controllers could be connected to a single view or model, as well as multiple views per model. Others broadcast changes to a list of associated views, again via a standard protocol. More modern implementations tend to use the publish./subscribe notification technique referred to in the last few paragraphs of the article. But MVC is not a single solution and any description will be flawed with regard to some implementation or other. So long as you are aware that differences exist (and are not "wrong" just because they are different) then the article is excellent. Alan G From nospamformeSVP at gmail.com Tue Dec 19 15:40:26 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Tue, 19 Dec 2006 09:40:26 -0500 Subject: [Tutor] MVC/MVP examples of how to implement it In-Reply-To: References: Message-ID: Basil Shubin wrote: > Hi friends! > > I have read articles about MVC/MVP, but still can't get a clue to how > implement it in really working application :-( Because I better > understand with ready to use examples, can you provide link to free > python+GUI application which implements MVC/MVP design? > Here is another example of MVP in Python/wxPython. http://wiki.wxpython.org/index.cgi/ModelViewPresenter Don. From bizag007 at yahoo.com Tue Dec 19 16:11:45 2006 From: bizag007 at yahoo.com (ray sa) Date: Tue, 19 Dec 2006 07:11:45 -0800 (PST) Subject: [Tutor] Ftp files Message-ID: <20061219151146.90424.qmail@web31208.mail.mud.yahoo.com> Hi I have just started to learn Python and think it is a superb language. I am faced with an issue that I would like some help with. I need to fetch files on a daliy basis from a unix machine. I would like to run a batch command for this. I would also like to automate this task. The files are stored on the unix box; are hourly files with date and time as the file name. What I would like to do is log in to the relevant directory and fetch the files for that day. I have managed to log in to the ftp site and navigate to the directory where the files are. I have also used the following command to look for a particular day: dateMatch = str(localtime()[0])+str(localtime()[1])+str(localtime()[2]) This will give me the date portion of the string to search in the file name using: re.search(dateMatch,filename) I am now stuck on how to use the files = listdir(pathName) to get a list of the files and by using the following code: for i in files: matchFile = search(dateMatch,i) if matchFile: get the file What I would like to know is how to get the file using ftplib functions. Your expert advice would be very helpful. Please feel free to suggest some code and an explanation... I need help on the following: -How to get a function to return a list of the files on the directory -Using this list I should be able to use the for loop to match the date case and - fetch the files using the get command. How to use the get command to fetch the files in the list prevously where the match was found and store this in my local directory? - Also how to run this python file daily automatically? Looking forward to you responses.. BR Ray __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061219/c20a038e/attachment.htm From python at venix.com Tue Dec 19 17:49:23 2006 From: python at venix.com (Python) Date: Tue, 19 Dec 2006 11:49:23 -0500 Subject: [Tutor] Ftp files In-Reply-To: <20061219151146.90424.qmail@web31208.mail.mud.yahoo.com> References: <20061219151146.90424.qmail@web31208.mail.mud.yahoo.com> Message-ID: <1166546963.12468.185.camel@www.venix.com> On Tue, 2006-12-19 at 07:11 -0800, ray sa wrote: > Hi > > I have just started to learn Python and think it is a superb language. > I am faced with an issue that I would like some help with. I need to > fetch files on a daliy basis from a unix machine. I would like to run > a batch command for this. I would also like to automate this task. The > files are stored on the unix box; are hourly files with date and time > as the file name. What I would like to do is log in to the relevant > directory and fetch the files for that day. I have managed to log in > to the ftp site and navigate to the directory where the files are. I > have also used the following command to look for a particular day: > > dateMatch = str(localtime()[0])+str(localtime()[1])+str(localtime > ()[2]) > > This will give me the date portion of the string to search in the file > name using: > > re.search(dateMatch,filename) > > I am now stuck on how to use the > > files = listdir(pathName) > > to get a list of the files and by using the following code: > > for i in files: > matchFile = search(dateMatch,i) > if matchFile: > get the file > > What I would like to know is how to get the file using ftplib > functions. Your expert advice would be very helpful. Please feel free > to suggest some code and an explanation... > > I need help on the following: > > -How to get a function to return a list of the files on the directory session = ftplib.FTP("ftpservername") session.login() # supply credentials session.set_pasv(1) # may not be necessary for you file_list = session.nlst() > -Using this list I should be able to use the for loop to match the > date case and > - fetch the files using the get command. How to use the get command to > fetch the files in the list prevously where the match was found and > store this in my local directory? for f in file_list: # YOU WILL NEED TO ADD YOUR MATCH LOGIC session.voidcmd("TYPE I") # binary transfer size = session.size( f) outname = "download.tmp" outfile = file(outname,"wb") session.retrbinary("RETR " + f, outfile.write) outfile.close() mode,ino,dev,nlink,uid,gid,fsize,atime,mtime,ctime = os.stat(outname) if size == fsize: shutil.copy(outname, f) else: # error handling goes here Checking the size may be overkill for your needs. > - Also how to run this python file daily automatically? Use a cron job to set this up details. Exact details depend on your flavor of Unix. > > Looking forward to you responses.. > You would almost certainly be better off using SSH (Secure Shell), public keys, and rsync to do this kind of processing. > BR > > Ray > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From martin.marcher at openforce.com Tue Dec 19 18:36:15 2006 From: martin.marcher at openforce.com (Martin Marcher) Date: Tue, 19 Dec 2006 18:36:15 +0100 Subject: [Tutor] tarfile +stdin Message-ID: <46E253EF-F3F5-43DE-9EB2-DB61FFC87E5D@openforce.com> Hello, I'm trying to create a backup script which in one of the last steps is to create a tarball that is possibly gzipped or bzipped2. >>> import tarfile >>> tbz = tarfile.open(name="tarfile.tar.bz2", mode="w:bz2") >>> tbz.add("myfile.dmp") >>> for tarinfo in tbz: ... print tarinfo.name ... myfile.dmp >>> Now how would I open stdin to add files to this tarball? >>> import sys >>> tbz.add(sys.stdin) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/tarfile.py", line 1333, in add and os.path.abspath(name) == os.path.abspath(self.name): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/posixpath.py", line 403, in abspath if not isabs(path): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/posixpath.py", line 49, in isabs return s.startswith('/') AttributeError: 'file' object has no attribute 'startswith' happy about all hints thanks martin -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 2474 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20061219/d772ec30/attachment.bin From kent37 at tds.net Tue Dec 19 19:26:14 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Dec 2006 13:26:14 -0500 Subject: [Tutor] Data hiding in Python. In-Reply-To: References: Message-ID: <45882EC6.3070902@tds.net> Don Taylor wrote: > I am working my way through 'wxPython in Action' by Noel Rappin and > Robin Dunn and came across this comment about data hiding in their > explanation of the MVC pattern: > > ".. the View... should never get to see the private internals of the > Model. Admittedly, this is difficult to enforce in Python, but one way > to help enforcement it is to create an abstract Model class that defines > the API that the View can see. Subclasses of the Model can either act > as proxies for an internal class that can be changed, or can simply > contain the internal workings themselves. The first option is more > structured, the second easier to implement." > > I like the idea of data hiding but Googling 'Python data hiding' yields > lots of discussion to the effect that it cannot/should not be done. Python culture tends towards "we're all consenting adults here". If you attempt to shoot yourself in the foot, you should get some kind of warning that perhaps it is not what you really want to do, but if you insist, hey, go ahead, it's your foot! With regard to data hiding this means using leading underscore for names that are considered implementation details, this is fair warning to clients to use them at your own risk. > So what do the authors mean? They do not give any examples of this > technique (at least not so far as I have read in the book) so I have > been trying to figure something out. And then, is it worth the trouble? My vote is, no, not worth the trouble. It's Java / C++ / static-typing / put-the-client-in-a-straightjacket-so-they-don't-touch-anything thinking. > Any suggestions? Preferably with code fragments. > > Here is what I have got so far: > > A calling module: > -caller.py--------------------------------------------------------------------- > > import model > > if __name__ == '__main__': > model.methodA() # test a method call interface > testInstance = model.TestClass() #test a class generation interface > testInstance.methodB() # test a method call within the new class > ------------------------------------------------------------------------------- > > The actual model module, which does not contain any (or much) > implementation code: > -model.py---------------------------------------------------------------------- > > import innermodel > > __implementation = innermodel.Implementation() > > def methodA(): > "Example of a method interface." > __implementation.methodA() > > def TestClass(): > "Example of a class interface." > return __implementation.TestClass() > > ------------------------------------------------------------------------------- > > and then the actual implementation code: > -innermodel.py----------------------------------------------------------------- > > class Implementation: > def __init__(self): > print "Implementation initializing..." > > def methodA(self): > print "Implementation methodA called." > > class TestClass: > def __init__(self): > print "TestClass initializing..." > > def methodB(self): > print "TestClass methodB called." > ------------------------------------------------------------------------------- > > I am not sure if this is what they mean, and if so which is this - a > proxy for an internal class that can be changed, or does it simply > contain the internal workings. Neither, really. You haven't provided the abstract base class to show the API, and you are not really delegating to Implementation.TestClass. methodA() (which is not a method) is a proxy function because it delegates to __implementation. > > It seems to provide some degree of data hiding, but perhaps too much? Not really, clients can still access __implementation, it's just a little harder. > You cannot figure out from the model.py file what are the available > methods for the TestClass class. I guess that these could be documented > in the TestClass docstring. Ask yourself what is the benefit of all this? Kent From sisson.j at gmail.com Tue Dec 19 22:13:11 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Tue, 19 Dec 2006 15:13:11 -0600 Subject: [Tutor] Data hiding in Python. In-Reply-To: <45882EC6.3070902@tds.net> References: <45882EC6.3070902@tds.net> Message-ID: <458855E7.1000003@gmail.com> > My vote is, no, not worth the trouble. It's Java / C++ / static-typing / > put-the-client-in-a-straightjacket-so-they-don't-touch-anything thinking. > Heh...and don't forget the king-pin of them all, C#. Between private, public, protected, internal, and protected internal I lose track of what I was originally doing and end up contemplating the meaning of "what if another programmer wants to use this creation of mine" instead of doing what I set out to do... I'm with Kent on this one...definitely not worth the trouble to bastardize Python like that... As a side note, does anyone have a good argument for access level controls like C#? I personally think it's a waste of time (much like C#/ASP.NET...my apologies to any .NET fans out there...), and honestly the arguable margin of security that access modifiers provide is outweighed by the cons, in my opinion. (And usually what programmers end up doing is creating "service methods" that allow access anyways, so the margin of "security" is lost). Thoughts? Jonathon From alan.gauld at btinternet.com Tue Dec 19 22:23:29 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Dec 2006 21:23:29 -0000 Subject: [Tutor] Data hiding in Python. References: <45882EC6.3070902@tds.net> <458855E7.1000003@gmail.com> Message-ID: "Jonathon Sisson" wrote > As a side note, does anyone have a good argument for access level > controls like C#? These kinds of controls do help in large projects with many teams, often geographically dispersed. It is a form of documentation about the intent of the class designer, but also enforces that intent. This is espectially important during the early development of libraries where the internal representation is constantly evolving. The use of these access modifiers also provides an extra level of namespace control in some cases. However, that having been said I think anything beyond public/private is overkill. I actually like the Delphi 2 model (they have since added protected etc) was a good compromise where implementation section(*) attributes could be seen within a module even by other classes, but not outside the module. By combining that with public/private declarations in the class you had good control but much less confusion than in C++ etc. For smaller programs the whole mess is overkill and the Python approach of consenting adults makes much more sense IMHO. > I personally think it's a waste of time (much like > C#/ASP.NET...my apologies to any .NET fans out there...) The whole .NET thing is pretty neat, except that it could have all been done using Java and thius avoided a language war. But multiple languages compiling to a common runtime all with a single class library is powerful medicine... > end up doing is creating "service methods" that allow access > anyways, so > the margin of "security" is lost). Thoughts? And here I agree. So called getters/setters for every attribute are a JavaBeans kluge that eats away at the very essence of OOP - like so much in Java... Appropriate accessor methods are fine but they should be used with great caution, classes should expose behaviours not attributes! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sisson.j at gmail.com Wed Dec 20 00:07:08 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Tue, 19 Dec 2006 17:07:08 -0600 Subject: [Tutor] Data hiding in Python. In-Reply-To: References: <45882EC6.3070902@tds.net> <458855E7.1000003@gmail.com> Message-ID: <4588709C.2030507@gmail.com> Alan Gauld wrote: > but also enforces that intent. This is espectially important > during the early development of libraries where the internal > representation is constantly evolving. Yeah, I would have to agree with you there. I hadn't considered that angle... > But multiple languages compiling to a common runtime > all with a single class library is powerful medicine... I would argue the only real "innovation" provided by .NET is just that: the ability to produce and consume project components from different languages. I have to say I'd still prefer Java development over .NET, but that's probably more personal issues with Microsoft than language implementation. I recently used Python for a relatively large project for a Linux scripting class (the professor was kind enough to allow any relatively common scripting language (i.e. available on our Linux server...heh)) and I have to admit, I'm much more productive with Python than with virtually any language I've used before. (No, I haven't tried Ruby yet, but I hear it's just as addicting). Access modifiers or not, you can't really argue with development productivity like that...or the grade that I got on that project. =) And, it was actually kind of fun listening to some other students gripe about Perl...haha. Anyhow, thanks for the additional info, Alan! Jonathon From pyro9219 at gmail.com Wed Dec 20 00:34:48 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Tue, 19 Dec 2006 15:34:48 -0800 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: References: <45834618.9070901@gmail.com> <45834A21.4090800@gmail.com> Message-ID: If it adds to the fun, does it make a difference if I tell you that this will be looking through [0][0] - approx [0][6544] On 12/16/06, Alan Gauld wrote: > > > "Roel Schroeven" wrote > > >> In that case put the inner lists in a Set. That will eliminate > >> duplicates. > > > > That won't work: list objects are unhashable so you can't put them > > in a > > set. You'll have to convert them to tuples first. > > Hmm, I took that a self evident but I guess maybe it wasn't... > > As for Luke's point about the speed of conversion, I'm not > sure how that would stack up. I have a gut feel that it might > be faster than trying to compare the lists element by > element, that sounds like an algebraic expansion with list > size to me, a hashed set sounds like it should be faster. > But as with all such things, if speed matters: measure > and profile it. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061219/5fc3247e/attachment.html From alan.gauld at btinternet.com Wed Dec 20 02:04:40 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 20 Dec 2006 01:04:40 -0000 Subject: [Tutor] Data hiding in Python. References: <45882EC6.3070902@tds.net><458855E7.1000003@gmail.com> Message-ID: "Alan Gauld" wrote > public/private is overkill. I actually like the Delphi 2 model > (they have since added protected etc) was a good compromise > where implementation section(*) attributes Oops! I meant to add a footnote here that explained that Delphi modules comprise two sections, an interface and an implementation. Only functions declared in the interface can be used by clients of the module. I often think that this scheme would be a useful addition to Python's module structure. It would look something like this: #### module foo #### interface: def myfunc(p1,p2) def anotherFunc(p3) class bar: def __init__(...) def f(self) def g(self,x) mylist = [] # can be used by clients implementation: secretVar = {} # hidden from clients def myfunc(p1,p2): #code here can use secretVar def anotherFunc(p3): # code here class bar: def __init__(self): self.x = 42 # etc... ######################### Its fairly easy to understand and provides a good mix of access control and readability without tying the programmers hands. It also means you can very easily see all that a module has to offer by just reading the top (relatively) few lines of code. It thus gives the advantages of C header files without the problems of managing/synchronising two files per module. All IMHO of course... :-) Alan G. From andreas at kostyrka.org Wed Dec 20 03:01:22 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 20 Dec 2006 03:01:22 +0100 Subject: [Tutor] Data hiding in Python. In-Reply-To: <458855E7.1000003@gmail.com> References: <45882EC6.3070902@tds.net> <458855E7.1000003@gmail.com> Message-ID: <20061220020122.GH5609@andi-lap.la.revver.com> * Jonathon Sisson [061219 21:45]: > > > My vote is, no, not worth the trouble. It's Java / C++ / static-typing / > > put-the-client-in-a-straightjacket-so-they-don't-touch-anything thinking. > > > > Heh...and don't forget the king-pin of them all, C#. Between private, > public, protected, internal, and protected internal I lose track of what > I was originally doing and end up contemplating the meaning of "what if > another programmer wants to use this creation of mine" instead of doing > what I set out to do... > > I'm with Kent on this one...definitely not worth the trouble to > bastardize Python like that... > > As a side note, does anyone have a good argument for access level > controls like C#? I personally think it's a waste of time (much like > C#/ASP.NET...my apologies to any .NET fans out there...), and honestly > the arguable margin of security that access modifiers provide is > outweighed by the cons, in my opinion. (And usually what programmers > end up doing is creating "service methods" that allow access anyways, so > the margin of "security" is lost). Thoughts? Well, what does make sense at least in a static language situation is to support an arbitrate number of "interfaces", e.g. like Modula3 is providing with partial revealing the exact type of an opaque type. Basically, taking the classical IO stream example, you get the following roles: *) simple user *) advanced user (does it's own thread locking, unsafe) *) implementer (simple) *) advanced implementer (does it's own buffer management) and so on. All this is not really covered by public/protected/private, because depending upon your relationship with the class, you might different levels of access. Python as a dynamic language in practice does not need access roles like the above, albeit a comparable service is provided by zope.interfaces. Andreas From john at fouhy.net Wed Dec 20 02:59:16 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 20 Dec 2006 14:59:16 +1300 Subject: [Tutor] Best method for filtering lists in lists... In-Reply-To: References: <45834618.9070901@gmail.com> <45834A21.4090800@gmail.com> Message-ID: <5e58f2e40612191759y31a3bee8wcd3b184fd55b96a1@mail.gmail.com> On 17/12/06, Alan Gauld wrote: > As for Luke's point about the speed of conversion, I'm not > sure how that would stack up. I have a gut feel that it might > be faster than trying to compare the lists element by > element, that sounds like an algebraic expansion with list > size to me, a hashed set sounds like it should be faster. > But as with all such things, if speed matters: measure > and profile it. Here's my attempt at a "smarter" way of removing duplicates: (note that this code assumes 'None' does not occur in your lists) def nodupes(lst): trie = {} for l in lst: addToTrie(l, trie) return unTrie([], trie) def addToTrie(lst, trie): curr = trie for i, elem in enumerate(lst): try: curr = curr[elem] except KeyError: for e in lst[i:]: curr[e] = {} curr = curr[e] curr[None] = None break def unTrie(prefix, trie): lst = [] for elem in trie: if elem is None: lst.append(prefix) else: lst.extend(unTrie(prefix + [elem], trie[elem])) return lst According to timeit, this is over five times slower than the one-line solution: def nodupes2(lst): return [list(y) for y in set(tuple(x) for x in lst)] Finally, neither of these are order-preserving... -- John. From wescpy at gmail.com Wed Dec 20 04:34:59 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 19 Dec 2006 19:34:59 -0800 Subject: [Tutor] tarfile +stdin In-Reply-To: <46E253EF-F3F5-43DE-9EB2-DB61FFC87E5D@openforce.com> References: <46E253EF-F3F5-43DE-9EB2-DB61FFC87E5D@openforce.com> Message-ID: <78b3a9580612191934p8430f68l529f7b6106863d18@mail.gmail.com> > >>> tbz.add(sys.stdin) > Traceback (most recent call last): > File "", line 1, in > : > return s.startswith('/') > AttributeError: 'file' object has no attribute 'startswith' altho i cannot help you with your original query, i *can* tell you that the reason why you get the error is that add() expects a filename (not a file object). i think that you have to create a TarInfo object and use the addfile() method instead but can't confirm that. anyone else know? thanks, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From carloslara at web.de Wed Dec 20 18:59:00 2006 From: carloslara at web.de (Carlos) Date: Wed, 20 Dec 2006 18:59:00 +0100 Subject: [Tutor] How many times X is in a list? In-Reply-To: References: Message-ID: <458979E4.8070007@web.de> Hello, Can you help me with this please? I have a list that contains elements to be created (in a 3D app), in the list each element is a dictionary that contains data, like: Elements = [ {'Width': 3.0, 'Depth': 3.0, 'Name': 'Access', 'Parent': 'Plot', 'Height': 3.0}, {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_01', 'Parent': 'Access', 'Height': 3.0}, {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_02', 'Parent': 'Access', 'Height': 3.0}, {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_03', 'Parent': 'Access', 'Height': 3.0}, {'Width': 2.0, 'Depth': 6.0, 'Name': 'Int_Circ_01', 'Parent': 'Circulation_01', 'Height': 3.0}, {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_02', 'Parent': 'Circulation_01', 'Height': 3.0}, {'Width': 2.0, 'Depth': 6.5, 'Name': 'Int_Circ_03', 'Parent': 'Circulation_02', 'Height': 3.0}, {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_04', 'Parent': 'Circulation_02', 'Height': 3.0}, {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_05', 'Parent': 'Circulation_03', 'Height': 3.0}, {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_06', 'Parent': 'Circulation_03', 'Height': 3.0}, ] so a for loop is used to iterate the list, like: for element in elements: create object with the desired width, depth, name, etc The thing is that there can only be a "Circulation" by story, so I am thinking in adding each created object to a built_Objects list and appending the created object to the list, like: for element in elements: create element append element['Name'] to built_Objects My question is, how can I check how many times "Circulation" appears in the built_Objects list? I think that if I get the number of times /N/ that "Circulation" appears I can multiply the next circulation elevation /N/ times and avoid having two circulations in the same level. Is this a correct reasoning? I did a little research and found that count could help me, so I tried: print Built_Elements.count('Circulation') but well is not working. The result is 0, I guess that count is looking for the exact term and not something similar If you know the solution or a better way to do this please let me know. Thanks in advance, Carlos From kent37 at tds.net Wed Dec 20 19:12:58 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Dec 2006 13:12:58 -0500 Subject: [Tutor] How many times X is in a list? In-Reply-To: <458979E4.8070007@web.de> References: <458979E4.8070007@web.de> Message-ID: <45897D2A.1080802@tds.net> Carlos wrote: > Hello, > > Can you help me with this please? > > I have a list that contains elements to be created (in a 3D app), in the > list each element is a dictionary that contains data, like: > > Elements = [ > {'Width': 3.0, 'Depth': 3.0, 'Name': 'Access', 'Parent': > 'Plot', 'Height': 3.0}, > {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_01', > 'Parent': 'Access', 'Height': 3.0}, > {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_02', > 'Parent': 'Access', 'Height': 3.0}, > {'Width': 3.0, 'Depth': 3.0, 'Name': 'Circulation_03', > 'Parent': 'Access', 'Height': 3.0}, > {'Width': 2.0, 'Depth': 6.0, 'Name': 'Int_Circ_01', > 'Parent': 'Circulation_01', 'Height': 3.0}, > {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_02', > 'Parent': 'Circulation_01', 'Height': 3.0}, > {'Width': 2.0, 'Depth': 6.5, 'Name': 'Int_Circ_03', > 'Parent': 'Circulation_02', 'Height': 3.0}, > {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_04', > 'Parent': 'Circulation_02', 'Height': 3.0}, > {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_05', > 'Parent': 'Circulation_03', 'Height': 3.0}, > {'Width': 2.0, 'Depth': 5.0, 'Name': 'Int_Circ_06', > 'Parent': 'Circulation_03', 'Height': 3.0}, > ] > > so a for loop is used to iterate the list, like: > > for element in elements: > create object with the desired width, depth, name, etc > > The thing is that there can only be a "Circulation" by story, so I am > thinking in adding each created object to a built_Objects list and > appending the created object to the list, like: > > for element in elements: > create element > append element['Name'] to built_Objects > > My question is, how can I check how many times "Circulation" appears in > the built_Objects list? I think that if I get the number of times /N/ > that "Circulation" appears I can multiply the next circulation elevation > /N/ times and avoid having two circulations in the same level. Is this a > correct reasoning? > > I did a little research and found that count could help me, so I tried: > > print Built_Elements.count('Circulation') > > but well is not working. The result is 0, I guess that count is looking > for the exact term and not something similar > > If you know the solution or a better way to do this please let me know. Yes, count() is looking for exact matches. You can make a new list with just the circulation names and take the length of that; something like this: len([name for name in built_Objects if name.startswith('Circulation')]) or perhaps slightly more efficient (Python 2.5): sum(1 for name in built_Objects if name.startswith('Circulation')) Kent From rabidpoobear at gmail.com Wed Dec 20 19:25:39 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 20 Dec 2006 12:25:39 -0600 Subject: [Tutor] How many times X is in a list? In-Reply-To: <45897D2A.1080802@tds.net> References: <458979E4.8070007@web.de> <45897D2A.1080802@tds.net> Message-ID: <45898023.3050808@gmail.com> > Yes, count() is looking for exact matches. You can make a new list with > just the circulation names and take the length of that; something like this: > len([name for name in built_Objects if name.startswith('Circulation')]) > > or perhaps slightly more efficient (Python 2.5): > sum(1 for name in built_Objects if name.startswith('Circulation')) > I thought sum only worked on lists. Is that supposed to be a list comprehension inside of sum or am I wrong? (still using 2.4.3, so I can't check) Thanks, -Luke > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Dec 20 19:45:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Dec 2006 13:45:20 -0500 Subject: [Tutor] How many times X is in a list? In-Reply-To: <45898023.3050808@gmail.com> References: <458979E4.8070007@web.de> <45897D2A.1080802@tds.net> <45898023.3050808@gmail.com> Message-ID: <458984C0.3040607@tds.net> Luke Paireepinart wrote: >> Yes, count() is looking for exact matches. You can make a new list with >> just the circulation names and take the length of that; something like this: >> len([name for name in built_Objects if name.startswith('Circulation')]) >> >> or perhaps slightly more efficient (Python 2.5): >> sum(1 for name in built_Objects if name.startswith('Circulation')) >> > I thought sum only worked on lists. According to the docs sum() works on sequences, but in fact it seems to work on any iterable (a weaker condition than sequence). For example you can sum a dict which is not a sequence: In [4]: d=dict.fromkeys(range(10)) In [6]: sum(d) Out[6]: 45 > Is that supposed to be a list comprehension inside of sum or am I wrong? No, it is a generator comprehension which is like a list comp except it uses () instead of [] and it creates an iterator rather than a list. The reason I postulate that using sum() *might* be more efficient is because it doesn't have to create the intermediate list. Of course for any reasonable size list it won't make a noticable difference anyway... Kent From carloslara at web.de Wed Dec 20 21:59:46 2006 From: carloslara at web.de (Carlos) Date: Wed, 20 Dec 2006 21:59:46 +0100 Subject: [Tutor] How many times X is in a list? In-Reply-To: <45897D2A.1080802@tds.net> References: <458979E4.8070007@web.de> <45897D2A.1080802@tds.net> Message-ID: <4589A442.6060701@web.de> Thanks Kent, That solves it pretty well. Carlos Kent Johnson wrote: > Yes, count() is looking for exact matches. You can make a new list > with just the circulation names and take the length of that; something > like this: > len([name for name in built_Objects if name.startswith('Circulation')]) > > or perhaps slightly more efficient (Python 2.5): > sum(1 for name in built_Objects if name.startswith('Circulation')) > > Kent From geeth4sg at gmail.com Thu Dec 21 06:56:55 2006 From: geeth4sg at gmail.com (sg) Date: Wed, 20 Dec 2006 21:56:55 -0800 (PST) Subject: [Tutor] python coding using regular expression Message-ID: <8003182.post@talk.nabble.com> hi,,,, i am new to python. i want help in regular expression.. anyone explain or guide me for following problem.. the content of txt file is splitted using the pipe | symbol and sorted . then the field in the first row is compared with field in the second row and the second row field is compared with third and so on till end of file.. if there is mismatch between the row, the error will be throw as follows.. For example, david thomson davis thomson in above string 'd' and 's' are mismatched.. so the error will be thrown. -- View this message in context: http://www.nabble.com/python-coding-using-regular-expression-tf2863876.html#a8003182 Sent from the Python - tutor mailing list archive at Nabble.com. From rabidpoobear at gmail.com Thu Dec 21 12:05:28 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 21 Dec 2006 05:05:28 -0600 Subject: [Tutor] python coding using regular expression In-Reply-To: <8003182.post@talk.nabble.com> References: <8003182.post@talk.nabble.com> Message-ID: <458A6A78.8070004@gmail.com> sg wrote: > hi,,,, > i am new to python. i want help in regular expression.. anyone explain > or guide me for following problem.. > > the content of txt file is splitted using the pipe | symbol and sorted . > then the field in the first row is compared with field in the second row and > the second row field is compared with third and so on till end of file.. if > there is mismatch between the row, the error will be throw as follows.. > For example, > > david thomson > davis thomson > > in above string 'd' and 's' are mismatched.. so the error will be thrown. > > This sounds to me like a homework problem. In any case, there's no reason to use regexps here. If you're checking for _any_ difference between two strings, you can just use the regular comparison operator: >>> 'david thomson' == 'davis thomson' False Unless you have some other requirements you haven't mentioned. HTH, -Luke From kent37 at tds.net Thu Dec 21 12:08:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Dec 2006 06:08:55 -0500 Subject: [Tutor] python coding using regular expression In-Reply-To: <8003182.post@talk.nabble.com> References: <8003182.post@talk.nabble.com> Message-ID: <458A6B47.9010102@tds.net> sg wrote: > hi,,,, > i am new to python. i want help in regular expression.. anyone explain > or guide me for following problem.. > > the content of txt file is splitted using the pipe | symbol and sorted . > then the field in the first row is compared with field in the second row and > the second row field is compared with third and so on till end of file.. if > there is mismatch between the row, the error will be throw as follows.. > For example, > > david thomson > davis thomson > > in above string 'd' and 's' are mismatched.. so the error will be thrown. I don't think you need regular expressions for this. What do you mean by mismatched? any difference between them, or something more subtle? If you compare the first row to the second, the second to the third, etc, then you will get the error unless every line is the same. Is that what you want? If I understand you, what you want to do can be done with a simple loop over the lines with a variable that remembers the value of the previous line. Kent From carloslara at web.de Thu Dec 21 16:32:23 2006 From: carloslara at web.de (Carlos) Date: Thu, 21 Dec 2006 16:32:23 +0100 Subject: [Tutor] Project Review In-Reply-To: References: Message-ID: <458AA907.8080906@web.de> Hello, I have been working in a script for my master thesis project (M Arch) and since this is the first project that I do in this way, I would like to know if someone here would be interested in taking a look at what I have done so far. My impression is that since I have been learning on my own, I am doing stuff probably not in the best way. The idea is that someone who really knows about programming can take a look and give me some advice to correct the points that are not so good in my code. I don't know if this is a good thing to ask in this mailing list, or if it is possible for someone to take a look and spot my errors, but I really can't think of a better way. Best regards, Carlos From kent37 at tds.net Thu Dec 21 16:40:13 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Dec 2006 10:40:13 -0500 Subject: [Tutor] Project Review In-Reply-To: <458AA907.8080906@web.de> References: <458AA907.8080906@web.de> Message-ID: <458AAADD.8080603@tds.net> Carlos wrote: > Hello, > > I have been working in a script for my master thesis project (M Arch) > and since this is the first project that I do in this way, I would like > to know if someone here would be interested in taking a look at what I > have done so far. My impression is that since I have been learning on my > own, I am doing stuff probably not in the best way. The idea is that > someone who really knows about programming can take a look and give me > some advice to correct the points that are not so good in my code. > > I don't know if this is a good thing to ask in this mailing list, or if > it is possible for someone to take a look and spot my errors, but I > really can't think of a better way. If it is a short script you can just include it in an email to the list. Longer than 50-100 lines is probably too long for mail. In this case the best thing is to put the script on a web site and post the URL to the list. Kent From geoframer at gmail.com Thu Dec 21 16:43:29 2006 From: geoframer at gmail.com (Geoframer) Date: Thu, 21 Dec 2006 16:43:29 +0100 Subject: [Tutor] Python and rpy Message-ID: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com> Okay this might not be the best place to post my question, but on the rpy-list i'm getting no response and i'm really stuck with this problem. Perhaps anyone on here has run into the same problem... I'm thinking my newbieness to python probably is one of the reasons why i fail to see what i'm doing wrong... R is a statistical language and Rpy is the python interface for it. However somehow I'm failing to see a step in the python code with which I address the R language. in R I can do : a=diag(10) #produces an identity matrix of size 10 b=kmeans(a,2,5,10,"Forgy") #calculate a kmeans clustering algorithm on the 10 vectors contained by the matrix just declared. in Ipython this does : --------- In [1]: from rpy import * RHOME= C:\Program Files\R\R-2.4.0 RVERSION= 2.4.0 RVER= 2040 RUSER= C:\Documents and Settings\Ronald Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. Loading Rpy version 2040 .. Done. Creating the R object 'r' .. Done In [2]: a = r.diag(10) In [3]: b = r.kmeans(a,2,10,5,"Forgy") --------------------------------------------------------------------------- rpy.RException Traceback (most recent call last) C:\Python24\ RException: Error in as.double.default(x) : (list) object cannot be coerced to ' double' --------- I've tried numerous things to get it to work, but i basically can not find out how i do something as simple as the two statements in R in RPython. Apparently something is going wrong somewhere in the conversion of python objects to R objects but i can't seem to fix it. There is a code snippet in the RPy-reference manual but it's only valid for python 2.2 and 2.1 and i couldn't get it to work on 2.4. If anyone has a clue on how to do this or can point me in the right direction, i'd be much oblidged. Kind Regards - Geofram -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061221/cb4e53e2/attachment.htm From carloslara at web.de Thu Dec 21 16:48:42 2006 From: carloslara at web.de (Carlos) Date: Thu, 21 Dec 2006 16:48:42 +0100 Subject: [Tutor] Project Review In-Reply-To: <458AAADD.8080603@tds.net> References: <458AA907.8080906@web.de> <458AAADD.8080603@tds.net> Message-ID: <458AACDA.7080805@web.de> Kent, Yes it is a little longer than that, let me see how can I make it more compact and will get back to the list with a URL. Thanks!!! Carlos Kent Johnson wrote: > Carlos wrote: >> Hello, >> >> I have been working in a script for my master thesis project (M Arch) >> and since this is the first project that I do in this way, I would >> like to know if someone here would be interested in taking a look at >> what I have done so far. My impression is that since I have been >> learning on my own, I am doing stuff probably not in the best way. >> The idea is that someone who really knows about programming can take >> a look and give me some advice to correct the points that are not so >> good in my code. >> >> I don't know if this is a good thing to ask in this mailing list, or >> if it is possible for someone to take a look and spot my errors, but >> I really can't think of a better way. > > If it is a short script you can just include it in an email to the > list. Longer than 50-100 lines is probably too long for mail. In this > case the best thing is to put the script on a web site and post the > URL to the list. > > Kent > > From chris.arndt at web.de Thu Dec 21 16:53:11 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 21 Dec 2006 16:53:11 +0100 Subject: [Tutor] Project Review In-Reply-To: <458AA907.8080906@web.de> References: <458AA907.8080906@web.de> Message-ID: <458AADE7.7090307@web.de> Carlos schrieb: > I don't know if this is a good thing to ask in this mailing list, or if > it is possible for someone to take a look and spot my errors, but I > really can't think of a better way. It might be a better idea to ask for solutions or hints for a specific problem or comments on a specific piece of code. Most of us here probably don't have the time to read through big amounts of code without knowing if we encounter anything interesting in the process. So my suggestion is: try to wake our interest by showing us some code where you think is a problem or by giving us some more background information on your project. So far I could only gather that you are writing a thesis and there is something with a cryptic acronym (M Arch) involved. I have not idea, what this is about, so tell us! Chris P.S. This is basically just rephrasing what has been already said by others and better: http://www.catb.org/~esr/faqs/smart-questions.html From sisson.j at gmail.com Thu Dec 21 19:14:36 2006 From: sisson.j at gmail.com (Jonathon Sisson) Date: Thu, 21 Dec 2006 12:14:36 -0600 Subject: [Tutor] Project Review In-Reply-To: <458AADE7.7090307@web.de> References: <458AA907.8080906@web.de> <458AADE7.7090307@web.de> Message-ID: <458ACF0C.7010807@gmail.com> Christopher Arndt wrote: > P.S. This is basically just rephrasing what has been already said by others and > better: http://www.catb.org/~esr/faqs/smart-questions.html Seriously, that is an excellent guide. Eric S. Raymond writes some high quality stuff. Anyone new to posting on this list (or any other, for that matter) should read that. I highly recommend it and thanks Chris for posting that link. And check out some of Eric's other guides and essays as well. A particular favorite of mine (especially if you are interested in open source software and the development model utilized by most of the open source community) is http://www.catb.org/~esr/writings/cathedral-bazaar/ Great post, Chris. Thanks! Jonathon From chris.arndt at web.de Thu Dec 21 18:52:38 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 21 Dec 2006 18:52:38 +0100 Subject: [Tutor] Project Review In-Reply-To: <458ACF0C.7010807@gmail.com> References: <458AA907.8080906@web.de> <458AADE7.7090307@web.de> <458ACF0C.7010807@gmail.com> Message-ID: <458AC9E6.2090500@web.de> Jonathon Sisson schrieb: > Christopher Arndt wrote: >> P.S. This is basically just rephrasing what has been already said by others and >> better: http://www.catb.org/~esr/faqs/smart-questions.html > > Seriously, that is an excellent guide. Eric S. Raymond writes some high > quality stuff. Anyone new to posting on this list (or any other, for > that matter) should read that. Well, not all admonitions from this article apply with full force to posters on this list, because this list is specifically for those who are not no well versed in Python and often in netiquette as well. But the main point to remember stays the same: When you write a question, always ask yourself: how do get somebody to bother answering _my_ question, by making it interesting for _him/her_, because, as you always have to keep in mind, he/she will get no other reward for it. Chris From carloslara at web.de Thu Dec 21 19:42:39 2006 From: carloslara at web.de (Carlos) Date: Thu, 21 Dec 2006 19:42:39 +0100 Subject: [Tutor] Tutor Digest, Vol 34, Issue 42 In-Reply-To: References: Message-ID: <458AD59F.4070603@web.de> Chis, In the past I have received very valuable info from other list users, that has helped me to solve problems that I had. Just yesterday Kent helped me with something very specific. I'm asking for a project review because my code is working now, it is not complete but it is working. What I need is not a specific solution, but more something like a general review of the code. Because while probably everything is working, there might be very evident problems that are general in nature and that are impossible for me to spot for a number of reasons. What is this project about? Well I'm allways a little bit afraid to speak about that, because after 30 seconds most of the people just wants to get away as fast as possible. But hey, you asked for it :-) My project is a building prototyping system, my idea is that it is possible to investigate different spatial configurations for an anchitectural project, for you to have a better idea, let me show a simplified step list: 1. - Locate the plot that contains the architectural project. Details like orientation, latitude and longitude are relevant. 2. - Generate the collection of spaces that compose the project. Details like size and position respect to other spaces are relevant. 3. - Analyze the collection of spaces. This is an intermediate step, and its function is that the system knows the details of the given data. 4. - Run the system. Based on a Genetic Algorithm, the system generates a population of possible solutions and evaluates how well they perform to give at the end a number of solutions that represent possible projects. For the first version of the system the evaluated considerations are going to be kept at a minimum, with the intention of simplifying the development process. Those considerations are going to be on the one hand, proximity that is expressed in the schematic design. And on the other hand an external evolutionary pressure, in this case sun incidence. Further versions of the system are intended to cover more aspects of an architectural project. If you, besides python, know something about Maya (the 3D App) that would just be great for me. I have spent the last semester learning python and mel the scripting language of maya. Thankfuly I found something called cgkit, that has let me use python inside of maya. And if by chance you are familiar with genetic algorithms, well that would be perfect, because you can take a look at how I took a genetic algorithm python module and applied to my project. But in the case that you are not familiar with maya or genetic algorithms, well the code is still python and I bet that a veteran like you can spot a bunch of things that could be done better, at the big scale of the code workings or a the small one of specific stuff. MArch as far as I know is not something cryptic, it stands for Master of Architecture and it follows the normal master courses notation. You can check it here . Just to clarify :-) Cheers Carlos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061221/dd517ac0/attachment.html From chris.arndt at web.de Thu Dec 21 20:32:45 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 21 Dec 2006 20:32:45 +0100 Subject: [Tutor] Project Review (Was: Tutor Digest, Vol 34, Issue 42) In-Reply-To: <458AD59F.4070603@web.de> References: <458AD59F.4070603@web.de> Message-ID: <458AE15D.4060204@web.de> Carlos schrieb: > And if by chance you are familiar with genetic algorithms, well that > would be perfect, because you can take a look at how I took a genetic > algorithm python module and applied to my project. I'm afraid that I don't have the domain specific knowledge to be of much help here and I must admit, that I'm not very interested in it either, but at least, now I know enough to make that decision ;-) > But in the case that you are not familiar with maya or genetic > algorithms, well the code is still python and I bet that a veteran like > you can spot a bunch of things that could be done better, at the big > scale of the code workings or a the small one of specific stuff. I would suggest, you upload you code somewhere (make it password protected, if you must) so that several people have an opportunity to look at it. I could probably comment on the 'Pythonicity' of the code, others might be better suited to 'understand' the code. > MArch as far as I know is not something cryptic, it stands for Master of > Architecture and it follows the normal master courses notation. You can > check it here > . Not everybody speaks English as their mothertongue or knows about the Anglo-saxon education system, you know ;-) Chris From kent37 at tds.net Thu Dec 21 21:26:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Dec 2006 15:26:11 -0500 Subject: [Tutor] Python and rpy In-Reply-To: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com> References: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com> Message-ID: <458AEDE3.8030006@tds.net> Geoframer wrote: > R is a statistical language and Rpy is the python interface for it. > However somehow I'm failing to see a step in the python code with which I > address the R language. > > in R I can do : > > a=diag(10) #produces an identity matrix of > size 10 > b=kmeans(a,2,5,10,"Forgy") #calculate a kmeans clustering algorithm > on the 10 vectors contained by the matrix just declared. > > > in Ipython this does : > > --------- > In [1]: from rpy import * > RHOME= C:\Program Files\R\R-2.4.0 > RVERSION= 2.4.0 > RVER= 2040 > RUSER= C:\Documents and Settings\Ronald > Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. > Loading Rpy version 2040 .. Done. > Creating the R object 'r' .. Done > > In [2]: a = r.diag(10) > > In [3]: b = r.kmeans(a,2,10,5,"Forgy") > --------------------------------------------------------------------------- > rpy.RException Traceback (most recent > call last) > > C:\Python24\ > > RException: Error in as.double.default(x) : (list) object cannot be > coerced to ' > double' > --------- This seems to work, it keeps a in the internal R representation instead of converting it to a list of lists: In [1]: from rpy import * RHOME= C:\Program Files\R\R-2.3.1 RVERSION= 2.3.1 RVER= 2031 RUSER= G:\ Loading the R DLL C:\Program Files\R\R-2.3.1\bin\R.dll .. Done. Loading Rpy version 2031 .. Done. Creating the R object 'r' .. Done In [22]: aa=with_mode(NO_CONVERSION, r.diag)(10) In [25]: b=r.kmeans(aa,2,10,5,"Forgy") In [26]: b Out[26]: {'centers': [[0.1111111111111111, 0.1111111111111111, 0.1111111111111111, 0.1111111111111111, 0.0, 0.1111111111111111, 0.1111111111111111, 0.1111111111111111, 0.1111111111111111, 0.1111111111111111], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], 'cluster': [1, 1, 1, 1, 2, 1, 1, 1, 1, 1], 'size': [9, 1], 'withinss': [8.0000000000000018, 0.0]} > I've tried numerous things to get it to work, but i basically can not > find out how i do something as simple as the two statements in R in > RPython. Apparently something is going wrong somewhere in the conversion > of python objects to R objects but i can't seem to fix it. There is a > code snippet in the RPy-reference manual but it's only valid for python > 2.2 and 2.1 and i couldn't get it to work on 2.4. Where is the snippet? Cheers, Kent From geoframer at gmail.com Fri Dec 22 11:21:57 2006 From: geoframer at gmail.com (Geoframer) Date: Fri, 22 Dec 2006 11:21:57 +0100 Subject: [Tutor] Python and rpy In-Reply-To: <458AEDE3.8030006@tds.net> References: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com> <458AEDE3.8030006@tds.net> Message-ID: <5d8e35a70612220221r7f324d1fl30ef1810d6c838c1@mail.gmail.com> Thanks Kent that helps some, at least i can do the basic stuff i can do in R now. But you kinda hit the nail on the head with your statement "This seems to work, it keeps a in the internal R representation instead of converting it to a list of lists" This all started with me trying to get R to do a kmeans algorithm on a list of lists (a list composed of vectors containing integers). What i want to do is convert a python list of lists to the approperiate R object so that i can use the r.kmeans algorithm on it. I'll write the basic program below. As i stated i think the conversion from Python to R is going wrong, but i have no clue on how to properly address that. The code snippet i was talking about is on page 15 and 16 of the rpy reference guide http://rpy.sourceforge.net/rpy/doc/rpy.pdf ; the examples just don't work and i am lacking enough python experience to see why :-S. What i'm trying to do now is : ---- from rpy import * class Test: def as_r(self): return [[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]] if __name__ == "__main__": a=with_mode(NO_CONVERSION, Test)() r.kmeans(a, 2, 5, 10, "Forgy") ---- Which gives as a result : ---- RHOME= C:\Program Files\R\R-2.4.0 RVERSION= 2.4.0 RVER= 2040 RUSER= C:\Documents and Settings\Ronald Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. Loading Rpy version 2040 .. Done. Creating the R object 'r' .. Done Traceback (most recent call last): File "rpy-test2.py", line 9, in ? r.kmeans(a, 2, 5, 10, "Forgy") rpy.RException: Error in as.double.default(x) : (list) object cannot be coerced to 'double' ---- Hope you can shed more light on it. Many thanx for your efforts - Geofram On 12/21/06, Kent Johnson wrote: > > Geoframer wrote: > > R is a statistical language and Rpy is the python interface for it. > > However somehow I'm failing to see a step in the python code with which > I > > address the R language. > > > > in R I can do : > > > > a=diag(10) #produces an identity matrix of > > size 10 > > b=kmeans(a,2,5,10,"Forgy") #calculate a kmeans clustering algorithm > > on the 10 vectors contained by the matrix just declared. > > > > > > in Ipython this does : > > > > --------- > > In [1]: from rpy import * > > RHOME= C:\Program Files\R\R-2.4.0 > > RVERSION= 2.4.0 > > RVER= 2040 > > RUSER= C:\Documents and Settings\Ronald > > Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. > > Loading Rpy version 2040 .. Done. > > Creating the R object 'r' .. Done > > > > In [2]: a = r.diag(10) > > > > In [3]: b = r.kmeans(a,2,10,5,"Forgy") > > > --------------------------------------------------------------------------- > > rpy.RException Traceback (most recent > > call last) > > > > C:\Python24\ > > > > RException: Error in as.double.default(x) : (list) object cannot be > > coerced to ' > > double' > > --------- > > This seems to work, it keeps a in the internal R representation instead > of converting it to a list of lists: > > In [1]: from rpy import * > RHOME= C:\Program Files\R\R-2.3.1 > RVERSION= 2.3.1 > RVER= 2031 > RUSER= G:\ > Loading the R DLL C:\Program Files\R\R-2.3.1\bin\R.dll .. Done. > Loading Rpy version 2031 .. Done. > Creating the R object 'r' .. Done > > In [22]: aa=with_mode(NO_CONVERSION, r.diag)(10) > > In [25]: b=r.kmeans(aa,2,10,5,"Forgy") > > In [26]: b > Out[26]: > {'centers': [[0.1111111111111111, > 0.1111111111111111, > 0.1111111111111111, > 0.1111111111111111, > 0.0, > 0.1111111111111111, > 0.1111111111111111, > 0.1111111111111111, > 0.1111111111111111, > 0.1111111111111111], > [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], > 'cluster': [1, 1, 1, 1, 2, 1, 1, 1, 1, 1], > 'size': [9, 1], > 'withinss': [8.0000000000000018, 0.0]} > > > I've tried numerous things to get it to work, but i basically can not > > find out how i do something as simple as the two statements in R in > > RPython. Apparently something is going wrong somewhere in the conversion > > of python objects to R objects but i can't seem to fix it. There is a > > code snippet in the RPy-reference manual but it's only valid for python > > 2.2 and 2.1 and i couldn't get it to work on 2.4. > > Where is the snippet? > > Cheers, > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061222/172beb74/attachment.html From nephish at gmail.com Fri Dec 22 16:38:25 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 22 Dec 2006 09:38:25 -0600 Subject: [Tutor] how to permanently add a module path Message-ID: <384c93600612220738v2919c792j5af090009c751e77@mail.gmail.com> lo there, i am working with python in ubuntu, my app has some modules that i would like to import from anywhere. i can sys.path.append(my_module_dir) but it only lasts as long as that python session. how can i add a directory to the import path permantly ? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061222/8bdbbeea/attachment.htm From chris.arndt at web.de Fri Dec 22 17:07:27 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 22 Dec 2006 17:07:27 +0100 Subject: [Tutor] how to permanently add a module path In-Reply-To: <384c93600612220738v2919c792j5af090009c751e77@mail.gmail.com> References: <384c93600612220738v2919c792j5af090009c751e77@mail.gmail.com> Message-ID: <458C02BF.9040708@web.de> shawn bright schrieb: > lo there, > > i am working with python in ubuntu, my app has some modules that i would > like to import from anywhere. > i can sys.path.append(my_module_dir) but it only lasts as long as > that python session. > how can i add a directory to the import path permantly http://article.gmane.org/gmane.comp.python.tutor/36916 See point 2) Addendum: To set the PYTHONPATH environment variable: Windows: "Control panel/System/Advanced/Envirnment..." or something similar and change/add value of PYTHONPATH (entries are separated by semicolons ';') Linux: Depends on your distribution: - Standard way would be to edit ~/.bash_profile and add e.g. # entries are separated by colons ':' PYTHONPATH=$HOME/lib/python:/where/my/other/python/modules/live export PYTHONPATH but not all desktop environment read this file. - On Debian, for the system wide environment, you can add the same snippet to /etc/environment or add a file with the same contents to /etc/profile.d HTH, Chris From carloslara at web.de Fri Dec 22 17:26:59 2006 From: carloslara at web.de (Carlos) Date: Fri, 22 Dec 2006 17:26:59 +0100 Subject: [Tutor] Lists on the fly? In-Reply-To: References: Message-ID: <458C0753.6040305@web.de> Hello, I am wondering if it is possible to create lists on the fly. The script that I'm working on needs a number of parameters, one of those is population, and this corresponds to the number of solutions that a genetic algorithm generates on each generation (iteration). The thing is that I need to generate one list for each population member and then append the corresponding population members to that particular list. This is only so you can have an idea: for i in range(5): 'list_%i' % (i) = [] or: for i in range(5): lista_+'%i' % (i) = [] :-[ Is this possible? Thanks in advance, And Merry Christmas, Carlos From kent37 at tds.net Fri Dec 22 17:37:50 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Dec 2006 11:37:50 -0500 Subject: [Tutor] Lists on the fly? In-Reply-To: <458C0753.6040305@web.de> References: <458C0753.6040305@web.de> Message-ID: <458C09DE.3030802@tds.net> Carlos wrote: > Hello, > > I am wondering if it is possible to create lists on the fly. The script > that I'm working on needs a number of parameters, one of those is > population, and this corresponds to the number of solutions that a > genetic algorithm generates on each generation (iteration). The thing is > that I need to generate one list for each population member and then > append the corresponding population members to that particular list. > > This is only so you can have an idea: > > for i in range(5): > 'list_%i' % (i) = [] > > or: > > for i in range(5): > lista_+'%i' % (i) = [] > > :-[ > > Is this possible? It is possible, using exec, but it is not the right solution to your problem. You want a bunch of lists each associated with a name. The way to do this is put the lists in a dict; the name is the key, the list is the value. Your example would look like this: lists = {} for i in range(5): lists['list_%i' % (i)] = [] Kent From chris.arndt at web.de Fri Dec 22 17:49:19 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 22 Dec 2006 17:49:19 +0100 Subject: [Tutor] how to permanently add a module path In-Reply-To: <384c93600612220829q3a6bb740u53513156798a604e@mail.gmail.com> References: <384c93600612220738v2919c792j5af090009c751e77@mail.gmail.com> <458C02BF.9040708@web.de> <384c93600612220829q3a6bb740u53513156798a604e@mail.gmail.com> Message-ID: <458C0C8F.5030406@web.de> shawn bright schrieb: > ok, > i am on ubuntu and there is no /etc/profile.d directory > i put this in the /etc/environment file > > PYTHONPATH=/usr/lib/python2.4/site-packages/pivotrac > export PYTHONPATH > > but it doesn't seem to be working. > There is no master python config file somewhere where all these are listed ? > i wonder becuase i add modules via apt, and they are put where they need > to be. Ok, I see, you're trying to add you module in the standard site modules path (/usr/lib/pythonX.Y/site-packages on Unices). This is an entirely different matter. You have two possibilities: 1) Turn your module directory into a paackage by adding a '__init__.py' file to it. This file may be empty. You can then iumport from your module like this: from pivotrac import mymodule For more information on Python module packages, see here: http://www.python.org/doc/current/tut/node8.html#SECTION008400000000000000000 2) You can add a .pth file to the site-packages directory that points to your module directory. E.g. ass a file pivotrac.pth to /usr/lib/python2.4/site-packages/ that just contains one line: pivotrac For more information about .pth files, see here: http://www.python.org/doc/current/lib/module-site.html With both methods you don't need to change PYTHONPATH at all. Chris P.S. Please don't answer privately to somebody writing on the list, unless asked to do so. Reply to the list instead. From carloslara at web.de Fri Dec 22 17:59:33 2006 From: carloslara at web.de (Carlos) Date: Fri, 22 Dec 2006 17:59:33 +0100 Subject: [Tutor] Lists on the fly? In-Reply-To: <458C09DE.3030802@tds.net> References: <458C0753.6040305@web.de> <458C09DE.3030802@tds.net> Message-ID: <458C0EF5.9020607@web.de> Kent, Thanks a lot, that solves it... again Carlos From bgailer at alum.rpi.edu Fri Dec 22 18:31:00 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 22 Dec 2006 09:31:00 -0800 Subject: [Tutor] Lists on the fly? In-Reply-To: <458C0753.6040305@web.de> References: <458C0753.6040305@web.de> Message-ID: <458C1654.4070204@alum.rpi.edu> Carlos wrote: > Hello, > > I am wondering if it is possible to create lists on the fly. This is an FAQ. The more general question is "Can I create variables with dynamically generated names." The answers are: (1) Yes (2) This is rarely a good idea. The preferred solution is to use a dict or list, each item of which is one of the "variables" you want to create. Use a list if the names, like yours, are of the form list_1, list_2, ..., list_n. Then refer to the list with n as the list index. To apply to your example: list_ = [[] for x in xrange(5)] # creates [[], [], [], [], []]. Then you may refer to list_[0], list_[1], etc. > The script > that I'm working on needs a number of parameters, one of those is > population, and this corresponds to the number of solutions that a > genetic algorithm generates on each generation (iteration). The thing is > that I need to generate one list for each population member and then > append the corresponding population members to that particular list. > > This is only so you can have an idea: > > for i in range(5): > 'list_%i' % (i) = [] > > or: > > for i in range(5): > lista_+'%i' % (i) = [] > > :-[ > > Is this possible? > > Thanks in advance, > And Merry Christmas, > Carlos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From Steven.Oldner at LA.GOV Fri Dec 22 18:20:56 2006 From: Steven.Oldner at LA.GOV (Steve Oldner) Date: Fri, 22 Dec 2006 11:20:56 -0600 Subject: [Tutor] Lists on the fly? In-Reply-To: <458C09DE.3030802@tds.net> Message-ID: Hi guys, I am reading and doing examples from Python Web Programming and Have a question about the dictionary: counter = {} file = open("d:\myfile.txt") # the time has come the walrus said while 1: line = file.readline() if line == "": break for w in line.split(): if counter.has_key(w): counter[w] += 1 else: counter[w] = 1 file.close() words = counter.keys() words.sort() wor w in words: print w, counter{w} Output is: Come 1 Has 1 Said 1 The 2 Time 1 Walaus 1 ???? Okay, I understand counter is set up as a dictionary and a dictionary has a key and a value. How does the dictionary get built? I'm not following the logic in how the key, the actual word, is having a value assigned. Thanks, SteveO -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Friday, December 22, 2006 10:38 AM To: Carlos Cc: tutor at python.org Subject: Re: [Tutor] Lists on the fly? Carlos wrote: > Hello, > > I am wondering if it is possible to create lists on the fly. The > script that I'm working on needs a number of parameters, one of those > is population, and this corresponds to the number of solutions that a > genetic algorithm generates on each generation (iteration). The thing > is that I need to generate one list for each population member and > then append the corresponding population members to that particular list. > > This is only so you can have an idea: > > for i in range(5): > 'list_%i' % (i) = [] > > or: > > for i in range(5): > lista_+'%i' % (i) = [] > > :-[ > > Is this possible? It is possible, using exec, but it is not the right solution to your problem. You want a bunch of lists each associated with a name. The way to do this is put the lists in a dict; the name is the key, the list is the value. Your example would look like this: lists = {} for i in range(5): lists['list_%i' % (i)] = [] Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From nephish at gmail.com Fri Dec 22 18:32:46 2006 From: nephish at gmail.com (shawn bright) Date: Fri, 22 Dec 2006 11:32:46 -0600 Subject: [Tutor] how to permanently add a module path In-Reply-To: <458C0C8F.5030406@web.de> References: <384c93600612220738v2919c792j5af090009c751e77@mail.gmail.com> <458C02BF.9040708@web.de> <384c93600612220829q3a6bb740u53513156798a604e@mail.gmail.com> <458C0C8F.5030406@web.de> Message-ID: <384c93600612220932t5bbe02ffib48028c3305af07f@mail.gmail.com> thanks, i usually intend to, getting used to gmail. thanks for all the help, all working now. shawn On 12/22/06, Christopher Arndt wrote: > > shawn bright schrieb: > > ok, > > i am on ubuntu and there is no /etc/profile.d directory > > i put this in the /etc/environment file > > > > PYTHONPATH=/usr/lib/python2.4/site-packages/pivotrac > > export PYTHONPATH > > > > but it doesn't seem to be working. > > There is no master python config file somewhere where all these are > listed ? > > i wonder becuase i add modules via apt, and they are put where they need > > to be. > > Ok, I see, you're trying to add you module in the standard site modules > path > (/usr/lib/pythonX.Y/site-packages on Unices). This is an entirely > different matter. > > You have two possibilities: > > 1) Turn your module directory into a paackage by adding a '__init__.py' > file to > it. This file may be empty. You can then iumport from your module like > this: > > from pivotrac import mymodule > > > For more information on Python module packages, see here: > > > http://www.python.org/doc/current/tut/node8.html#SECTION008400000000000000000 > > 2) You can add a .pth file to the site-packages directory that points to > your > module directory. E.g. ass a file pivotrac.pth to > /usr/lib/python2.4/site-packages/ that just contains one line: > > pivotrac > > For more information about .pth files, see here: > > http://www.python.org/doc/current/lib/module-site.html > > > With both methods you don't need to change PYTHONPATH at all. > > > Chris > > P.S. Please don't answer privately to somebody writing on the list, unless > asked to do so. Reply to the list instead. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061222/497dfe78/attachment-0001.htm From bgailer at alum.rpi.edu Fri Dec 22 18:46:12 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 22 Dec 2006 09:46:12 -0800 Subject: [Tutor] Lists on the fly? In-Reply-To: References: Message-ID: <458C19E4.6040902@alum.rpi.edu> Steve Oldner wrote: > Hi guys, > > I am reading and doing examples from Python Web Programming and > Have a question about the dictionary: > > counter = {} > file = open("d:\myfile.txt") # the time has come the walrus said > while 1: > line = file.readline() > if line == "": > break > for w in line.split(): > if counter.has_key(w): > counter[w] += 1 > else: > counter[w] = 1 > file.close() > words = counter.keys() > words.sort() > wor w in words: > print w, counter{w} > > Output is: > > Come 1 > Has 1 > Said 1 > The 2 > Time 1 > Walaus 1 > > ???? > Okay, I understand counter is set up as a dictionary and a dictionary > has a key and a value. > How does the dictionary get built? I'm not following the logic in how > the key, the actual word, is having a value assigned. > counter[w] = 1 # if w is not a key in the dictionary, this assignment adds it, with a value of 1 > -- Bob Gailer 510-978-4454 From Steven.Oldner at LA.GOV Fri Dec 22 18:57:29 2006 From: Steven.Oldner at LA.GOV (Steve Oldner) Date: Fri, 22 Dec 2006 11:57:29 -0600 Subject: [Tutor] Lists on the fly? In-Reply-To: <458C19E4.6040902@alum.rpi.edu> Message-ID: Thank you! I makes sense now and shows me I need to research more on file methods. -----Original Message----- From: Bob Gailer [mailto:bgailer at alum.rpi.edu] Sent: Friday, December 22, 2006 11:46 AM To: Steve Oldner Cc: tutor at python.org Subject: Re: [Tutor] Lists on the fly? Steve Oldner wrote: > Hi guys, > > I am reading and doing examples from Python Web Programming and Have a > question about the dictionary: > > counter = {} > file = open("d:\myfile.txt") # the time has come the walrus said while > 1: > line = file.readline() > if line == "": > break > for w in line.split(): > if counter.has_key(w): > counter[w] += 1 > else: > counter[w] = 1 > file.close() > words = counter.keys() > words.sort() > wor w in words: > print w, counter{w} > > Output is: > > Come 1 > Has 1 > Said 1 > The 2 > Time 1 > Walaus 1 > > ???? > Okay, I understand counter is set up as a dictionary and a dictionary > has a key and a value. > How does the dictionary get built? I'm not following the logic in how > the key, the actual word, is having a value assigned. > counter[w] = 1 # if w is not a key in the dictionary, this assignment adds it, with a value of 1 > -- Bob Gailer 510-978-4454 From bgailer at alum.rpi.edu Fri Dec 22 19:35:10 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 22 Dec 2006 10:35:10 -0800 Subject: [Tutor] Lists on the fly? In-Reply-To: References: Message-ID: <458C255E.4030700@alum.rpi.edu> Steve Oldner wrote: > Thank you! I makes sense now and shows me I need to research more on > file methods. Good. One other advisory: don't use file as a variable name. file is a built-in function; reassigning it makes the function unavailable. -- Bob Gailer 510-978-4454 From pytutmail at gmail.com Fri Dec 22 21:27:25 2006 From: pytutmail at gmail.com (Toon Pieton) Date: Fri, 22 Dec 2006 21:27:25 +0100 Subject: [Tutor] winreg question Message-ID: <7c3104d20612221227i2b4e4afevd896e9725b61ca17@mail.gmail.com> Hey friendly users! I'm trying to connect to a certain key in my registery using winreg. However, I have run into some problems. 1) I'm trying to open HKEY_CURRENT_USER\Softwar\PartyGaming\PartyPoker. Is this (see below) the correct way to open that key? from winreg import * PartyPoker = Key( HKCU, "Software\\PartyGaming\\PartyPoker" ) 2) From this set of keys just opened, I want to get the data stored under one called AppPath. How do I do that? Thanks in advance! Toon Pieton -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061222/216a9b33/attachment.htm From carroll at tjc.com Fri Dec 22 23:07:33 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 22 Dec 2006 14:07:33 -0800 (PST) Subject: [Tutor] winreg question In-Reply-To: <7c3104d20612221227i2b4e4afevd896e9725b61ca17@mail.gmail.com> Message-ID: On Fri, 22 Dec 2006, Toon Pieton wrote: > I'm trying to connect to a certain key in my registery using winreg. I don't know winreg, but I know of _winreg; Same thing? (I'm on Activestate Python 2.4). > from winreg import * "from foo import *" is generally a bad idea, because you'll get a lot of names imported you may not be expecting. Better to use: import winreg and then prefix the imported names with "winreg." > PartyPoker = Key( > HKCU, > "Software\\PartyGaming\\PartyPoker" > ) Using _winreg, I'd do: >>> import _winreg >>> subkey = "Software\\Google\\Picasa\\Picasa2\\Runtime" >>> #substitute your subkey above >>> mykey = _winreg.OpenKey( ... _winreg.HKEY_CURRENT_USER, ... subkey) >>> > 2) From this set of keys just opened, I want to get the data stored under > one called AppPath. How do I do that? >>> (apppath, type) = _winreg.QueryValueEx(mykey, "AppPath") >>> print apppath C:\Program Files\Picasa2\Picasa2.exe >>> Of course, if your "winreg" is not the same as my "_winreg", none of this helps you! From chris.arndt at web.de Fri Dec 22 23:16:40 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Fri, 22 Dec 2006 23:16:40 +0100 Subject: [Tutor] winreg question In-Reply-To: <7c3104d20612221227i2b4e4afevd896e9725b61ca17@mail.gmail.com> References: <7c3104d20612221227i2b4e4afevd896e9725b61ca17@mail.gmail.com> Message-ID: <458C5948.4060007@web.de> Toon Pieton schrieb: > I'm trying to connect to a certain key in my registery using winreg. > However, I have run into some problems. > > 1) I'm trying to open HKEY_CURRENT_USER\Softwar\PartyGaming\PartyPoker. > Is this (see below) the correct way to open that key? See here for some examples of using the windows registry: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146305 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66011 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473846 > 2) From this set of keys just opened, I want to get the data stored > under one called AppPath. How do I do that? See for example the function '_get_reg_value' in the third recipe listed above. Chris From carroll at tjc.com Fri Dec 22 23:21:43 2006 From: carroll at tjc.com (Terry Carroll) Date: Fri, 22 Dec 2006 14:21:43 -0800 (PST) Subject: [Tutor] winreg question In-Reply-To: Message-ID: On Fri, 22 Dec 2006, Terry Carroll wrote: > On Fri, 22 Dec 2006, Toon Pieton wrote: > > > I'm trying to connect to a certain key in my registery using winreg. > > I don't know winreg, but I know of _winreg; Same thing? (I'm on > Activestate Python 2.4). Ah, I see winreg is no doubt the third-party module described here: http://www.rutherfurd.net/python/winreg/index.html Based on this, I think what you want to do is: import winreg PartyPokerKey = Key( winreg.HKCU, "Software\\PartyGaming\\PartyPoker" ) PartyPokerAppPath = PartyPokerKey.values["AppPath"] I can't be sure, though, because I don't have winreg installed to try it out. From rabidpoobear at gmail.com Sat Dec 23 00:50:46 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 22 Dec 2006 17:50:46 -0600 Subject: [Tutor] Lists on the fly? In-Reply-To: <458C09DE.3030802@tds.net> References: <458C0753.6040305@web.de> <458C09DE.3030802@tds.net> Message-ID: <458C6F56.3070102@gmail.com> Kent Johnson wrote: > Carlos wrote: > >> Hello, >> >> I am wondering if it is possible to create lists on the fly. The script >> that I'm working on needs a number of parameters, one of those is >> population, and this corresponds to the number of solutions that a >> genetic algorithm generates on each generation (iteration). The thing is >> that I need to generate one list for each population member and then >> append the corresponding population members to that particular list. >> >> This is only so you can have an idea: >> >> for i in range(5): >> 'list_%i' % (i) = [] >> Note, though this is pretty arbitrary :) and only saves you 2 characters... You don't need to create a tuple if you're only packing in one value. >>> i = 1 >>> 'list_%i' % i 'list_1' works just fine. HTH, -Luke From alan.gauld at btinternet.com Sat Dec 23 10:04:43 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Dec 2006 09:04:43 -0000 Subject: [Tutor] how to permanently add a module path References: <384c93600612220738v2919c792j5af090009c751e77@mail.gmail.com> <458C02BF.9040708@web.de> Message-ID: "Christopher Arndt" wrote > Linux: > > Depends on your distribution: It depends even more on the shell you use. In csh or tcsh the file to modify is .cshrc > - Standard way would be to edit ~/.bash_profile and add e.g. I prefer to modify environment variables in .profile. That way they are visible in bash, sh, ksh, ash which all read .profile, whereas only bash reads .bash_profile. > # entries are separated by colons ':' > PYTHONPATH=$HOME/lib/python:/where/my/other/python/modules/live > export PYTHONPATH I usually put $PYTHONPATH in front too in case there is a site wide version defined already. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Dec 23 10:10:32 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Dec 2006 09:10:32 -0000 Subject: [Tutor] Lists on the fly? References: <458C0753.6040305@web.de> Message-ID: "Carlos" wrote > I am wondering if it is possible to create lists on the fly. In general you can use a list comprehension to do that. > This is only so you can have an idea: > > for i in range(5): > 'list_%i' % (i) = [] >>> mylists = [ [] for n in range(5)] creats a list of 5 empty lists. You can then poulate the sublists using normal indexing: >>> mylists[0].append(5) >>> print mylists[0][0] 5 You can find more on List Comprehensions in the Functional Programming topic of my web tutor. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Dec 23 10:16:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Dec 2006 09:16:53 -0000 Subject: [Tutor] Lists on the fly? References: <458C0753.6040305@web.de><458C09DE.3030802@tds.net> <458C6F56.3070102@gmail.com> Message-ID: "Luke Paireepinart" wrote >>> 'list_%i' % (i) = [] >>> > Note, though this is pretty arbitrary :) and only saves you 2 > characters... > You don't need to create a tuple if you're only packing in one > value. > >>> i = 1 > >>> 'list_%i' % i And that works for multiple values provided they are unambiguous. "%d,%d,%d" % 1,2,3 You need the parens if the substitution values are more complex and include operators: "%d,%d,%d" % 1, 2, 1+2 Will give an error (adding int to string) you need the parens here: "%d,%d,%d" % (1, 2, 1+2) HTH, Alan G From emilia12 at mail.bg Sat Dec 23 10:39:22 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Sat, 23 Dec 2006 11:39:22 +0200 Subject: [Tutor] [tutor] sort a list In-Reply-To: References: Message-ID: <1166866762.7bfba6c1b67f4@mail.bg> Hi List, I have a list like this x=[7,4,2,6] and print x.sort() gives to me None ! : >> x=[7,4,2,6] >> print x.sort() None ... but >> x=[7,4,2,6] >> x.sort() >> print x [2, 4, 6, 7] so, why list.sort() returns None? is this normal ? (the python is "Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32") E. ----------------------------- ??????? ?????? ?????? ???????????! ??????: ?? 15 ???????? ? ??????. http://reklama.mail.bg/eragon/ From rabidpoobear at gmail.com Sat Dec 23 10:53:27 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 23 Dec 2006 03:53:27 -0600 Subject: [Tutor] [tutor] sort a list In-Reply-To: <1166866762.7bfba6c1b67f4@mail.bg> References: <1166866762.7bfba6c1b67f4@mail.bg> Message-ID: <458CFC97.2010005@gmail.com> emilia12 at mail.bg wrote: > Hi List, > > I have a list like this x=[7,4,2,6] > and print x.sort() > gives to me None ! : > > >>> x=[7,4,2,6] >>> print x.sort() >>> > None > > ... but > > >>> x=[7,4,2,6] >>> x.sort() >>> print x >>> > [2, 4, 6, 7] > > so, why list.sort() returns None? is this normal ? > No, this is not normal. When the planets are aligned perfectly (which is very rare, thankfully), it creates magnetic interference that messes with Python interpreters in RAM and causes the list.sort method to return None. It's still being investigated. It just so happens that we had a momentary planet alignment earlier this week, which should explain the problems you've been having. Seriously, though, see http://www.python.org/infogami-faq/general/why-doesn-t-list-sort-return-the-sorted-list/ for an explanation. Basically, as we can see here > (the python is "Python 2.4.3 (#69, Mar 29 2006, 17:35:34) > [MSC v.1310 32 bit (Intel)] on win32") > you're using Python 2.4, so you can just do sorted(x) and it will return the sorted list. It also might be a good idea to read the rest of that FAQ. HTH, -Luke From carloslara at web.de Sat Dec 23 11:17:55 2006 From: carloslara at web.de (Carlos) Date: Sat, 23 Dec 2006 11:17:55 +0100 Subject: [Tutor] Lists on the fly? In-Reply-To: References: Message-ID: <458D0253.20604@web.de> Hi, First of all, thanks for your help. This is how this ended up: Elements = [ {'Name': 'Access', 'Parent': 'Plot', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Circulation_01', 'Parent': 'Access', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Circulation_02', 'Parent': 'Access', 'Level': 2.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Circulation_03', 'Parent': 'Access', 'Level': 3.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Int_Circ_01', 'Parent': 'Circulation_01', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Int_Circ_02', 'Parent': 'Circulation_01', 'Level': 1.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Int_Circ_03', 'Parent': 'Circulation_02', 'Level': 2.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Int_Circ_04', 'Parent': 'Circulation_02', 'Level': 2.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Int_Circ_05', 'Parent': 'Circulation_03', 'Level': 3.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0}, {'Name': 'Int_Circ_06', 'Parent': 'Circulation_03', 'Level': 3.0, 'Height': 3.0, 'Width': 3.0, 'Depth': 3.0} ] # Get Levels List for Element in Elements: Lev_List['Level_%i' % (Element['Level'])] = [] # Append Element to corresponding Level for Element in Elements: Lev_List['Level_%i' % (Element['Level'])].append(Element['Name']) print Lev_List And this is the result: Lev_List = { 'Level_1': ['Access', 'Circulation_01', 'Int_Circ_01', 'Int_Circ_02'], 'Level_2': ['Circulation_02', 'Int_Circ_03', 'Int_Circ_04'], 'Level_3': ['Circulation_03', 'Int_Circ_05', 'Int_Circ_06'] } It works fine, as far as I can tell. I mean, no matter how many 'Levels' it will allways get them right (levels so far are only integers). Probably the first loop is a little redundant, but performance is not one of my concerns now, but in the future the project will not be composed by a handful of spaces, probably by hundreds or more. Regards, Carlos From rabidpoobear at gmail.com Sat Dec 23 11:33:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 23 Dec 2006 04:33:22 -0600 Subject: [Tutor] Lists on the fly? In-Reply-To: <458D0253.20604@web.de> References: <458D0253.20604@web.de> Message-ID: <458D05F2.7050602@gmail.com> [snip] > # Get Levels List > for Element in Elements: > Lev_List['Level_%i' % (Element['Level'])] = [] > > # Append Element to corresponding Level > for Element in Elements: > Lev_List['Level_%i' % (Element['Level'])].append(Element['Name']) [snip snip] > Probably the first loop is a little redundant, but performance is not > one of my concerns now, but in the future the project will not be > composed by a handful of spaces, probably by hundreds or more. > I think a better way to do this is to check if 'Level_%i' is in your dictionary already. so the loop becomes Lev_List = {} for Element in Elements: keystr = 'Level_%i' % Element['Level'] if not Lev_List.has_key(keystr): Lev_List[keystr] = [] Lev_List[keystr].append(Element['Name']) And of course you can go the EAFP (easier to ask forgiveness than permission) route and use a try/accept block Lev_List = {} for Element in Elements: keystr = 'Level_%i' % Element['Level'] try: Lev_List[keystr].append(Element['Name']) except KeyError: Lev_List[keystr] = [Element['Name']] I suspect the try/accept would be the fastest, but you'd have to timeit to be sure, of course. HTH, -Luke From kent37 at tds.net Sat Dec 23 14:13:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Dec 2006 08:13:06 -0500 Subject: [Tutor] Lists on the fly? In-Reply-To: <458D05F2.7050602@gmail.com> References: <458D0253.20604@web.de> <458D05F2.7050602@gmail.com> Message-ID: <458D2B62.9070706@tds.net> Luke Paireepinart wrote: > I think a better way to do this is to check if 'Level_%i' is in your > dictionary already. > so the loop becomes > > Lev_List = {} > for Element in Elements: > keystr = 'Level_%i' % Element['Level'] > if not Lev_List.has_key(keystr): > Lev_List[keystr] = [] > Lev_List[keystr].append(Element['Name']) I am a fan of dict.setdefault() which has this logic built in: Lev_List = {} for Element in Elements: keystr = 'Level_%i' % Element['Level'] Lev_List.setdefault(keystr, []).append(Element['Name']) Also there is no need to create a string for the key, Element['Level'] is a fine key: Lev_List = {} for Element in Elements: Lev_List.setdefault(Element['Level'], []).append(Element['Name']) Kent From rabidpoobear at gmail.com Sat Dec 23 20:44:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 23 Dec 2006 13:44:37 -0600 Subject: [Tutor] Lists on the fly? In-Reply-To: <458D2B62.9070706@tds.net> References: <458D0253.20604@web.de> <458D05F2.7050602@gmail.com> <458D2B62.9070706@tds.net> Message-ID: <458D8725.7010305@gmail.com> Kent Johnson wrote: > Luke Paireepinart wrote: > >> I think a better way to do this is to check if 'Level_%i' is in your >> dictionary already. > I am a fan of dict.setdefault() which has this logic built in: > Lev_List = {} > for Element in Elements: > keystr = 'Level_%i' % Element['Level'] > Lev_List.setdefault(keystr, []).append(Element['Name']) > > Also there is no need to create a string for the key, Element['Level'] > is a fine key: > You're absolutely right, Kent. I just created a variable for it because I referred to it 3 times, and didn't want to write out the string over and over. The only reason I used 'Level_%i' instead of just Element['Level'] was because he had that in the original program. > Lev_List = {} > for Element in Elements: > Lev_List.setdefault(Element['Level'], []).append(Element['Name']) > Really cool. I'm a fan now, too :) Thanks for this. -Luke From bashu at yandex.ru Sun Dec 24 07:09:10 2006 From: bashu at yandex.ru (Basil Shubin) Date: Sun, 24 Dec 2006 12:09:10 +0600 Subject: [Tutor] MVC/MVP examples of how to implement it In-Reply-To: References: Message-ID: Don Taylor ?????: > Basil Shubin wrote: >> Hi friends! >> >> I have read articles about MVC/MVP, but still can't get a clue to how >> implement it in really working application :-( Because I better >> understand with ready to use examples, can you provide link to free >> python+GUI application which implements MVC/MVP design? >> > Here is another example of MVP in Python/wxPython. > > http://wiki.wxpython.org/index.cgi/ModelViewPresenter Thanks, now I almost implement what I want :-) BTW current design of my app is much better with MVP than with my own solution. From jonathan at acss.net.au Sun Dec 24 11:27:59 2006 From: jonathan at acss.net.au (Jonathan McManus) Date: Sun, 24 Dec 2006 20:27:59 +1000 Subject: [Tutor] Infinite Loops (and threads) Message-ID: <1166956079.5093.8.camel@Copernicus> Hi all, Just a quick question, really. Is there any good way to have an infinite loop in a program, without said infinite loop eating up the CPU? I've tried the trick of adding a pause (time.sleep(0.01)) somewhere in the loop, and this appears to have worked on a basic infinite loop, but this doesn't appear to work for two separate infinite loops (in threads). Thanks in advance. -- Regards, Jonathan McManus -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 191 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20061224/6b1457e4/attachment.pgp From kent37 at tds.net Sun Dec 24 13:52:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Dec 2006 07:52:05 -0500 Subject: [Tutor] Infinite Loops (and threads) In-Reply-To: <1166956079.5093.8.camel@Copernicus> References: <1166956079.5093.8.camel@Copernicus> Message-ID: <458E77F5.1000701@tds.net> Jonathan McManus wrote: > Hi all, > > Just a quick question, really. Is there any good way to have an infinite > loop in a program, without said infinite loop eating up the CPU? I've > tried the trick of adding a pause (time.sleep(0.01)) somewhere in the > loop, and this appears to have worked on a basic infinite loop, but this > doesn't appear to work for two separate infinite loops (in threads). You would have to put a sleep in each thread. Why are you using infinite loops? Are you implementing some kind of polling loop? Often there are better alternatives, either an event notification or some kind of lock. If you post some details of why you want to do this we may be able to help you find a better way. Kent From adam.jtm30 at gmail.com Sun Dec 24 13:56:43 2006 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 24 Dec 2006 12:56:43 +0000 Subject: [Tutor] Game server login encryption Message-ID: I'm currently writing a networked game and I'm about to write a proper implementation of the logon server. I would prefer to have some sort of encryption but would like some opinions. The way I see it either I can take a hash of some data eg. username, password, port and ip and check the hash against one generated on the server. Alternatively I could use twisted conch tunneling through ssh. I anybody has any opinions on either of these ideas or anything else that might be useful, fire away. Cheers, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061224/e251edeb/attachment.html From rabidpoobear at gmail.com Sun Dec 24 17:02:19 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 24 Dec 2006 10:02:19 -0600 Subject: [Tutor] Infinite Loops (and threads) In-Reply-To: <458E77F5.1000701@tds.net> References: <1166956079.5093.8.camel@Copernicus> <458E77F5.1000701@tds.net> Message-ID: <458EA48B.3040602@gmail.com> Kent Johnson wrote: > Jonathan McManus wrote: > >> Hi all, >> >> Just a quick question, really. Is there any good way to have an infinite >> loop in a program, without said infinite loop eating up the CPU? I've >> tried the trick of adding a pause (time.sleep(0.01)) somewhere in the >> loop, and this appears to have worked on a basic infinite loop, but this >> doesn't appear to work for two separate infinite loops (in threads). >> > > You would have to put a sleep in each thread. > > Why are you using infinite loops? Are you implementing some kind of > polling loop? Often there are better alternatives, either an event > notification or some kind of lock. If you post some details of why you > want to do this we may be able to help you find a better way. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Kent et. al., I'm writing something that has to do with sockets. I need to recv any incoming packets from the socket. I will have potentially hundreds of separate sockets open in a single application. I was just going to create a thread for each, so I could receive from them separately. Alternately, I figured I could read from each socket in sequence if I could get the recv method to not block until it gets input, so I tried this, #code ---- self.conn.setblocking(False) info = self.conn.recv(8000)#this should read everything. #---- code where conn is connected to another computer already, and I get the following error: (Verbatim except for line 3, changed to hide username/password) Traceback (most recent call last): File "C:\Python Scripts\AIM Connection Server\toc2.py", line 199, in ? toc.login('---username---','---password---') File "C:\Python Scripts\AIM Connection Server\toc2.py", line 116, in login print self.getFlap() File "C:\Python Scripts\AIM Connection Server\toc2.py", line 93, in getFlap info = self.conn.recv(8000)#this should read everything. error: (10035, 'The socket operation could not complete without blocking') Do I misunderstand what blocking is? It seems to me that blocking would mainly apply to inputs. (My understanding is that 'blocking' means when you call 'recv' it will return '' if it didn't receive anything.) I'd appreciate any links that I could read up on, or any advice on how to make socket inputs with event notification, as Kent mentioned earlier. Basically, as Kent said, I have a polling loop, and I am not sure what the alternative is to threads. Thanks, -Luke From adam.jtm30 at gmail.com Sun Dec 24 18:06:47 2006 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 24 Dec 2006 17:06:47 +0000 Subject: [Tutor] Infinite Loops (and threads) In-Reply-To: <458EA48B.3040602@gmail.com> References: <1166956079.5093.8.camel@Copernicus> <458E77F5.1000701@tds.net> <458EA48B.3040602@gmail.com> Message-ID: On 24/12/06, Luke Paireepinart wrote: > > Kent Johnson wrote: > > Jonathan McManus wrote: > > > >> Hi all, > >> > >> Just a quick question, really. Is there any good way to have an > infinite > >> loop in a program, without said infinite loop eating up the CPU? I've > >> tried the trick of adding a pause (time.sleep(0.01)) somewhere in the > >> loop, and this appears to have worked on a basic infinite loop, but > this > >> doesn't appear to work for two separate infinite loops (in threads). > >> > > > > You would have to put a sleep in each thread. > > > > Why are you using infinite loops? Are you implementing some kind of > > polling loop? Often there are better alternatives, either an event > > notification or some kind of lock. If you post some details of why you > > want to do this we may be able to help you find a better way. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > Kent et. al., > > I'm writing something that has to do with sockets. > I need to recv any incoming packets from the socket. > I will have potentially hundreds of separate sockets open in a single > application. > I was just going to create a thread for each, so I could receive from > them separately. > > Alternately, I figured I could read from each socket in sequence if I > could get the recv method to not block until it gets input, > so I tried this, > > #code ---- > self.conn.setblocking(False) > info = self.conn.recv(8000)#this should read everything. > #---- code > > where conn is connected to another computer already, > and I get the following error: > > (Verbatim except for line 3, changed to hide username/password) > Traceback (most recent call last): > File "C:\Python Scripts\AIM Connection Server\toc2.py", line 199, in ? > toc.login('---username---','---password---') > File "C:\Python Scripts\AIM Connection Server\toc2.py", line 116, in > login > print self.getFlap() > File "C:\Python Scripts\AIM Connection Server\toc2.py", line 93, in > getFlap > info = self.conn.recv(8000)#this should read everything. > error: (10035, 'The socket operation could not complete without blocking') > > Do I misunderstand what blocking is? > It seems to me that blocking would mainly apply to inputs. > (My understanding is that 'blocking' means when you call 'recv' it will > return '' if it didn't receive anything.) > > I'd appreciate any links that I could read up on, or any advice on how > to make socket inputs with event notification, as Kent mentioned earlier. > > Basically, as Kent said, I have a polling loop, and I am not sure what > the alternative is to threads. > > Thanks, > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Well I've been doing some networking stuff in stackless myself recently and I would probably do something like this: import select import stackless import socket def get_data(sock): sock.setblocking(0) poller = select.poll() poller.register(sock, select.POLLIN) while True: if poller.poll(0): sock.recv(1024) stackless.schedule() stackless.tasklet(get_data)(socket.socket(socket.AF_INET, socket.SOCK_DGRAM )) stackless.run() stackless thread things are really low on resources so you can run tens of thousands without too much trouble. HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061224/bb6b8bbb/attachment.html From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= Sun Dec 24 18:58:55 2006 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?=) Date: Sun, 24 Dec 2006 20:58:55 +0300 Subject: [Tutor] Infinite Loops (and threads) In-Reply-To: <458EA48B.3040602@gmail.com> References: <1166956079.5093.8.camel@Copernicus> <458E77F5.1000701@tds.net> <458EA48B.3040602@gmail.com> Message-ID: <20061224205855.23fcc7f8@arch.zamb.pc> Luke Paireepinart On Sun, 24 Dec 2006 10:02:19 -0600 wrote: > Kent Johnson wrote: > Kent et. al., > > I'm writing something that has to do with sockets. > I need to recv any incoming packets from the socket. > I will have potentially hundreds of separate sockets open in a single > application. > I was just going to create a thread for each, so I could receive from > them separately. > > Alternately, I figured I could read from each socket in sequence if I > could get the recv method to not block until it gets input, > so I tried this, > > Thanks, > -Luke Use "import select" and read about it for more information (i.e. help(select) within Python shell). I advice you (and others interested in writing Python code dealing with sockets) *very strongly* to read the following: http://www.amk.ca/python/howto/sockets/ (Currently, I'm having trouble accessing that URL. I don't know if it's my ISP or the the site is down.) I hope that helps. Ziyad. From kent37 at tds.net Sun Dec 24 19:33:42 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Dec 2006 13:33:42 -0500 Subject: [Tutor] Infinite Loops (and threads) In-Reply-To: <458EA48B.3040602@gmail.com> References: <1166956079.5093.8.camel@Copernicus> <458E77F5.1000701@tds.net> <458EA48B.3040602@gmail.com> Message-ID: <458EC806.5060904@tds.net> Luke Paireepinart wrote: > Kent et. al., > > I'm writing something that has to do with sockets. > I need to recv any incoming packets from the socket. > I will have potentially hundreds of separate sockets open in a single > application. > I was just going to create a thread for each, so I could receive from > them separately. Yes, that is one way to do it - make a thread for each socket and use blocking I/O. Then each thread will block until data is available. This avoids the kind of busy wait loop the OP described. > > Alternately, I figured I could read from each socket in sequence if I > could get the recv method to not block until it gets input, That is another good approach. You might want to look at Twisted or Medusa, they are both server frameworks that use asynchronous, non-blocking I/O to manage multiple sockets in a single thread: http://twistedmatrix.com/trac/ http://www.nightmare.com/medusa/ > Do I misunderstand what blocking is? > It seems to me that blocking would mainly apply to inputs. Usually, though output can block too. > (My understanding is that 'blocking' means when you call 'recv' it will > return '' if it didn't receive anything.) No; with a blocking socket, recv() will not return until data is available; with a non-blocking socket recv() will raise an exception if data is not available. Kent From clsdaniel at gmail.com Sun Dec 24 19:55:19 2006 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Sun, 24 Dec 2006 11:55:19 -0700 Subject: [Tutor] Game server login encryption In-Reply-To: References: Message-ID: <4fae7dfa0612241055yc8a7f3at4beff8a68bd36ded@mail.gmail.com> You can use SSL encripted connections, for logon and all session if you like, socket module has SSL support too: http://docs.python.org/lib/module-socket.html http://docs.python.org/lib/ssl-objects.html http://docs.python.org/lib/socket-example.html (check last example) As for hashes, password hashing with md5, most sites or systems authenticates against the hash, never use the clear password, a hash is better and can be faster. http://docs.python.org/lib/module-md5.html Regards, Carlos Daniel Ruvalcaba Valenzuela On 12/24/06, Adam Bark wrote: > I'm currently writing a networked game and I'm about to write a proper > implementation of the logon server. I would prefer to have some sort of > encryption but would like some opinions. The way I see it either I can take > a hash of some data eg. username, password, port and ip and check the hash > against one generated on the server. Alternatively I could use twisted conch > tunneling through ssh. I anybody has any opinions on either of these ideas > or anything else that might be useful, fire away. > Cheers, > Adam. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From raistlen117 at msn.com Sun Dec 24 20:09:36 2006 From: raistlen117 at msn.com (Raven Of Night Raven Of Night) Date: Sun, 24 Dec 2006 11:09:36 -0800 Subject: [Tutor] hi, learning python Message-ID: print "Guesses you've taken: ",i, "\nGuess letter: " letter_guess = raw_input()' this is a line of my program, and raw_input only takes one argument. I want it to display like this Guesses you've taken: 0 Guess letter: (letter would go here) instead of Guesses you've taken: 0 Guess letter: (leter you've taken) is there a way to continue the input line, like in java you would just do System.out.print? thanks _________________________________________________________________ Experience the magic of the holidays. Talk to Santa on Messenger. http://clk.atdmt.com/MSN/go/msnnkwme0080000001msn/direct/01/?href=http://imagine-windowslive.com/minisites/santabot/default.aspx?locale=en-us From bgailer at alum.rpi.edu Sun Dec 24 21:00:06 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 24 Dec 2006 12:00:06 -0800 Subject: [Tutor] hi, learning python In-Reply-To: References: Message-ID: <458EDC46.5040600@alum.rpi.edu> Raven Of Night Raven Of Night wrote: > print "Guesses you've taken: ",i, "\nGuess letter: " > letter_guess = raw_input()' > > > this is a line of my program, and raw_input only takes one argument. I want > it to display like this > > Guesses you've taken: 0 > Guess letter: (letter would go here) > > instead of > > Guesses you've taken: 0 > Guess letter: > (leter you've taken) > > is there a way to continue the input line, like in java you would just do > System.out.print? > print "Guesses you've taken: " ,i letter_guess = raw_input("Guess letter: ") -- Bob Gailer 510-978-4454 From midtoad at yahoo.com Sun Dec 24 21:47:16 2006 From: midtoad at yahoo.com (Stewart Midwinter) Date: Sun, 24 Dec 2006 12:47:16 -0800 (PST) Subject: [Tutor] Possible with list comprehension? Message-ID: <20061224204716.87741.qmail@web53910.mail.yahoo.com> List comprehension is a wondering feature, well covered in diveintopython.org. I learned some new tricks there, especially from example 8.15. Now I'm wondering if I can express the following more succinctly using list comprehension: for key,val in dataDict.items(): for i in range(val): prods.append(key) I have a dictionary containing an x,y set of values and occurrences: {'1':1, '10':2, '100':3, '1000':1, '10000':2} and want to find the mean value, so I need to build a list containing an occurrence weight set of values, and then select the middle value in the list. The list created by the above code snippet will look like this: [1, 10,10, 100,100,100, 1000, 10000,10000] and it has 9 elements, so the mean will be the 4.5th (call it 4th) element, so mean = 100. My attempt at the list comprehension is complicated by the fact that I'm trying to add elements to the list that's under construction in the list comprehension. How do I refer to the list istself? I tried using 'self' but that didn't work. Would I need to use a lambda function instead? Here's my attempt: prods = [eval("for i in range(%i): self.append(%s)" % (val,key)) for key,val in dataDict.items()] which gives a syntax error. If I try it with a lambda (below),I get an error message saying self is not defined: prods = [lambda self=self,val=val,key=key: eval("for i in range(%i): self.append(%s)" % (val,key)) for key,val in dataDict.items()] Maybe this is beyond the capabilities of list comprehension? Or perhaps even if it's possible it's too obtuse and not pythonic idiom? Certainly my original version at the top of this message is clear and readable. It's just on three lines instead of one. Perhaps that isn't so bad. thanks, Stewart __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Sun Dec 24 22:15:57 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Dec 2006 16:15:57 -0500 Subject: [Tutor] Possible with list comprehension? In-Reply-To: <20061224204716.87741.qmail@web53910.mail.yahoo.com> References: <20061224204716.87741.qmail@web53910.mail.yahoo.com> Message-ID: <458EEE0D.2020204@tds.net> Stewart Midwinter wrote: > List comprehension is a wondering feature, well covered in diveintopython.org. I learned some new tricks there, especially from example 8.15. Now I'm wondering if I can express the following more succinctly using list comprehension: > for key,val in dataDict.items(): > for i in range(val): > prods.append(key) I think this will do it: prods = [ key for key,val in dataDict.items() for i in range(val) ] > > I have a dictionary containing an x,y set of values and occurrences: > {'1':1, '10':2, '100':3, '1000':1, '10000':2} and want to find the mean value, so I need to build a list containing an occurrence weight set of values, and then select the middle value in the list. The list created by the above code snippet will look like this: > [1, 10,10, 100,100,100, 1000, 10000,10000] > and it has 9 elements, so the mean will be the 4.5th (call it 4th) element, so mean = 100. That is the median, not the mean. For this approach to work you have to sort dataDict.items(), in general dict keys and values are not in any obvious order. Fortunately it is easy to do this: prods = [ key for key,val in sorted(dataDict.items()) for i in range(val) ] > > My attempt at the list comprehension is complicated by the fact that I'm trying to add elements to the list that's under construction in the list comprehension. That is what every list comprehension does - it builds a new list, adding elements to the list that is under construction. Kent From midtoad at yahoo.com Mon Dec 25 00:50:37 2006 From: midtoad at yahoo.com (Stewart Midwinter) Date: Sun, 24 Dec 2006 15:50:37 -0800 (PST) Subject: [Tutor] Possible with list comprehension? Message-ID: <20061224235038.57453.qmail@web53910.mail.yahoo.com> Aah! A nested list comprehension. I hadn't considered that. Thanks, your solution is both concise and easy to read. and, oops, you're right, I was thinking of median but saying mean. cheers S ----- Original Message ---- From: Kent Johnson That is the median, not the mean. For this approach to work you have to sort dataDict.items(), in general dict keys and values are not in any obvious order. Fortunately it is easy to do this: prods = [ key for key,val in sorted(dataDict.items()) for i in range(val) ] __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at btinternet.com Mon Dec 25 02:07:59 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Dec 2006 01:07:59 -0000 Subject: [Tutor] hi, learning python References: Message-ID: "Raven Of Night Raven Of Night" wrote > print "Guesses you've taken: ",i, "\nGuess letter: " > letter_guess = raw_input()' > > > this is a line of my program, and raw_input only takes one argument. Yes, and that argument is the prompt to display to the user, which is what you want... letter_guess = raw_input('Guess letter. ') > is there a way to continue the input line, like in java you would > just do > System.out.print? As to simulating Java's print style, yes, there are a couple of ways. 1) put a comma at the end of the string to be printed: print 'hello ", print 'world' prints hello world 2) use sys.stdout.write() sys.stdout.write('hello ') sys.stdout.write('world') 3) use string formatting to create the string before printing outstring = "%s %s %" % (var1,var2,var3) It all depends what you are trying to do which one suits best... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Dec 25 03:05:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Dec 2006 21:05:20 -0500 Subject: [Tutor] Python and rpy In-Reply-To: <5d8e35a70612220221r7f324d1fl30ef1810d6c838c1@mail.gmail.com> References: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com> <458AEDE3.8030006@tds.net> <5d8e35a70612220221r7f324d1fl30ef1810d6c838c1@mail.gmail.com> Message-ID: <458F31E0.9070107@tds.net> Geoframer wrote: > As i stated i think the conversion from Python to R is going wrong, but > i have no clue on how to properly address that. I agree. If you have Numeric installed (which I do) then r.diag() should return a Numeric array, not a list of lists. This looks like the same problem discussed in this thread: http://sourceforge.net/mailarchive/message.php?msg_id=15307721 which does not seem to have been resolved. I don't want to get involved in the Rpy mailing list but I would suggest posting a very simple question asking why the result of r.diag() is not a Numeric array. Perhaps this will lead to a solution. > The code snippet i was talking about is on page 15 and 16 of the rpy > reference guide http://rpy.sourceforge.net/rpy/doc/rpy.pdf ; the > examples just don't work and i am lacking enough python experience to > see why :-S. > > What i'm trying to do now is : > > ---- > from rpy import * > > class Test: > def as_r(self): > return [[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]] > > if __name__ == "__main__": > a=with_mode(NO_CONVERSION, Test)() > r.kmeans(a, 2, 5, 10, "Forgy") I don't see how this will help. My understanding is that as_r() should return an Robj, not a Python object. I think this code is the same as passing a list of lists directly to kmeans. Kent From midtoad at yahoo.com Mon Dec 25 07:25:48 2006 From: midtoad at yahoo.com (Stewart Midwinter) Date: Sun, 24 Dec 2006 22:25:48 -0800 (PST) Subject: [Tutor] Possible with list comprehension? Message-ID: <20061225062548.97367.qmail@web53913.mail.yahoo.com> hmm, maybe you're right. I certainly agree that your example is nested and mine is not. I wonder what the exact description of Kent's solution is? ----- Original Message ---- From: Luke Paireepinart I don't think this is a 'nested list comprehension.' I think that would be c = 'Hello, World!' [a for a in [b for b in c]] in other words: a list comprehension inside of a list comprehension. Whereas this example is a single list comprehension because it only builds one list, despite having multiple 'for' loops. -Luke __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061224/03a9a4f2/attachment.html From mobiledreamers at gmail.com Mon Dec 25 08:39:17 2006 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sun, 24 Dec 2006 23:39:17 -0800 Subject: [Tutor] Pointers on accessing request object in python webprogramming frameworks Message-ID: Regarding sessions set by a different application say yahoo mail or MYSPACE Session set by a different app say yahoo mail api Hi guys One app i m developing needs integrating with the client site and get their users, so I need to use their login to log the users in and once they are in they should use my application sort of like Microsoft Passport... Here is the problem the example usage is in Django and they are talking about a request object if 'session_key' in request.session and 'uid' in request.session: fb.session_key = request.session['session_key'] Anyone can tell me how I can access this in webpy Isnt flup something that is set from webpy, how do we use sessions that are set by a different Application This question has a wide range of implications for eg., this can be used to apply to newly opened yahoo mail api etc., So please share your insights. I m sharing the example code below.. Thanks # ----------------------- # Web application example # ----------------------- def simple_web_app(request, api_key, secret_key): fb = WebAppWidget(api_key, secret_key, request.GET['auth_token']) fb.auth_getSession() friend_ids = fb.friends_get() info = fb.users_getInfo(friend_ids, ['name', 'pic']) print '' for friend in info: print '%(name)s' % friend print '' def web_app(request): """Get the user's friends and their pictures. This example uses the Django web framework, but should be adaptable to others.""" # Get api_key and secret_key from a file fb_file = open('facebook_keys.txt').readlines() api_key = fb_file[0].strip() secret_key = fb_file[1].strip() fb = WebAppWidget(api_key, secret_key) # Use the data from the cookie if present if 'session_key' in request.session and 'uid' in request.session: fb.session_key = request.session['session_key'] fb.uid = request.session['uid'] else: try: fb.auth_token = request.GET['auth_token'] except KeyError: # Send user to the WebAppWidget to login return HttpResponseRedirect(fb.get_login_url()) # getSession sets the session_key and uid # Store these in the cookie so we don't have to get them again fb.auth_getSession() request.session['session_key'] = fb.session_key request.session['uid'] = fb.uid try: friend_ids = fb.friends_get() except WebAppWidgetError, e: # Error 102 means the session has expired. # Delete the cookie and send the user to WebAppWidget to login if e.info['code'] == u'102': del request.session['session_key'] del request.session['uid'] return HttpResponseRedirect(fb.get_login_url()) else: # Other WebAppWidget errors are possible too. Don't ignore them. raise info = fb.users_getInfo(friend_ids, ['name', 'pic']) # info is a list of dictionaries # you would never do this in an actual Django application, # it's just an example of accessing the results. links = [] for friend in info: html = '%(name)s' % friend links.append(html) return render_to_response('template.html', {'links': links}) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061224/d3a0559f/attachment-0001.htm From anilmrn at yahoo.com Mon Dec 25 13:03:06 2006 From: anilmrn at yahoo.com (anil maran) Date: Mon, 25 Dec 2006 04:03:06 -0800 (PST) Subject: [Tutor] Sending email from windows python Message-ID: <109532.94517.qm@web55204.mail.re4.yahoo.com> Hi guys how do we use sendmail to send mail from windows smtplib works in unix flawlessly thanks Anil __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061225/0cfaad09/attachment.html From alan.gauld at btinternet.com Mon Dec 25 13:26:53 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Dec 2006 12:26:53 -0000 Subject: [Tutor] Sending email from windows python References: <109532.94517.qm@web55204.mail.re4.yahoo.com> Message-ID: "anil maran" wrote > how do we use sendmail to send mail from windows > smtplib works in unix flawlessly It should work in windows too provided you have an SMTP server such as sendmail running somewhere. Alan G. From anilmrn at yahoo.com Mon Dec 25 06:02:24 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 24 Dec 2006 21:02:24 -0800 (PST) Subject: [Tutor] index of max value in a list In-Reply-To: Message-ID: <939228.9856.qm@web55211.mail.re4.yahoo.com> the max function, it returns the maximum value in the list rather than the index associated with that value. How do I return the index? thanks Anil __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Mon Dec 25 13:58:36 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Dec 2006 07:58:36 -0500 Subject: [Tutor] index of max value in a list In-Reply-To: <939228.9856.qm@web55211.mail.re4.yahoo.com> References: <939228.9856.qm@web55211.mail.re4.yahoo.com> Message-ID: <458FCAFC.6050309@tds.net> anil maran wrote: > the max function, it returns the maximum value in the > list rather than the index associated with that value. > > How do I return the index? l.index(max(l)) will give you the index of the first occurrance of the maximum. m = max(l) [ i for i,v in enumerate(l) if v==m ] will give you a list of all indices where the max occurs. (Putting the 'max(l)' outside the list comprehension prevents it from being evaluated for each loop element.) Kent From mobiledreamers at gmail.com Mon Dec 25 22:12:23 2006 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 25 Dec 2006 13:12:23 -0800 Subject: [Tutor] Sending email from windows python In-Reply-To: References: <109532.94517.qm@web55204.mail.re4.yahoo.com> Message-ID: How do we run sendmail from windows I found Xmail http://www.xmailserver.org/ On 12/25/06, Alan Gauld wrote: > > > > > > how do we use sendmail to send mail from windows > > smtplib works in unix flawlessly > > It should work in windows too provided you have an > SMTP server such as sendmail running somewhere. > > Alan G. > > _______________________________________________ > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061225/52571f26/attachment.htm From samrobertsmith at gmail.com Tue Dec 26 02:57:41 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 25 Dec 2006 17:57:41 -0800 Subject: [Tutor] RandomArray and numeric Message-ID: <1d987df30612251757o3fbfcab8uda4496137a1bd6c9@mail.gmail.com> Since RandomArray is with Numeric, why I saw a code has something like: from Numeric import * from RandomArray import * Tks, Linda From adam.jtm30 at gmail.com Tue Dec 26 03:00:53 2006 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 26 Dec 2006 02:00:53 +0000 Subject: [Tutor] Game server login encryption In-Reply-To: <4fae7dfa0612241055yc8a7f3at4beff8a68bd36ded@mail.gmail.com> References: <4fae7dfa0612241055yc8a7f3at4beff8a68bd36ded@mail.gmail.com> Message-ID: Thanks a lot Bob that looks like a plan. Carlos I think the major problem with the SSL sockets is the lack of certificate checking which, I suspect, make it vulnerable to several exploits. Thanks anyway. Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061226/bb0c802d/attachment.htm From samrobertsmith at gmail.com Tue Dec 26 05:07:46 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 25 Dec 2006 20:07:46 -0800 Subject: [Tutor] idle and version Message-ID: <1d987df30612252007m5952e095n8421b280224d6403@mail.gmail.com> in my computer, there are python 2.3 and 2.4 Every time I right click a python code and select "edit with IDLE", it goes to python2.4; I am very curious why it does not got to python 2.3 because I set python 23 in my PYTHONPATH in the My Computer - Properties - Advanced - Environment Variables. From samrobertsmith at gmail.com Tue Dec 26 07:17:47 2006 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 25 Dec 2006 22:17:47 -0800 Subject: [Tutor] about array Message-ID: <1d987df30612252217r16ff6624tfcabdaa8d0f8c879@mail.gmail.com> When I read the following code, I found it was very hard for me to understand the meaning of a[1:3,:-1:2] for a[i,j] for i=1,2 and j=0,2,4; the same as a[::3,2:-1:2] >>> a array([[ 0., 1., 2., 3., 4., 5.], [ 6., 7., 8., 9., 10., 11.], [ 12., 13., 14., 15., 16., 17.], [ 18., 19., 20., 21., 22., 23.], [ 24., 25., 26., 27., 28., 29.]]) >>> a[1:3,:-1:2] # a[i,j] for i=1,2 and j=0,2,4 array([[ 6., 8., 10.], [ 12., 14., 16.]]) >>> a[::3,2:-1:2] # a[i,j] for i=0,3 and j=2,4 array([[ 2., 4.], [ 20., 22.]]) From rabidpoobear at gmail.com Tue Dec 26 08:17:33 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 26 Dec 2006 01:17:33 -0600 Subject: [Tutor] Possible with list comprehension? In-Reply-To: <20061225062548.97367.qmail@web53913.mail.yahoo.com> References: <20061225062548.97367.qmail@web53913.mail.yahoo.com> Message-ID: On 12/25/06, Stewart Midwinter wrote: > > hmm, maybe you're right. I certainly agree that your example is nested > and mine is not. I wonder what the exact description of Kent's solution is? > http://docs.python.org/tut/node7.html states: Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it. So I guess it just counts as a single list comprehension. HTH, -Luke ----- Original Message ---- > From: Luke Paireepinart > I don't think this is a 'nested list comprehension.' > I think that would be > c = 'Hello, World!' > [a for a in [b for b in c]] > in other words: a list comprehension inside of a list comprehension. > > Whereas this example is a single list comprehension because it only builds > one list, despite having multiple 'for' loops. > -Luke > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061226/98eca71e/attachment.html From rabidpoobear at gmail.com Tue Dec 26 08:19:20 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 26 Dec 2006 01:19:20 -0600 Subject: [Tutor] RandomArray and numeric In-Reply-To: References: <1d987df30612251757o3fbfcab8uda4496137a1bd6c9@mail.gmail.com> Message-ID: Sorry, everyone, I accidentally replied to a few e-mails off-list because I'm using the Gmail web interface, and I forgot that reply-all is not default (I normally use thunderbird. Yay Google for giving POP3 access to mail. Boo Yahoo for charging for it.) ---------- Forwarded message ---------- From: Luke Paireepinart Date: Dec 26, 2006 12:52 AM Subject: Re: [Tutor] RandomArray and numeric To: "linda. s" On 12/25/06, linda.s wrote: > > Since RandomArray is with Numeric, > why I saw a code has something like: > from Numeric import * > from RandomArray import * Just because a package contains different functions does not mean they're added as sub-modules or sub-packages or wahtever the correct term is. For example, in the Python Imaging Library, you do import Image import ImageGrab etc. not import PIL.Image. Think of packages like a directory structure. lib -site-packages --Image --ImageGrab etc. whereas Pygame would be lib -site-packages --pygame ---display ---joystick ---draw etc. I'm pretty sure this is how it works. packages are just a directory tree with a collection of .py scripts (plus a special __init__.py in each directory, I believe.) HTH, -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061226/e4a6c57b/attachment.htm From rabidpoobear at gmail.com Tue Dec 26 08:20:01 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 26 Dec 2006 01:20:01 -0600 Subject: [Tutor] about array In-Reply-To: References: <1d987df30612252217r16ff6624tfcabdaa8d0f8c879@mail.gmail.com> Message-ID: Oops, another one where I replied off-list. ---------- Forwarded message ---------- From: Luke Paireepinart Date: Dec 26, 2006 12:46 AM Subject: Re: [Tutor] about array To: "linda. s" On 12/26/06, linda.s wrote: > > When I read the following code, I found it was very hard for me to > understand the meaning of a[1:3,:-1:2] for a[i,j] for i=1,2 and > j=0,2,4; the same as a[::3,2:-1:2] What is your question here? you want an explanation of list slicing? what does this mean? " the meaning of a[1:3,:-1:2] for a[i,j] for i=1,2 and j=0,2,4; the same as a[::3,2:-1:2] " Do you mean your lack of understanding is the same in both cases or the slices are the same? they aren't. The weird way you worded this was really confusing, and I'm not sure what you meant. >>> a > array([[ 0., 1., 2., 3., 4., 5.], > [ 6., 7., 8., 9., 10., 11.], > [ 12., 13., 14., 15., 16., 17.], > [ 18., 19., 20., 21., 22., 23.], > [ 24., 25., 26., 27., 28., 29.]]) Where'd this array function come from? Are you using Numeric or Numpy or something? in that case, these should have good documentation on how list slicing works in them. It should be the same as in regular Python, but I won't assume that's the case, because I have no experience with any of these libraries. or are you using the built-in Python array function? It probably doesn't matter, but the more information, the better. Again, I don't have access to a python interpreter, so I can't give you any specific help. But you should read an article on Python list slicing. I'd have to say GIYF here. If you find an article and when you're reading through it you come to something that doesn't make sense, and ask about that specifically, it will be easier for us to answer. HTH, -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061226/586bb8e7/attachment.html From rabidpoobear at gmail.com Tue Dec 26 08:20:53 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 26 Dec 2006 01:20:53 -0600 Subject: [Tutor] idle and version In-Reply-To: References: <1d987df30612252007m5952e095n8421b280224d6403@mail.gmail.com> Message-ID: Another where I replied off-list. :( On 12/26/06, Luke Paireepinart wrote: > > Python is installed just like any other program. > If you install Counter-Strike 1.5, and then Counter-Strike 1.6 (video > games), the shortcut on your desktop will be changed to refer to > Counter-Strike 1.6. Changing environment variables wouldn't change this. > > When you right-click something and you see shortcuts such as 'unzip with > Win-Rar', 'edit with IDLE', etc. It is in essence the same as such a > shortcut would be on your desktop, except it's specific to the object you > have selected, whereas a shortcut wouldn't be. > > Okay, so when you installed python 2.3, IDLE was installed with it (the > version of IDLE that comes with python2.3 in the WIndows binaries). When > you installed python 2.4, IDLE (the version that comes with the python 2.4 WIndows > binaries) was installed into your python 2.4 install path. Now during > each install, context menu options are added for files with .py, .pyw, etc. > that are called 'edit with IDLE'. the ones that were added during the > second install ( 2.4) overwrote the context menu options of the python 2.3install. > > Also note that you now have 2 installs of IDLE, in each Python directory. > > This can be rectified (assuming you think it's a problem that the 2.4version of IDLE is being used) by following these steps: > open "My Computer", press Alt, T, O. (tools -> folder options) > select "File Types" tab. > scroll down to PY > choose ADVANCED > there should be an option that says "Edit with IDLE" > (I don't have python on this computer, can't check. Should be pretty > obvious waht you want to choose here) > select that option, and click "Edit" > change the 'Application used to perform this action:' field from > c:\Python2.4\whatever > to c:\Python2.3 or wherever you instaleld python 2.3 > make sure not to change any of the parameters that IDLE gets passed here, > though. > I.E. don't use 'Browse' to find the python 2.3 version of IDLE because it > may (read: probably will) delete the command line options you have set > there. > > HTH, > -Luke > > On 12/25/06, linda.s wrote: > > > in my computer, there are python 2.3 and 2.4 > > Every time I right click a python code and select "edit with IDLE", it > > goes to python2.4; I am very curious why it does not got to python 2.3 > > because I set python 23 in my PYTHONPATH in the My Computer - > > Properties - Advanced - Environment Variables. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061226/f4f370dc/attachment.htm From mobiledreamers at gmail.com Tue Dec 26 08:23:08 2006 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 25 Dec 2006 23:23:08 -0800 Subject: [Tutor] Sending email from windows python In-Reply-To: <631478.56948.qm@web86110.mail.ird.yahoo.com> References: <631478.56948.qm@web86110.mail.ird.yahoo.com> Message-ID: indigo is paid do u know free windows smtp servers On 12/25/06, ALAN GAULD wrote: > > > > How do we run sendmail from windows > > Searching Google for 'sendmail windows' gave me this: > > http://www.indigostar.com/sendmail.htm > > as the first link... > > > I found Xmail > > > > http://www.xmailserver.org/ > > But any smtp server will do just as well. > > Alan G. > > > > > how do we use sendmail to send mail from windows > > > > smtplib works in unix flawlessly > > > > > > It should work in windows too provided you have an > > > SMTP server such as sendmail running somewhere. > > > > > > Alan G. > > > > > > _______________________________________________ > > > > > > > > > > ___________________________________________________________ > To help you stay safe and secure online, we've developed the all new > Yahoo! Security Centre. http://uk.security.yahoo.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061225/328249a3/attachment.html From alan.gauld at btinternet.com Tue Dec 26 02:22:04 2006 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 26 Dec 2006 01:22:04 +0000 (GMT) Subject: [Tutor] Sending email from windows python In-Reply-To: Message-ID: <631478.56948.qm@web86110.mail.ird.yahoo.com> > How do we run sendmail from windows Searching Google for 'sendmail windows' gave me this: http://www.indigostar.com/sendmail.htm as the first link... > I found Xmail > > http://www.xmailserver.org/ But any smtp server will do just as well. Alan G. > > > how do we use sendmail to send mail from windows > > > smtplib works in unix flawlessly > > > > It should work in windows too provided you have an > > SMTP server such as sendmail running somewhere. > > > > Alan G. > > > > _______________________________________________ > > > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com From samrobertsmith at gmail.com Tue Dec 26 09:35:09 2006 From: samrobertsmith at gmail.com (linda.s) Date: Tue, 26 Dec 2006 00:35:09 -0800 Subject: [Tutor] code in a folder Message-ID: <1d987df30612260035q781b193aqfbbfe5e6c2be7bda@mail.gmail.com> I read an example code, with something like: from a.b import * I checked and found a is a folder name and b is python code in that folder. I typed the above code in the IDLE and no error was reported. Why a.b works? From oscar.ctr.savaryn at faa.gov Tue Dec 26 10:02:47 2006 From: oscar.ctr.savaryn at faa.gov (oscar.ctr.savaryn at faa.gov) Date: Tue, 26 Dec 2006 04:02:47 -0500 Subject: [Tutor] Oscar CTR Savaryn is out of the office. Message-ID: I will be out of the office starting 12/26/2006 and will not return until 01/08/2007. I will respond to your message when I return. From art at maildotcom.com Tue Dec 26 10:30:29 2006 From: art at maildotcom.com (Art Hollingsworth) Date: Tue, 26 Dec 2006 02:30:29 -0700 (MST) Subject: [Tutor] Sending email from windows python In-Reply-To: Message-ID: <8722644.51167125429440.JavaMail.root@mail.maildotcom.com> I can think of at least four free ones for Windows off the top of my head. However hMailServer is easy to set up and use. I have used it myself in the past. I'll leave it as an exercise to you to find it's website. Also, learn to use Google. It is your friend. ----- Original Message ----- From: mobiledreamers at gmail.com To: ALAN GAULD Cc: tutor at python.org Sent: Tuesday, December 26, 2006 0:23:08 AM GMT-0700 US/Mountain Subject: Re: [Tutor] Sending email from windows python indigo is paid do u know free windows smtp servers On 12/25/06, ALAN GAULD < alan.gauld at btinternet.com > wrote: > How do we run sendmail from windows Searching Google for 'sendmail windows' gave me this: http://www.indigostar.com/sendmail.htm as the first link... > I found Xmail > > http://www.xmailserver.org/ But any smtp server will do just as well. Alan G. > > > how do we use sendmail to send mail from windows > > > smtplib works in unix flawlessly > > > > It should work in windows too provided you have an > > SMTP server such as sendmail running somewhere. > > > > Alan G. > > > > _______________________________________________ > > > ___________________________________________________________ To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com -- http://www.mychinavacation.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061226/5c1a4b0b/attachment.htm From alan.gauld at btinternet.com Tue Dec 26 12:51:22 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Dec 2006 11:51:22 -0000 Subject: [Tutor] about array References: <1d987df30612252217r16ff6624tfcabdaa8d0f8c879@mail.gmail.com> Message-ID: "linda.s" wrote >>>> a > array([[ 0., 1., 2., 3., 4., 5.], > [ 6., 7., 8., 9., 10., 11.], > [ 12., 13., 14., 15., 16., 17.], > [ 18., 19., 20., 21., 22., 23.], > [ 24., 25., 26., 27., 28., 29.]]) OK, This sets up your test array. >>>> a[1:3,:-1:2] # a[i,j] for i=1,2 and j=0,2,4 And this passes two slices. The first is 1:3 which means 1,2 - normal slice behaviour he second is :-1:2 which uses extended slice syntax to specify a stepsize. So the slice says go from 0 (default) to the last element(-1) using a step sizeof 2, which is 0,2,4 So we extract the 0,2,4 elements from rows 1,2 to get: > array([[ 6., 8., 10.], > [ 12., 14., 16.]]) >>>> a[::3,2:-1:2] # a[i,j] for i=0,3 and j=2,4 Similarly the first slice here is the whole array(:) with a step size of 3, thus 0,3 The second slice is 2:-1:2 which means in practice start at 2 and go to the end stepping in 2s, which is: 2,4 So this time we take the 2,4 index items from rows 0,3 which is: > array([[ 2., 4.], > [ 20., 22.]]) Its just normal slicing notation but with a pair of them inside the brackets instead of one. Which module are you using that supports this? I've never seen it before. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Dec 26 12:56:54 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Dec 2006 11:56:54 -0000 Subject: [Tutor] code in a folder References: <1d987df30612260035q781b193aqfbbfe5e6c2be7bda@mail.gmail.com> Message-ID: "linda.s" wrote >I read an example code, with something like: > from a.b import * > I checked and found a is a folder name and b is python code in that > folder. I typed the above code in the IDLE and no error was > reported. > Why a.b works? This is Python "package" notation. You can make a folder of python modules into a package by adding a file called __init__.py. The details are described here: http://docs.python.org/tut/node8.html#SECTION008400000000000000000 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From samrobertsmith at gmail.com Tue Dec 26 20:59:09 2006 From: samrobertsmith at gmail.com (linda.s) Date: Tue, 26 Dec 2006 11:59:09 -0800 Subject: [Tutor] about array In-Reply-To: References: <1d987df30612252217r16ff6624tfcabdaa8d0f8c879@mail.gmail.com> Message-ID: <1d987df30612261159r1f4a10bcn1b0b800d42129f5e@mail.gmail.com> On 12/26/06, Alan Gauld wrote: > > "linda.s" wrote > > >>>> a > > array([[ 0., 1., 2., 3., 4., 5.], > > [ 6., 7., 8., 9., 10., 11.], > > [ 12., 13., 14., 15., 16., 17.], > > [ 18., 19., 20., 21., 22., 23.], > > [ 24., 25., 26., 27., 28., 29.]]) > > OK, This sets up your test array. > > >>>> a[1:3,:-1:2] # a[i,j] for i=1,2 and j=0,2,4 > > And this passes two slices. > The first is 1:3 which means 1,2 - normal slice behaviour > he second is :-1:2 which uses extended slice syntax to > specify a stepsize. So the slice says go from 0 (default) > to the last element(-1) using a step sizeof 2, which is 0,2,4 > > So we extract the 0,2,4 elements from rows 1,2 to get: > > > array([[ 6., 8., 10.], > > [ 12., 14., 16.]]) > > >>>> a[::3,2:-1:2] # a[i,j] for i=0,3 and j=2,4 > > Similarly the first slice here is the whole array(:) with a > step size of 3, thus 0,3 > The second slice is 2:-1:2 which means in practice start > at 2 and go to the end stepping in 2s, which is: 2,4 > So this time we take the 2,4 index items from rows 0,3 > which is: > > > array([[ 2., 4.], > > [ 20., 22.]]) > > Its just normal slicing notation but with a pair of them > inside the brackets instead of one. > > Which module are you using that supports this? > I've never seen it before. It is from Hans' Book 'Python Scripting for Computational Science'. He uses Numpy: Numeric From carloslara at web.de Wed Dec 27 12:38:10 2006 From: carloslara at web.de (Carlos) Date: Wed, 27 Dec 2006 12:38:10 +0100 Subject: [Tutor] Why a global? In-Reply-To: References: Message-ID: <45925B22.3060000@web.de> Hello, Can help me with this: I am using a python module that someone else wrote http://www.alextreme.org/projects/python_ai/ This is an example of how it works # Usage: # import ga # # ga = ga.GA() # ga.evolve() # Function arguments (fun defaults are used otherwise): # # ga.GA(population_size, gene_size, crossover_rate, mutation_rate, list_of_alleles) # ga.evolve(number_of_generations_to_process) # # ga.set_fitness(your_fitness_function) # Interesting public variables (besides the ones you can modify using arguments) # # ga.debug = 1 (turns on lots of output) # ga.halt = X.X (stop if this fitness is reached) # Note: crossover_rate is the chance two entities will reproduce # mutation_rate is the chance a single entity will have an allele changed My problem is that no matter were I put this, I have to declare ga a global. So I ended up with this: def runGA(Pop, Gen, It): # Declare a Global. This is the only solution for now global ga # Set the arguments of the GA ga = ga.GA(pop = 2, alleles = range(10), gene_size = 8) ga.debug = 1 ga.echo_entities() Can you help me with this information? or what else is needed for you to help me solve this problem? Regards, Carlos From chris.arndt at web.de Wed Dec 27 14:26:36 2006 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 27 Dec 2006 14:26:36 +0100 Subject: [Tutor] Why a global? In-Reply-To: <45925B22.3060000@web.de> References: <45925B22.3060000@web.de> Message-ID: <4592748C.40603@web.de> Carlos schrieb: > My problem is that no matter were I put this, I have to declare ga a > global. You are confusing two different objects with the name 'ga' here: a) the module object 'ga' which you create by import ing it: import ga this binds the name 'ga' to the module object created by reading in the module ga (probably some file name 'ga.py' or a package). b) The instance object of the the 'GA' class you create with ga = ga.GA(pop = 2, alleles = range(10), gene_size = 8) You have named the variable that holds a reference to this instance object b) also 'ga' thereby *overwriting the global variable 'ga'*, which held a reference to the module object a). If you want to overwrite a global variable in a function, you have to declar it global with the 'global' keyword. *But that's not what you want here.* Just give another name to your instance variable: import ga def runGA(pop, gen, it): ga_inst = ga.GA(pop = 2, alleles = range(10), gene_size = 8) ga_inst.debug = 1 ... HTH, Chris From troy at warpdriveonline.com Wed Dec 27 06:00:47 2006 From: troy at warpdriveonline.com (Troy) Date: Tue, 26 Dec 2006 23:00:47 -0600 Subject: [Tutor] Python cgi scripting Message-ID: <1167195647.8388.1.camel@abit> Hello. I'm just starting to learn Python, and want to do some python cgi scripting. Can someone recommend a good web site or online reference (beginner level)? Thank you. From Mike.Hansen at atmel.com Wed Dec 27 15:17:13 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 27 Dec 2006 07:17:13 -0700 Subject: [Tutor] Python cgi scripting Message-ID: <57B026980605A64F9B23484C5659E32E4C6E92@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Troy > Sent: Tuesday, December 26, 2006 10:01 PM > To: tutor at python.org > Subject: [Tutor] Python cgi scripting > > Hello. I'm just starting to learn Python, and want to do some python > cgi scripting. Can someone recommend a good web site or online > reference (beginner level)? > > Thank you. > Check out the docs on the cgi module http://docs.python.org/lib/module-cgi.html Also, devshed has an article on cgi programming with Python http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ Mike -------------- next part -------------- ------------- NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS From alan.gauld at btinternet.com Wed Dec 27 21:39:00 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Dec 2006 20:39:00 -0000 Subject: [Tutor] Python cgi scripting References: <1167195647.8388.1.camel@abit> Message-ID: "Troy" wrote > Hello. I'm just starting to learn Python, and want to do some > python > cgi scripting. Can someone recommend a good web site or online > reference (beginner level)? The standard documentation for cgi is pretty good. Also check out the Web Programming Topic Guide on CGIScripts - it has links to several other tutorials. Finally, if you are serioud abouyt web programming there are quite a few Python web frameworks that take a lot of the pain away. Django and TurboGears (mainly the CherryPy stuff IMHO) seem to be the current favourites, and Zope if your needs are ambitious. But basic CGI is fine for simple apps with just a few pages. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ricardo at palmtx.com.ar Thu Dec 28 00:23:00 2006 From: ricardo at palmtx.com.ar (Ricardo Barberis) Date: Wed, 27 Dec 2006 20:23:00 -0300 Subject: [Tutor] [OT]Test Message-ID: <20061227233148.C06C91E4017@bag.python.org> Sorry, just testing if I can receive mail from this list again. From pyro9219 at gmail.com Thu Dec 28 10:14:37 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 28 Dec 2006 01:14:37 -0800 Subject: [Tutor] XML-RPC data transfers. Message-ID: I'm trying to figure out how to send data using XML-RPC. Currently my target is to send a PIL imagegrab.grab() from one side of the connection to the other. I've got stuff like numbers and strings going back and forth, so I know my connection is working, but I'm not sure how to send the image. 'Server and Client Connect' 'Server asks client for screen capture, client captures and sends to server.' I've been trying to figure it out using this bit of information I found, but I'm not sure how to map it to what I need: http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html Using this example I get error's about 'expected binary .read(), but got instance instead. ' when trying to convert the image data to binary to transfer, I've also just tried passing the image data directly, but that gets a return 'None" exception. I've just been using xmlrpclib and simplexmlrpcserver for this, but I'm wondering if I should perhaps use twisted instead. Happy Holiday's and Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061228/cc2c970d/attachment.htm From hyperneato at gmail.com Thu Dec 28 10:20:54 2006 From: hyperneato at gmail.com (Isaac) Date: Thu, 28 Dec 2006 01:20:54 -0800 Subject: [Tutor] subprocess.Popen.communicate()[] Message-ID: <7260654a0612280120s37b0210dy43fea65a1cd0f3c@mail.gmail.com> Hello tutors! I have the following in my PYTHONSTARTUP file def clear(): x = subprocess.Popen("clear").communicate(None)[0] return x so that when I type: >>>clear() at the prompt, my terminal screen clears and I get only my prompt at the top of the screen. without the index at the end of .communicate() I get a tuple '(None, None)' before my prompt at the top of the cleared screen. If I call either x[0] or x[1] the command will return a single None, which is not displayed in the interpreter but if I leave off the index".communicate(None)"- so that it returns both stdout and sterr then clear() will return a tuple which will be displayed by the interpreter. Am in correct in my interpretation of the interpreter? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061228/ea8e38b7/attachment.html From alan.gauld at btinternet.com Thu Dec 28 11:13:03 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Dec 2006 10:13:03 -0000 Subject: [Tutor] XML-RPC data transfers. References: Message-ID: "Chris Hengge" wrote in message news:c25107380612280114j107e3154j5ae7ee85f3cf6210 at mail.gmail.com... > I'm trying to figure out how to send data using XML-RPC. Currently > my target > is to send a PIL imagegrab.grab() from one side of the connection to > the > other. Any particular reason to use RPC here? This will likely be a slow process and not really what I expect to see RPCs being used for. Normally I'd expect to send a url to the server and it would then fetch the file using ftp or similar. Tying up an XML-RPC server and blocking the sending side for a long time(10-30s?) is a risky procedure, especially given the fragile nature of XML-RPC (compared to traditional techniques, or even to SOAP) Just a thought, Alan G. From alan.gauld at btinternet.com Thu Dec 28 11:18:24 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Dec 2006 10:18:24 -0000 Subject: [Tutor] subprocess.Popen.communicate()[] References: <7260654a0612280120s37b0210dy43fea65a1cd0f3c@mail.gmail.com> Message-ID: "Isaac" wrote in > I have the following in my PYTHONSTARTUP file > > def clear(): > x = subprocess.Popen("clear").communicate(None)[0] > return x > > Am in correct in my interpretation of the interpreter? Yes, but can't you simplify this to just: import subprocess def clear(): subProcess.Popen('clear') if all you want to do is clear the screen... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From geoframer at gmail.com Thu Dec 28 13:31:15 2006 From: geoframer at gmail.com (Geoframer) Date: Thu, 28 Dec 2006 13:31:15 +0100 Subject: [Tutor] Python and rpy In-Reply-To: <458F31E0.9070107@tds.net> References: <5d8e35a70612210743j69f30d54kfec867df695a93b6@mail.gmail.com> <458AEDE3.8030006@tds.net> <5d8e35a70612220221r7f324d1fl30ef1810d6c838c1@mail.gmail.com> <458F31E0.9070107@tds.net> Message-ID: <5d8e35a70612280431s6a423dffg720a6bd8a3abd241@mail.gmail.com> Hey Kent, Well i've gotten exactly no response on the Rpy-list on both my questions :-(. However i switched to Ubuntu 6.10 today (from WinXP) and to my suprise it does work under linux! :-) RHOME= /usr/lib/R RVERSION= 2.3.1 RVER= 2031 RUSER= /home/geofram Loading Rpy version 2031 .. Done. Creating the R object 'r' .. Done In [2]: r.diag(2) Out[2]: array([[ 1., 0.], [ 0., 1.]]) In [3]: r.kmeans(r.diag(2),1,2,5,"Forgy") Out[3]: {'centers': array([ [ 0.5, 0.5]]), 'cluster': [1, 1], 'size': 2, 'withinss': 1.0} Older version somewhat but apparently this works, so it might just be a bug under windows or in the newer version from Rpy... For now at least I can work with it. Thanx a bunch for all your help Kent. Regards - Geofram On 12/25/06, Kent Johnson wrote: > > Geoframer wrote: > > > As i stated i think the conversion from Python to R is going wrong, but > > i have no clue on how to properly address that. > > I agree. If you have Numeric installed (which I do) then r.diag() should > return a Numeric array, not a list of lists. This looks like the same > problem discussed in this thread: > http://sourceforge.net/mailarchive/message.php?msg_id=15307721 > which does not seem to have been resolved. > > I don't want to get involved in the Rpy mailing list but I would suggest > posting a very simple question asking why the result of r.diag() is not > a Numeric array. Perhaps this will lead to a solution. > > > The code snippet i was talking about is on page 15 and 16 of the rpy > > reference guide http://rpy.sourceforge.net/rpy/doc/rpy.pdf ; the > > examples just don't work and i am lacking enough python experience to > > see why :-S. > > > > What i'm trying to do now is : > > > > ---- > > from rpy import * > > > > class Test: > > def as_r(self): > > return > [[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]] > > > > if __name__ == "__main__": > > a=with_mode(NO_CONVERSION, Test)() > > r.kmeans(a, 2, 5, 10, "Forgy") > > I don't see how this will help. My understanding is that as_r() should > return an Robj, not a Python object. I think this code is the same as > passing a list of lists directly to kmeans. > > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061228/59bfd3d4/attachment.html From carloslara at web.de Thu Dec 28 16:46:51 2006 From: carloslara at web.de (Carlos) Date: Thu, 28 Dec 2006 16:46:51 +0100 Subject: [Tutor] Why a global? In-Reply-To: References: Message-ID: <4593E6EB.4050205@web.de> Chris, Sheesh, that solved it, guess that I got to learn OO next. Unles it is not related... :-[ Thanks a lot! Carlos From alan.gauld at btinternet.com Thu Dec 28 17:15:31 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Dec 2006 16:15:31 -0000 Subject: [Tutor] Why a global? References: <4593E6EB.4050205@web.de> Message-ID: "Carlos" wrote > > Sheesh, that solved it, guess that I got to learn OO next. Unles it > is > not related... :-[ The problem you had was about reassigning a name from a module to an object, but it could have been any kind of object - a variable, a function, another module, anything. So really it had nothing to do with OO. If you do: import sys as s s = 42 s.exit() you will get an error because you renamed sys to s then used s as a local varuiable, thus overwriting (and thus losing) the module reference. You need to ensure that your names don't collide. Alan G From cappy2112 at gmail.com Thu Dec 28 20:27:07 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Thu, 28 Dec 2006 11:27:07 -0800 Subject: [Tutor] Length of longest item in a list, using a list comp Message-ID: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> I want to use a list comp to get the length of the longest string in a list, but can't quite get the syntax right. l1=['abc', 'abcde', 'abcfdtea'] longest=0 [x for x in l1 if len(x) > longest] The problem is I can't add the true clause to the if statement in a list comp as in if len(x) > longest: longest = len(x) Is this possible using a list comp? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061228/d705fc6d/attachment.html From python at venix.com Thu Dec 28 20:43:46 2006 From: python at venix.com (Python) Date: Thu, 28 Dec 2006 14:43:46 -0500 Subject: [Tutor] Length of longest item in a list, using a list comp In-Reply-To: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> Message-ID: <1167335026.12468.484.camel@www.venix.com> On Thu, 2006-12-28 at 11:27 -0800, Tony Cappellini wrote: > > > I want to use a list comp to get the length of the longest string in a > list, but can't quite get the syntax right. > > l1=['abc', 'abcde', 'abcfdtea'] > > longest=0 > [x for x in l1 if len(x) > longest] Use max to get the longest longest = max([len(x) for x in ll]) With versions >= 2.4 you can omit the [] > > The problem is I can't add the true clause to the if statement in a > list comp as in > if len(x) > longest: > longest = len(x) > > > Is this possible using a list comp? > > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From andreas at kostyrka.org Thu Dec 28 21:16:31 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 28 Dec 2006 21:16:31 +0100 Subject: [Tutor] Length of longest item in a list, using a list comp In-Reply-To: <1167335026.12468.484.camel@www.venix.com> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> Message-ID: <20061228201631.GG12195@andi-lap.la.revver.com> * Python [061228 20:44]: > On Thu, 2006-12-28 at 11:27 -0800, Tony Cappellini wrote: > > > > > > I want to use a list comp to get the length of the longest string in a > > list, but can't quite get the syntax right. > > > > l1=['abc', 'abcde', 'abcfdtea'] > > > > longest=0 > > [x for x in l1 if len(x) > longest] > > Use max to get the longest > > longest = max([len(x) for x in ll]) > > With versions >= 2.4 you can omit the [] With 2.5 you can even do stuff like that: >>> x=[range(5), range(3), range(7)] >>> max(x, key=lambda i: len(i)) [0, 1, 2, 3, 4, 5, 6] >>> Andreas From cappy2112 at gmail.com Thu Dec 28 21:14:31 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Thu, 28 Dec 2006 12:14:31 -0800 Subject: [Tutor] Length of longest item in a list, using a list comp In-Reply-To: <20061228201631.GG12195@andi-lap.la.revver.com> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: <8249c4ac0612281214x6175a29di5ed944191c100b1b@mail.gmail.com> Thanks, but I am restricted to using 2.3.4 for now, so longest = max([len(x) for x in ll]) works for me On 12/28/06, Andreas Kostyrka wrote: > > * Python [061228 20:44]: > > On Thu, 2006-12-28 at 11:27 -0800, Tony Cappellini wrote: > > > > > > > > > I want to use a list comp to get the length of the longest string in a > > > list, but can't quite get the syntax right. > > > > > > l1=['abc', 'abcde', 'abcfdtea'] > > > > > > longest=0 > > > [x for x in l1 if len(x) > longest] > > > > Use max to get the longest > > > > longest = max([len(x) for x in ll]) > > > > With versions >= 2.4 you can omit the [] > With 2.5 you can even do stuff like that: > > >>> x=[range(5), range(3), range(7)] > >>> max(x, key=lambda i: len(i)) > [0, 1, 2, 3, 4, 5, 6] > >>> > > Andreas > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061228/032d087a/attachment.html From kent37 at tds.net Thu Dec 28 23:21:03 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Dec 2006 17:21:03 -0500 Subject: [Tutor] Length of longest item in a list, using a list comp In-Reply-To: <20061228201631.GG12195@andi-lap.la.revver.com> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: <4594434F.5060403@tds.net> Andreas Kostyrka wrote: > With 2.5 you can even do stuff like that: > >>>> x=[range(5), range(3), range(7)] >>>> max(x, key=lambda i: len(i)) > [0, 1, 2, 3, 4, 5, 6] No need for the lambda, just use max(x, key=len) Kent From alan.gauld at btinternet.com Fri Dec 29 01:04:09 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Dec 2006 00:04:09 -0000 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com><1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: "Andreas Kostyrka" wrote >> With versions >= 2.4 you can omit the [] > With 2.5 you can even do stuff like that: I missed the announcement somewhere but 2.5 seems to have been out for a spell now. What are the must-have new features? (I could read the what's-new doc but that tells me about stuff I may not see the value in!) What are the features people are actually using regularly and find an improvement? Alan G. From pyro9219 at gmail.com Fri Dec 29 02:24:41 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Thu, 28 Dec 2006 17:24:41 -0800 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: I hope this is related enough for this thread, but I'm curious why people didn't seem to unanimously jump into 2.5 upon release. Python seems very good about holding its backward compatibility vs some other languages I've dealt with like C# that seems to require applications rewritten with every patch. Was there just nothing that "grand" about the new version? I've personally held back just because most of the documentation I've come across is for 2.4, and until I get a firmer feel for the language I'm trying to not mix things up. On 12/28/06, Alan Gauld wrote: > > "Andreas Kostyrka" wrote > > >> With versions >= 2.4 you can omit the [] > > With 2.5 you can even do stuff like that: > > I missed the announcement somewhere but 2.5 seems to > have been out for a spell now. > > What are the must-have new features? (I could read the what's-new > doc but that tells me about stuff I may not see the value in!) > > What are the features people are actually using regularly and find > an improvement? > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061228/3eb99eb2/attachment.html From carroll at tjc.com Fri Dec 29 04:07:07 2006 From: carroll at tjc.com (Terry Carroll) Date: Thu, 28 Dec 2006 19:07:07 -0800 (PST) Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: Message-ID: On Thu, 28 Dec 2006, Chris Hengge wrote: > I hope this is related enough for this thread, but I'm curious why people > didn't seem to unanimously jump into 2.5 upon release. I find the Activestate distribution particularly convenient, so I'm awaiting that. From wescpy at gmail.com Fri Dec 29 07:26:42 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 28 Dec 2006 22:26:42 -0800 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: <78b3a9580612282226p6dfbada9n471ac75eaadda75@mail.gmail.com> > What are the must-have new features? (I could read the what's-new > doc but that tells me about stuff I may not see the value in!) > > What are the features people are actually using regularly and find > an improvement? below is a quick summary of the 2.5 highlights. of these, i like/use the following: 1, 2, 4, 5, 6, 7, (8), 9a, 9b. of course, my workplace is still on 2.3, and i've been "dying" to use generator expressions (2.4), conditional expressions, and executing modules as scripts (easier to run pdb directly on a module). Python 2.5 Summary ================= 1) Conditional Expressions/Ternary Operators (PEP 308) -- finally! :-) C ? T : F --> (C and [T] or [F])[0] --> T if C else F 2) Partial Function Application (PEP 309) -- adds to Python support for currying and generalized partial function application: from... from operator import add def add2(x): return add(2, x) to... from operator import add from functools import partial add2 = partial(add, 2) demo... (this is a short example of what it does... anyone have a more *useful* example?) >>> from operator import add >>> def add2(x): return add(2, x) >>> add2(5) 7 >>> from functools import partial >>> add2b = partial(add, 2) >>> add2b(5) 7 3) Absolute and Relative Imports (PEP 328) -- meant to address intra-package import problems, esp. with std lib module name conflicts 4) Executing Modules as Scripts (PEP 338) -- new -m option very useful for executing std lib modules as scripts 5) Unified try/except/finally (PEP 341) -- probably will be used a lot since it turns a multi-level try-try-except-finally block into a single-level try-except-finally block 6) The 'with' statement (PEP 343) - somewhat related to just above... simplifies try-except-finally even further but "subsuming" the finally clause (see context mgrs below) so you need just the single with clause (and try-except if nec.). popular uses: - need to have an open file (open it now and to close it later automagically) - need to acquire a lock (now and release it later automagically) - need to obtain a database pool cxn (now and release it later automagically) 7) Enhanced Generator Features (PEP 342) -- now you can "talk-back" to a generator, meaning you can send data into it as you resume it... .next() sends None, .send(obj) sends obj, .throw(exc) throws exception exc 8) Exceptions as New-Style Classes -- all exceptions converted to new classes 9) new modules: a) sqlite3 - probly used heavily due to interest in this lightweight RDBMS b) ElementTree - probly used even *more* heavily due to interest in this lightweight XML DOMish processor c) ctypes - useful for those that want to interface directly to a .so or .dll without writing extension wrappers d) wsgiref - some reference tools for the new WSGI standard (for web apps) e) hashlib - replaces most encryption modules f) contextlib - used to write "context mgrs" for use with the 'with' stmt for more demos and information about many of these features, check out "Core Python Programming." :-) cheers, -wesley -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From hyperneato at gmail.com Fri Dec 29 08:42:55 2006 From: hyperneato at gmail.com (Isaac) Date: Thu, 28 Dec 2006 23:42:55 -0800 Subject: [Tutor] subprocess.Popen.communicate()[] Message-ID: <7260654a0612282342x71d405dcm71a3fab41b49e0bd@mail.gmail.com> > "Isaac" > > I have the following in my PYTHONSTARTUP file > > > > def clear(): > > x = subprocess.Popen("clear").communicate(None)[0] > > return x > > > > Yes, but can't you simplify this to just: > > > import subprocess > def clear(): > subProcess.Popen('clear') > > if all you want to do is clear the screen... > Yes, but this way the screen more unix like after calling the function- it is cleared and only my prompt is shown at the top of the screen; which is currently ' python > ' Without communicate()[0] the screen is blank and no prompt. Thanks for your reply. From mail at timgolden.me.uk Fri Dec 29 09:26:05 2006 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 29 Dec 2006 08:26:05 +0000 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: <4594D11D.4060804@timgolden.me.uk> Chris Hengge wrote: > I hope this is related enough for this thread, but I'm curious why > people didn't seem to unanimously jump into 2.5 upon release. Python > seems very good about holding its backward compatibility vs some other > languages I've dealt with like C# that seems to require applications > rewritten with every patch. Was there just nothing that "grand" about > the new version? I've personally held back just because most of the > documentation I've come across is for 2.4, and until I get a firmer feel > for the language I'm trying to not mix things up. Speaking for myself as a Win32 user, you generally have to recompile / download compiled binaries for any new release of Python. I have downloaded 2.5 and there certainly are things which interest me, but I won't shift to using it for mainstream work until all the modules I need are available at 2.5. (For the most part I could compile them myself with mingw32, but you start to realise just how much work is involved when you need to download libs and headers for all the externals. So I'm lazy and wait for the project maintainer to supply...). Also I'm faintly chary of starting to use some whizz-bang new feature (like the with block) which is incompatible with 2.4 and then trying to run the code on my webserver where I've only got 2.4! TJG From alan.gauld at btinternet.com Fri Dec 29 09:44:28 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Dec 2006 08:44:28 -0000 Subject: [Tutor] subprocess.Popen.communicate()[] References: <7260654a0612282342x71d405dcm71a3fab41b49e0bd@mail.gmail.com> Message-ID: "Isaac" wrote > Without communicate()[0] the screen is blank and no prompt. Ah. I see. OK, Thanks for clarifying that. I should have tried both versions, I only checked that my version did, in fact, clear the screen, I didn't check how yours behaved - naughty! Alan G. From alan.gauld at btinternet.com Fri Dec 29 09:56:07 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Dec 2006 08:56:07 -0000 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in alist, using a list comp) References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com><1167335026.12468.484.camel@www.venix.com><20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: "Chris Hengge" wrote >...I'm curious why people didn't seem to unanimously jump > into 2.5 upon release. I can't speak for anyone else, but personally I never load the first version of any software. I only upgrade when I find a feature I actually know I need and after I'm confident that the bugs have been squashed. This applies to all software not just Python. I'm currently running FrameMaker 5.5 (latest vesion is 7!) and MS Word 97/2002(latest version???). Most of my Oracle databases are still at version 8. On my servers at work Python is still at v2.2. We only upgraded our Win2000 boxes to XP after SP2 came out (6 months after to be accurate!) Chasing the latest release is a time consuming sport that isn't worth doing unless it actually delivers some real benefit IMHO. Which is why I asked what the real benefits of 2.5 are? >From Wes' list I only see tertiary operators and try/except/finally as useful to me - and both are just minor style fixes. So I doubt if I'll move from 2.3(MacOS)/2.4(XP and Linux) for a while yet - at least not until the ActiveState version comes out for XP. One thing I will be investigating is the WSGI stuff, I've come across mentions of that several times now, and know nothing about it. Alan G. From kent37 at tds.net Fri Dec 29 14:00:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Dec 2006 08:00:49 -0500 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: <78b3a9580612282226p6dfbada9n471ac75eaadda75@mail.gmail.com> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> <78b3a9580612282226p6dfbada9n471ac75eaadda75@mail.gmail.com> Message-ID: <45951181.3060807@tds.net> wesley chun wrote: > below is a quick summary of the 2.5 highlights. of these, i like/use > the following: > 1, 2, 4, 5, 6, 7, (8), 9a, 9b. > > 7) Enhanced Generator Features (PEP 342) -- now you can "talk-back" to > a generator, meaning you can send data into it as you resume it... > .next() sends None, .send(obj) sends obj, .throw(exc) throws exception > exc Are you using this? I would be interested in finding out how. This seems like a feature that allows Python to be used in a new way, but I have not yet seen any real applications of it. Kent From missive at hotmail.com Fri Dec 29 18:24:48 2006 From: missive at hotmail.com (Lee Harr) Date: Fri, 29 Dec 2006 21:54:48 +0430 Subject: [Tutor] XML-RPC data transfers. Message-ID: >http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > >Using this example I get error's about 'expected binary .read(), but got >instance instead. I assume you are using this ... >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) Are you using windows? I think you would need to pass the binary flag to open ... imagedata = open(filename, 'rb').read() It's probably a good idea to use the binary flag if you are expecting binary data just in case it gets ported somewhere else later. >I've just been using xmlrpclib and simplexmlrpcserver for this, but I'm >wondering if I should perhaps use twisted instead. I've used xml-rpc to send image data before. It worked. _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ From andreas at kostyrka.org Fri Dec 29 19:25:23 2006 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 29 Dec 2006 19:25:23 +0100 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: <20061229182522.GI12195@andi-lap.la.revver.com> * Chris Hengge [061229 02:25]: > I hope this is related enough for this thread, but I'm curious why people > didn't seem to unanimously jump into 2.5 upon release. Python seems very > good about holding its backward compatibility vs some other languages I've > dealt with like C# that seems to require applications rewritten with every > patch. Was there just nothing that "grand" about the new version? I've > personally held back just because most of the documentation I've come > across is for 2.4, and until I get a firmer feel for the language I'm > trying to not mix things up. I'd say it's a deployment issue. So basically people with deployement issues keep back. People with small user populations are already upgrading to 2.5. Andreas From cbc at unc.edu Fri Dec 29 19:50:05 2006 From: cbc at unc.edu (Chris Calloway) Date: Fri, 29 Dec 2006 13:50:05 -0500 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> Message-ID: <4595635D.6060609@unc.edu> Chris Hengge wrote: > I hope this is related enough for this thread, but I'm curious why > people didn't seem to unanimously jump into 2.5 upon release. If I'm driving a 2006 model car, I don't rush right out and trade for a 2007 model just because they are available. There's cost and effort involved with changing versions. Not the least is having to retest all your existing applications. Generators now have a different syntax, so some applications would need some updating in order to take advantage of 2.5. The new "with" statement is very cool, though. > I've personally held back just because most of the > documentation I've come across is for 2.4, 100% of this is Python 2.5 documentation: http://docs.python.org/ Very little of it had to change from the last version. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From kent37 at tds.net Fri Dec 29 20:24:39 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Dec 2006 14:24:39 -0500 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: <4595635D.6060609@unc.edu> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> <4595635D.6060609@unc.edu> Message-ID: <45956B77.9030909@tds.net> Chris Calloway wrote: > Generators now have a different syntax, so some applications would need > some updating in order to take advantage of 2.5. The old syntax still works. "yield x" is now an expression returning a value, rather than a statement, so it can be used in new ways, but a plain "yield x" is fine. > The new "with" statement is very cool, though. > >> I've personally held back just because most of the >> documentation I've come across is for 2.4, > > 100% of this is Python 2.5 documentation: > > http://docs.python.org/ > > Very little of it had to change from the last version. To amplify this a bit - backward compatibility between Python releases is generally excellent. It is rare for something that works in 2.x to fail in 2.x+1. There may be a better way to do something using a new feature but the old ways will usually work. So if you are learning Python from a book that covers 2.3 or 2.4, you should do fine with 2.5. When you want to know what has been added that is not in your book, check the excellent "What's New in Python 2.x" guides that are included with the docs for each version. These guides also include a "Porting to Python 2.x" section that lists the incompatible changes in the new version. For example, see http://docs.python.org/whatsnew/porting.html Kent From bgailer at alum.rpi.edu Fri Dec 29 20:25:34 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 29 Dec 2006 11:25:34 -0800 Subject: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in a list, using a list comp) In-Reply-To: <45951181.3060807@tds.net> References: <8249c4ac0612281127x5a22a677k757208c7a584e4f1@mail.gmail.com> <1167335026.12468.484.camel@www.venix.com> <20061228201631.GG12195@andi-lap.la.revver.com> <78b3a9580612282226p6dfbada9n471ac75eaadda75@mail.gmail.com> <45951181.3060807@tds.net> Message-ID: <45956BAE.3080800@alum.rpi.edu> Kent Johnson wrote: > wesley chun wrote: > >> below is a quick summary of the 2.5 highlights. of these, i like/use >> the following: >> 1, 2, 4, 5, 6, 7, (8), 9a, 9b. >> >> 7) Enhanced Generator Features (PEP 342) -- now you can "talk-back" to >> a generator, meaning you can send data into it as you resume it... >> .next() sends None, .send(obj) sends obj, .throw(exc) throws exception >> exc >> > > Are you using this? I would be interested in finding out how. \ In the past month I wrote a file parser that is sorta recursive descent. I wrote a generator that takes the first token of each file line and looks it up in the current keyword list. If not found it stops iteration, control returns to a higher level which has its own version of the generator instantiated with a different keyword list. With the ability to pass an object, I can simplify my code so there is one instance of the generator, and each level passes its own keyword list. > This seems > like a feature that allows Python to be used in a new way, but I have > not yet seen any real applications of it. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From cappy2112 at gmail.com Fri Dec 29 21:56:13 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Fri, 29 Dec 2006 12:56:13 -0800 Subject: [Tutor] Tutor Digest, Vol 34, Issue 55 In-Reply-To: References: Message-ID: <8249c4ac0612291256i7f901639m825424748dbc885b@mail.gmail.com> Message: 1 Date: Thu, 28 Dec 2006 17:24:41 -0800 From: "Chris Hengge" Subject: Re: [Tutor] OT: Python 2.5 (Was Re: Length of longest item in >>I hope this is related enough for this thread, but I'm curious why people >>didn't seem to unanimously jump into 2.5 upon release. One reason- having to upgrade all the packages that you've installed is time consuming. Another- we have a very large tools framework where I work. Someone needs to make sure these tools will work with any new version of Python. We use 2.3at the moment, and there is no significant reason to upgrade to 2.4 or 2.5, to justify the time involved in testing all the tools to make sure every line of code is executed with the new version. As far as my home use, I'm still using 2.4, and will keep it that way until I need to install something that requires 2.5. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061229/2f257f0c/attachment.html From samrobertsmith at gmail.com Fri Dec 29 22:05:21 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 29 Dec 2006 13:05:21 -0800 Subject: [Tutor] about reload Message-ID: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> I read something about reload of modules. #test.py from ABC import M # M is an attribute of Module ABC if I change module ABC, I need import ABC and reload ABC before "from ABC import M" work. in IDLE, I just click F5 and run the code, it works and does not need type anything like "Import ABC", "Reload(ABC)". Why the book say the two steps are needed? Thanks, Linda From dyoo at hkn.eecs.berkeley.edu Fri Dec 29 23:06:57 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 29 Dec 2006 14:06:57 -0800 (PST) Subject: [Tutor] about reload In-Reply-To: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> References: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> Message-ID: On Fri, 29 Dec 2006, linda.s wrote: > I read something about reload of modules. > #test.py > from ABC import M # M is an attribute of Module ABC > > if I change module ABC, I need import ABC and reload ABC before "from > ABC import M" work. in IDLE, I just click F5 and run the code, it works > and does not need type anything like "Import ABC", "Reload(ABC)". Why > the book say the two steps are needed? reload() is necessary if we don't re-run everything from scratch. When you're pressing F5 in IDLE, IDLE restarts the whole program, so in that particular case, you don't need to worry about reload() at all. From rabidpoobear at gmail.com Fri Dec 29 23:48:42 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 29 Dec 2006 16:48:42 -0600 Subject: [Tutor] about reload In-Reply-To: References: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> Message-ID: <45959B4A.7020001@gmail.com> Danny Yoo wrote: > On Fri, 29 Dec 2006, linda.s wrote: > > >> I read something about reload of modules. >> #test.py >> from ABC import M # M is an attribute of Module ABC >> >> if I change module ABC, I need import ABC and reload ABC before "from >> ABC import M" work. in IDLE, I just click F5 and run the code, it works >> and does not need type anything like "Import ABC", "Reload(ABC)". Why >> the book say the two steps are needed? >> > > reload() is necessary if we don't re-run everything from scratch. > > When you're pressing F5 in IDLE, IDLE restarts the whole program, so in > that particular case, you don't need to worry about reload() at all. > Actually, if you have IDLE in the default setup on Windows and you right-click something to edit it, IDLE doesn't open a subprocess each time a script is executed, so it will keep the imports in between runs of the program. I.E. if I type "import math" into the IDLE interpreter, I can then make a file with the contents #---- start print math.pi #----- end and it will work. just thought I'd mention that. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From macsareback at mac.com Sat Dec 30 00:20:33 2006 From: macsareback at mac.com (Daniel kavic) Date: Fri, 29 Dec 2006 18:20:33 -0500 Subject: [Tutor] Best way to learn python Message-ID: <98E50EAA-1880-40E7-84B0-19CB05F74AC9@mac.com> What is the best way for someone who is not very efficient in mathematics to learn Python, I was turned away from C++ and others because of the math issue. Ruby has been recommended as well. From rob.andrews at gmail.com Sat Dec 30 00:31:53 2006 From: rob.andrews at gmail.com (Rob Andrews) Date: Fri, 29 Dec 2006 17:31:53 -0600 Subject: [Tutor] Best way to learn python In-Reply-To: <98E50EAA-1880-40E7-84B0-19CB05F74AC9@mac.com> References: <98E50EAA-1880-40E7-84B0-19CB05F74AC9@mac.com> Message-ID: <8d757d2e0612291531h1c1eff31x8c0abb2c38fae9d2@mail.gmail.com> I'm not exactly a math guru, either, but know some algebra & geometry from school. When I first tried my hand at Python, I started with just the tutorial bundled with the Python download. I had been taken a semester in Pascal & tinkered with Perl & Java at that point, and found Python to be simpler & more obvious, so if you have a bit of programming at all your experience is likely as good as mine was at the time. What's your programming background? What sort of programming would you most immediately like to do? And Ruby's also a fine language. -Rob A. On 12/29/06, Daniel kavic wrote: > What is the best way for someone who is not very efficient in > mathematics to learn Python, I was turned away from C++ and others > because of the math issue. Ruby has been recommended as well. From alan.gauld at btinternet.com Sat Dec 30 01:45:05 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 30 Dec 2006 00:45:05 -0000 Subject: [Tutor] Best way to learn python References: <98E50EAA-1880-40E7-84B0-19CB05F74AC9@mac.com> Message-ID: "Daniel kavic" wrote > What is the best way for someone who is not very efficient in > mathematics to learn Python, You don't need math to program, but it definitely helps and for some problems is essential. But the level of math required is not high, definitely sub college level for most things. As a learning language Python is excellent. There are a multitude of tutorials listed on the Python web site, including mine. Pick one that seems to make sense to you. > I was turned away from C++ and others > because of the math issue. > Ruby has been recommended as well. # Ruby and Python are very similar in many ways, and are growing ever closer in some ways. I personally think Python edges it for a beginner just because there are more books and web sites available, but both are good languages. HTH. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Sat Dec 30 03:40:18 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 29 Dec 2006 18:40:18 -0800 (PST) Subject: [Tutor] about reload In-Reply-To: <45959B4A.7020001@gmail.com> References: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> <45959B4A.7020001@gmail.com> Message-ID: > Actually, if you have IDLE in the default setup on Windows and you > right-click something to edit it, > IDLE doesn't open a subprocess each time a script is executed, so it > will keep the imports in between runs of the program. Hi Luke, Ah, thanks for the correction. From pyro9219 at gmail.com Sat Dec 30 06:14:35 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Fri, 29 Dec 2006 21:14:35 -0800 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: References: Message-ID: I might have been unclear, or this tid-bit might have been lost in the thread... but I'm trying to send directly from ImageGrab.Grab(), without saving the data as a file. Thats where I'm getting hung... If it try to send an actual stored file, I have no problem. Is this maybe impossible? My thought was that I could just save a little process time and file fragmentation if I cut out the middle man, plus there really is no reason to save the screen capture on the server side. Maybe I really need to look into SOAP for this sort of stuff? I'm just playing with the technology, and from the searching I've done, the XML-RPC seemed to fit my needs best. I could certainly be wrong though. Thanks for both of you giving me feedback. On 12/29/06, Lee Harr wrote: > > >http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > > >Using this example I get error's about 'expected binary .read(), but got > >instance instead. > > > I assume you are using this ... > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > Are you using windows? > > I think you would need to pass the binary flag to open ... > > imagedata = open(filename, 'rb').read() > > > > It's probably a good idea to use the binary flag if you are expecting > binary data just in case it gets ported somewhere else later. > > > >I've just been using xmlrpclib and simplexmlrpcserver for this, but I'm > >wondering if I should perhaps use twisted instead. > > I've used xml-rpc to send image data before. It worked. > > _________________________________________________________________ > Don't just search. Find. Check out the new MSN Search! > http://search.msn.com/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061229/8c3b2a56/attachment.htm From samrobertsmith at gmail.com Sat Dec 30 08:01:06 2006 From: samrobertsmith at gmail.com (linda.s) Date: Fri, 29 Dec 2006 23:01:06 -0800 Subject: [Tutor] about reload In-Reply-To: References: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> <45959B4A.7020001@gmail.com> Message-ID: <1d987df30612292301k31f070e8ya92bace1020cd160@mail.gmail.com> On 12/29/06, Danny Yoo wrote: > > Actually, if you have IDLE in the default setup on Windows and you > > right-click something to edit it, > > IDLE doesn't open a subprocess each time a script is executed, so it > > will keep the imports in between runs of the program. > > Hi Luke, > > Ah, thanks for the correction. I got confused now:-> if IDLE keeps the imports in between runs of the program, do I still need import and reload? or click F5 in IDLE is OK? From rabidpoobear at gmail.com Sat Dec 30 11:19:02 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Dec 2006 04:19:02 -0600 Subject: [Tutor] about reload In-Reply-To: <1d987df30612292301k31f070e8ya92bace1020cd160@mail.gmail.com> References: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> <45959B4A.7020001@gmail.com> <1d987df30612292301k31f070e8ya92bace1020cd160@mail.gmail.com> Message-ID: <45963D16.5060505@gmail.com> > I got confused now:-> if IDLE keeps the imports in between runs of the > program, do I still need import and reload? or click F5 in IDLE is OK? > The purpose of import is so that python knows what packages you intend to use, because if it imported every package every time, then many bad things would occur - one broken package would cause every python script on your computer to stop running until you deleted or fixed the problem package - it would clutter the global namespace - it would slow down startup of your scripts. - various other things that I can't think of. So this explains why we need import. Now in IDLE, because it is itself written in Python, there are strange side effects (when it can't open a subprocess). If you write a script in IDLE that goes into an infinite loop, the IDLE windows will stop responding. As we mentioned before, if you run one script through an IDLE shell that imports a module, on all the subsequent runs, even of different scripts, through the same IDLE shell, the imports will still be in the global namespace. That does not mean that you don't need to have an import at the top of each of your scripts. You want the program to run outside of IDLE, right? How about in a fresh copy of IDLE? then you better put the imports in. Python won't know what you mean when you say something like 'print math.pi' unless you have an 'import math' at the beginning of your script. As far as reload goes: reload does NOTHING if you're running your script from the command line (as far as you're concerned, at this stage in learning Python.). Take this for example: #----- config.py a = 'apples' #----- end #----- script.py import config print a reload(config) print a #------ The output of this is going to be apples apples unless you change the 'config.py' file in between the first 'print a' and the 'reload'. In other words, reload updates changes that you make to your modules/packages. If you aren't planning on editing modules while your script is running, you don't have to worry about what 'reload' does. The imports will always be reloaded automatically when you run the Python interpreter again. There are 2 situations, as a beginner, that you would want reload. Take this for example. #-----config.py a = 'apples' #----- >>> import config >>> print config.a apples #------- we go and edit config.py while the interactive interpreter is still running, and we change it to this: a = 'aardvark' #----- >>> print config.a apples >>> reload(config) >>> print config.a aardvark See, the 'config' module's attributes didn't change until we reloaded it. So case 1: when using an interactive interpreter and editing modules, reload updates our changes. The second case is, if IDLE is running, remember how we said that it keeps the imported modules imported? Well, say your program does this: #---- import config print config.a #----- Now, the first time, and all subsequent times we run this program, it will do the same thing: it will print whatever 'a' was when config was imported in the FIRST run of the program. So if we went and edited config.py, none of the changes would be reflected in the print statement of this script. Basically, if you're designing a module in IDLE and you're making lots of changes to it, you have 2 choices: First, you could add a reload() to the top of the script that's using the module, and take it out when you're done. Or, a better solution, start IDLE from the start menu, instead of right-clicking and choosing "Edit..." and it will open a subprocess, and none of these 'imported stuff hanging around' problems will occur. HTH - tell me if anything's unclear -Luke From nephish at gmail.com Sat Dec 30 15:44:51 2006 From: nephish at gmail.com (shawn bright) Date: Sat, 30 Dec 2006 08:44:51 -0600 Subject: [Tutor] question about importing threads Message-ID: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> Hello there all. i have an app that has grown to about 4000 lines. It uses 6 threads and a GTK2 GUI. i was wondering if i could split it into seperate files that i could import. Each thread is a class. i did not think that this would be a problem, but some of the threads pass information to views and buffers. If i had a thread outside of the main file, could i pass a gtk object to it so that it could write to it when it needed too? and one last thing. If i did this, would i be able to only import the class when i started the thread, and then re-import it if i started the thread later . If so, this would allow me to work on a thread without having to restart the main program, and i could let the other threads keep running. As i find bugs, i could squash them without loosing any functionality of the other threads. Then if i wanted to stop or restart a thread by clicking a button, i could just re-import the class. is this ok ? thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061230/318e84a9/attachment.html From kent37 at tds.net Sat Dec 30 15:51:56 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Dec 2006 09:51:56 -0500 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: References: Message-ID: <45967D0C.9040205@tds.net> Chris Hengge wrote: > I might have been unclear, or this tid-bit might have been lost in the > thread... but I'm trying to send directly from ImageGrab.Grab(), without > saving the data as a file. Thats where I'm getting hung... If it try to > send an actual stored file, I have no problem. Is this maybe impossible? > My thought was that I could just save a little process time and file > fragmentation if I cut out the middle man, plus there really is no > reason to save the screen capture on the server side. Can you show the code that works? If you are writing your image data to a file, then using something like Lee's example below, that just reads the file data into a Binary object, you should be able to just create the Binary object from the image data directly. Kent > > Maybe I really need to look into SOAP for this sort of stuff? I'm just > playing with the technology, and from the searching I've done, the > XML-RPC seemed to fit my needs best. I could certainly be wrong though. > > Thanks for both of you giving me feedback. > > On 12/29/06, *Lee Harr* > wrote: > > >http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > > > >Using this example I get error's about 'expected binary .read(), > but got > >instance instead. > > > I assume you are using this ... > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > Are you using windows? > > I think you would need to pass the binary flag to open ... > > imagedata = open(filename, 'rb').read() > > > > It's probably a good idea to use the binary flag if you are expecting > binary data just in case it gets ported somewhere else later. > > > >I've just been using xmlrpclib and simplexmlrpcserver for this, > but I'm > >wondering if I should perhaps use twisted instead. > > I've used xml-rpc to send image data before. It worked. > > _________________________________________________________________ > Don't just search. Find. Check out the new MSN Search! > http://search.msn.com/ > > _______________________________________________ > 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 kent37 at tds.net Sat Dec 30 15:59:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Dec 2006 09:59:01 -0500 Subject: [Tutor] question about importing threads In-Reply-To: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> Message-ID: <45967EB5.3020902@tds.net> shawn bright wrote: > Hello there all. > i have an app that has grown to about 4000 lines. It uses 6 threads and > a GTK2 GUI. > i was wondering if i could split it into seperate files that i could > import. Each thread is a class. That should be fine. > i did not think that this would be a problem, but some of the threads > pass information to views and buffers. How do the threads find out about the views and buffers? If they are global objects then you will have a problem. If they are passed to the threads as parameters then it should be fine. > If i had a thread outside of the main file, could i pass a gtk object to > it so that it could write to it when it needed too? Yes. > and one last thing. If i did this, would i be able to only import the > class when i started the thread, and then re-import it if i started the > thread later . If so, this would allow me to work on a thread without > having to restart the main program, and i could let the other threads > keep running. As i find bugs, i could squash them without loosing any > functionality of the other threads. Then if i wanted to stop or restart > a thread by clicking a button, i could just re-import the class. > > is this ok ? You can use reload() to update a module that has been changed. You will also have to recreate any objects that were created from classes in the module so they become instances of the modified module. You might be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Kent > > thanks > shawn > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From nephish at gmail.com Sat Dec 30 16:13:15 2006 From: nephish at gmail.com (shawn bright) Date: Sat, 30 Dec 2006 09:13:15 -0600 Subject: [Tutor] question about importing threads In-Reply-To: <45967EB5.3020902@tds.net> References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> <45967EB5.3020902@tds.net> Message-ID: <384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> Kent, Thanks. this is great. Yes, when i start the thread, i also pass the gtk object to it. kinda like this. serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) serial_1.start() so i am wanting to change that, but i do not exactly know how to stop a thread once i have it running, so that i could start another one. anyway, thanks for the link and the info, i am going to get started on testing this right away. This long a .py script is becomming a headache and i think it will be easier by far if it is pulled apart somewhat. thanks again shawn On 12/30/06, Kent Johnson wrote: > > shawn bright wrote: > > Hello there all. > > i have an app that has grown to about 4000 lines. It uses 6 threads and > > a GTK2 GUI. > > i was wondering if i could split it into seperate files that i could > > import. Each thread is a class. > > That should be fine. > > > i did not think that this would be a problem, but some of the threads > > pass information to views and buffers. > > How do the threads find out about the views and buffers? If they are > global objects then you will have a problem. If they are passed to the > threads as parameters then it should be fine. > > > If i had a thread outside of the main file, could i pass a gtk object to > > it so that it could write to it when it needed too? > > Yes. > > > and one last thing. If i did this, would i be able to only import the > > class when i started the thread, and then re-import it if i started the > > thread later . If so, this would allow me to work on a thread without > > having to restart the main program, and i could let the other threads > > keep running. As i find bugs, i could squash them without loosing any > > functionality of the other threads. Then if i wanted to stop or restart > > a thread by clicking a button, i could just re-import the class. > > > > is this ok ? > > You can use reload() to update a module that has been changed. You will > also have to recreate any objects that were created from classes in the > module so they become instances of the modified module. You might be > interested in this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > > Kent > > > > > thanks > > shawn > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061230/cff913b4/attachment.htm From kent37 at tds.net Sat Dec 30 17:29:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Dec 2006 11:29:24 -0500 Subject: [Tutor] question about importing threads In-Reply-To: <384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> <45967EB5.3020902@tds.net> <384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> Message-ID: <459693E4.2070109@tds.net> shawn bright wrote: > Kent, Thanks. > this is great. Yes, when i start the thread, i also pass the gtk object > to it. > kinda like this. > > serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) > serial_1.start() > > so i am wanting to change that, but i do not exactly know how to stop a > thread once i have it running, so that i could start another one. The usual way to stop a thread is to set a flag that the thread checks. Here is an example using a threading.Event as a flag: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 > anyway, thanks for the link and the info, i am going to get started on > testing this right away. This long a .py script is becomming a headache > and i think it will be easier by far if it is pulled apart somewhat. Yes, 4000 lines is pretty long for one file IMO. Kent From nephish at gmail.com Sat Dec 30 17:39:42 2006 From: nephish at gmail.com (shawn bright) Date: Sat, 30 Dec 2006 10:39:42 -0600 Subject: [Tutor] question about importing threads In-Reply-To: <459693E4.2070109@tds.net> References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> <45967EB5.3020902@tds.net> <384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> <459693E4.2070109@tds.net> Message-ID: <384c93600612300839t5cd0b2f4vcb8d0d118a3c96aa@mail.gmail.com> great help, and great link, thanks again. shawn On 12/30/06, Kent Johnson wrote: > > shawn bright wrote: > > Kent, Thanks. > > this is great. Yes, when i start the thread, i also pass the gtk object > > to it. > > kinda like this. > > > > serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view) > > serial_1.start() > > > > so i am wanting to change that, but i do not exactly know how to stop a > > thread once i have it running, so that i could start another one. > > The usual way to stop a thread is to set a flag that the thread checks. > Here is an example using a threading.Event as a flag: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 > > > anyway, thanks for the link and the info, i am going to get started on > > testing this right away. This long a .py script is becomming a headache > > and i think it will be easier by far if it is pulled apart somewhat. > > Yes, 4000 lines is pretty long for one file IMO. > > Kent > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061230/91925f07/attachment.html From alan.gauld at btinternet.com Sat Dec 30 20:16:54 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 30 Dec 2006 19:16:54 -0000 Subject: [Tutor] question about importing threads References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com><45967EB5.3020902@tds.net> <384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> Message-ID: "shawn bright" wrote i > testing this right away. This long a .py script is becomming a > headache and > i think it will be easier by far if it is pulled apart somewhat. As a general rule of thumb, any Python script (or any programming language file for that matter!) that gets longer than 4 or 5 hundred lines should be looked at closely in terms of splitting it into modules. There are a few (very few) times where I've seen a thousand line file that was justified, but nearly any time you get beyond 500 lines you should be splitting things up - especially in high level languages like Python where the methods/functions tend to be short anyway. FWIW A quick check of the Python standard library shows the average file size there to be: 459 lines(*) And that's pretty high IMHO! There are 19 files over a thousand lines and the biggest file is over 3000 lines... which seems way too big to me! But that's out of 188 files... (*) Cygwin; Python 2.4 In case you want to repeat for your version I used: >>> libs = [len(open(f).readlines()) for f in glob('*.py')] >>> print sum(libs)/len(libs) >>> print max(libs) >>> print len([s for s in libs if s>1000]) Alan G From samrobertsmith at gmail.com Sat Dec 30 22:17:04 2006 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 30 Dec 2006 13:17:04 -0800 Subject: [Tutor] about reload In-Reply-To: <45963D16.5060505@gmail.com> References: <1d987df30612291305p22a3f2d8g967fc397322f90f2@mail.gmail.com> <45959B4A.7020001@gmail.com> <1d987df30612292301k31f070e8ya92bace1020cd160@mail.gmail.com> <45963D16.5060505@gmail.com> Message-ID: <1d987df30612301317x1ced0a6fs16d1d9a4060990ef@mail.gmail.com> On 12/30/06, Luke Paireepinart wrote: > > > I got confused now:-> if IDLE keeps the imports in between runs of the > > program, do I still need import and reload? or click F5 in IDLE is OK? > > > The purpose of import is so that python knows what packages you intend > to use, > because if it imported every package every time, then many bad things > would occur > - one broken package would cause every python script on your computer to > stop running until you deleted or fixed the problem package > - it would clutter the global namespace > - it would slow down startup of your scripts. > - various other things that I can't think of. > > So this explains why we need import. > > Now in IDLE, because it is itself written in Python, > there are strange side effects (when it can't open a subprocess). > If you write a script in IDLE that goes into an infinite loop, the IDLE > windows will stop responding. > As we mentioned before, if you run one script through an IDLE shell that > imports a module, > on all the subsequent runs, even of different scripts, through the same > IDLE shell, the imports will still be in the global namespace. > > That does not mean that you don't need to have an import at the top of > each of your scripts. > You want the program to run outside of IDLE, right? How about in a > fresh copy of IDLE? > then you better put the imports in. > Python won't know what you mean when you say something like 'print > math.pi' unless you have an 'import math' at the beginning of your script. > > As far as reload goes: > > reload does NOTHING if you're running your script from the command line > (as far as you're concerned, at this stage in learning Python.). > Take this for example: > > #----- config.py > a = 'apples' > #----- end > > #----- script.py > > import config > print a > reload(config) > print a > > #------ > The output of this is going to be > apples > apples > unless you change the 'config.py' file in between the first 'print a' > and the 'reload'. > > In other words, reload updates changes that you make to your > modules/packages. > If you aren't planning on editing modules while your script is running, > you don't have to worry about what 'reload' does. > The imports will always be reloaded automatically when you run the > Python interpreter again. > > There are 2 situations, as a beginner, that you would want reload. > Take this for example. > > #-----config.py > a = 'apples' > #----- > > >>> import config > >>> print config.a > apples > > #------- we go and edit config.py while the interactive interpreter is > still running, and we change it to this: > a = 'aardvark' > #----- > > >>> print config.a > apples > >>> reload(config) > >>> print config.a > aardvark > > See, the 'config' module's attributes didn't change until we reloaded > it. So case 1: when using an interactive interpreter and editing modules, > reload updates our changes. > > The second case is, if IDLE is running, remember how we said that it > keeps the imported modules imported? > > Well, say your program does this: > #---- > import config > print config.a > #----- > Now, the first time, and all subsequent times we run this program, it > will do the same thing: > it will print whatever 'a' was when config was imported in the FIRST run > of the program. > So if we went and edited config.py, none of the changes would be > reflected in the print statement of this script. > > Basically, if you're designing a module in IDLE and you're making lots > of changes to it, you have 2 choices: > First, you could add a reload() to the top of the script that's using > the module, > and take it out when you're done. > > Or, a better solution, start IDLE from the start menu, instead of > right-clicking and choosing "Edit..." and it will open a subprocess, > and none of these 'imported stuff hanging around' problems will occur. > > HTH - tell me if anything's unclear > -Luke > > Thanks a lot! From pyro9219 at gmail.com Sun Dec 31 00:04:25 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 30 Dec 2006 15:04:25 -0800 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: <45967D0C.9040205@tds.net> References: <45967D0C.9040205@tds.net> Message-ID: if I'm trying to transmit a 'file' that is actually saved on the HD, the code from the link in my first post works fine (reading in the file using binary mode access). My problem is that I'm trying to figure out how to transfer data that isn't yet saved to the drive, because I'm wanting to be able to send any sort of data type across the connection. This is getting rather frustrating because I'm getting so many replies back that aren't even attempts at answers, but rather questions about things I'm not trying to do. I'll restate the problem. grab image data from server side connection. transfer image data to client side write image data to file on client side. I've already established a working RPC connection, and if I transmit a 'file' that can be read using binary mode (exact same code as posted in both the link in my first email, and by others in this thread) it works fine. My problem I'm trying to overcome is that I ***do not want to write the image data from the server to a file, just to send it, then delete the image file on the server*** For this specific challenge, I've found no actual "how-to" help... Just bits of information making it sound possible. Again, I dont want to "file transfer" anything, I want to send data that isn't in the default data-types for xml-rpc, which I've read can be done using binary mode transfers. On 12/30/06, Kent Johnson wrote: > > Chris Hengge wrote: > > I might have been unclear, or this tid-bit might have been lost in the > > thread... but I'm trying to send directly from ImageGrab.Grab(), without > > saving the data as a file. Thats where I'm getting hung... If it try to > > send an actual stored file, I have no problem. Is this maybe impossible? > > My thought was that I could just save a little process time and file > > fragmentation if I cut out the middle man, plus there really is no > > reason to save the screen capture on the server side. > > Can you show the code that works? If you are writing your image data to > a file, then using something like Lee's example below, that just reads > the file data into a Binary object, you should be able to just create > the Binary object from the image data directly. > > Kent > > > > > Maybe I really need to look into SOAP for this sort of stuff? I'm just > > playing with the technology, and from the searching I've done, the > > XML-RPC seemed to fit my needs best. I could certainly be wrong though. > > > > Thanks for both of you giving me feedback. > > > > On 12/29/06, *Lee Harr* > > wrote: > > > > > > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > > > > > > > >Using this example I get error's about 'expected binary .read(), > > but got > > >instance instead. > > > > > > I assume you are using this ... > > > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > > > > Are you using windows? > > > > I think you would need to pass the binary flag to open ... > > > > imagedata = open(filename, 'rb').read() > > > > > > > > It's probably a good idea to use the binary flag if you are > expecting > > binary data just in case it gets ported somewhere else later. > > > > > > >I've just been using xmlrpclib and simplexmlrpcserver for this, > > but I'm > > >wondering if I should perhaps use twisted instead. > > > > I've used xml-rpc to send image data before. It worked. > > > > _________________________________________________________________ > > Don't just search. Find. Check out the new MSN Search! > > http://search.msn.com/ > > > > _______________________________________________ > > 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: http://mail.python.org/pipermail/tutor/attachments/20061230/84a050a3/attachment.html From pyro9219 at gmail.com Sun Dec 31 00:10:08 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 30 Dec 2006 15:10:08 -0800 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: <45967D0C.9040205@tds.net> References: <45967D0C.9040205@tds.net> Message-ID: This works... d = xmlrpclib.Binary(open("C:\\somefile.exe", "rb").read()) What I need is more like screenShot = ImageGrab.Grab() d = xmlrpclib.Binary(screenShot) This doesn't work though. On 12/30/06, Kent Johnson wrote: > > Chris Hengge wrote: > > I might have been unclear, or this tid-bit might have been lost in the > > thread... but I'm trying to send directly from ImageGrab.Grab(), without > > saving the data as a file. Thats where I'm getting hung... If it try to > > send an actual stored file, I have no problem. Is this maybe impossible? > > My thought was that I could just save a little process time and file > > fragmentation if I cut out the middle man, plus there really is no > > reason to save the screen capture on the server side. > > Can you show the code that works? If you are writing your image data to > a file, then using something like Lee's example below, that just reads > the file data into a Binary object, you should be able to just create > the Binary object from the image data directly. > > Kent > > > > > Maybe I really need to look into SOAP for this sort of stuff? I'm just > > playing with the technology, and from the searching I've done, the > > XML-RPC seemed to fit my needs best. I could certainly be wrong though. > > > > Thanks for both of you giving me feedback. > > > > On 12/29/06, *Lee Harr* > > wrote: > > > > > > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > > > > > > > >Using this example I get error's about 'expected binary .read(), > > but got > > >instance instead. > > > > > > I assume you are using this ... > > > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > > > > Are you using windows? > > > > I think you would need to pass the binary flag to open ... > > > > imagedata = open(filename, 'rb').read() > > > > > > > > It's probably a good idea to use the binary flag if you are > expecting > > binary data just in case it gets ported somewhere else later. > > > > > > >I've just been using xmlrpclib and simplexmlrpcserver for this, > > but I'm > > >wondering if I should perhaps use twisted instead. > > > > I've used xml-rpc to send image data before. It worked. > > > > _________________________________________________________________ > > Don't just search. Find. Check out the new MSN Search! > > http://search.msn.com/ > > > > _______________________________________________ > > 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: http://mail.python.org/pipermail/tutor/attachments/20061230/5f137772/attachment.htm From rabidpoobear at gmail.com Sun Dec 31 01:08:47 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Dec 2006 18:08:47 -0600 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: References: <45967D0C.9040205@tds.net> Message-ID: <4596FF8F.8080401@gmail.com> Chris Hengge wrote: > if I'm trying to transmit a 'file' that is actually saved on the HD, > the code from the link in my first post works fine (reading in the > file using binary mode access). My problem is that I'm trying to > figure out how to transfer data that isn't yet saved to the drive, > because I'm wanting to be able to send any sort of data type across > the connection. This is getting rather frustrating because I'm getting > so many replies back that aren't even attempts at answers, but rather > questions about things I'm not trying to do. I'll restate the problem. > > grab image data from server side connection. > transfer image data to client side > write image data to file on client side. > > I've already established a working RPC connection, and if I transmit a > 'file' that can be read using binary mode (exact same code as posted > in both the link in my first email, and by others in this thread) it > works fine. My problem I'm trying to overcome is that I > > ***do not want to write the image data from the server to a file, just > to send it, then delete the image file on the server*** > And how... It's clear what you're trying to do. The problem is this: 1) ImageGrab.grab() -> returns image object that has a 'save' method. You use this method with the following syntax import Image, ImageGrab im = ImageGrab.grab() im.save('filename.jpg') to save the file . 2) you read back in the file by doing: f = file('filename.jpg','rb') contents = f.read() 3) you send it with this: xmlrpclib.Binary(contents) What you're trying to do is to eliminate step 1 and 2, so that you read the ImageGrab's data directly into the xmlrpclib.Binary method call without having to write a file. Okay. So the main problem we're having here is that you seem to think that you should be able to send the ImageGrab object itself over the connection. What is the problem is that xmlrpclib doesn't understand these class instances. you need to give it plain binary data that it can send. So there's a few ways you can go about this. But the main strategy is to get the data out of the ImageGrab object. one way is stated above - use the save method to write to a file. another possible way is to create a filelike class, implementing 'tell' 'seek' and 'write' methods, that just collects all the data written to it and keeps it in memory rather than writing it out to a file. This is hinted at in the documentation for im.save(): "You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the *seek*, *tell*, and *write* methods, and be opened in binary mode." (I assume it means you can use a file-like object, also, but it's possible that you can't, and I leave it to you to test that :) ) a third solution is to convert the data to a string using *im.tostring(). *send that over your connection, and use im.fromstring() on the other end to recreate the image. you could even use im.getdata(), iterate over it, construct your own representation of the data, and convert this back to an image at the other end. All of these strategies have nothing at all to do with xmlrpc. I have no idea what xmlrpc is, but I don't need to. Your question is simplified to: How do I convert a PIL Image instance into binary data? As Kent said: "If you are writing your image data to a file, then using something like Lee's example below, that just reads the file data into a Binary object, you should be able to just create the Binary object from the image data directly." > For this specific challenge, I've found no actual "how-to" help... Just bits of information making it sound possible. Again, I dont want to "file transfer" anything, I want to send data that isn't in the default data-types for xml-rpc, which I've read can be done using binary mode transfers. The reason you haven't had any actual 'how-to' help is because we believe that you could figure out what to do from the information given to you. One of the greatest things about learning programming is figuring out how to do things yourself. That being said, this mailing list's purpose is to help you when you get stuck along the way. Not to give you code snippets that do exactly what you want - just to give you that little nudge in the right direction so you can continue working things out for yourself. An example of this - I was playing Twilight Princess last night, and I got stuck in this one area. I couldn't figure out what to do, and I ran around for an hour trying to find out what to do next. I finally asked the in-game character that follows you around for help - and she gave me a hint. I went to the place she told me to (I'm trying to avoid spoilers) and I did what she suggested - looking more closely at something. After a good 30 seconds, it all of the sudden hit me. I knew exactly what to do, and I went on happily through the game. The point is that the most enjoyable part of the game is when you figure out something like that. I had all the clues right there, I just couldn't piece them together. So we've given you clues. Kent suggested - try to get the image data directly without going through a save-open process. You already know how to send binary data. So how do you get binary data from the image? That's what we wanted you to figure out. well, as I said before, you can try to pass save() a file-like object and keep it in memory, or, probably a much better solution, is just to convert it to a string. Also, why are you using xml? you're still working on that VNC right? Why not just plain sockets, or twisted, or something? HTH, -Luke > > On 12/30/06, *Kent Johnson* > > wrote: > > Chris Hengge wrote: > > I might have been unclear, or this tid-bit might have been lost > in the > > thread... but I'm trying to send directly from ImageGrab.Grab(), > without > > saving the data as a file. Thats where I'm getting hung... If it > try to > > send an actual stored file, I have no problem. Is this maybe > impossible? > > My thought was that I could just save a little process time and file > > fragmentation if I cut out the middle man, plus there really is no > > reason to save the screen capture on the server side. > > Can you show the code that works? If you are writing your image > data to > a file, then using something like Lee's example below, that just reads > the file data into a Binary object, you should be able to just create > the Binary object from the image data directly. > > Kent > > > > > Maybe I really need to look into SOAP for this sort of stuff? > I'm just > > playing with the technology, and from the searching I've done, the > > XML-RPC seemed to fit my needs best. I could certainly be wrong > though. > > > > Thanks for both of you giving me feedback. > > > > On 12/29/06, *Lee Harr* > > >> wrote: > > > > > > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > < > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html> > > > > > >Using this example I get error's about 'expected binary > .read(), > > but got > > >instance instead. > > > > > > I assume you are using this ... > > > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > > > > Are you using windows? > > > > I think you would need to pass the binary flag to open ... > > > > imagedata = open(filename, 'rb').read() > > > > > > > > It's probably a good idea to use the binary flag if you are > expecting > > binary data just in case it gets ported somewhere else later. > > > > > > >I've just been using xmlrpclib and simplexmlrpcserver for > this, > > but I'm > > >wondering if I should perhaps use twisted instead. > > > > I've used xml-rpc to send image data before. It worked. > > > > > _________________________________________________________________ > > Don't just search. Find. Check out the new MSN Search! > > http://search.msn.com/ > > > > _______________________________________________ > > 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 > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Sun Dec 31 01:09:29 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Dec 2006 18:09:29 -0600 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: References: <45967D0C.9040205@tds.net> Message-ID: <4596FFB9.1040508@gmail.com> Chris Hengge wrote: > This works... > d = xmlrpclib.Binary(open("C:\\somefile.exe", "rb").read()) > > What I need is more like > screenShot = ImageGrab.Grab() > d = xmlrpclib.Binary(screenShot) because screenShot is not binary data. It's an instance of the class Image. From pyro9219 at gmail.com Sun Dec 31 02:21:24 2006 From: pyro9219 at gmail.com (Chris Hengge) Date: Sat, 30 Dec 2006 17:21:24 -0800 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: <4596FF8F.8080401@gmail.com> References: <45967D0C.9040205@tds.net> <4596FF8F.8080401@gmail.com> Message-ID: First off, thanks for the info luke, I'll give these idea's a shot. Second, I fully understand the wow factor from figuring out stuff on my own, but I also work fulltime and attend roughly 20 credits of college a term, while taking care of my family/homelife and this xmas break is one of the few chances where I got time away from both work and from school, leaving just my family and my freetime. All I'm trying to do is get the most of my time. I also prefer examples as answers, not necessarily code... but something more then "you need to figure out how to do X", because more often then not, I've already come up with that possibility. However, that doesn't mean the method is a good one. Much like your own answers to most of my questions, you state several ways varying from "probably works" to "how I'd try to do it". Personally, I'd rather understand more of the "how I know it works" so that later as I get better I can fall back to working methods, and leave myself open to creating my own ways as I stumble upon them, or have need for a different approach. It's like cooking.. first you learn how to make a pizza like everyone else, but after a while you get tired of eating that pizza, so you make your own variation. And yes, I'm still messing around with my VNC program, thats what this is in relation too. I was just trying out XML-RPC because its suited for the job best I can tell from what I've read and seen it used for. I've got most of the projects features already done using plain sockets, this is just another way I was trying, and if you check the other emails I've said a few reasons why. As for twisted.. Thats next.. I even stated that it might be better, and tossed it out for critic review, but nobody said otherwise so I figured I was fine. (I started with sockets for simplicity, then XML-RPC is supposed to be next easiest with twisted being last for my needs, also the most overhead) Anyways, I'll give your suggestions a shot and see what I come up with. On 12/30/06, Luke Paireepinart wrote: > > Chris Hengge wrote: > > if I'm trying to transmit a 'file' that is actually saved on the HD, > > the code from the link in my first post works fine (reading in the > > file using binary mode access). My problem is that I'm trying to > > figure out how to transfer data that isn't yet saved to the drive, > > because I'm wanting to be able to send any sort of data type across > > the connection. This is getting rather frustrating because I'm getting > > so many replies back that aren't even attempts at answers, but rather > > questions about things I'm not trying to do. I'll restate the problem. > > > > grab image data from server side connection. > > transfer image data to client side > > write image data to file on client side. > > > > I've already established a working RPC connection, and if I transmit a > > 'file' that can be read using binary mode (exact same code as posted > > in both the link in my first email, and by others in this thread) it > > works fine. My problem I'm trying to overcome is that I > > > > ***do not want to write the image data from the server to a file, just > > to send it, then delete the image file on the server*** > > > And how... > > It's clear what you're trying to do. > The problem is this: > > 1) ImageGrab.grab() -> returns image object that has a 'save' method. > You use this method with the following syntax > import Image, ImageGrab > im = ImageGrab.grab() > im.save('filename.jpg') > > to save the file . > 2) > you read back in the file by doing: > f = file('filename.jpg','rb') > contents = f.read() > > > 3) > you send it with this: > xmlrpclib.Binary(contents) > > > What you're trying to do is to eliminate step 1 and 2, so that you read > the ImageGrab's data directly into the xmlrpclib.Binary method call > without having to write a file. > > Okay. > So the main problem we're having here is that you seem to think that you > should be able to send the ImageGrab object itself over the connection. > What is the problem is that xmlrpclib doesn't understand these class > instances. you need to give it plain binary data that it can send. > So there's a few ways you can go about this. > > But the main strategy is to get the data out of the ImageGrab object. > one way is stated above - use the save method to write to a file. > another possible way is to create a filelike class, implementing 'tell' > 'seek' and 'write' methods, that just collects all the data written to > it and keeps it in memory > rather than writing it out to a file. > This is hinted at in the documentation for im.save(): > "You can use a file object instead of a filename. In this case, you must > always specify the format. The file object must implement the *seek*, > *tell*, and *write* methods, and be opened in binary mode." > (I assume it means you can use a file-like object, also, but it's > possible that you can't, and I leave it to you to test that :) ) > > a third solution is to convert the data to a string using > *im.tostring(). > *send that over your connection, and use im.fromstring() on the other > end to recreate the image. > > you could even use im.getdata(), iterate over it, construct your own > representation of the data, and convert this back to an image at the > other end. > > All of these strategies have nothing at all to do with xmlrpc. > I have no idea what xmlrpc is, but I don't need to. > Your question is simplified to: > How do I convert a PIL Image instance into binary data? > > As Kent said: > "If you are writing your image data to > a file, then using something like Lee's example below, that just reads > the file data into a Binary object, you should be able to just create > the Binary object from the image data directly." > > > For this specific challenge, I've found no actual "how-to" help... > Just bits of information making it sound possible. Again, I dont want to > "file transfer" anything, I want to send data that isn't in the default > data-types for xml-rpc, which I've read can be done using binary mode > transfers. > > The reason you haven't had any actual 'how-to' help is because we > believe that you could figure out what to do from the information given > to you. > One of the greatest things about learning programming is figuring out > how to do things yourself. > That being said, this mailing list's purpose is to help you when you get > stuck along the way. > Not to give you code snippets that do exactly what you want - just to > give you that little nudge in the right direction so you can continue > working things out for yourself. > An example of this - I was playing Twilight Princess last night, and I > got stuck in this one area. I couldn't figure out what to do, and I ran > around for an hour trying to find out what to do next. I finally asked > the in-game character that follows you around for help - and she gave me > a hint. > I went to the place she told me to (I'm trying to avoid spoilers) and I > did what she suggested - looking more closely at something. > After a good 30 seconds, it all of the sudden hit me. I knew exactly > what to do, and I went on happily through the game. > > The point is that the most enjoyable part of the game is when you figure > out something like that. I had all the clues right there, I just > couldn't piece them together. > > So we've given you clues. Kent suggested - try to get the image data > directly without going through a save-open process. > You already know how to send binary data. So how do you get binary data > from the image? > That's what we wanted you to figure out. > well, as I said before, you can try to pass save() a file-like object > and keep it in memory, > or, probably a much better solution, is just to convert it to a string. > > Also, why are you using xml? you're still working on that VNC right? > Why not just plain sockets, or twisted, or something? > > HTH, > -Luke > > > > On 12/30/06, *Kent Johnson* > > > wrote: > > > > Chris Hengge wrote: > > > I might have been unclear, or this tid-bit might have been lost > > in the > > > thread... but I'm trying to send directly from ImageGrab.Grab(), > > without > > > saving the data as a file. Thats where I'm getting hung... If it > > try to > > > send an actual stored file, I have no problem. Is this maybe > > impossible? > > > My thought was that I could just save a little process time and > file > > > fragmentation if I cut out the middle man, plus there really is no > > > reason to save the screen capture on the server side. > > > > Can you show the code that works? If you are writing your image > > data to > > a file, then using something like Lee's example below, that just > reads > > the file data into a Binary object, you should be able to just > create > > the Binary object from the image data directly. > > > > Kent > > > > > > > > Maybe I really need to look into SOAP for this sort of stuff? > > I'm just > > > playing with the technology, and from the searching I've done, the > > > XML-RPC seemed to fit my needs best. I could certainly be wrong > > though. > > > > > > Thanks for both of you giving me feedback. > > > > > > On 12/29/06, *Lee Harr* > > > > >> wrote: > > > > > > > > > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > > < > > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html> > > > > > > > >Using this example I get error's about 'expected binary > > .read(), > > > but got > > > >instance instead. > > > > > > > > > I assume you are using this ... > > > > > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > > > > > > > Are you using windows? > > > > > > I think you would need to pass the binary flag to open ... > > > > > > imagedata = open(filename, 'rb').read() > > > > > > > > > > > > It's probably a good idea to use the binary flag if you are > > expecting > > > binary data just in case it gets ported somewhere else later. > > > > > > > > > >I've just been using xmlrpclib and simplexmlrpcserver for > > this, > > > but I'm > > > >wondering if I should perhaps use twisted instead. > > > > > > I've used xml-rpc to send image data before. It worked. > > > > > > > > _________________________________________________________________ > > > Don't just search. Find. Check out the new MSN Search! > > > http://search.msn.com/ > > > > > > _______________________________________________ > > > 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 > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061230/cdfbee64/attachment.html From kent37 at tds.net Sun Dec 31 03:15:49 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Dec 2006 21:15:49 -0500 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: References: <45967D0C.9040205@tds.net> Message-ID: <45971D55.60002@tds.net> Chris Hengge wrote: > if I'm trying to transmit a 'file' that is actually saved on the HD, the > code from the link in my first post works fine (reading in the file > using binary mode access). My problem is that I'm trying to figure out > how to transfer data that isn't yet saved to the drive, because I'm > wanting to be able to send any sort of data type across the connection. > This is getting rather frustrating because I'm getting so many replies > back that aren't even attempts at answers, but rather questions about > things I'm not trying to do. I'll restate the problem. > > grab image data from server side connection. > transfer image data to client side > write image data to file on client side. > > I've already established a working RPC connection, and if I transmit a > 'file' that can be read using binary mode (exact same code as posted in > both the link in my first email, and by others in this thread) it works > fine. My problem I'm trying to overcome is that I > > ***do not want to write the image data from the server to a file, just > to send it, then delete the image file on the server*** I understand all that. What I want to know is, do you have code that does write the image data to a file and successfully send the file? Could you show that code so we can help you change it to what you want? Or are you just sending a random file? Kent > > For this specific challenge, I've found no actual "how-to" help... Just > bits of information making it sound possible. Again, I dont want to > "file transfer" anything, I want to send data that isn't in the default > data-types for xml-rpc, which I've read can be done using binary mode > transfers. > > On 12/30/06, *Kent Johnson* > wrote: > > Chris Hengge wrote: > > I might have been unclear, or this tid-bit might have been lost > in the > > thread... but I'm trying to send directly from ImageGrab.Grab(), > without > > saving the data as a file. Thats where I'm getting hung... If it > try to > > send an actual stored file, I have no problem. Is this maybe > impossible? > > My thought was that I could just save a little process time and file > > fragmentation if I cut out the middle man, plus there really is no > > reason to save the screen capture on the server side. > > Can you show the code that works? If you are writing your image data to > a file, then using something like Lee's example below, that just reads > the file data into a Binary object, you should be able to just create > the Binary object from the image data directly. > > Kent > > > > > Maybe I really need to look into SOAP for this sort of stuff? I'm > just > > playing with the technology, and from the searching I've done, the > > XML-RPC seemed to fit my needs best. I could certainly be wrong > though. > > > > Thanks for both of you giving me feedback. > > > > On 12/29/06, *Lee Harr* > > >> wrote: > > > > > > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html > > < > http://www.velocityreviews.com/forums/t343990-xmlrpc-send-file.html> > > > > > >Using this example I get error's about 'expected binary > .read(), > > but got > > >instance instead. > > > > > > I assume you are using this ... > > > > >d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) > > > > > > Are you using windows? > > > > I think you would need to pass the binary flag to open ... > > > > imagedata = open(filename, 'rb').read() > > > > > > > > It's probably a good idea to use the binary flag if you are > expecting > > binary data just in case it gets ported somewhere else later. > > > > > > >I've just been using xmlrpclib and simplexmlrpcserver for this, > > but I'm > > >wondering if I should perhaps use twisted instead. > > > > I've used xml-rpc to send image data before. It worked. > > > > _________________________________________________________________ > > Don't just search. Find. Check out the new MSN Search! > > http://search.msn.com/ > > > > _______________________________________________ > > 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 kent37 at tds.net Sun Dec 31 03:22:24 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Dec 2006 21:22:24 -0500 Subject: [Tutor] XML-RPC data transfers. In-Reply-To: <4596FF8F.8080401@gmail.com> References: <45967D0C.9040205@tds.net> <4596FF8F.8080401@gmail.com> Message-ID: <45971EE0.5020102@tds.net> Luke Paireepinart wrote: > But the main strategy is to get the data out of the ImageGrab object. > one way is stated above - use the save method to write to a file. > another possible way is to create a filelike class, implementing 'tell' > 'seek' and 'write' methods, that just collects all the data written to > it and keeps it in memory > rather than writing it out to a file. > This is hinted at in the documentation for im.save(): > "You can use a file object instead of a filename. In this case, you must > always specify the format. The file object must implement the *seek*, > *tell*, and *write* methods, and be opened in binary mode." > (I assume it means you can use a file-like object, also, but it's > possible that you can't, and I leave it to you to test that :) ) You can probably use a StringIO or cStringIO object instead of an actual file. > a third solution is to convert the data to a string using > *im.tostring(). > *send that over your connection, and use im.fromstring() on the other > end to recreate the image. That sounds like a good plan too. Kent From simplebob at gmail.com Sun Dec 31 06:10:39 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Sun, 31 Dec 2006 00:10:39 -0500 Subject: [Tutor] Starting python from a DOS prompt from any directory? Message-ID: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com> hello fellow programmers, newbie question here and this isn't much a programming question as it is a windows and python question, so sorry in advance. i have been having what i think is a problem with running python on windows from a DOS prompt. i am used to running python from a linux box where you can just type "python" or "python24" from a shell prompt and the python shell executes from any directory. now if i remember right, when used a window 2000, i could break out a DOS prompt and type "python" from any directory and it would execute the python screen where you could then begin testing code. now i am using a windows xp media center edition laptop with python 2.5 installed and when i go to run and then type "cmd" and then type "python" from the directory where the run "cmd" command drops me it says 'python' is not a recognized as an internal or external command. i would like to be able to just type "python" from any directory and have it run. does any one know why it's doing this or how i can achieve running python from just any directory. now i can navigate to the python folder and execute python from there. but there seems to me to be a way to achieve what i want to do. sorry for such a newbie question but i would like to figure this out because there are some situations where i need that to work from any directory. thanks in advance, -- Daniel McQuay boxster.homelinux.org H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061231/5912b8de/attachment.html From alan.gauld at btinternet.com Sun Dec 31 09:42:24 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Dec 2006 08:42:24 -0000 Subject: [Tutor] Starting python from a DOS prompt from any directory? References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com> Message-ID: "Daniel McQuay" wrote > from a DOS prompt. i am used to running python from a linux box > where you > can just type "python" or "python24" from a shell prompt and the > python > shell executes from any directory. > testing code. now i am using a windows xp media center edition > laptop with > python 2.5 installed and when i go to run and then type "cmd" and > then type > "python" from the directory where the run "cmd" command drops me it > says > 'python' is not a recognized as an internal or external command. You need to set up your PATH environment variable to include the python directory. You do this on XP(not so sure about Media Centre!) via the MyComputer->Properties->Advanced->Environment Variables route Once there you need to find the PATH variable and edit it to add the folder where Python lives (look at the properties of the shortcut to Python that you normally use to stat it). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Sun Dec 31 09:46:15 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 31 Dec 2006 02:46:15 -0600 Subject: [Tutor] Starting python from a DOS prompt from any directory? In-Reply-To: References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com> Message-ID: <459778D7.70603@gmail.com> Alan Gauld wrote: > "Daniel McQuay" wrote > > >> from a DOS prompt. i am used to running python from a linux box >> where you >> can just type "python" or "python24" from a shell prompt and the >> python >> shell executes from any directory. >> > > >> testing code. now i am using a windows xp media center edition >> laptop with >> python 2.5 installed and when i go to run and then type "cmd" and >> then type >> "python" from the directory where the run "cmd" command drops me it >> says >> 'python' is not a recognized as an internal or external command. >> > > You need to set up your PATH environment variable to include the > python directory. You do this on XP(not so sure about Media Centre!) > via the MyComputer->Properties->Advanced->Environment Variables route > Once there you need to find the PATH variable and edit it to add the > folder where Python lives (look at the properties of the shortcut to > Python that you normally use to stat it). > Also, if you just need a temporary fix (say you're using Python on someone else's system and you don't want to permanently change their PATH) you can type path = %path%;c:\python25 to add it to your path just for that DOS session. HTH, -Luke From alan.gauld at btinternet.com Sun Dec 31 09:59:47 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Dec 2006 08:59:47 -0000 Subject: [Tutor] XML-RPC data transfers. References: <45967D0C.9040205@tds.net><4596FF8F.8080401@gmail.com> Message-ID: "Chris Hengge" wrote > method is a good one. Much like your own answers to most of my > questions, > you state several ways varying from "probably works" to "how I'd try > to do > it". Personally, I'd rather understand more of the "how I know it > works" One reason may be that you are doing something unusual. Like sending images directly from memory over an XMLRPC connection. It should be possible but its not likely something many perople on this list will have actually done. So you only get suggestions of how they *might* do it ifd they had to. Because of the reliability issues with XMLRPC I'd always save image data to a file and send the file. (As I said earlier I'd try to avoid sending the file via RPC but thats another story that we've covered') But the advantages of having a file mean that the whole process is much more repeatable and resilient particularly if the object you are trying to send is subject to change - like a screen shot. If you have to resend because of RPC errors then the new screen grab might be different to the original. The alternative involves holding the screen image in RAM for a longish time which makes your program into a resource hog which is also bad practice... although with PCs having hundreds of Meg of RAM nowadays its sadly becoming more common! Bloatware rules :-( But I suspect the main reason you aren't getting working examples is simply that you are trying to do something that is outside normal programming experience on this list. But I may be wrong! ;-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nephish at gmail.com Sun Dec 31 15:46:15 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 31 Dec 2006 08:46:15 -0600 Subject: [Tutor] question about importing threads In-Reply-To: References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com> <45967EB5.3020902@tds.net> <384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> Message-ID: <384c93600612310646v63e958cdjdf4e72f15f35b8c0@mail.gmail.com> Thanks, Alan. Yes, the thing is getting to be a pain to deal with at this size, i am in-process of splitting out the classes into their own files. Thanks for your help. shawn On 12/30/06, Alan Gauld wrote: > > > "shawn bright" wrote i > > > testing this right away. This long a .py script is becomming a > > headache and > > i think it will be easier by far if it is pulled apart somewhat. > > As a general rule of thumb, any Python script (or any programming > language file for that matter!) that gets longer than 4 or 5 hundred > lines should be looked at closely in terms of splitting it into > modules. > > There are a few (very few) times where I've seen a thousand line > file that was justified, but nearly any time you get beyond 500 > lines you should be splitting things up - especially in high level > languages like Python where the methods/functions tend to be > short anyway. > > FWIW > > A quick check of the Python standard library shows the > average file size there to be: 459 lines(*) And that's pretty > high IMHO! > > There are 19 files over a thousand lines and the biggest file > is over 3000 lines... which seems way too big to me! > But that's out of 188 files... > > (*) > Cygwin; Python 2.4 > In case you want to repeat for your version I used: > >>> libs = [len(open(f).readlines()) for f in glob('*.py')] > >>> print sum(libs)/len(libs) > >>> print max(libs) > >>> print len([s for s in libs if s>1000]) > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20061231/70b981a7/attachment.html From alan.gauld at btinternet.com Sun Dec 31 19:44:25 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Dec 2006 18:44:25 -0000 Subject: [Tutor] question about importing threads References: <384c93600612300644o76e9be0aq28ed03d3b0962465@mail.gmail.com><45967EB5.3020902@tds.net><384c93600612300713i2a81159ao4d4bd2b0f38f7787@mail.gmail.com> <384c93600612310646v63e958cdjdf4e72f15f35b8c0@mail.gmail.com> Message-ID: "shawn bright" wrote > Yes, the thing is getting to be a pain to deal with at this size, i > am > in-process of splitting out the classes into their own files. One thing to watch is that while its easy and tempting to create one file per class it's often better to keep dependant classes together. In other words if class A can only be used together with class B then it is often better to keep A and B in the same module. Anyone who needs B can import the module and anyone who needs A needs B too so it saves them having to import two modules. As in all things in programming a little bit of thought is often better than the first "obvious" strategy. Grady Booch described the above strategy by saying that "the unit of reuse is the category" (which in his OO notation was a set of related classes) and in Python that means the module. Regards, Alan G. From Steven.Oldner at LA.GOV Sun Dec 31 20:27:01 2006 From: Steven.Oldner at LA.GOV (Steve Oldner) Date: Sun, 31 Dec 2006 13:27:01 -0600 Subject: [Tutor] Starting python from a DOS prompt from any directory? References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com> Message-ID: I am learning Python on the office computer which is networked, and am not allowed to change defaults (programmers aren't allowed to do system admin stuff, heck, we can't even move our PC's or monitors). I've got PYTHON installed in d:\python25. So at the DOS prompt, g:\ type in d:\ Then at the d:\ type in CD python25, which changes it to d:\python25. >From there, it's just python mystuff.py to run my programs. ________________________________ From: tutor-bounces at python.org on behalf of Alan Gauld Sent: Sun 12/31/2006 2:42 AM To: tutor at python.org Subject: Re: [Tutor] Starting python from a DOS prompt from any directory? "Daniel McQuay" wrote > from a DOS prompt. i am used to running python from a linux box > where you > can just type "python" or "python24" from a shell prompt and the > python > shell executes from any directory. > testing code. now i am using a windows xp media center edition > laptop with > python 2.5 installed and when i go to run and then type "cmd" and > then type > "python" from the directory where the run "cmd" command drops me it > says > 'python' is not a recognized as an internal or external command. You need to set up your PATH environment variable to include the python directory. You do this on XP(not so sure about Media Centre!) via the MyComputer->Properties->Advanced->Environment Variables route Once there you need to find the PATH variable and edit it to add the folder where Python lives (look at the properties of the shortcut to Python that you normally use to stat it). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Dec 31 23:25:16 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Dec 2006 22:25:16 -0000 Subject: [Tutor] Starting python from a DOS prompt from any directory? References: <6d87ecf40612302110j375f3ef1r615691934c451c17@mail.gmail.com> Message-ID: "Steve Oldner" wrote > change defaults (programmers aren't allowed to do system > admin stuff, heck, we can't even move our PC's or monitors). You can just type in the PATH statement every time you start DOS PATH= %PATH%;D:\Python25 And it will have the same effect. You can even create a Batch file and put it into somewhere your PATH can see D:\Python25\python %1 %2 %3 %4 %5 %6 %7 %8 %9 should work. But how did you install Python if you can't change the system? If you have access to install programs you have access to set environment variables, at least for yourself! Alan G.