[Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help
Hello, I am really new to python and really have not programmed much since college, I played with it a little now, and it seems to be a tool I feel comfortable implementing a personal project in. I wish to communicate via a serial port to a device that is using COBS. I wish to configure it and then receive data at an interval and store it in a rrd. The device itself receives telemetry information from other devices, and this telemetry info is going to get graphed and made available via a web page. The serial port will be com or tty, for which I prepped by playing with pygarmin and miniterm. The device is working and communicable? via a program written in .NET by a friend of the friend who gave it to me. The program has so many things I wish to change that it would be easiest to start from scratch. I have some of the source for bits and pieces that may be needed. The data coming in/going out will be COBS encoded, which changes/escapes all 0x00 bytes, then uses a 0x00 byte for the framing. COBS theory is explained here: http://www.stuartcheshire.org/papers/COBSforToN.pdf and it looks like a version written in c is at: http://gtk-gnutella.sourceforge.net/doxygen/cobs_8c.htm I would initially be happy creating a cobs.py and then modding the initial 1.1 release of miniterm and seeing if I could listen to the device... The device will be sending packets of 2-12 bytes at regular intervals (99% will be 7 byte packets every minute or so), and I can just move the serial cable over from the com port with the working application to the cobs-miniterm one to see if I am getting the right. Thanks in advance! -mike clearwater, fl __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More than one thing at a time?
[ cc'ing the Kamaelia list in case it makes sense to move this conversation there. ] On Sunday 02 October 2005 15:20, Joseph Quigley wrote: > Hi Michael, > You're explanation helped a lot, however, I'm really not good at gui > programming and the irc client was supposed to be a console application, > but: Would it be hard to just have a send texbox and receive read-only > text box? It shouldn't be difficult at all really. If you find an example of a hello world program, and a "hello who are you" program, then it's just a simple matter of using that. If you're happy using pygame as a display, then you could use our Ticker component already. Example 11 shows how to use the Ticker. (Essentially though it takes text strings on it's inbox and displays them. Which gives you a read-only text box) I should've thought of it sooner though, but you //could// do this: pipeline( ConsoleReader(), IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), Ticker(background_colour=(128,48,128), render_left = 1, render_top = 1, render_right = 600, render_bottom = 200, position = (100, 300), ) ).run() We don't actually have a console reader component, but it's simple to knock one up. The only complicating factor here is that reading from the console can be blocking which would lock up the whole system. As a result you'd want that to be a threaded component. (The API for those needs cleaning up admittedly) However the code and simple system test for that looks like this: # Tested on my machine just now and works :-):-) from Axon.ThreadedComponent import threadedcomponent from Kamaelia.Util.ConsoleEcho import consoleEchoer from Kamaelia.Util.PipelineComponent import pipeline class ConsoleReader(threadedcomponent): def run(self): # Threaded components use this method instead of "main" while 1: line = raw_input() line = line + "\n" self.outqueues["outbox"].put(line) pipeline(ConsoleReader(), consoleEchoer() ).run() ### Considering we do have a nascent IRClient component in /Sketches, the Ticker exists and the above ConsoleReader exists, this might speed things up for you. > I'll try this, but I think I should mention that I'm using python-irclib > from sourceforge. I'd suggest that our IRCClient code is nowhere near complete though, and whilst I've not tried python-irclib, I'd suggest looking at our IRCClient component to see how you might want to rewrite it to use python-irclib. > I'll try Kamaelia, thanks a lot. Please do. If you're willing to wait 24 hours we're doing the 0.3 release, which is a much expanded base to work with. If you can't wait, do a cvs checkout of the whole tree - ie: mkdir kamaelia cd kamaelia # So easy to forget to do this, leaving clutter everywhere :-):-) cvs -d:pserver:[EMAIL PROTECTED]:/cvsroot/kamaelia login cvs -z3 -d:pserver:[EMAIL PROTECTED]:/cvsroot/kamaelia co -d . That'll leave you with a full check out. You'll need to then install Axon: cd Code/Python/Axon python setup.py install Similarly to install Kamaelia: cd Code/Python/Kamaelia python setup.py install You'll then find an example program using the ticker in: Code/Python/Kamaelia/Examples/example11 You might also find Code/Python/Kamaelia/Examples/example9 of interest given your query on the pygame list regarding moving pictures about. :):) It's a **simple** game designed to amuse very young children bouncing sprites around the screen. It demonstrates very simple keyboard handling as well - specifically pausing, unpausing and toggling movement. As I say to everyone who looks at Kamaelia - if you find it useful, that's great - if you have any ideas for improvement, please let us know. If you have any criticisms (postive or negative - especially if negative) please let us know. Finally if you want to share any components back to the project we'd be happy to merge them first into sketches and then into the main tree if there's a logical fit. Even a trivial component (such as the one above) has a useful place in the tree - as you can see from this reply :-):-) Best Regards, Michael. -- "Though we are not now that which in days of old moved heaven and earth, that which we are, we are: one equal temper of heroic hearts made weak by time and fate but strong in will to strive, to seek, to find and not to yield" -- "Ulysses", Tennyson ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More than one thing at a time?
On Saturday 01 October 2005 12:36, Kent Johnson wrote: > Another way to do what you want is to use Twisted; this is touched on in > the second thread above. Another way is to use Kamaelia - its' specifically aimed at making it easy for newbies (and everyone else, me especially :-) do more than one thing at a time. If you understand unix pipelines you already understand the core ideas. (or indeed, how to wire a battery to a bulb :) Though until we've had a number newbies do the mini-axon tutorial and say what they wold like to see improved (in terms of clarity, ease of use), I'd hesitate suggestng it. (People who write things have already by definition gone up the learning curve and hence can't truly evaluate ease no matter how hard they try). However logically using Kamaelia (or any other system) you have 3 concurrent activities/3 things happening at a time here: * Handling sending & receiving of data * Accepting user input to send * Displaying output from the connection In Kamaelia we would /directly/ wrap this as 3 hypothetical components with a top level that might look like this: pipeline( TkTextInputWidget(mode="lineatatime"), IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), TkDisplayWidget(), ).run() Or using a more explicit/low level description of the same system: Graphline( IRC = IRCClient(host="server", port = 6667, nick = "userid", nickinfo = "myclient 1.0", defaultChannel = "#test" ), TOIRC = TkTextInputWidget(mode="lineatatime"), FROMIRC = TkDisplayWidget(), linkages = { ("IRC", "outbox") : ("FROMIRC", "inbox"), ("TOIRC", "outbox") : ("IRC", "inbox"), } ).run() (personally I prefer the latter implementation here since it's more clear the 3 things are relatively independent rather than dependent on the start of the chain. They are both equivalent though.) We've got a nascent IRCClient component in /Sketches of our codebase, and there's display & type in code in the PipeBuilder code in /Sketches that could serve as a starting point. Writing TkDIsplayWidget should be trivial - since it's equivalent if a "hello world" program (more or less) in Tk, and the TkTextInputWidget should also be trivial since it's a matter of writing a Tk based program that allows you to say "What is your name" and have a type in box to answer. In the mainloop, the display widget would check its inbox for data, grab it and display it. The input widget would send data to it's outbox when some types something in. We'd normally recommend writing standalone small scripts for each of these interacting with stdin (instead of an inbox) and stdout (instead of an outbox) - say via "print" when writing them and then turn them into components and then wire everything together. Also aside from a tutorial on how to build the system itself (it's not really that complex) at: * http://kamaelia.sourceforge.net/MiniAxon. We've also got a tutorilal on writing components here: * http://kamaelia.sourceforge.net/cgi-bin/blog/blog.cgi?rm=viewpost&postid=1113495151 If the OP does choose to take this approach, they'd need to use a CVS checkout rather than the main release though since we haven't done a release yet including the TK stuff (Though one is imminent). One key aim of Kamaelia is to make it simple & easy to make it possible to have more than one thing at a time to be dealt with - especially with regard to networking things, so I'd //hope// that using Kamaelia here might be the easiest place to start. Hoping this was useful, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Request for newbies :-)
[ This /may/ be very "off-netiquette" for the tutor list. If it is, I apologise in advance. ] Hi, One of the aims of the project I'm working on is that it aims to make writing programs which are inherently (and potentially) highly parallel/concurrent easy & safe to work with. We've tested our hypothesis so far with a pre-university trainee who had very little programming experience before joining our team (a little bit of visual basic, some Access). During his time with us he learnt python during his first week, and did learnt our system in his second week. In the remainder of his time with us he wrote a highly parallel program that simulated a digital TV decoder - using a shakespeare script as the data source, and doing things like scene detection, and displayed the script & characters using pygame (which was handled by other parts of the system.) That was a side project (20% style project if you like) whereas his main project he implemented during his short time with us was a system for going through an mpeg video, and sending snapshots every few seconds to a client running on a mobile phone (using python and our system). (An application of this could be browsing PVR content on a mobile). We've since also had a vacation trainee (who's just completed 2 years of his course) join us, and in his 6 weeks with us he learnt python, our system, and despite no prior networking knowledge implemented a system for joining multicast islands together and adding in reliability on top. (A possible application of this is "broadcast" of news over the internet) It's worth noting that the first trainee had very little experience of programming, networks, mobiles and so on, and that the second had no real knowledge of python, networks, concurrency, etc. The approach we took for teaching the system was to get people to implement a simple version of the core of the system itself. (After getting them to work through "How to think like a computer scientist" the week before). This implementation was guied by a simple tutorial that is formulated as a series of guided exercises (Standing, Walking, Talking, Conversing), with a couple of interludes discussing the implications of the results of the exercise. As a result this is where I come to a request. If there is anyone out there who is willing to do the following tutorial/exercises, could they please do so at their own pace and when they've done them please get in touch? * http://kamaelia.sourceforge.net/MiniAxon/ If you want a holding hand, I'm often on #kamaelia on irc on freenode. In order to do the tutorial you need to understand the following concepts: * classes, methods, functions, if/elif/else, while, try..except, for..in.., generators (yield), lists, dictionaries, tuples. If you're not clear on generators, this might be a good way of understanding what you can do with them :-) Thanks in advance to anyone willing to give this a go, and to others for their patience regarding this message! Best Regards, Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group [EMAIL PROTECTED], http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] call a def/class by reference
On Thursday 29 September 2005 22:26, Alan G wrote: > string -> function mapping directly. > > Its not usually a very useful thing to do This is precisely how shared libraries under linux and IIRC DLLs in windows work. cf dlopen, dysym in C. > how would the typical user know what the function names were? Under linux one can examine the names of functions in a library using "nm". eg: # nm libpython2.4.so|head -20 U abort@@GLIBC_2.0 000dfea0 d abs_doc 0001fcf0 t abstract_get_bases 0001fe20 t abstract_issubclass U access@@GLIBC_2.0 000e9ba0 d acquire_doc 0008f970 t addcleanup 0001be40 t addclosure 000d2040 d add_doc 0009d7c0 t add_flag 0001b8f0 t addnfaarc 0001b870 t addnfastate 00059680 t add_subclass 00049de0 t adjust_tp_compare 000ea680 d alarm_doc U alarm@@GLIBC_2.0 000e9760 d allocate_doc 000e6280 d api_version_warning 0003a6f0 t app1 000cfc40 d append_doc Obviously, ctypes does much the same thing. Compare and contrast: try: from ctypes import * libc = cdll.LoadLibrary("/lib/libc.so.6") sched_yield = libc.sched_yield except ImportError: def sched_yield(): pass except AttributeError: def sched_yield(): pass with ... try: import functions as libc sched_yield = getattr(libc, "sched_yield") # this is of course effectively equivalent to: # sched_yield = libc.sched_yield except ImportError: def sched_yield(): pass except AttributeError: def sched_yield(): pass It's pretty much the same thing. I could see that this may have uses in systems that allow plugins. Devils-advocate-ly , ;-) Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] stopping threads?
On Thursday 29 September 2005 07:27, Pierre Barbier de Reuille wrote: > IMO, it is better to explicitely call the base class ... I think it is > more readable. But I don't know if there is any drawback for any > solution... A drawback of NOT using super is that you're potetially setting yourself you for a fall. Consider the following code (Option 1) from hypothetical import SomeBaseClass class myClass(SomeBaseClass): def __init__(self, ...): super(myClass, self).__init__(...) (Option 2) from hypothetical import SomeBaseClass class myClass(SomeBaseClass): def __init__(self, ...): SomeBaseClass.__init__(self) In the case of option 1, this will work, and have reliable, predictable behaviour even if the implementation of SomeBaseClass in the "hypothetical" library changes from something like: class SomeBaseClass(ActualBase): ... To something like: class SomeBaseClass(ActualBase,mixin1, mixin2): ... In Option 2, you run the risk of methods higher up the tree being run more than once. Obviously in your *own* code you can avoid this if you like, but as soon as you start using and inheriting from classes in other people's libraries you can't guarantee that you're not running that risk. I posted an example about this via gmane's email to news gateway last week, but it doesn't appear to have hit the archive (or the list :) for some reason, so I've included the reply I gave illustrating what can go wrong if you don't use super at the end. Regards, Michael. --- Original post regarding super: Subject: Re: Using superclass __init__ method paul brian wrote: > class Base: >def __init__(self): >print "hello" > > class Child(Base): >def __init__(self): >Base.__init__(self) > >def foo(self): > print "foo" I note this is using "old" style classes. However it's normal to recommend that people use "new" style classes these days. (I only started using python after they invented new style classes, hence the quotes around new/old) A more canonical example here is this: class Base(object): def __init__(self): print "hello" class Child(Base): def __init__(self): super(Child,self).__init__() def foo(self): print "foo" Whilst this might an esoteric change, it's really to handle the fact that python has multiple inheritance. Consider: >>> class ChildOne(Base): ... def __init__(self): ... Base.__init__(self) ... print "Hello from ChildOne" ... >>> class ChildTwo(Base): ... def __init__(self): ... Base.__init__(self) ... print "Hello from ChildTwo" ... >>> class GrandChild(ChildOne,ChildTwo): ... def __init__(self): ... ChildOne.__init__(self) ... ChildTwo.__init__(self) ... print "Hello from GrandChild" ... >>> GrandChild() Hello from Base Hello from ChildOne Hello from Base Hello from ChildTwo Hello from GrandChild <__main__.GrandChild instance at 0x40397f8c> What you can see here is that the __init__ in Base was executed twice. This may or may not be a problem with some things, but where people use classes to "mixin" functionality it can be a real problem. Consider the alternative using "super" instead: >>> class Base(object): ... def __init__(self): ... print "Hello from Base" ... >>> class ChildOne(Base): ... def __init__(self): ... super(ChildOne,self).__init__() ... print "Hello from ChildOne" ... >>> class ChildTwo(Base): ... def __init__(self): ... super(ChildTwo,self).__init__() ... print "Hello from ChildTwo" ... >>> class GrandChild(ChildOne,ChildTwo): ... def __init__(self): ... super(GrandChild,self).__init__() ... print "Hello from GrandChild" ... >>> GrandChild() Hello from Base Hello from ChildTwo Hello from ChildOne Hello from GrandChild <__main__.GrandChild object at 0x4039ccac> Regards, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Embedding
On Tuesday 27 September 2005 23:16, Kent Johnson wrote: > Joseph Quigley wrote:... > > Well we are three programmers. I know python, another knows Java and the > > other C++. We are trying to figure out how to combine all three > > langauges to make a game. > > Sounds like a bit of a hash to me. Show them pygame and convince them to > learn Python :-) If you tell them to drop the type declarations, braces {}, semicolons, and make their code a touch simpler, then they already (more or less) know python (At least that's the way I normally introduce people who know C/C++/Java to python). Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Linking with C programs
On Tuesday 27 September 2005 14:49, Matt Williams wrote: > Could someone explain how, in very general terms, one would use python > to wrap some C libraries/ API. > > I ask because there are a few bits of C software that look quite > interesting, and I know that Python can be used to wrap the C - but how > does it work? Use Pyrex. If you don't care about produce bindings for languages other than python and you just want access to C based libraries, then pyrex is by far the most pleasant way I've found of wrapping C. Essentially pyrex is a bridge language - half C and half python. It compiles down to pure C, but handles all the awkward parts of bridging the two for you. (like handling ref counts and similar.) We've used this to wrap a few libraries so far and it's been a pleasant experience everytime. It has a couple of tutorials, that work, and even shows you how to use distutils (aka setup.py) to make it easy for others to build your bindings too. * http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ * http://ldots.org/pyrex-guide/ - Michael Smith's guide to Pyrex - it's IMO brilliant and the examples work, and if you're used to C and used to python just feels _natural_ . If you're after a couple of examples to work forward, you can download them from: * http://sourceforge.net/projects/kamaelia Specifically the vorbissimple and python-dirac downloads will hopefully get you started. (The vorbissimple example includes a small simple library written in C and show hand off of data from python to C and from C to python, as well as how to have a "context" variable in C that python doesn't need to understand the internal structure of. (Much like with a FILE structure you don't need to understand the FILE structure's internals, just how you pass it about) Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Diamond Equivalent
On Thursday 22 September 2005 23:46, [EMAIL PROTECTED] wrote: > I am coming to Python from Perl. Does Python have anything like the diamond > operator found in Perl? The correct answer is not really no, but you can manually perform the same tasks. For those who don't know perl, <> is an incredibly useful little operator that does some really wierd and wonderful things :-) (That said, I don't think I'd like a magic operator like this in python :-) If you want to do this: @a = <>; The equivalent is probably best expressed thus: def diamond_array(): # Note, untested... import sys if len(sys.argv ==1): return sys.stdin.readlines() else: result = [] for file in sys.argv[1:]: try: file = open(file) result.extend(file.readlines()) except IOError: pass return result a = diamond_array() If however you want to do the equivalent of: while ($line = <>) { ... } That mode of <> probably best equates to this: for line in diamond_lines(): def diamond_lines(): # Note, untested... import sys if len(sys.argv ==1): for line in sys.stdin.xreadlines(): yield line else: for file in sys.argv[1:]: try: file = open(file) for line in file.xreadlines(): yield line except IOError: pass As for this idiom: while(1) { $line = <>; ... } That probably matches best to this: diamond_iterator = diamond_lines() # same function as above while 1: line = diamond_iterator.next() Whereas this kind of trick: $firstline = <>; @remaining_lines = <>; Would map to this: (using the functions above) diamond_iterator = diamond_lines() firstline = diamond_iterator.next() remaining_lines = list(diamond_iterator.next()) Or to show a relatively common perl idiom: $firstline, @remaining_lines= <>,<>; Maps to: diamond_iterator = diamond_lines() firstline,remaining_lines = diamond_iterator.next(), list(diamond_iterator.next()) Best Regards, Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] where to insert?
On 9/22/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I would like to insert string.join(msgList,"") into the following program > where do I insert it? do you want to build a temporary list and join its elements afterwards? This can look like: # Loop through each substring and build ASCII message msgList = [] for numStr in string.split(inString): asciiNum = int(numStr) # convert digits to a number msgList.append(chr(asciiNum)) # after completing the msgList, join it message = "".join(msgList) Few notes: I have changed eval(numStr) into int(numStr) because int() does everything you need here. eval() can do more but than just converting digits into integers but this came at the cost of possible unpredictable results. For example eval('1.23') is perfectly valid but allowing floating point numbers wasn't your intention. int('1.23') will fail with an exception wich is a good thing, because you can catch the error and report the user back how to make better usage of your programm. Other examples for unpredictable results with eval invole eval('os.system("evilcommand")') or eval('range(2147483647)'). The latter would build a very large temporay list with numbers from 0 through 2147483646 which is likly to consume all of your machines memory! Second I'm using the "".join(msgList) (join as a string method) instead of string.join(msgList, "") (join as a function of the string modul), because it's slightly more readable and you mustn't remember how string.join want to get its arguments. Last not least: joining a list of strings instead of adding those strings directly is a pattern used to avoid the problem that each 'alteration' of a string (as in 'message = message + chr(asciiNum)) is in fact no alteration of the string but creates a new string every time (because strings are immutable, i.e. can't be altered in place). OTOH this problem doesn't seem to be such a big one ... In fact for small strings and a small numer of them, the joining-a-list approach can take more time. This is why I prefer to add strings directly and only switch to an temporary list when I have really many strings or when I gain some other advantages, when I e.g. want to join the strings with a newline. regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Focus in tkinter
On Wed, 14 Sep 2005 19:58:07 +0100 (BST) David Holland <[EMAIL PROTECTED]> wrote: > I want to make the mouse focus in a GUI move to the > correct button/text entry widget. Does anyone know > how to do this ? > Hi David, to set the focus to a particular widget you need the focus_Set() method: b = Button(parent) b.focus_set() Maybe you want to have a look at Frederik Lundh's excellent Tkinter books: <http://www.effbot.org/tkinterbook> or the more complete, but a little outdated version: <http://www.pythonware.com/library/tkinter/introduction/index.htm> I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where did those spaces come from?
On 9/12/05, Tom Tucker <[EMAIL PROTECTED]> wrote: Tutor, Good evening! The goal is to parse a simple file and grab column one. Then print each value horizontally separated by a comma. Why is Python adding a space padding between each value? Please see below. Thanks ahead of time. INPUT_FILE # unwanted lines removed [EMAIL PROTECTED] blah blah [EMAIL PROTECTED] blah blah [EMAIL PROTECTED] blah blah [EMAIL PROTECTED] blah blah OUTPUT DESIRED ## ,,, SCRIPT # import re input_file = open('/tmp/file','r') number_match = re.compile('^\d+\s+\w+\@') for line in input_file.readlines(): if number_match.match(line): line = re.split('\s+', line) print line[0], print ",", OUTPUT GENERATED , , , , To add to Danny's posting, I recently had to stream out an unknown list of values from a database, something like what you are doing. I created a class that formats the lines like you want and writes them out when the line gets close the the maximum length. class Line: length = 72 seperator = ', ' def __init__(self): self.reset() def reset(self): self.contents = '' def __str__(self): return str(self.contents) def __len__(self): return len(self.contents) def __add__(self, other): o = str(other) l = len(o) s = len(self.seperator) if len(self) + l + s > self.length: self.flush() if self.contents: self.contents += self.seperator self.contents += str(other) return self def flush(self): if self.contents: self._print(self.contents) self.reset() def _print(self, line): print line For your purposes, you would want to change the separator to just ','. Then you would just create an instance and add strings to it. formatted_line = Line() for line in input_file.readlines(): if number_match.match(line): line = re.split(r'\s+', line) formatted_line += line[0] else: formatted_line.flush() # clear anything left to print HTH, -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] upgrading from 2.3 to 2.4.1 on Mandrake Linux 10.1
On Mon, 12 Sep 2005 07:35:52 -0500 "Andy Dani" <[EMAIL PROTECTED]> wrote: > Hi, > > Which is the best location to install Python in Linux? Should it be under one > directory or different (like lib, doc, bin etc.)? > > I followed installation instructions in "inst.pdf" from python documents. I > can see that Python 2.4.1 has been installed in /user/lib/local by standard > installation procedure. When I launch my IDLE or "Python" at shell, Python > 2.3 comes up! Why? Do I need to upgrade any other config files? > > Also, I am looking for help in upgrading xwPython package, OpenGL package, > and installation of BOA constructor. They go in which directories? > Hi Nirav, I recommend not to *upgrade* the existing python installation but simply install a second version. The reason is that some system specific programs may depend on python-2.3 or one of the extensions that are already installed. If you are running Mandrake the best bet is to download mandrake's source rpm from <http://fr2.rpmfind.net//linux/RPM/cooker/cooker/SRPMS/main/python-2.4.1-3mdk.src.html> and build the binary RPM from it. After installing the RPM you should make sure that the link "/usr/bin/python" points to "/usr/bin/python2.3" . If you want to run the new python, just type "python2.4" (or in your scripts use the shebang line "#!/usr/bin/env python2.4" ) (this should work if you already installed python-2.4 into /usr/local , too). WxPython and OpenGL should probably be installed into the python2.x/site-packages directory, BOA is (as far as I know) pure python and can be installed anywhere; if you want to run BOA with python-2.4 you will probably have to edit the shebandg line in BOA's main program file (or type python2.4 boa (or however the main program is called). Maybe you can find mandrake source RPM's for these, too, which might make it easier for you to install everything in the correct place. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Killing a thread from main - was RE: "Lock"ing threads
On 8/29/05, Hans Dushanthakumar <[EMAIL PROTECTED]> wrote: Thanks KentHow do I send a signal from the main thread to stop execution of a childthread?I tried the foll:, but got an error:Other than by this method, is there any other mechanism to stop athread? import threadingimport timeclass shownum(threading.Thread):def __init__(self, start_num):threading.Thread.__init__(self)self.num = start_numself.stop = 0 def run(self):for i in range(12):time.sleep(1)print "shownum: ", self.numself.num = self.num + 1if self.stop == 1:break def stop(self):self.stop = 1def chng(self):self.num = 1incr_num_thread = shownum1(201)incr_num_thread.start()time.sleep(3)incr_num_thread.chng()time.sleep (3)incr_num_thread.stop()Output:shownum: 201shownum: 202shownum: 1shownum: 2shownum: 3Traceback (most recent call last): File "H:\Docs\PyScripts\test_threads.py", line 31, in ? incr_num_thread.stop()TypeError: 'int' object is not callableshownum: 4shownum: 5shownum: 6 You would probably want to use a shared threading.Condition object. A number of threads manuals mention using this in a boss shutdown model. -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
On 8/26/05, Alberto Troiano <[EMAIL PROTECTED]> wrote: Hi everyoneI need to generate a password..It has to be an 8 digit number and it has tobe randomThe code I've been trying is the following:import randomrandom.randrange(,) The code works but sometimes it picks a number with 7 digits. Is there anyway that I can tell him to select always a random number with 8 digits?Thanks in advancedAlberto Along with everyone else's solutions, I'll throw out: str(random.randrange()).zfill(8) -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to make a script do two things at once.
On Sun, 21 Aug 2005 16:23:20 -0500 nephish <[EMAIL PROTECTED]> wrote: > Hey there, > i have a simple question about getting a script to do > two things at once. > like this. > > > for i in range(100): > print i > time.sleep(.2) > if i == 15: > os.system('python /home/me/ipupdate.py') > > print 'done' > > when i run this, it stops at 15 and runs the script called out in the > os.system line. i know it is supposed to do that. But, how could i get a > script to do this without stopping the count (or delaying it unill the > script called exits) I don' t have to run it this way, i can import it > if necessary as a module. or whatever will work so i can execute two > things at once. > If you just need to call a unix system command you can simply add "&" to the command string to make it run in the background. Regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] LiveWires problems
Compiling it in Root worked, thanks. On 8/16/05, Luis N <[EMAIL PROTECTED]> wrote: > On 8/15/05, ZIYAD A. M. AL-BATLY <[EMAIL PROTECTED]> wrote: > > On Mon, 2005-08-15 at 11:52 -0400, Michael Murphy wrote: > > > Hi all > > > > > > I'm having problems with installing LiveWire for python for Linux > > > (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py. > > > Heres the results: > > > > > > running install > > > running build > > > running build_py > > > running install_lib > > > creating /usr/lib/python2.3/site-packages/livewires > > > error: could not create '/usr/lib/python2.3/site-packages/livewires': > > > Permission denied > > > > > > I'm new at this but I'm sure this is an easy fix but I can't figure it > > > out, any help is appreciated. > > Consider typing: > > python setup.py install home=$HOME > > instead of, > > python setup.py install > > You will then install into ~/lib/python2.3/livewires if this location > is acceptable to livewires. > > Luis. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Mike Erie Freeze will rise again! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] convert a file from plaintext(Ascii) to unicode? very quickquestions
On Mon, 15 Aug 2005 22:51:20 -0400 Kent Johnson <[EMAIL PROTECTED]> wrote: > I think Luke's suggestion will work if you use f.read() (to read the whole > file as a single string) instead of f.readlines() and f.write() instead of > writelines(). > > Kent > And if you want to convert ascii into unicode you need to call * decode() * ( which does pretty much the same as unicode() ) on the string, not encode() . Michael > luke wrote: > > List: > > I'm forwarding this private message(hope you don't mind Denise) > > I personally have no idea what to do, but > > someone else might be able to help. > > -Luke > > > > > > - Forwarded Message - > > > > text is a list, so you can't encode it. but you can iterate over each > > of the elements and encode them. I have tried several variations of > > that, but keep ending up with all my newlines being little boxes. any > > ideas? > > > > Thanks, > > Denise > > > > On 8/15/05, luke <[EMAIL PROTECTED]> wrote: > >>I dont know much about Unicode but it seems like > >>f = file(filename, "r") > >>text = f.readlines() > >>text = text.encode() > >>#or maybe just text.encode()? > >>f.close() > >> > >>should encode the filetext to unicode. > >>then you could do a > >>f = file(filename, "w") > >>f.writelines(text) > >>f.close() > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] LiveWires problems
Hi all I'm having problems with installing LiveWire for python for Linux (Linspire 5.0 to be exact) and I'm having trouble compiling setup.py. Heres the results: running install running build running build_py running install_lib creating /usr/lib/python2.3/site-packages/livewires error: could not create '/usr/lib/python2.3/site-packages/livewires': Permission denied I'm new at this but I'm sure this is an easy fix but I can't figure it out, any help is appreciated. -- Mike Erie Freeze will rise again! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Customized endswith/startswith version
On 8/10/05, Negroup - <[EMAIL PROTECTED]> wrote: > >>> f = open('codes.txt') > >>> # valid codes starts with 'abc' or '123' or 'ff5' > >>> [valid for valid in f.readlines() if valid.startswith('abc') or > valid.startswith('123') or valid.startswith('ff5')] > > This is just an example, in my application I don't need to check > strings against a huge number of cases. If however it would happen, > how to modify startswith in order to make it accept a list instead of > a simple string? > > [valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])] the easy way is not to use the string method startwith but write your own function. So it looks like: [valid for valid in f.readlines() if startswith(valid, ['abc', '123', 'ff5'])] (I suppose you have your fun, writing a startswith-function for yourself?) The hard way is to subclass from str and ovewrite the default startswith function (or add your own function). Whilst subclassing isn't hard, here it can be, because strings are immutable types, which means that a new string is created ervery time we "mutate" one. Which in turn means that you have to know how to subclass from immutable types (using __new__ instead of __init__ and things like that I can't remember and allways have a hard time to figure it out again). And then you might want to subclass your file-object so that it spit out strings of your own class? regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] surprising len() results ???
On 8/9/05, Tom Cloyd <[EMAIL PROTECTED]> wrote: > print len('()ÄäÀÁàáÇçÈÉèéÌÍìíÑñÒÓòóÙÚúù') > print len('--AaAAaaCcEEeeIIiiNnOOooUUuu') > > the result: > > 54 > 28 > > I'm completely mystified by this. All of it. None of it makes sense. This > program was working fine. Now it doesn't. And those two parameter string > are plainly the same length, but Python doesn't think so. on my computer (python 2.3): >>> s = 'ä' # a-umlaut >>> len(s) 1 >>> len(s.decode('latin-1')) # prepare for utf-8 encoding 1 >>> len(s.decode('latin-1').encode('utf-8')) 2 >>> len('a'.decode('latin-1').encode('utf-8')) 1 seems like len returns the number of bytes and some encodings uses more than one byte for certain chars. You can proberbly decode your strings from utf-8 (or whatever encoding you use (and perhaps encode it back into a one-char-one-byte encoding [on my system the decoded (unicode) string is just fine]). regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] redirecting output to logfile and logrotate
On 7/23/05, Winfried Tilanus <[EMAIL PROTECTED]> wrote: > Somebody else suggested (in private) to make logrotate send a -HUP this was me. Sorry for that, I'm still unfamilar with gmail. Danny's suggestion using RotatingFileHandler is better than mine, cause it uses a standard module. I suggest to consider using SysLogHandler for fairly sized server apps which get distributed. This way the user has full control over the logfiles (where to store, when to rotate, how to compress and when to delete) by normal configuring via syslogd and logrotate (Well this means it's normal to configure syslogd and logrotate for a sysadmin user...). regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter event for changing OptionMenu items
On Thu, 21 Jul 2005 14:16:05 -0400 Bernard Lebel <[EMAIL PROTECTED]> wrote: > Hi Michael, > > Let say I have a MenuOption, that consists of 3 items. This MenuOption > sits on top of the Tkinter window. > > In the lower part, I have a bunch of widgets (text fields). When the > choose a different item from the MenuOption, it would call a function > that clears the lower part and repopulates it with new fields. My > problem is binding this callback to the event of choosing an item. > > In this case I would try the StringVar()'s trace method, which you can use to track changes of its value; a simple example: >>> from Tkinter import * >>> root = Tk() >>> s = StringVar() >>> s.set('a') >>> om = OptionMenu(root, s, 'a', 'b', 'c', 'd') >>> om.pack() >>> def changed(*args): ... print s.get() ... >>> s.trace('w', changed) In the example changed() is called each time you select an item in the menu and with s.get() you can query the current selection and update the window according to the current value. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter event for changing OptionMenu items
On Thu, 21 Jul 2005 12:19:00 -0400 Bernard Lebel <[EMAIL PROTECTED]> wrote: > Hello, > > I'm trying to bind an event to the changes made to an OptionMenu. Ie > the user chooses a different item, the rest of the Tk window gets > updated. To repopulate the window, a function would be called by the > binding. > > Any suggestion? > > > var1 = StringVar() > var1.set( aTables[0] ) > oOptionMenu = OptionMenu( oRoot, var1, aTables[0], *aTables[1:] ) > sTableName = var1.get() > oOptionMenu.bind( '', getTableColumns ) > oOptionMenu.pack( fill = X ) > > Here the '' event is obviously not the one I'm looking for, > but is there to illustrate what code I have so far. > > Hi Bernard, if I understand you correctly, the "" event of the OptionMenu's Menu may be the best bet for you (not very much tested though): oOptionMenu['menu'].bind('', getTableColumns) Otherwise you would probably have to call oOptionMenu['menu'].entryconfigure(command=...) on all menu entries. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Scrolling multilistbox help
On Mon, 18 Jul 2005 13:54:45 + "Alberto Troiano" <[EMAIL PROTECTED]> wrote: > Hey tutors > > I'm using the Multilistbox class and I noticed that it only handles the > mouse scroll and the scrollbar to go down or up.I succesfully implemented > the sort function that came with the class > I also added code to handle the up and down arrow keys and it goes down all > right but only select the item and it doesn't scroll down or up > > How can make it go up or down? > I'm sendind the class here: > Hi Alberto, I haven't tested your code, but if I understand you correctly, the problem is that the list is not automatically scrolled when you select a new item with the Up and Down keys (right?). Maybe it's the easiest to add a line like this to your _select1() and _select2() methods: l.see(int(l.curselection()[0])) where l is the first of the listboxes; this should make sure the selected item is visible (at least if you use selectmode=SINGLE). If keeping all lists in sync works, this should be enough to scroll all other lists, too (like I said, untested though). I hope this helps Michael > class MultiListbox(Frame): > fila=0 > sortedBy=-1 > def __init__(self, master, lists): > Frame.__init__(self, master) > self.lists = [] > for l,w,a in lists: > frame = Frame(self,background="red"); frame.pack(side=LEFT, > expand=YES, > fill=BOTH) > Button(frame,background="red",foreground="white",font="Verdana 8 > bold",text=l, borderwidth=1, relief=RAISED,command=lambda a=a: > self._sortBy(a)).pack(fill=X) > lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0, >relief=FLAT, exportselection=FALSE) > lb.pack(expand=YES, fill=BOTH) > self.lists.append(lb) > lb.bind('', lambda e, s=self: s._select(e.y)) > lb.bind('', lambda e, s=self: s._devolverfila(e.y)) > lb.bind('', lambda e, s=self: s._devolverfila(e.y)) > lb.bind('', lambda e, s=self: s._select(e.y)) > lb.bind('', lambda s: _select1()) > lb.bind('', lambda s: _select2()) > lb.bind('', lambda e: 'break') > lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y)) > lb.bind('', lambda e, s=self: s._button2(e.x, e.y)) > frame = Frame(self,background="red"); frame.pack(side=LEFT, fill=Y) > Label(frame,background="red",foreground="white",font="Verdana 8 bold", > borderwidth=1, relief=RAISED).pack(fill=X) > sb = Scrollbar(frame,background="red", orient=VERTICAL, > command=self._scroll) > sb.pack(expand=YES, fill=Y) > self.lists[0]['yscrollcommand']=sb.set > > def _sortBy(self, column): > """ Sort by a given column. """ > if column == self.sortedBy: > direction = -1 * self.direction > else: > direction = 1 > elements = self.get(0, END) > self.delete(0, END) > elements.sort(lambda x, y: self._sortAssist(column, direction, x, > y)) > self.insert(END, *elements) > self.sortedBy = column > self.direction = direction > > def _sortAssist(self, column, direction, x, y): > if column!=0: > c = cmp(x[column], y[column]) > if c: > return direction * c > else: > return direction * cmp(x, y) > else: > c = cmp(int(x[column]), int(y[column])) > if c: > return direction * c > else: > return direction * cmp(x, y) > > def _select(self, y): > row = self.lists[0].nearest(y) > self.selection_clear(0, END) > self.selection_set(row) > self.fila=row > return 'break' > > def _devolverfila(self, y): > row = self.lists[0].nearest(y) > self.selection_clear(0, END) > self.selection_set(row) > self.fila=row > > def _select1(self): > if self.fila==self.size()-1: > pass > else: > self.selection_clear(0, END) > self.selection_set(self.fila+1) > self.fila+=1 > self._scroll() > return 'break' > > def _select2(self): > if self.fila==0: > pass > else: > self.selection_clear(0, END) > self.selection_set(
Re: [Tutor] This should be easy
I'm not sure why your first example worked: "Table" is a reserved word in SQL (i.e. it's used as a SQL command), so you shouldn't use it as a table name. Imagine a poor dumb computer trying to parse "create table table"... Cheers, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ListBox in Tkinter
On Mon, 18 Jul 2005 17:54:34 +0200 geon <[EMAIL PROTECTED]> wrote: > Alan G napsal(a): > > >> I would like to ask if it is possible to create such a listbox > >> (attached) in TKinter itself or must have pmw ot tix...or ... > > > > > > PMW is written in Tkinter so yes, you could do it yourself but it is > > not a native widget. Using PMW would be much easier! > > > I have just found this: http://effbot.org/tkinterbook/optionmenu.htm - > that is nearly what I needed , just another design. > I think there are even other new widgets in new Tk/Tcl compared to the > http://www.pythonware.com/library/tkinter/introduction/, but > undocumented yet. Or poorly or only in original Tk documentation. > There are three new widgets in Tk 8.4: the Spinbox (an entry field with "up" and "down" arrow buttons), the PanedWindow , which lets you dynamically add resizable frames and the LabelFrame, a Frame with a decorative border and a Label in one of its corners. Regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tk -- which label clicked
On Fri, 15 Jul 2005 23:29:22 +1200 (NZST) [EMAIL PROTECTED] wrote: > Quoting Michael Lange <[EMAIL PROTECTED]>: > > > I don't think it will work this way, because you don't catch the event > > bind() passes to the callback > > (you also use a variable "e" in makeCallback() that isn't defined > > anywhere). > > That's what the variable 'e' is doing! > > Here is some code I just wrote and tested: > > >>> def clicked(w): > ... print 'Widget %s clicked! Text: %s' % (str(w), w.cget('text')) > ... > >>> def makeCallback(w): > ... def callback(e): > ... clicked(w) > ... return callback > ... Aah, you're right, I guess I got confused a little. Still I think it's overly complicated in this context, when you can you get the same result with: def makeCallback(event): print "Widget %s clicked! Text %s" % (str(event.widget), event.widget['text']) Regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HTML links from Tkinter
On Fri, 15 Jul 2005 10:55:37 +1200 (NZST) [EMAIL PROTECTED] wrote: > There's no table widget in standard Tkinter. Search in the Python Cookbook > (on > ActiveState) for a MultiListbox; it might do what you need. > > -- On the Tkinter wiki there are some links to Tkinter table widgets (I have not tried any of these though): <http://tkinter.unpythonic.net/wiki/Widgets> Regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tk -- which label clicked
On Fri, 15 Jul 2005 10:20:48 +1200 (NZST) [EMAIL PROTECTED] wrote: > def clicked(w): > print 'Widget %s clicked! Text:' % (str(w), w.cget('text')) > > def makeCallback(w): > def callback(e): > clicked(w) > return callback > > # create labels > for text in ['foo', 'bar', 'baz']: > lb = Label(master, text=text) > lb.bind('', makeCallback(lb)) > I don't think it will work this way, because you don't catch the event bind() passes to the callback (you also use a variable "e" in makeCallback() that isn't defined anywhere). You probably better use a lambda in this case: def callback(text): print text for text in ('foo', 'bar', 'baz'): lb = Label(master, text=text) lb.pack() lb.bind('<1>', lambda event, t=text: callback(t)) or use event.widget to determine which label was clicked: def callback(event): print event.widget['text'] for text in ('foo', 'bar', 'baz'): lb = Label(master, text=text) lb.pack() lb.bind('<1>', callback) I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter Q's
> >def changeQuote(): > >currQuote = showquote.cget('config') # Get the current quote > >newQuote = random.choice(quotes.quote) > >while newQuote == currQuote: # Make sure the new quote > > differs > >newQuote = random.choice(quotes.quote) > >showquote.config(text=newQuote) > >Button(self, text='Show another quote', command=changeQuote).pack() > > Aaag. I'm confused... I just tried you changeQuote example with out the above > stuff... didn't work. My error message: > AttributeError: 'NoneType' object has no attribute 'config' > Just a guess: a common mistake among Tkinter beginners is: mylabel = Label(parent, text="Hello").pack() The problem here is, because pack() returns None you don't have a reference to the Label, but set the "mylabel" variable to None. If this is what happened, you need to split the above into two lines: mylabel = Label(parent, text="hello") mylabel.pack() > so I edited it a little, still didn't work (same error). I tried the class > Main(Frame) and didn't get it to work either. Do you think you could make it > a little bit simpler? If you can't that's ok, I'll try to study it more. > The changeQuote() method in the example contains a typo: currQuote = showquote.cget('config') # Get the current quote ^^ this must be: currQuote = showquote.cget('text') I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter Q's
On Mon, 11 Jul 2005 17:22:57 + Joseph Quigley <[EMAIL PROTECTED]> wrote: Hi, Joseph, > Hi first off, here's my code: > > # -*- coding: utf-8 -*- > from Tkinter import * > import random > import time > import about > import quotes > > > def closeprog(): > raise SystemExit > > class main: > root = Tk() > frame = Frame() > root.title("Quoter %s" % (about.ver)) > root.minsize(300, 50) > > showquote = Label(root, text=random.choice(quotes.quote)) > showquote.pack() > > exit = Button(root, text="Exit", command=closeprog) > exit.pack(side=LEFT) > > aboutprg = Button(root, text="About", command=about.main) > aboutprg.pack(side=LEFT) > > > totalq = Label(root, text=quotes.qts) > totalq.pack(side=BOTTOM) > > root.mainloop() > > (I'd appreciate some suggestions, or notifications on how bad something is) > I think you should change the way you define the main class, so you keep references to the class attributes; it looks like your main class fires up a Tk() window, so it's probably best to subclass Tk() : class Main(Tk):# this doesn't really matter, but upper case letters are generally preferrred for class names def __init__(self, *args, **kw): Tk.__init__(self, *args, **kw) # at this point the Main() class practically is a Tk(), so it can be handled just like a regular # Tk() window from the outside; the "*args, **kw" construct allows to pass an arbitrary amount of # arguments and keyword arguments to the parent class. "self" is a placeholder for the class instance # that will be actually used in the code. # To get a benefit over a normal Tk() window you can now start adding attributes: self.showquote = Label(self, text=random.choice(quotes.quote)) self.showquote.pack() < etc. > # of course you can use the parent classes methods on "self", too: self.title("Quoter %s" % (about.ver)) self.minsize(300, 50) # now you can add a button which uses a "class-specific" command: self.switchbutton = Button, text="Switch quote", command=self.switch_quote) self.switchbutton.pack() # finally the class method has to be defined: def switch_quote(self): newquote = get_the_new_quote()# it's up to you how to do this of course self.showquote.configure(text=newquote) Now the Main() class can be used like a regular Tk() : root = Main() root.mainloop() And for something completely different: be careful mixing pack(side = LEFT / RIGHT) with pack(side = BOTTOM / TOP), you might not get the results you expected. For complex layouts you are probably better off using grid() ( or you will find that you have to use extra Frames to pack() your widgets in. I hope this helps Michael > I have a small problem: I don't know how to make a button that would > redisplay another quote in the same window, ie I need a button that > says: Show Another Quote. (Actually I don't know how to make it show > another quote even in a new window!!). I got the interface from Catfood > Fortune Cookie. > > Here's a tid-bit of the quotes module: > # Brian Kernighan > bk1 = """Controlling complexity is the essence of computer programming. > > -- Brian Kernighan""" > > yadayada = """Foo/bar""" > > quote = [bk1, yadayada] > > Thanks, > Joe > > -- > Unix Love, Linux Pride > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Adding attributes to imported class
On Thu, 07 Jul 2005 11:03:00 +1200 (NZST) [EMAIL PROTECTED] wrote: > Quoting Michael Lange <[EMAIL PROTECTED]>: > > > I'm trying to write a python wrapper for the tkDnD Tk extension to add > > drag and drop support > > Hi Michael, > > Just a side issue --- tkDnD seems to be broken in python 2.4: see bug 1164742, > http://sourceforge.net/tracker/index.php?func=detail&aid=1164742&group_id=5470&atid=105470 > > -- Hi John, thanks for the pointer , but of course I did not mean the python module but the Tk extension library ( http://sourceforge.net/projects/tkdnd ), which adds "real" dnd support to Tk. As far as I have tested (not very much however) it seems to work now, but I'm still not sure if the on-the-fly adding of attributes to classes of an imported module is proper programming style or "do-it-yourself lobotomy" . It is the first time for me to try wrapping a Tk extension for python, so I am not sure of the way to go. Anyway, it's a cool new feature for Tkinter, so I thought I should share it with the community; anyone who is interested can find it at http://www.8ung.at/klappnase/TkinterDnD/TkinterDnD.html . Any feedback is much appreciated. Best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Adding attributes to imported class
Hello list, I'm trying to write a python wrapper for the tkDnD Tk extension to add drag and drop support to Tkinter. Looking for a way to give all widgets access to the newly defined dnd methods I came to create a subclass of Tkinter.Tk() and pass the dnd methods to Tkinter.BaseWidget() (all Tkinter widgets except Tk() inherit from BaseWidget()), like this: ## file TkinterDnD.py # import Tkinter class Tk(Tkinter.Tk): def __init__(self, *args, **kw): Tkinter.Tk.__init__(self, *args, **kw) self.tk.eval('package require tkdnd') def dnd_clearsource(self): '''Unregister widget as drag source.''' return self.tk.call('dnd', 'clearsource', self) Tkinter.BaseWidget.dnd_clearsource = dnd_clearsource < etc. > ### This is nice, because now I can simply do: from Tkinter import * import TkinterDnD root = TkinterDnD.Tk() to magically add dnd methods to all Tkinter widgets. However, I can't help that this trick somehow reminds me of a do-it-yourself lobotomy, so now my question, is this a common way to add new attributes to existing classes or is it possible that this causes problems that I don't see at the moment? Thanks in advance Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding Desktop Files
Repost - I forgot a subject In python under windows, how can I create and access a file on the Desktop? The following do NOT work: fp = open(r'Desktop\myFile','r') fp = open(r'\Desktop\myFile','r') fp = open(r'c:\Desktop\myFile','r') fp = open(r'c:\Windows\Desktop\myFile','r') I don't want to drill into c:\Documents and Setting\... because the user name is often obscure AND not all desktop files appear in the same subdir. of that. For example some are in 'All Users" or 'Default User'. Michael Huster, Simpson University ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
In python under windows, how can I create and access a file on the Desktop? The following do NOT work: fp = open(r'Desktop\myFile','r') fp = open(r'\Desktop\myFile','r') fp = open(r'c:\Desktop\myFile','r') fp = open(r'c:\Windows\Desktop\myFile','r') I don't want to drill into c:\Documents and Setting\... because the user name is often obscure AND not all desktop files appear in the same subdir. of that. For example some are in 'All Users" or 'Default User'. Michael Huster, Simpson University ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT self-implementation?
On 7/1/05, Brian van den Broek <[EMAIL PROTECTED]> wrote: Hi all,a bit off topic for Python Tutor, but I am think there are decent oddsthat folks here both know good resources and have an idea of whatlevel would be appropriate for me. So, I hope no one minds. A recent thread on comp.lang.python has touched on to what extent Cwas written in C. I know PyPy aims to implement Python in Python. Ibelieve I've heard that many lisp fans think you don't have a languageunless you can write the language's interpreter in the language itself. (Perhaps one or more of these claims is a bit inaccurate, butthe substance seems right.)This sounds, to the untutored, rather like magic. (It reminds me of aline from the German mathematician and philosopher, Gottlob Frege, who, in a book on the foundations of arithmetic, characterized anopposing position as akin to "trying to pull yourself out of the swampby your own top-knot" -- which, I can only assume, is even funnier in the original 19th c. German ;-) Naively, one thinks that to writeanything in C, you'd have to *have* C to write in, etc.Now's not the time in my life to start a comp. sci. degree. So, myquestions are: 1) What would be good terms to google for to find an explanation ofhow the seeming magic doesn't violate all reason?2) Much harder, so please pass unless you've a link you know ofoff-hand: any recommendations of particular things that I could read? If you are interested in a more abstract explanation on this, you can read up on one reason why lisp programmers are such fans of writting lisp interpreters in lisp: Turing Machines (TM). Abstract computer constructs that, arguably, are equivalent to your desktop computer in terms of programming. They are really for theoretical research, especially good for algorithm creation. But one of the early algorithms was to create a TM with a TM. http://en.wikipedia.org/wiki/Turing_machine http://plato.stanford.edu/entries/turing-machine/ You'll be able to find a lot more hits on any web search. -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Tkinter teachers' report program?
On 6/24/05, Adam Cripps <[EMAIL PROTECTED]> wrote: On 6/24/05, Michael P. Reilly <[EMAIL PROTECTED]> wrote:> On 6/24/05, Adam Cripps <[EMAIL PROTECTED]> wrote:> > I hadn't thought about a scrollbar - that would be very useful, > > although doesn't add to the management side of the statement (i.e.> > organising them according to subjects).> >> > The user can load a text file and adapt that - so they don't have to > > enter them by hand if they have them in a .txt file. Typing them in by> > hand once is better than typing them in by hand for every child that> > you have in your class, which is the whole aim of the software. > >>> I could try to whip up an example a little later if you like. I probably> wouldn't be large, but it could demonstrate tabbed frames with scrolling.>> -Arcege> -- Michael,That would be much appreciated.ThanksAdam Here you go, Adam. It's not full and complete, but it's working and you can customize it how you like. -Michael-- There's so many different worlds,So many different suns.And we have just one world, But we live in different ones. from Tkinter import * class TabbedFrame(Frame): """Create a frame with two areas, one is a small bar at the top where tabs will be placed, like a menu. The second area will be one container panel. When a tab is pressed, the panel will display the contents of a selected frame (created with the new() method). Each tab has a unique given name that identifies it. These are the public methods: new(tab_name) -> frame create a new tab and panel frame, return that frame remove(tab_name) destroy the tab and associated panel frame has_tab(tab_name) -> boolean does a tab exist with this name? select(tab_name) switch to selected tab """ def __init__(self, master): Frame.__init__(self, master) self.tabs = {} self.current_tab = None self._create_widgets() def _create_widgets(self): self.tabframe = Frame(self, height=25, relief=SUNKEN, bg='grey25', bd=2) self.tabframe.pack(side=TOP, fill=X, expand=YES) self.baseframe = Frame(self, bg='white', bd=2) self.baseframe.pack(side=BOTTOM, fill=BOTH, expand=YES) def _add_tab(self, name, button, frame): self.tabs[name] = (button, frame) def new(self, name): if self.has_tab(name): raise ValueError(name) button = Button(self.tabframe, relief=FLAT, text=str(name), bg='grey50', command=lambda n=name, s=self: s.select(n)) button.pack(side=LEFT, pady=1, padx=1) frame = Frame(self.baseframe) self._add_tab(name, button, frame) self.select(name) return frame def remove(self, name): try: button, frame = self.tabs[name] except: raise ValueError(name) if self.current_tag == name: frame.forget() button.forget() self.current_tag = None frame.destroy() button.destroy() del self.tabs[name] def has_tab(self, name): return self.tabs.has_key(name) def select(self, name): if self.current_tab: button, frame = self.tabs[self.current_tab] button['bg'] = 'grey50' frame.forget() button, frame = self.tabs[name] button['bg'] = 'grey75' frame.pack(fill=BOTH, expand=YES) self.current_tab = name def Adam_Report(tabbedframe): # Reproduce something like Adam's teacher report frame = tabbedframe.new('subject') topframe = Frame(frame) nameframe = Frame(topframe) firstnameframe = Frame(nameframe) Label(firstnameframe, text="First name: ").pack(side=LEFT) Entry(firstnameframe).pack(side=LEFT) firstnameframe.pack(side=TOP) lastnameframe = Frame(nameframe) Label(lastnameframe, text="Last name: ").pack(side=LEFT) Entry(lastnameframe).pack(side=LEFT) lastnameframe.pack(side=TOP) nameframe.pack(side=LEFT, fill=BOTH, expand=YES) sexframe = Frame(topframe) Label(sexframe, text="Sex: ").pack(side=LEFT) sexm_r = Radiobutton(sexframe, value="male", text="male") sexf_r = Radiobutton(sexframe, value="female", text="female") sexm_r.pack(side=LEFT) sexf_r.pack(side=LEFT) sexframe.pack(side=RIGHT, fill=BOTH, expand=YES) topframe.pack(side=TOP, fill=X, expand=YES) splitbottom = Frame(frame) NoStatements = 16 leftsplitframe = Frame(splitbottom) # has statementframe and Scrollbar sb = Scrollbar(leftsplitframe, orient=VERTICAL) canv = Canvas(leftsplitframe, yscrollcommand=sb, heig
Re: [Tutor] Help with Tkinter teachers' report program?
On 6/24/05, Adam Cripps <[EMAIL PROTECTED]> wrote: I hadn't thought about a scrollbar - that would be very useful,although doesn't add to the management side of the statement (i.e.organising them according to subjects).The user can load a text file and adapt that - so they don't have to enter them by hand if they have them in a .txt file. Typing them in byhand once is better than typing them in by hand for every child thatyou have in your class, which is the whole aim of the software. I could try to whip up an example a little later if you like. I probably wouldn't be large, but it could demonstrate tabbed frames with scrolling. -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Tkinter teachers' report program?
On 6/24/05, Adam Cripps <[EMAIL PROTECTED]> wrote: I am a teacher and have written this little Python/Tkinter applicationto help me with my report writing:http://cvs.sourceforge.net/viewcvs.py/squawk/ It's released under GPL and was quite fun to write.However, currently the application only allows for 15 statements to bemanaged. Increasing it to 25 would be easy. But I'm not sure how Iwould manage the widget to present 100 or organise the statements according to subjects.Can anyone have a look at the code - perhaps run it and if possiblesuggest a way of implementing many more statements? Tabbed frameswould be a good way forward (where each tab is a school subject) but under Tkinter they don't appear to be that easy. You can do tabbed frames in Tkinter. They take a little bit of coding, but to get right, but it is certainly something to think about. You might want to look into PMW (Python MegaWidgets) which is a Tkinter library. Myself, I had always prefered to write things in Tkinter, but a lot of people like the widget set in PMW. As for scaling the statements you have, you might want to think about putting the Label/Entry/Button widgets in a Frame with a Scrollbar widget. Then you can add as many as you like and the user can scroll down to the 200th statement. (I'm assuming that the user fills out each statement one by one, ugh!) Incidently, this Frame would be the same frame used for the tabbing, I would expect. -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clearing the Console Screen
On 6/16/05, Don Parris <[EMAIL PROTECTED]> wrote: Thanks! I thought there had to be a way to call the OS' clear screencommand, but was going about it the wrong way. I was trying to usesys.clear instead of os.system. Would it be difficult to test the OS, store the result in a variable, and call the comand based on the variableresult? Or would it be simpler to have users edit the script for their OS?Mind you, there may be other areas where I need an OS-specific command. I'm beginning to get an idea of the challenges of portability though. ;)Don You might want to use the tput command. It returns control sequences for the terminal that are used by all programs, e.g. emacs, vi(m). Your could capture the output with the commands module and send it to the terminal with stdout.write (instead of print). import commands clear_str = None def clearscreen(): global clear_str from sys import stdout if not clear_str: clear_str = commands.getoutput('tput clear') stdout.write(clear_str) clearscreen() If you wanted, you could encapsulate this into a module or a class. This would work on just about any UNIX/Linux/BSD system, and might work on Mac OS/X (I don't know if they use terminfo). You can use the other tput subcommands in your program if you wished as well. (Hide the cursor, go to column X row Y, etc.) -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Process problem
On 6/16/05, Alberto Troiano <[EMAIL PROTECTED]> wrote: Hey allNevermind, it worked with the & trick.I just posted because the first 2 times didn't do anything but there was anerror in the crontab so... Alberto, If you are going to use put the processes in the background with the ampersand ('&'), then you probably want to use 'nohup' as well in the os.system() call: os.system("nohup %s >/dev/null 2>&1 &" % cmd) This may save some headaches later. -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Process problem
On Wed, 15 Jun 2005 22:04:48 + "Alberto Troiano" <[EMAIL PROTECTED]> wrote: Hi Alberto, > Hey > > Let me make you understand > > I need that levantamuertos.py run cotascamon.py (every script with it > differents arguments that are passed) and then die letting the cotascamon.py > scripts running independently > > Now, I don't know if my code is right, and thinking now you're right, > levantamuertos.py waits until cotascamon.py finish. > What can I do since cotascamon will never die (and it doesn't have to die)? > > Maybe a different approach will be the solution but I can't find a way to do > it > > Best Regards > > Alberto > I didn't follow the thread completely, so maybe I missed something, but if the problem is that python waits until the os.system() calls are finished, I think adding a "&" to the command to make it run in the background should do the trick. Best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Buttons automatically executing
On Wed, 15 Jun 2005 14:31:55 -0500 Phillip Hart <[EMAIL PROTECTED]> wrote: Hi Phillip, > #!usr/bin/python > > from Tkinter import * > > def location(x,y): > print "I am in row ",x," and column ",y > > > root=Tk() > root.geometry('300x300') > can=Canvas(root,width=250, height=250) > > bimage=PhotoImage(file='sq1.gif') > > b1=Button(can,bg="black",image=bimage,command=location(0,0)).grid(row=0,column=0) That's an error which frequently happens to Tkinter beginners. When you assign the button's command like this the command is executed immediately after button creation, the correct usage is: b1 = Button(can, command=location) without the parentheses; however if you need to pass arguments to the callback, you can use a lambda expression like this: b1 = Button(can, command = lambda x=0, y=0 : location(x, y)) Another problem in this line that doesn't matter here, but might cause confusion later on is the use of grid() ; note that grid() returns None, so actually you set your variable b1 to None which is probably not what you intended; if you need to keep a reference to the Button object you need to split the above into two statements: b1 = Button(can, ) b1.grid() If you don't need a reference you can simply do: Button(can,).grid(row=0,column=0) without creating a (quite useless) variable. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finding path to resource files in a GUI application
On Thu, 9 Jun 2005 08:52:59 +0200 Christian Meesters <[EMAIL PROTECTED]> wrote: > Hi > > Currently I'm writing a GUI application with wxPython (on OS X, but I > guess the problem is the same, regardless of the UNIX derivative one is > using). When I start the main script where it is located the > application finds all resource files (non-Python files like images and > html files for html windows) without any problem. However, if a put a > link in /usr/local/bin and start the script using the link the > application cannot find those resource files - unless, of course, I > will use full absolute paths to point to those files. One brief example > to illustrate the problem: > > The class Goals is in a file called Help.py, located in '/gui_lib/' as > seen from my main script. > > class Goals(wx.Frame): > def __init__(self,parent,frame,title,size,pos=wx.DefaultPosition): > wx.Frame.__init__(self,parent, > -1,title,size,style=wx.DEFAULT_FRAME_STYLE) > self.frame = frame > self.cwd = os.getcwd() > > self.html = HtmlWindow(self,-1) > self.html.LoadPage(os.path.join(self.cwd,'gui_lib/Goals.html')) > > #this, of course, won't work > #if the main script is called from somewhere else and not the > directory where the main script > #is located > > Any ideas what I could use instead of os.getcwd to construct a relative > path which will work even if I port the script to an other machine? > > Cheers > Christian > Hi Christian, try self.cwd = os.path.abspath(sys.path[0]) sys.path[0] is the directory of your main program file, with os.path.abspath() you can get rid of the "../../" stuff at the beginning of the path if the program is called from a link. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactif or not
On 6/3/05, Cedric BRINER <[EMAIL PROTECTED]> wrote: hi,How can I know if a script is launched interactively or not because I'd like to make a script verbose or not depending if it is executed as interactive or not.eg.If I invoke it in a shell.. then it can be verboseIf it is launched from a crontab.. then it is less verbose.Ced. If you want to know if your program has been launched from an interactive terminal or from a system background process like cron or init, then you look to see if stdin is a tty. Unix is usually very careful about who has a "controlling tty" and who does not. In Python, file objects have an isatty() method that will return True or False. import sys isinteractive = sys.stdin.isatty() if isinteractive: ... else: ... How you make a program this way manually (i.e. to make a program into cron) is slightly more complicated, but still all the tools are there in Python. -Arcege -- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help me on python + snack
On Tue, 17 May 2005 21:18:09 -0700 (PDT) Mahmad Sadique Hannure <[EMAIL PROTECTED]> wrote: Hi Mahmad, > Hello friends, > I m currently working on sound stuff. I have installed > all stuff related to Snack. My code for playing mp3 > song is like this > > #!/usr/bin/python2.3 > > from Tkinter import * > import tkSnack > > def main(): > root = Tk() > tkSnack.initializeSnack(root) > mysound = tkSnack.Sound('xyz.mp3') I believe the last line is the problematic one. Try to change it into: mysound = tkSnack.Sound(file='xyz.mp3') > #mysound.read() > mysound.play() > if __name__=='__main__': > main() > I works fine without any error but can't get any > sound. > > So friend help me, I don't know whats wroung with my > code. > I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] total newbie
WARNING: TOTAL NEWBIE QUESTION BELOW Had to warn ya, I just finished reading a book on learning python for beginners and decided to write a small game program as an exercise. The game I wrote was breakout (in case you dont know it, its a very simple game where there is several rows of bricks in the upper portion of the screen and a paddle at the bottom, a ball bounces around destroying bricks...) I used pygame for all of the graphics, sprites, collision, etc... What I noticed while testing the program is that the ball moves fairly slowly, I tried incrementing the ball's speed (dx and dy) but it still seemed to move pretty slow no matter how much I increased its speed. I went ahead and played out the game, destroying bricks (sprites, 128 of them). As the number of remaining bricks decreased the ball's speed increased, dramatically. so i guess what I want to know is, is python normally this slow when dealing with such a small number of objects? or is this something particular about pygame's handling of sprites? and, if this is something intrinsic to python, can anything be done to speed it up? I realize python is an intrepeted language but this seems almost useless for any decent number of objects Thanks in advance. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scoping oddity
Ziyad, Thanks for the tip. Much of the code written here in my office, do exactly what you describe. The code I am working on is purely personal and educational. I guess I got sloppy, which in a way is educational. All, Obviously, you can't put every variable on the 'def' line. Is there a utility of some sort that will present me with a list of the variables used in an application? Preferably, something that might pick up possible scope 'collisions'? If you know what I mean. And if that isn't the right word, what is? thanks guys! Michael -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of ZIYAD A. M. AL-BATLY def testb(astr, x = x): x = x - 1 print astr, x ___ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scoping oddity
Tanja, Bob, Brian, Many thanks for your help. And perhaps the way in which I posed the question was misleading. In a process I am writing, I was actually trying not to use global variables, as I agree with Brian. However, I inadvertantly used a variable within a 'def' block that I had used outside of that 'def' block and got 'bitten'. It was in tracking my bug down that I became a tad confused. Actually, now that I know the answer, it all seems so obvious. At least until I get bitten by it again! D'OH! Michael -Original Message- Behalf Of Brian van den Broek >> >> > def testb(astr): >> > x = x - 1 >> > print astr, x >> global will indeed fix that, yes. But, I've been lead to believe that one's first thought when tempted to write a global statement should be to reflect on whether that temptation isn't the symptom of a sub-optimal design. ___ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] scoping oddity
Good morning, I came across a rather odd issue with scoping. Can someone explain why testa and testc works, but not testb. I am running under python 2.4.1 on Windows NT. thanks, Michael x = 5 def testa(astr): print astr, x testa(22) def testb(astr): x = x - 1 print astr, x testb(22) def testc(astr): print astr, x-1 testc(22) ___ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter and Animation
On Wed, 27 Apr 2005 19:31:06 -0700 Jeremiah Rushton <[EMAIL PROTECTED]> wrote: > > I tried your idea and it doesn't animate it. I made a for loop and told it > to mover 1 pixel downward every .3 seconds for 25 times. It just waits till > the for loop is completed and then displays the result of the loop ending. I > also tried it without the for loop by writing each one of the steps out > repetively and I had the same result. The only thing that has kind of got > close to the visual is that I wrote a program that everytime the user > clicked the button it moved down one pixel, but I want it to move 100 > pixels, one by one, with only one click from the user. Here's the code that > I wrote: > > from Tkinter import * > from time import sleep > > class Main: > > def __init__(self,master): > button = Button(master,text='button') > button.place(x=1,y=1) > y=3 > for x in range(1,25): > sleep(.3) > button.place_forget() > button.place(x=1,y=y) > y+=2 > > > root = Tk() > Main(root) > root.title('test') > root.mainloop() > > Thanks for all the help so far. > > Jeremiah > Hi Jeremiah, you should call update_idletasks() to make the changed geometry visible. I've written a (very quick and dirty) demo that shows how to animate a Label with place() : ### from Tkinter import * class AnimatedFrame(Frame): def __init__(self, master, **kw): Frame.__init__(self, master, **kw) self.labelx = 100 self.labely = 100 self.label = Label(self, text='Look at me!') self.label.place(x=self.labelx, y=self.labely) self.button = Button(self, text='Start', command=self.start) self.button.place(x=100, y=200) def start(self): if self.labelx > 20: self.labelx -= 1 self.labely -= 1 self.label.place(x=self.labelx, y=self.labely) self.update_idletasks() self.start() def test(): root = Tk() f = AnimatedFrame(root, width=300, height=300) f.pack() root.mainloop() if __name__ == '__main__': test() # I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Tkinter and Animation
On Wed, 27 Apr 2005 09:35:47 -0700 Jeremiah Rushton <[EMAIL PROTECTED]> wrote: > > I wanted them to visually shrink and visually move to a corner on the frame. > I did not know how to do it the way you explained, thanks for that. But is > there any way to do it visually? > I guess so, if you use the "place" geometry manager. With place() you can determine things like x- and y-coordinates on the parent widget and relative width / height, so if you start a loop that moves the button 2 pixels up and one pixel to the left every 50ms for example it might come close to the kind of animation you want. It's probably tricky, but I think it's possible. Best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using TK to view an image and then close the window
On Mon, 25 Apr 2005 10:24:08 -0700 "Ertl, John" <[EMAIL PROTECTED]> wrote: Hi John, > I can get the image to show > up and minimize and maximize but I can not get the window to close and then > display the next image. > > I have tired several things but no luck. > > Any help on getting the TK window to shutdown cleanly would be appreciated. > Thanks > > John Ertl > > # this is supposed to display an image in a TK window but the close > (X) does not work. > import Image > import Tkinter,ImageTk > > def TKview(img,mainTitle="image"): > > app = Tkinter.Tk() > app.withdraw() > > top = Tkinter.Toplevel(app,visual="truecolor",colormap="new") > top.title(mainTitle) > top.protocol("WM_DELETE_WINDOW", quit) > top.bind("",quit) > top.bind("",quit) > > canvas = Tkinter.Canvas(top) > canvas.pack() > > p = ImageTk.PhotoImage(img) > > canvas['width'] = img.size[0] > canvas['height'] = img.size[1] > > canvas.create_image(0,0,anchor='nw',image=p) > > top.mainloop() > > def quit(event=None): > top.destroy() > top.quit() > If that's all of the code, "top" is created as a local variable inside your TKview() function, so your quit() function doesn't know about it. Second, I don't see much use for using a second Toplevel window at all, why not just pack the canvas onto the main Tk() window? > > # this code gets the images opens them and calls the TK code above to > display them > > import glob > import thread > import Image > > import TKviewTest # the module to view the images > > > gifList = glob.glob("./*.gif") > print gifList > for image in gifList: >image = image[2:] # glob leaves ./ in file name > >newIm= Image.open(image) > >TK = TKviewTest >thread.start_new_thread(TK.TKview(newIm,mainTitle="image")) > > I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TKinter and things over Linux
On Mon, 18 Apr 2005 13:24:03 + "Alberto Troiano" <[EMAIL PROTECTED]> wrote: Hi Alberto, > Hey > Let me know if this format is better (I use Hotmail in the web so...) > Looks pretty much ok to me :-) > Sadly I'm not in the linux machine so I can't run the command you sent me > but I shall explain the version just so you know > > The fullname version is Red Hat Advanced Server 3.0. This is a commercial > version of Linux > But it has so many problems and so few documentation that I switched to Red > Hat 9.0 (I think that you're familiar with this version) > > I have installed tcl and tk support and I will download and install the > anthony's RPMs > What can I do to make Tkinter work on Linux Red Hat 9.0?? > First you should make sure that all necessary RPMs are installed; the basic python RPM will be installed by default on RedHat 9 but probably not Tkinter ( I'm not sure how the RPM is called on RedHat, maybe python-tkinter or python-tk or tkinter or... ). Best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with encodings
On Mon, 18 Apr 2005 09:22:28 +0300 Olli Rajala <[EMAIL PROTECTED]> wrote: > Hi! > Been offlist for a while, but now I started to code an administration > tool for my own photo gallery and have some troubles, so thought to > write and ask some help. :) > > So, I'm from Finland and I'm using ISO-8859-15 -encoding but Python > don't "understand" letters outside ASCII. I've read PEP-0263 and tried > to add the encoding line to my sources, but it doesn't help. Here's a > little example: > > #!/usr/bin/python2.4 > # -*- coding: -*- > def printHeader(): > print "" > > Don't know how you see the 4th line, but that's not my "problem", is it? ;) > > And I got this error message: > "sys:1: DeprecationWarning: Non-ASCII character '\xe4' in file > generalHtml.py on line 11, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details" > > I code with Kate (2.4, KDE 3.4.0) and everything else works well when > speaking about this encoding thing. I really hope that someone would > know a solution. I don't mind if I have to write only ASCII but I'm > not the only user for that tool, so... > Hi Olli, does it help if you change the second line into: # -*- coding: iso-8859-15 -*- ? I *think* that is the correct syntax (at least it works for me). Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UselessPython 2.0
On Apr 11, 2005 7:30 PM, Michael Janssen <[EMAIL PROTECTED]> wrote: > [what's bad about non-alphabetic characters?] I found it out for myself. To quote from Dick's post: "A man, a plan, a canal, Panama!" Seems like palindromes are allowed not to reflect whitespace and punctuation (an how could this be?). cheers Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UselessPython 2.0
On Apr 10, 2005 7:18 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > I'm a newbie, but would this qualify as a contribution to UselessPython 2.0? Hello Dick, don't be shy, or do you suspect it might be too usefull? ;-) I found it funny, so it must be good enough. here my remarks: > def makeStringAllLowercaseAlpha(s): > """ > Take any string, convert all uppercase alphabetic characters to > lower case, > then strip all non-alphabetic characters [what's bad about non-alphabetic characters?] > """ > s1 = string.lower(userstring) oops: this function gets an argument s, here you're using the global variable userstring. I know, it works, but there will be functions were mistakes like this weren't just ugly but buggy. > s2 = "" > for index in range(len(s1)): > if s1[index] in string.ascii_lowercase: > s2 += s1[index] or easier (much more readable, helps understanding the programm): for char in s1: if char in string.ascii_lowercase: s2 += char regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Entry widgets
On Sun, 10 Apr 2005 18:07:48 +1000 "Diana Hawksworth" <[EMAIL PROTECTED]> wrote: > Hello list, > > Is it possible to change the width of an Entry widget - or not? I am using > Tkinter, GUI - and have an Entry widget that accepts a number. I just don't > want it to extend the width of the column. I have tried width = - but get > an error. > You should be able to use the width option as for any other widget: e = Entry(parent, width=5) or e.configure(width=5) What exactly did you write, and what was the error? > Maybe a text widget would be preferable? > If you just want one line to enter a number, I don't think so. > Also - how do I set the insertion symbol there already, so I don't need to > click there to enter the number? > You can use focus_set(): e = Entry(parent) e.focus_set() > TIA. Diana I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using the enter key
On Thu, 07 Apr 2005 10:06:46 +1000 "Nova Nova" <[EMAIL PROTECTED]> wrote: > def create_widgets(self): >self.a_lbl=Label(self,text="",fg="Red") >self.a_lbl.grid(row=0,column=0,columnspan=2,sticky=W) >self.inst_lbl=Label(self,text="Enter A Number Between 1 and > 100.",fg="blue") >self.inst_lbl.grid(row=1,column=0,columnspan=2,sticky=W) >self.pw_lbl=Label(self,text="Number: ") >self.pw_lbl.grid(row=2,column=0,sticky=W) >self.pw_ent=Entry(self) >self.pw_ent.grid(row=2,column=1,sticky=W) >self.submit_bttn=Button(self,text=str(self.g)+" Turns > Left",command=self.reveal,fg="red",bg="black") >self.submit_bttn.grid(row=3,column=0,sticky=W) >self.win_txt=Text(self,width=35,height=5,wrap=WORD) >self.win_txt.grid(row=4,column=0,columnspan=2,sticky=W) > > > def submit(self): >self.reveal >entry.bind('',self.submit) > > this is what im doing and i get an error, IT DOES NOT WORK > The problematic part is your submit() method: def submit(self): self.reveal# you forgot the parentheses here to call your reveal() method ^^ entry.bind('',self.submit) this only binds the event handler to the Entry when the submit button was pressed before; you better apply this binding in your create_widgets() method immediately after creating the Entry widget. Please note that if you want to use the submit() method both as button-command and as event handler for the entry, it needs an optional event instance as argument: def submit(self, event=None): (...) because the button's "command" doesn't pass an event to the callback, but the entry's event handler does. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using the enter key
On Tue, 5 Apr 2005 06:28:54 +1000 "Diana Hawksworth" <[EMAIL PROTECTED]> wrote: > Hello list! > > At the moment I have some user input tied to a button that allows the input > to be "submitted" and then an answer is supplied. How can I get rid of this > submit button, and have the user just press the "enter" key and have the same > result happen? > > TIA. Diana You need to create an event handler for the Entry widget that is called each time the Enter key is pressed over the widget: entry.bind('', submit) where "entry" is of course your Entry widget and "submit" the function to be called. Please note that the "enter" key's event descriptor is "''" in Tk (there's an '' event, too, which is when the mouse pointer enters the widget) and that the callback gets an event instance passed, so the function definition has to look like this: def submit(event): (...) I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wxPython / Tkinter Grid
On Fri, 1 Apr 2005 09:11:20 +0100 "Alan Gauld" <[EMAIL PROTECTED]> wrote: > > I know a wxPython grid is totally different to a Tkinter grid, but > is > > there a Tkinter equivalent of a wxPython grid? I'm finding wxPython > to > > be fiddly and restrictive... > > Then Tkinter will be more so. Tk is a fairly basic toolkit, fine for > wrapping a command line app in a glossy front end but not for > sophisticated GUI work. > > There is no grid component in Tk out of the box, but some add on > toolkits > supply one. Try searching on the Vaults of Parnassus or on the > ActiveState site if you are determined to try Tkinter... > > Alan G. > Or look here: http://tkinter.unpythonic.net/wiki/Widgets There is a number of links to table widget implementations in Tkinter o nthe wiki page. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter and keyboard output
On Thu, 24 Mar 2005 18:05:25 - "Igor Riabtchuk" <[EMAIL PROTECTED]> wrote: > Hi, > > I was playing around with Tkinter bindings and I got a question which is > probably not particularly bright. > > If I have the following code, it works because I specifically code a function > for keypress: > > from Tkinter import * > > class CRED(Frame): > def __init__(self): > Frame.__init__(self) > self.txt=Text(self) > self.txt.bind('', self.conv) > self.txt.pack() > self.pack() > self.txt.focus() > > def conv(self,event): > self.txt.insert(END,'t') > return 'break' > > app=CRED() > app.mainloop() > > What if instead of coding , I coded - how would I implement > the function which would allow the code to determine which 'Key' was pressed > after Alt? > > Thank you. > Igor Do you mean something like this: >>> from Tkinter import * >>> r=Tk() >>> t=Text(r) >>> t.pack() >>> >>> def test(event): ... print event.keysym ... >>> t.bind('', test) '1077686180test' >>> x # Alt-x was pressed ? Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining functions
Something I've always wondered: if input() is so dangerous, why is it there? What valid uses does it have in the wild? I ask this because this confusion comes up a lot: people expect input() to return a string and it throws them when it doesn't. We all just learn to use raw_input(), and to forget about input(). But if you really needed the current input() function, isn't eval(raw_input()) the same thing? And it leaves you space to check the input string for anything stupid or dangerous before you feed it to eval(). Perplexed, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining functions
Hi John, when you want user input, you almost always need raw_input(), not input(). Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python cgi doesn't get data from html form as expected
I haven't done too much web stuff (or much of anything) with python, but I looked into your question a bit (researching other's problems may help me avoid them =)). A quick search brought up this page which seems to have information which may help you. http://gnosis.cx/publish/programming/feature_5min_python.html Hope that helps. Best Regards, Michael Lasky On Tue, 2005-03-22 at 14:02 +, Vicki Stanfield wrote: > I have recently started doing cgi in Python and have run into a problem. I > have an html form which has various widgets which accept data. I also have > this in that html file: > > > > formdata.py runs but doesn't seem to contain the data from the form. I'm > not sure of the format for the for with regard to FieldStorage btw. Here > is the contents of formdata.py: > > > #! /usr/bin/python > import cgitb, os, sys > cgitb.enable() > > import cgi > > print "Content-Type: text/html\n\n" > print "" > form = cgi.FieldStorage() > for each in form: > print "each" > print form['fname'].value, form['lname'].value > #print "address:", form['addr'].value() > print "" > -- > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing Keyboard output
On Sun, 20 Mar 2005 19:38:40 - "Igor Riabtchuk" <[EMAIL PROTECTED]> wrote: > Hi, > > I am totally new to Python and still learning. > > I am looking for a way to change keyboard output within Tkinter widget - for > example, say I press "p" and I want it to come out as "t". > > Could anyone possibly point me in the right direction? > > Igor You can use the widget's bind() method to replace the standard callback with a new one: from Tkinter import * root = Tk() e = Entry(r) e.pack() def PtoT(event): e.insert('insert', 't') return 'break' e.bind('', PtoT) the "return 'break'" statement prevents the event from being propagated to Tk's standard event handler; without it both "p" and "t" would be inserted into the Entry. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] stopping greedy matches
As Kent said, redemo.py is a script that you run (e.g. from the command line), rather than something to import into the python interpretor. On my OSX machine it's located in the directory: /Applications/MacPython-2.3/Extras/Tools/scripts Cheers, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using signal handlers
Hello tutors, I experience problems with signal handlers, and the explanatzions in the docs don't seem to help me much. The code I try to handle basically comes down to this (it's supposed to run on linux only, btw): from Tkinter import * import tkSnack root = Tk() tkSnack.initializeSnack(root) root.mainloop() initializeSnack() tries to access the sound device, however if this fails it tries forever and doesn't return. I *thought* a signal handler might be what I need, and in fact it partially works, at least initializeSnack() is stopped when I add this: from Tkinter import * import tkSnack, signal root = Tk() signal.signal(signal.SIGALRM, signal.getsignal(signal.SIGALRM)) signal.alarm(5) tkSnack.initializeSnack(root) signal.alarm(0) root.mainloop() Now when the audio device is busy, after 5 seconds the app prints "Alarm clock" and exits. However I would prefer to have a more controlled exit, but as soon as I define a custom signal handler it's the same as before - it never gets called. Any help is much appreciated Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On Mon, 07 Mar 2005 11:46:42 -0500 Kent Johnson <[EMAIL PROTECTED]> wrote: > Gregory Sexton wrote: > > Thanks for the help! Sorry for the trivial questions, but I guess we all > > have to start somewhere. Beginning python student, OS Windows XP,using > > Python 2.4. Also novice to programming. I cant get the "/a" command to > > work. > > I don't know what the "/a" command is, please give more details. > > I get an elongated 0 in my Python interpreter, but no sound. > Sound? Maybe you meant print "\a" ? Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Saving Entry fields in Tkinter
On Tue, 1 Mar 2005 12:52:57 +0100 Ewald Ertl <[EMAIL PROTECTED]> wrote: > Hi! > > Perhaps this could help you: > > fileContent=open( "my/file/to/read", "r").readlines() > > for line in fileContent: > print line.strip() # remove leading and trailing whitspace's incl. \n > > > In the loop you could perhaps populate the entry-widgets. > > HTH > > Ewald Or use the fileinput module: var_list = [] for line in fileinput.input(filename): var = Tkinter.StringVar() var.set(line) var_list.append(var) Best regards Michael > > on Tue, 1 Mar 2005 09:22:06 + Adam Cripps <[EMAIL PROTECTED]> wrote : > - > > Adam Cripps > I'm writing an application which has rows of Entry fields > (created in > Adam Cripps > a loop - see previous thread; and thanks guys!). All the > content of > Adam Cripps > the Entry fields are accessed through self.contentlist[i].get() > Adam Cripps > > Adam Cripps > Now I'm trying to save the content of those fields in a friendly > Adam Cripps > format. I've used pickle in the past, but experienced problems > with > Adam Cripps > pickling Tkinter widgets. > Adam Cripps > > Adam Cripps > I'm saving using this method :- > Adam Cripps > > Adam Cripps > for i in self.contentlist: > Adam Cripps > saving = i.get() + "\n" > Adam Cripps > f.write(saving) > Adam Cripps > f.close() > Adam Cripps > > Adam Cripps > which creates a text file with each entry field separated with > a "\n". > Adam Cripps > > Adam Cripps > What would be a good way to open this file and re-populate the > entry > Adam Cripps > fields with the content? I'm not sure how to parse the text > according > Adam Cripps > to the \n separator. > Adam Cripps > > Adam Cripps > Am I going down the right path here? > Adam Cripps > > Adam Cripps > TIA > Adam Cripps > Adam > > > --- end -- > > > -- > Ing. Ewald Ertl HartterGruppe Phone : > +43-3352-33085-558 > trinomic Projektmanagement & Informationstechnik GmbH Fax : > +43-3352-33085-600 > Wiener Straße 41mailto:[EMAIL > PROTECTED] > A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL > PROTECTED] > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursive Tkinter buttons
On Sat, 26 Feb 2005 19:48:25 + Adam Cripps <[EMAIL PROTECTED]> wrote: > On Fri, 25 Feb 2005 12:21:18 +0100, Michael Lange > > > > > You see, in my example above I called the list "buttonlist" instead of > > "button"; maybe this naming > > helps avoid confusion . > > > > Best regards > > > > Michael > > Many thanks for the help here. > > I got all my buttons displayed and stored in the list with: > > for i in range (1, 11): > submittext = ">>> " > self.s = Button(text=submittext, command = > self.showButton) > self.s.grid(column=4, row=i+4) > submitlist.append(self.s) > Hi Adam, note that there's no use in making the button an attribute of its parent class with self.s = Button(text=submittext, command = self.showButton) because self.s gets overridden on every iteration in the for-loop; it's not a bug, but might be a source of confusion, when you try to access self.s later in your code; you don't need the reference anyway, because you keep the references to all buttons in the list. > > - however, when I click the button, I want self.showButton to know > which one of them was pressed. I've seen in other gui programming the > idea of an id or identifier - I can't see that here. Ideally, I would > like to know the value of i in self.showButtons - but when I use > self.showButtons(i) showButtons gets called straight at run time. > > Any ideas? You have two options here: 1. use a lambda expression as button command, lambda allows you to pass an argument to the callback: s = Button(text=submittext, command = lambda index=i: self.showButton(index)) 2. if you don't like lambdas, you can use the button's bind() method instead of the command option: s = Button(text=submittext) s.bind('', self.showButton) s.bind('', self.showButton) bind() passes an event to the callback which allows you to find out which widget sent the event via the event's widget attribute: def showButton(self, event): button = event.widget print button['text'] I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursive Tkinter buttons
On Fri, 25 Feb 2005 20:19:15 +1300 Liam Clarke <[EMAIL PROTECTED]> wrote: > > > > for i in range(0,10): > > print i > > buttonlabel = "field " +str(i) > > button[i].append = Button (text=buttonlabel) > > button[i].grid(column=3, row = i+3) > > > > The current error is: > > > > File "report.py", line 80, in createWidgets > > button[i].append = Button (text=buttonlabel) > > IndexError: list index out of range > > > button = [] > for i in range(0,10): > print i > print button[i] > > > Will cause the exact same error as button[i].append. Why? button=[], > it has no index. > Perhaps you just mean button[i] = Button (text=buttonlabel)? > > Regards, > > Or : buttonlist = [] for i in range(0, 10): print i buttonlabel = "field" + str(i) b = Button(text=buttonlabel) b.grid(column=3, row=i+3) buttonlist.append(b) Remember what you are doing when you call "button[i].append = Button(text=buttonlabel)": button is a list of Tkinter.Button objects, so button[i] is the "i-th" item in this list and that's exactly one more than the list actually contains, so you get an IndexError . However, if this IndexError wouldn't occur, it didn't help much, because you would probably get an AttributeError, saying something like "Tkinter.Button instance has no attribute 'append'". Even without this AttributeError nothing would be won, because the list's append() method returns None, so you would have: None = Button(text=buttonlabel) which is probably not what you intended. You see, in my example above I called the list "buttonlist" instead of "button"; maybe this naming helps avoid confusion . Best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading Tutor with gmail: monospace fonts
Hi all, This is slightly off topic, but I've noticed a lot of people are using gmail accounts to post to tutor and I just wanted to share a useful trick I just learned for making gmail display and edit mail with a monospace rather than proportional font. I'm sure anyone who's tried it agrees that significant whitespace means that python and proportional fonts don't play well together... Basically, you need to get your browser to override the stylesheet of the page with the following snippet of css: div.msg div.mb, .cm, .tb { font-family: monospace !important; font-size: 12px !important; } In Firefox, you add it to the userContent.css file in your preferences (you'll probably have to create this, see http://www.mozilla.org/support/firefox/edit). With Safari on MacOSX you make a css file anywhere you like (I used ~/Library/Safari/MyPrefs.css), add this snippet, and then select the file from the "Advanced" tab in Safari's Preferences. I don't know about other browsers, but the same sort of thing is almost certainly possible. Cheers, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print text position problems when using triple quotes
Hi Luke, > Is there a way to preserve the readability of the code and have > printed text from indented blocks, say, nested conditionals, appear > flush at left, not printed exactly where I've written them in the > script? you can use the textwrap module for this. >>> from textwrap import dedent >>> print dedent("""\ ... some ... indented ... text""") some indented text >>> "dedent" is a utility function of the textwrap module that trims every line by an equal amount. The trick here is the backslash so that the first line doesn't count. The "fill" and "wrap" functions of textwrap might also interest you: http://www.python.org/doc/2.3.5/lib/module-textwrap.html. Cheers, Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode issues
On Thu, 24 Feb 2005 07:51:04 -0500 Kent Johnson <[EMAIL PROTECTED]> wrote: > Michael Lange wrote: > > I *thought* I would have to convert the user input which might be any > > encoding back into > > byte string first > > How are you getting the user input? Is it from the console or from a GUI? > It's a (Tkinter) gui, but anyway, I think I now understand why this idea is total nonsense. > If your intent is to create a unicode string, try this: > if not isinstance(result, unicode): > result = result.decode(sys.stdin.encoding) > Ok, user input must be checked whether it's unicode or not and if necessary be decoded to unicode with system encoding. For internal operations I should then use only unicode strings and if I need to print something to stdout I must encode it again with system encoding, right? > This article gives a lot of good background: > http://www.joelonsoftware.com/articles/Unicode.html > > I have written an essay about console encoding issues. At the end there is a > collection of links to > more general Python and Unicode articles. > http://www.pycs.net/users/323/stories/14.html > > Kent > That's great! Exactly the kind of articles I've been looking for but couldn't find. Thanks!!! Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Unicode issues (was: UnicodeDecodeError)
On Wed, 23 Feb 2005 23:16:20 -0500 Kent Johnson <[EMAIL PROTECTED]> wrote: > How about >n = self.nextfile >if not isinstance(n, unicode): > n = unicode(n, 'iso8859-1') > ? > > > At least this might explain why "A\xe4" worked and "\xe4" not as I > > mentioned in a previous post. > > Now the problem arises how to determine if self.nextfile is unicode or a > > byte string? > > Or maybe even better, make sure that self.nextfile is always a byte string > > so I can safely convert > > it to unicode later on. But how to convert unicode user input into byte > > strings when I don't even > > know the user's encoding ? I guess this will require some further research. > > Why do you need to convert back to byte strings? > > You can find out the console encoding from sys.stdin and stdout: > >>> import sys > >>> sys.stdout.encoding > 'cp437' > >>> sys.stdin.encoding > 'cp437' > I *thought* I would have to convert the user input which might be any encoding back into byte string first (remember, I got heavily confused, because user input was sometimes unicode and sometimes byte string), so I can convert it to "standard" unicode (utf-8) later on. I've added this test to the file selection method, where "result" holds the filename the user chose: if isinstance(result, unicode): result = result.encode('iso8859-1') return result later on self.nextfile is set to "result" . The idea was, if I could catch the user's encoding, I could do something like: if isinstance(result, unicode): result = result.encode(sys.stdin.encoding) result = unicode(result, 'utf-8') to avoid problems with unicode objects that have different encodings - or isn't this necessary at all ? I'm sorry if this is a dumb question, but I'm afraid I'm a complete encoding-idiot. Thanks and best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UnicodeDecodeError
On Wed, 23 Feb 2005 07:21:40 -0500 Kent Johnson <[EMAIL PROTECTED]> wrote: > > This is a part of Python that still confuses me. I think what is happening is > - self.nextfile is a Unicode string sometimes (when it includes special > characters) > - the gettext string is a byte string > - to compare the two, the byte string is promoted to Unicode by decoding it > with the system default > encoding, which is generally 'ascii'. > - the gettext string includes non-ascii characters and the codec raises an > exception. > Thanks Kent, now it looks like the total confusion seems to clear up (at least partially). After some googling it seems to me that the best bet is to use unicode strings exclusively. When I set the unicode flag in gettext.install() to 1 the gettext strings are unicode, however there's still a problem with the user input. As you guessed, "self.nextfile" is unicode only *sometimes*; I tried and changed the line from the old traceback into: if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'): Now when self.nextfile is an existing file "\xe4.wav" that was clicked on in the file dialog's file list this works, however when I type "\xe4.wav" into the file dialog's entry field I get: TypeError Exception in Tk callback Function: > (type: ) Args: () Traceback (innermost last): File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/local/share/phonoripper-0.6.2/snackrecorder.py", line 304, in start if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'): TypeError: decoding Unicode is not supported At least this might explain why "A\xe4" worked and "\xe4" not as I mentioned in a previous post. Now the problem arises how to determine if self.nextfile is unicode or a byte string? Or maybe even better, make sure that self.nextfile is always a byte string so I can safely convert it to unicode later on. But how to convert unicode user input into byte strings when I don't even know the user's encoding ? I guess this will require some further research. > I don't know what the best solution is. Two possibilities (substitute your > favorite encoding for > latin-1): > - decode the gettext string, e.g. >if self.nextfile == _('No destination file selected').decode('latin-1'): > > - set your default encoding to latin-1. (This solution is frowned on by the > Python-Unicode > cognoscenti and it makes your programs non-portable). Do this by creating a > file > site-packages/sitecustomize.py containing the lines > import sys > sys.setdefaultencoding('latin-1') > > Kent > Unfortunately the latter is no option, because I definitely need portability. I guess I should probably use utf-8. Thanks and best regards Michael > > > > ## > > Error: 1 > > UnicodeDecodeError Exception in Tk callback > > Function: > > (type: > 'instancemethod'>) > > Args: () > > Traceback (innermost last): > > File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line > > 1747, in __call__ > > return apply(self.func, args) > > File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start > > if self.nextfile == _('No destination file selected'): > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: > > ordinal not in range(128) > > > > ## > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UnicodeDecodeError
On Tue, 22 Feb 2005 19:17:40 -0500 "Isr Gish" <[EMAIL PROTECTED]> wrote: > This part of the error is saying what the problem is. > >>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: > ordinal not in range(128) > > Thatthe ascii codec that's being used can't decode any ascii code above 128. > And the code 0xe4 is higher then that. > You would have to use a different encoding, like msbc. > If i remmeber correctly you should do something like the following. > > self.nextfile = self.nextfile.encode('msbc') > Then it should work. > > If it doesn't work try posting what error you get. > > All the best > Irr > > Thanks for the reply, it looks to me however that the problem is rather the gettext part; once I discovered this problem I can produce similar errors at other points in my app that *seem* to only occur when a gettext string gets combined with a string that is returned by user input from some Tkinter widget. The final complaint in the traceback is always about a (german) special character in the translated gettext string: ## UnicodeDecodeError Exception in Tk callback Function: at 0xb72ec304> (type: ) Args: () Traceback (innermost last): File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwDialog.py", line 153, in command=lambda self=self, name=name: self._doCommand(name)) File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwDialog.py", line 132, in _doCommand return command(name) File "/usr/local/share/phonoripper-0.6.2/widgets/FileSelectDialog.py", line 206, in go if not self.ok(): File "/usr/local/share/phonoripper-0.6.2/widgets/FileSelectDialog.py", line 201, in ok return self.fo_handler.create_ok(self.full_path) File "/usr/local/share/phonoripper-0.6.2/FileOperationHandler.py", line 43, in create_ok message=_('File already exists:\n"%s"\nDo you want to overwrite it?') % filename) UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 19: ordinal not in range(128) ## The german translation of 'File already exists:\n"%s"\nDo you want to overwrite it?' contains a special character ('\xfc'), filename is of course simply the complete path to a file as it is returned by a "Save as..." dialog box. I get this error for some reason if I choose '\xe4.wav' as basename for "filename" but not if I choose 'A\xe4.wav' . Like I said in my first post, there are no errors if I remove the german .mo file, so gettext uses the english strings. What seems really weird to me here is that it looks like both the translated gettext string and the special characters in my "filename" variable *can* be decoded, but not both at a time - but only under (rare) circumstances ( setting "filename" to "/somepath/A\xe4.wav" works but "/somepath/\xe4.wav" not). I'm really lost here, so any further hints are very appreciated. Thanks and best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can i use both float and int?
Hi .,, An error will certainly occur (you should always try it and see). You could do something like: n = raw_input("Number1: ") try: number1 = int(n) except ValueError: number1 = float(n) This will make number1 an integer if possible, and a float otherwise. But (and wiser heads may correct me here) I'm not sure this is a good idea. Couldn't you just use floats throughout, given that floats are at least sometimes acceptable? I'm just guessing what you need here, but if you really are trying to avoid floats whereever possible, and if you're using python version 2.4, you might find that the decimal type is what you need. As I understand it, it allows you to specify the precision of your number, so 1 will be come out as to 1. and not 1.0001 (or whatever). I'm not using 2.4 myself yet, so ask the list if you need examples or explanation. Michael On Tue, 22 Feb 2005 21:25:41 +, . , <[EMAIL PROTECTED]> wrote: > like... > > number1 = raw_input(float int("Number1: ") > > But, I think error will occur... > > Cheers! :) > > _ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] UnicodeDecodeError
Hello list, I've encountered an (at least for me) weird error in the project I'm working on (see the traceback below). Unfortunately there are several of my application's modules involved, so I cannot post all of my code here. I hope I can explain in plain words what I'm doing. The line in the traceback that seems to cause the problems: if self.nextfile == _('No destination file selected'): "self.nextfile" is a variable that contains either the path to a file (the destination file for sound recording) or the gettext string you see above. For some reason I get the error below when "self.nextfile" contains a special character *and* the gettext string holds the german translation, which contains a special character, too (of course '\xe4' as 23rd character). It looks like there are no problems when I remove the german translation or when there are no special characters in the filename, but as soon as I have special characters on both sides of the equation the error occurs. ## Error: 1 UnicodeDecodeError Exception in Tk callback Function: > (type: ) Args: () Traceback (innermost last): File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start if self.nextfile == _('No destination file selected'): UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: ordinal not in range(128) ## I've looked into PmwBase.py, but I couldn't figure out what's going on, so I hope that someone here can give me a hint. Thanks in advance and best regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] database programming
Hi Chris, If you just want to learn about databases, then sqlite is a good way to go. It's small, it's typeless (which means you don't have to define ahead of time what sort of thing is going to go in which bit of the database; python is typeless too), and it is not split into client and server (making it much simpler to install and manage, although you can't use it for fancy stuff over a network). You can install sqlite from http://www.sqlite.org/ if you want to play around with the interpreter. This is a good idea if you're not used to databases or you don't know sql, because then you'll learn better what python is trying to do (or what you're trying to make python do). There are plenty of one-off jobs that are easier to do directly in the sqlite interpreter too. To use sqlite from python you need pysqlite from http://sourceforge.net/projects/pysqlite. If you install the binary you don't need to install sqlite separately. There are simple examples of usage in the manual (at http://pysqlite.org/manual.html, or with the installation files). A short example is: import sqlite connection = sqlite.connect("my_database") # make a connection cursor = connection.cursor() # make a database cursor cursor.execute("select * from table1") # send a sql command to the database results = cursor.fetchall() # get a list with the results Cheers, Michael On Mon, 21 Feb 2005 18:42:22 +0800, Chris Mallari <[EMAIL PROTECTED]> wrote: > hi there! can u pls send me sample code in accessing a simple database > using python. > > Chris Mallari > thanks > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with .get in Tkinter
On Sun, 20 Feb 2005 17:12:54 +0200 Mark Kels <[EMAIL PROTECTED]> wrote: > Hi all. > First, here is the code I have a problem with (I got same problem in > my project) : > from Tkinter import * > def go(): > e.get() > print e > > main=Tk() > e=Entry(main) > e.pack() > b=Button(main,text='OK',command=go()).pack() > main.mainloop() > > For some reason the function is called before I click the button, and > I get .10037088 before I have done a thing. > How do I do it right ??? > -- Hi Mark, First problem: you need to assign the command for the button without parenthesis: b = Button(main, text='OK', command=go) b.pack() I split the line you used into two lines, because pack() returns None , so you don't have a reference to the button once you created it. Of course you can do it the way you did if you don't need to reference the button anymore, however there's not much use in assigning a new variable to it, just write: Button(main,text='OK',command=go()).pack() Second problem: your go() function does just what you told it to: it prints the "window name" (or however this is called) of the entry widget. You surely meant something like this: def go(): contents = e.get() print contents or simply: def go(): print e.get() I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i have a question???
[the problem provided by alieks] > >>"EXERCISE 3.9 > >>Use the math library to write a program to print out > >>the sin and cos of numbers from 0 to 2pi in intervals > >>of pi/6. You will need to use the range() function." [Michael] > > You _can_ do the exercise > > with the range function but it would be easier without (eg. with a > > while-loop). [Pierre] > I disagree ... :P And your next remark makes it clear range (or even > better : xrange) is exactly what's needed for that problem ! [Michael's next remark] > > Hint-no-solution: You will need a certain number of intervals, which > > (the number of intervalls) is plain integer. Then translate from > > current-intervall-number to pi'ish (sorry for that, my english ;-) > > value. You're right, I've described the range-solution. But what makes you think, that the range-solution is actually the best/ simplest/ easiest? Within a while-loop you would increment your variable each time by pi/6 and test if still lower-equal than 2*pi (need care for float comparision) . With range you need to compute the "certain number of intervals", then for-loop through the range-generated list and compute the "pi'ish" value. There's a loop one way or another ;-) Unless one want to add some extra exercises like list comprehension and the map function. With the while-loop, you don't need to know certainly which number of intervals are needed, you just check if the upper boundary is reached. Don't know, perhaps I should post examples but alieks might still be working on the exercise and I don't want to spoil anybodies joy for my own one ;-) So, please alieks, post your results to us! regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i have a question???
On Thu, 3 Feb 2005 05:53:31 -0800 (PST), alieks laouhe <[EMAIL PROTECTED]> wrote: > This is from a tutorial > > "EXERCISE 3.9 > Use the math library to write a program to print out > the sin and cos of numbers from 0 to 2pi in intervals > of pi/6. You will need to use the range() function." > > Range won't let me use pi/6 as an incremator correct. The range is for integers only. You _can_ do the exercise with the range function but it would be easier without (eg. with a while-loop). Hint-no-solution: You will need a certain number of intervals, which (the number of intervalls) is plain integer. Then translate from current-intervall-number to pi'ish (sorry for that, my english ;-) value. regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter questions
On Tue, 1 Feb 2005 19:08:41 +0200 Mark Kels <[EMAIL PROTECTED]> wrote: Hi Mark, > Hello, > I got some Tkinter questions that I need the answer for to complete a > little project of mine: > 1. How can I make the program to open in a X*Y sized window ? from Tkinter import * root = Tk() root.geometry('600x400+0+0') This makes a window of 600x400 pixels placed in the upper left corner of the screen (+0+0 is the x- and y- offset; both of the window size and the offset may be omitted, so you can use '600x400' or '+0+0' as arguments for geometry() as well). > 2. How can I open another window from the first one (without closing it) ? Use instances of Toplevel() to create new windows as children of the root (Tk()) window. > 3. How can I add a file browser for my app (like the one you get when > you press "Save as..." in windows apps) ? import tkFileDialog filename = tkFileDialog.asksaveasfilename() if filename: # save the file...; if the user presses the 'Cancel' button, filename should be set to an empty string. > 4. How do I configure the font size on the Text widget (its realy > huge, and I would like to change it to somthing like 12). text = Text(parent, font=('helvetica', '-12', 'normal'))# "negative" size -> pixel size or: text.configure(font=('helvetica', '12', 'normal'))# "positive" size -> point size You can use any 3-tuple of the form (family, size, weight) as font descriptor; if the requested font is not found, the widget should fall back to some (probably ugly) default; tk guarantees that at least 'times', 'helvetica' and 'courier' font families are available, the availability of other fonts depends on your system. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] carriage return on windows
On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex <[EMAIL PROTECTED]> wrote: > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. > > Do you happen to know how this in done? you might want to flush stdout after printing to it. "print" will cares for this only when not using that trailing comma. "flush" means to write immedatly instead to wait for a fair amount of data. import sys,time for i in range(8): sys.stdout.write( "step: %s\r" % i) # or: print "step: %s\r" % i, sys.stdout.flush() time.sleep(.5) There's still another possibilty using ansi control sequences. The dirty way is to print (without trailing comma) and go back to previous line: import time for i in range(8): print "step: %s\033[A" % i # print subsystem has done stdout.flush time.sleep(.5) It's dirty cause the next line was already entered and thus is written (as an empty line) and content of older "steps" will stay an screen, when subsequents lines aren't long enough to overwrite them. Which also applies to \r: import sys,time for i in range(8,0,-1): # printing 8**8, ..., 0**0 on line. Forget to overwrite sys.stdout.write( "step: %s\r" % (i**i)) sys.stdout.flush() time.sleep(.5) Fixes are to add whitespace to the line. Stepping back with \033[D fixes the empty newline issue (which is most often not worth the effort): import sys,time for i in range(8,0,-1): # fixing output length to 30 output = "%-30s" % "step: %s" % (i**i) length = len(output) sys.stdout.write(output) # "print output," would be different, because of implizit spaces sys.stdout.write("\033[D"* (length)) sys.stdout.flush() time.sleep(.5) regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How does import work?
On Fri, 28 Jan 2005 18:40:53 +0100, Johan Nilsson <[EMAIL PROTECTED]> wrote: > >>> from scipy.signal.signaltools import * > > /Traceback (most recent call last): > File "", line 1, in -toplevel- > from scipy.signal.signaltools import * > ImportError: No module named signaltools/ > > So I try the methodic way and this works, giving me access to the > functions I need > > >>> from scipy import * > >>> from scipy.signal import * > >>> from scipy.signal.signaltools import * seems like overkill (and I don't understand why it works better than the above, but that's more an issue about my understanding and not about python ;-). Try from scipy.signal import signaltools # don't import everything from signal and go on using functions from signaltools like this: signaltools.function > Now what confuses me is that when I put the above three lines in a file > (of course without the >>>) and execute them I get a long error message. perhaps different python versions? > / Traceback (most recent call last): > File "/home/johan/pyton/import_test.py", line 5, in -toplevel- > from scipy.signal import * note that the error occours while importing everything from scipy.signal . The chance are well that this error goes away when using a reduced import statement. [snip long traceback talking about scipy and Numerics imports] > import lapack_lite > ImportError: > /usr/local/lib/python2.3/site-packages/Numeric/lapack_lite.so: undefined > symbol: dgesdd_/ given the fact that I'm no c-programmer this seems to me like a broken c module. I would try to reinstall Numeric/ scipy (After hunting the problem down to a specific import). The most obvious reason why the import in idle works is that idle uses another version of python (ask sys.version) regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Clash of the Titans and Mundane Matters
Clash of the Titans >From "Dive into Python": __init__ is called immediately after an instance of the class is created. It would be tempting but incorrect to call this the constructor of the class. It's tempting, because it looks like a constructor (by convention, __init__ is the first method defined for the class), acts like one (it's the first piece of code executed in a newly created instance of the class), and even sounds like one ("init" certainly suggests a constructor-ish nature). Incorrect, because the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class. But __init__ is the closest thing you're going to get to a constructor in Python, and it fills much the same role. >From Alan's book "Learning to Program": One of the methods of this class is called __init__ and it is a special method called a constructor. The reason for the name is that it is called when a new object instance is created or constructed. Any variables assigned (and hence created in Python) inside this method will be unique to the new instance. There are a number of special methods like this in Python, nearly all distinguished by the __xxx__ naming format. Mundane Matters I'm having a hard time with classes in python, but it's coming slowly. One thing that I think is generally difficult is to parse a task into "objects." Here's an example: in Java, I wrote an application to track my travelling expenses (I'm a consultant; this tracking of expenses is the itch I am constantly scratching. ;-) I've also written this application in a perl/CGI web application as well.) It's easy to see the outline of this task: create an abstract class for expense and then extend it for the particular types of expenses -- travel, food, transportation, lodging and so forth. In python, I guess I'd create a class and then "subclass" it. But ... what are reading/writing to files and printing? Of course, I create a "file object" in order to accomplish these tasks -- but how is this object fit into the application design? Do I just create methods within the expense class to accomplish these parts of the task? When I tried this on, it seemed hacky. The other option seemed to be creating an I/O class and passing the expense objects to it. But, should that class be an interface or an object? The one thing you don't see in "how to program" java books is an implementation of I/O in the context of an application. A similar problem occurs with my HTML-parsing routine that I brought to the list recently. Use of HTMLParser was suggested. I've looked into this and usage means subclassing HTMLParser in order to implement the methods in the way that will accomplish my task. Conceptually, I'm having a hard time with the "object" here. (The fairly poor documentation for HTMLParser doesn't help.) Apparently, I'm creating a "parser" object and feeding it data. At least, that's the closest I can get to understanding this process. How I'm actually feeding data to the "parser" object and retrieving the results are matters open to discussion. I'll be working on that when I get another chance. Finally, in terms of "understanding python," the question I keep coming up against is: why do we have both functions and methods? What is the rationale for making join() a string method and a os.path function? Thanks for your time. It's late. ;-) Sometimes, I just have to get these things off my chest. mp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tix and Table printing
On Fri, 14 Jan 2005 08:47:49 - "Alan Gauld" <[EMAIL PROTECTED]> wrote: > Tk was written in the 80's so given > its origins was not likely to have a table. > > Of course it would be nice if they added one now!!! > It looks like they are already working on it: http://wiki.tcl.tk/12753 Regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reinitializing namespace
On Fri, 14 Jan 2005 09:30:46 +0100, Dimitri D'Or <[EMAIL PROTECTED]> wrote: > Thank you for your answer. Actually, my question is not specific to > interactive sessions. I've written a script that loads some modules, create > variables and show figures. What I would like to find, is a command for > clearing all the created variables and close all figures before beginning > the execution of the script. This command will be placed at the beginning of > the script and automatically reinitialize the namespace. The utility of this > command is to guarantee that all the variables that are available in the > namespace after the execution of the script were created by it and are not > remainders from older commands or scripts. In Python you do this by mentally tracking when and by which code variables get created and by careful programm design. Most the time it's as easy as: var1 = func1() var2 = func2() It's obviously easy to track which variable gets created by which function ;-) It's harder when func1 for example looks like: def func1(): global var3 var3 = "something" return "somthing" this way func1 has the *sideeffect* of setting var3. Sideeffects are sometimes really bad and it's a good idea to a) document them and b) use them seldom. Furthermore, reusing old variables can happen and results in hard to debug bugs. Look at this for-loop: meaning_full_variable = None for thing in list_of_things: if strange_condition(): meaning_full_variable = check(thing) print thing, meaning_full_variable Of course, you will reuse the meaning_full_variable whenever strange_condition() is not met. The print statment will print out the actual "thing" but possibly the "meaning_full_variable" from an earlier run. You solve this issue by setting meaning_full_variable in every iteration of this loop: for thing in list_of_things: meaning_full_variable = None if strange_condition(): meaning_full_variable = check(thing) print thing, meaning_full_variable which is a slightly saner version of the code ;-) Since such problems are a little hard to debug, you should learn to get wary when you see code like the above example (feel the problems before running into them). The main tactic to minimize namespace problems is to use functions and classes which comes all with their own namespaces. Perhaps you should post code, you find problematic, and we might find strategies to restructure it, so that namespace problems are claryfied. regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reinitializing namespace
On Thu, 13 Jan 2005 13:20:11 +0100, Dimitri D'Or <[EMAIL PROTECTED]> wrote: > For some purpose, I would like to reinitialize the main namespace, i.e. I want > to delete all the variables I have created through the use of functions or > keyboard entries. Hello Dimiti, sound like you're talking about an interactive session. Otherwise (within a script) it would be a really bad idea to try this (better put your stuff into functions, that don't create global variables). Even in an interactive session it sounds like a not that brilliant idea, especially since I can't think of a way other than using exec "del %s" % key for appropriate keys from globals(). Finding "appropiate" keys is one tricky thing. Why not end your ugly python session and start a new one? You can define all your imports in the python startfile (on Linux, consult python manpage. On Windows, I don't know). You can also define useful functions or variables in your python startfile. This way, you're really shure that all ugly variables are away without del'iting anything important. regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hi
On Tue, 11 Jan 2005 11:39:36 +0530, Gopinath V, ASDC Chennai <[EMAIL PROTECTED]> wrote: > Can any1 please tell me how do i open an editor in python running in > linux os can be as easy as: os.system("editor-cmd") regards Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CGI problem
Hi David... You need to explicitly name your form element to "inputkey" to make your current code work correctly. ( Based on what you have shown below.) Or, to make the code correct, change "inputkey" to "language". Remember that the name in each form element becomes the key in the key/value pairs sent via POST or GET. Patric > I am trying to write a CGI program here is the code of > the HTML > > > ALL > Bromley > Lewisham > > Here is the python > #!/usr/bin/env python > > boroughdict = { > 'BROMLEY': 0.5, > 'LEWISHAM':0.1 > } > > > class dummy:#mocked up input obj > def __init__(self, str): > self.value = str > > import cgi, string > form = cgi.FieldStorage() > > def showboroughinfo(form): > try: > choice = form[inputkey].value > except: > choice = 'BROMLEY' > print "not getting from form" > choice = string.upper(choice) > info = boroughdict[choice] > #this is not being called > newinfo = calcinfo(info) > print "" > print cgi.escape (newinfo) > print "" > #print '' > > def calcinfo(info): > #this is calcuate stuff > info = str(info) > return info > > print "Content-type: text/html\n" > print "Languages" > print "This will happen" > > > showboroughinfo(form) > #print "Hi" > print '' > > For some reason it is not get the info in the try > block. > If I do not have the try block I get this message :- > Traceback (most recent call last): > File > "/home/david/Documents/pyprogramming/cgi-bin/party2.py", > line 45, in ? > showboroughinfo(form) > File > "/home/david/Documents/pyprogramming/cgi-bin/party2.py", > line 19, in showboroughinfo > choice = form[inputkey].value > File "/usr/lib/python2.3/cgi.py", line 552, in > __getitem__ > raise KeyError, key > KeyError: 'borough' > > > Why is the input key not working ? > Thanks in advance. > > > > > > ___ > ALL-NEW Yahoo! Messenger - all new features - even more fun! > http://uk.messenger.yahoo.com > ___ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Something is wrong in file input output functions.
On Mon, Jan 10, 2005 at 12:15:18PM -0800, kumar s wrote: > Dear group, > I have written a small piece of code that takes a file > and selects the columns that I am interested in and > checks the value of the column on a condition (value > that eqauls 25) and then write it the to another file. > > > > Code: > import sys > from string import split > import string > print "enter the file name" ### Takes the file name### > psl = sys.stdin.readline() ### psl has the file > object### I may be wrong but it does not appear to me that you open the files for reading/writing. The variable psl does not contain the file object, it contains the file name. To create a file object, you have to open it. E.g., f = open(psl,"r") w = open(out,"w") Now str_psl = f.readlines() creates an array of strings -- what you are trying to do with psl.split? I don't know what sys.stdout.write returns (and I'm not looking it up), but my guess would be something like the number of characters written. As a matter of form, I suggest writing all function definitions and then follow with execution code (input and function calls) -- makes it easier to read and follow what you're doing. I think it's unfortunate that python does not allow us to put function defs at the end of the file, so we can put execution code at the top ... but that's the way of it. I put my execution in a main function, and then call that. Seems tidier. HTH mp > > f2 = sys.stdout.write("File name to write") > def extCor(psl): > ''' This function, splits the file and writes the > desired columns to > to another file only if the first column value equals > 25.''' > str_psl = psl.split('\n') > str_psl = str_psl[5:] > for ele in range(len(str_psl)): > cols = split(str_psl[ele],'\t') > des_cols = > cols[0]+'\t'+cols[1]+'\t'+cols[8]+'\t'+cols[9]+'\t'+cols[11]+'\t'+cols[12]+'\t'+cols[13]+'\t'+cols[15]+'\t'+cols[16]+'\t'+cols[17]) > if cols[0] == 25: > '''This condition checks if the first > column value == 25, then it writes it to the file, if > not then it does not''' > f2.write(des_cols) > f2.write("\n") > > extCor(psl) > > > > Question: > when i give it the file name that it should parse, I > do not get to asked the file name i am interested in > it gives me nothing. Please help me. > Thanks > K > > > > __ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regex problem
On Wed, Jan 05, 2005 at 06:33:32AM -0500, Kent Johnson wrote: > If you search comp.lang.python for 'convert html text', the top four > results all have solutions for this problem including a reference to this > cookbook recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52297 > > comp.lang.python can be found here: > http://groups-beta.google.com/group/comp.lang.python?hl=en&lr=&ie=UTF-8&c2coff=1 Shame on me, I have to get back into that habit. I will check these references, thanks. mp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regex problem
On Wed, Jan 05, 2005 at 07:37:58AM -, Alan Gauld wrote: > > This function removes HTML formatting codes from a text email > Using regex to remove HTML is usually the wrong approach unless > you can guarantee the format of the HTML in advance. The > HTMLparser is usually better and simpler. I think theres an example > in the module doc of converting HTML to plain text. Thanks. This is one of those projects I've had in mind for a long time, decided it was a good way to learn some python. I will look at the HTMLParser module. But then once I get started on one of these projects, it has a way of taking over. ;-) mp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regex problem
On Tue, Jan 04, 2005 at 09:15:46PM -0800, Danny Yoo wrote: > > > On Tue, 4 Jan 2005, Michael Powe wrote: > > > def parseFile(inFile) : > > import re > > bSpace = re.compile("^ ") > > multiSpace = re.compile(r"\s\s+") > > nbsp = re.compile(r" ") > > HTMLRegEx = > > > > re.compile(r"(<|<)/?((!--.*--)|(STYLE.*STYLE)|(P|BR|b|STRONG))/?(>|>) > > ",re.I) > > > > f = open(inFile,"r") > > lines = f.readlines() > > newLines = [] > > for line in lines : > > line = HTMLRegEx.sub(' ',line) > > line = bSpace.sub('',line) > > line = nbsp.sub(' ',line) > > line = multiSpace.sub(' ',line) > > newLines.append(line) > > f.close() > > return newLines > > > > Now, the main issue I'm looking at is with the multiSpace regex. When > > applied, this removes some blank lines but not others. I don't want it > > to remove any blank lines, just contiguous multiple spaces in a line. > > > Hi Michael, > > Do you have an example of a file where this bug takes place? As far as I > can tell, since the processing is being done line-by-line, the program > shouldn't be losing any blank lines at all. That is what I thought. And the effect is erratic, it removes some but not all empty lines. > Do you mean that the 'multiSpace' pattern is eating the line-terminating > newlines? If you don't want it to do this, you can modify the pattern > slightly. '\s' is defined to be this group of characters: > > '[ \t\n\r\f\v]' > > (from http://www.python.org/doc/lib/re-syntax.html) > > So we can adjust our pattern from: > > r"\s\s+" > > to > > r"[ \t\f\v][ \t\f\v]+" > > so that we don't capture newlines or carriage returns. Regular > expressions have a brace operator for dealing with repetition: > if we're looking for at least 2 or more > of some thing 'x', we can say: I will take a look at this option. Thanks. mp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] German Totorial!?!
Hello, Im a German peaople whou would learn Python. But I cant find a german tutorial. So you know a German Tutorial? Daer Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to run a script file
HI Bernard... I think I see what you might mean I'm guessing your session goes something like this: >>> import sys >>> sys.path.append(' /home/bernardl/python/') >>> import /home/bernardl/python/myScript File "", line 1 import /home/bernardl/python/myScript ^ SyntaxError: invalid syntax Right? If so, its because the full pathname is no longer necessary after you've added it to the path. Just type >>>import myScript and that will bring it in. :) Let us know if we've still misunderstood... Patric > Okay sorry I meant once you're in Python. > > I'm in Bash console, type Python, enter the Python interpreter. > > Then I add my custom path to the sys.path list (because my user > permissions do not allow my to put anything in the Lib directory) and > then I try an import /home/bernardl/python/myScript.py but of course > if fails as soon the first slash is read. > > > Thanks > Bernard > > > John Purser wrote: > > Bernard, > > > > If you're new to Linux you might not be aware of an additional > > method to run python scripts. If the first line of your script is: > > #!/usr/bin/python > > > > And you've set your script permissions to be executable (chmod 700 > > myscript.py) then you can run your script just like any other > > program. You can double click on it in a GUI environment or run it > > from a command prompt by just typing the script name. Or depending > > on the value of $PATH variable you might need to type > > "./myscript.py". Those first characters have to be right though. > > I'm assuming your python is in /usr/bin. And that is a hash mark > > followed by an exclamation point. This is called "hash bang" in > > uningo. > > > > John Purser > > > > -Original Message- > > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On > > Behalf Of Patric Michael Sent: Tuesday, January 04, 2005 14:56 To: > > tutor@python.org Subject: Re: [Tutor] How to run a script file > > > > Hi Bernard... > > > > The most basic form is to type "python" followed by the script you > > want to run. If your script is not in the system path, you'll > > either need to cd to the directory, or give a full pathname: (the > > pythonpath doesn't come into play until the interperter is running. > > > > python /usr/local/share/filename.py > > > > Remember that the script will inherit whatever permissions you > > currently have, so either log in or su to the user that's expected > > to run the script. > > > > Oh, and in case python itself isnt in your system path, (it probably > > is) you can find it by typing "which python" at the shell prompt. > > > > > > Patric > > > > > > > > > >>Hi, > >> > >>Sorry if I missed something obvious, but how do I execute a python > >>script file in the interpreter? I have "Using the Python > >>Interpreter" in the Python tutorial but not much is said... > >> > >>(this might be a lame quesiton but so far I always used either the > >>PythonWin interpreter wich has the Import function, or I ran Python > >>code in an application. Now I'm on Linux so I have to learn the hard > >>way!) > >> > >> > >>Thanks > >>Bernard > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor